import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
import { useLocation } from "react-router-dom";

interface TocItem {
  id: string;
  title: string;
  level: number;
}

function useTocItems(): TocItem[] {
  const [items, setItems] = useState<TocItem[]>([]);
  const location = useLocation();

  useEffect(() => {
    // Small delay to allow page to render
    const timer = setTimeout(() => {
      const headings = Array.from(document.querySelectorAll("[data-doc-content] h2, [data-doc-content] h3"));
      const tocItems: TocItem[] = headings.map((el) => ({
        id: el.id,
        title: el.textContent ?? "",
        level: el.tagName === "H2" ? 2 : 3,
      }));
      setItems(tocItems);
    }, 50);
    return () => clearTimeout(timer);
  }, [location.pathname]);

  return items;
}

function useActiveId(ids: string[]): string {
  const [activeId, setActiveId] = useState("");

  useEffect(() => {
    if (ids.length === 0) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.filter((e) => e.isIntersecting);
        if (visible.length > 0) {
          setActiveId(visible[0].target.id);
        }
      },
      { rootMargin: "0% 0% -70% 0%", threshold: 0 }
    );

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

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

  return activeId;
}

export function TableOfContents() {
  const items = useTocItems();
  const activeId = useActiveId(items.map((i) => i.id));

  if (items.length === 0) return null;

  return (
    <nav className="sticky top-20">
      <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3">
        On this page
      </p>
      <ul className="space-y-1">
        {items.map((item) => (
          <li key={item.id}>
            <a
              href={`#${item.id}`}
              className={cn(
                "block text-sm leading-5 py-0.5 transition-colors",
                item.level === 3 && "pl-4",
                activeId === item.id
                  ? "text-primary font-medium"
                  : "text-muted-foreground hover:text-foreground"
              )}
              onClick={(e) => {
                e.preventDefault();
                document.getElementById(item.id)?.scrollIntoView({ behavior: "smooth" });
              }}
            >
              {item.title}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}
