"use client";

import { useEffect, useState } from "react";
import { ChevronDown } from "lucide-react";

/** Sticky table of contents that highlights the section currently in view. */
export default function GuideIndex({ title, items }: { title: string; items: { id: string; title: string }[] }) {
  const [active, setActive] = useState(items[0]?.id);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.filter((e) => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
        if (visible[0]) setActive(visible[0].target.id);
      },
      { rootMargin: "-20% 0px -65% 0px" },
    );
    items.forEach(({ id }) => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [items]);

  const list = (
    <ol className="space-y-1">
      {items.map((item, i) => (
        <li key={item.id}>
          <a
            href={`#${item.id}`}
            aria-current={active === item.id ? "true" : undefined}
            className={`flex gap-3 border-l-2 py-2 pl-4 text-sm leading-snug transition ${
              active === item.id ? "border-gold text-ink" : "border-transparent text-stone hover:text-ink"
            }`}
          >
            <span className="font-serif text-gold-ink">{String(i + 1).padStart(2, "0")}</span>
            {item.title}
          </a>
        </li>
      ))}
    </ol>
  );

  return (
    <>
      <details className="group border border-sand bg-white/60 lg:hidden">
        <summary className="flex cursor-pointer list-none items-center justify-between p-5 [&::-webkit-details-marker]:hidden">
          <span className="eyebrow text-stone">{title}</span>
          <ChevronDown size={16} strokeWidth={1.4} className="text-gold-ink transition group-open:rotate-180" />
        </summary>
        <div className="px-3 pb-4">{list}</div>
      </details>
      <nav aria-label={title} className="sticky top-28 hidden lg:block">
        <p className="eyebrow mb-5 text-stone">{title}</p>
        {list}
      </nav>
    </>
  );
}
