"use client";

import { useEffect, useState, useRef, type MouseEvent } from "react";

interface TOCItem {
  id: string;
  text: string;
  level: number;
}

function useHeadings(): TOCItem[] {
  const [headings, setHeadings] = useState<TOCItem[]>([]);

  useEffect(() => {
    const elements = Array.from(
      document.querySelectorAll("article h2, article h3")
    ) as HTMLElement[];

    const parsed = elements.map((el) => ({
      id: el.id,
      text: el.textContent ?? "",
      level: el.tagName === "H2" ? 2 : 3,
    }));

    // eslint-disable-next-line react-hooks/set-state-in-effect
    setHeadings(parsed);
  }, []);

  return headings;
}

export function TableOfContents() {
  const [activeId, setActiveId] = useState("");
  const observerRef = useRef<IntersectionObserver | null>(null);
  const headings = useHeadings();

  useEffect(() => {
    observerRef.current = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        });
      },
      { rootMargin: "-20% 0px -70% 0px", threshold: 0 }
    );

    const elements = Array.from(
      document.querySelectorAll("article h2, article h3")
    ) as HTMLElement[];

    elements.forEach((el) => observerRef.current?.observe(el));

    return () => observerRef.current?.disconnect();
  }, []);

  const handleLinkClick = (e: MouseEvent<HTMLAnchorElement>, id: string) => {
    e.preventDefault();
    const target = document.getElementById(id);
    if (!target) return;

    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    if (prefersReducedMotion) {
      window.history.pushState(null, '', `#${id}`);
      target.scrollIntoView({ behavior: 'auto' });
    } else {
      target.scrollIntoView({ behavior: 'smooth' });
      window.history.pushState(null, '', `#${id}`);
    }
  };

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

  return (
    <nav aria-label="Table of contents" className="lg:sticky lg:top-20">
      <h4 className="section-label mb-3">
        INDEX
      </h4>
      <ul className="space-y-1">
        {headings.map((heading) => (
          <li key={heading.id}>
            <a
              href={`#${heading.id}`}
              onClick={(e) => handleLinkClick(e, heading.id)}
              className={`block text-sm transition-colors ${
                heading.level === 3 ? "pl-3 text-ink-soft" : "text-ink"
              } ${activeId === heading.id ? "font-semibold text-accent" : ""}`}
            >
              {heading.text}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}
