"use client";

import { useEffect, useState } from "react";

interface TocItem {
  id: string;
  label: string;
}

interface Props {
  items: TocItem[];
}

export function AuditTOC({ items }: Props) {
  const [activeId, setActiveId] = useState<string>(items[0]?.id ?? "");

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        }
      },
      { rootMargin: "-10% 0px -80% 0px", threshold: 0 },
    );

    items.forEach(({ id }) => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });

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

  function scrollTo(id: string) {
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  }

  return (
    <nav className="space-y-0.5">
      {items.map(({ id, label }) => {
        const active = activeId === id;
        return (
          <button
            key={id}
            onClick={() => scrollTo(id)}
            className={`w-full text-left px-3 py-2 rounded-lg text-xs transition-colors ${
              active
                ? "bg-slate-900 text-white font-semibold"
                : "text-slate-500 hover:text-slate-900 hover:bg-slate-100"
            }`}
          >
            {label}
          </button>
        );
      })}
    </nav>
  );
}
