"use client";

import { useEffect } from "react";

/** Native disclosure remains usable before hydration and with JavaScript disabled. */
export function HomeInteractions() {
  useEffect(() => {
    const sectors = [...document.querySelectorAll<HTMLDetailsElement>(".portal-sector")];
    function select(section: HTMLDetailsElement) {
      sectors.forEach(other => { if (other !== section) other.open = false; });
      document.dispatchEvent(new CustomEvent("portal:segment", { detail: section.id }));
    }
    function toggle(event: Event) {
      const section = event.currentTarget as HTMLDetailsElement;
      if (section.open) select(section);
    }
    sectors.forEach(section => section.addEventListener("toggle", toggle));
    function revealSegment() {
      const id = window.location.hash.slice(1);
      const section = document.getElementById(id);
      if (section instanceof HTMLDetailsElement && section.classList.contains("portal-sector")) {
        section.open = true;
        select(section);
      }
    }
    revealSegment();
    window.addEventListener("hashchange", revealSegment);
    return () => {
      window.removeEventListener("hashchange", revealSegment);
      sectors.forEach(section => section.removeEventListener("toggle", toggle));
    };
  }, []);
  return null;
}
