"use client"

import { useEffect, useState } from "react"

type TocItem = {
  id: string
  text: string
  level: 2 | 3
}

export default function TableOfContents() {
  const [items, setItems] = useState<TocItem[]>([])
  const [activeId, setActiveId] = useState("")

  useEffect(() => {
    const headings = Array.from(
      document.querySelectorAll<HTMLHeadingElement>("#report-body h2, #report-body h3"),
    )
      .filter((heading) => heading.id && heading.textContent)
      .map((heading) => ({
        id: heading.id,
        text: heading.textContent ?? "",
        level: heading.tagName === "H2" ? 2 : 3,
      })) as TocItem[]

    setItems(headings)

    if (headings.length === 0) {
      return
    }

    const observer = new IntersectionObserver(
      (entries) => {
        const visibleEntry = entries.find((entry) => entry.isIntersecting)

        if (visibleEntry) {
          setActiveId(visibleEntry.target.id)
        }
      },
      {
        rootMargin: "-20% 0px -65% 0px",
        threshold: 0,
      },
    )

    headings.forEach((item) => {
      const element = document.getElementById(item.id)

      if (element) {
        observer.observe(element)
      }
    })

    return () => observer.disconnect()
  }, [])

  if (items.length === 0) {
    return null
  }

  return (
    <nav className="sticky top-24 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-5">
      <p className="mb-3 text-[10px] font-semibold uppercase tracking-widest text-[var(--color-accent)]">
        IN THIS REPORT
      </p>
      <div>
        {items.map((item) => (
          <a
            key={item.id}
            href={`#${item.id}`}
            className={[
              "block transition hover:text-[var(--color-text-primary)]",
              activeId === item.id
                ? "text-[var(--color-accent)]"
                : "text-[var(--color-text-secondary)]",
              item.level === 2
                ? "py-1 text-[13px]"
                : "border-l-2 border-[var(--color-border)] py-0.5 pl-3 text-xs",
            ].join(" ")}
          >
            {item.text}
          </a>
        ))}
      </div>
    </nav>
  )
}
