/**
 * Table of Contents for v2 technique pages with nested sections.
 *
 * Renders a nested list of anchor links matching the H2/H3 section structure.
 * Uses slugified headings as IDs for scroll targeting.
 * Tracks the active section via IntersectionObserver and highlights it.
 */

import { useEffect, useMemo, useState } from "react";
import type { BodySectionV2 } from "../api/public-client";

export function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");
}

interface TableOfContentsProps {
  sections: BodySectionV2[];
}

export default function TableOfContents({ sections }: TableOfContentsProps) {
  const [activeId, setActiveId] = useState<string>("");

  // Collect all section/subsection IDs in document order
  const allIds = useMemo(() => {
    const ids: string[] = [];
    for (const section of sections) {
      const sectionSlug = slugify(section.heading);
      ids.push(sectionSlug);
      for (const sub of section.subsections) {
        ids.push(`${sectionSlug}--${slugify(sub.heading)}`);
      }
    }
    return ids;
  }, [sections]);

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

    const observer = new IntersectionObserver(
      (entries) => {
        // Find the topmost currently-intersecting entry
        const intersecting = entries
          .filter((e) => e.isIntersecting)
          .sort(
            (a, b) =>
              a.boundingClientRect.top - b.boundingClientRect.top
          );

        if (intersecting.length > 0) {
          setActiveId(intersecting[0]!.target.id);
        }
      },
      {
        // Trigger when a section enters the top 30% of the viewport
        rootMargin: "0px 0px -70% 0px",
      }
    );

    for (const id of allIds) {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    }

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

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

  return (
    <nav className="technique-toc" aria-label="Table of contents">
      <h3 className="technique-toc__title">On this page</h3>
      <ul className="technique-toc__list">
        {sections.map((section) => {
          const sectionSlug = slugify(section.heading);
          const isActive = activeId === sectionSlug;
          return (
            <li key={sectionSlug} className="technique-toc__item">
              <a
                href={`#${sectionSlug}`}
                className={`technique-toc__link${isActive ? " technique-toc__link--active" : ""}`}
              >
                {section.heading}
              </a>
              {section.subsections.length > 0 && (
                <ul className="technique-toc__sublist">
                  {section.subsections.map((sub) => {
                    const subSlug = `${sectionSlug}--${slugify(sub.heading)}`;
                    const isSubActive = activeId === subSlug;
                    return (
                      <li key={subSlug} className="technique-toc__subitem">
                        <a
                          href={`#${subSlug}`}
                          className={`technique-toc__sublink${isSubActive ? " technique-toc__sublink--active" : ""}`}
                        >
                          {sub.heading}
                        </a>
                      </li>
                    );
                  })}
                </ul>
              )}
            </li>
          );
        })}
      </ul>
    </nav>
  );
}
