"use client";

import { useEffect } from "react";

/**
 * Makes the collapsible guide sections open when navigated to. The sections are
 * native <details> elements (closed by default, toggled by clicking their title).
 * This adds the one behaviour the browser doesn't give for free: clicking a Table
 * of Contents link — or any in-page #anchor — opens the matching section and
 * scrolls it into view. Renders nothing.
 */
export default function GuideInteractivity() {
  useEffect(() => {
    const openById = (rawId: string) => {
      if (!rawId) return;
      const el = document.getElementById(decodeURIComponent(rawId));
      if (el instanceof HTMLDetailsElement) {
        el.open = true;
        el.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    };

    const fromHash = () => openById(window.location.hash.replace(/^#/, ""));

    // Deep link: open the targeted section on first load.
    fromHash();
    window.addEventListener("hashchange", fromHash);

    // Delegated click: also handles re-clicking a link whose hash is already set
    // (which wouldn't fire hashchange).
    const onClick = (e: MouseEvent) => {
      const anchor = (e.target as HTMLElement | null)?.closest('a[href^="#"]') as HTMLAnchorElement | null;
      if (!anchor) return;
      const id = anchor.getAttribute("href")?.slice(1) ?? "";
      // Let the default hash navigation happen first, then open + scroll.
      requestAnimationFrame(() => openById(id));
    };
    document.addEventListener("click", onClick);

    return () => {
      window.removeEventListener("hashchange", fromHash);
      document.removeEventListener("click", onClick);
    };
  }, []);

  return null;
}
