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

export function useActiveSection(sectionIds: string[]) {
  const [active, setActive] = useState(sectionIds[0] ?? "");
  const visibleMap = useRef<Map<string, number>>(new Map());

  useEffect(() => {
    visibleMap.current.clear();

    const pickActive = () => {
      // If scrolled to the very bottom, always select the last section
      const doc = document.documentElement;
      if (doc.scrollTop + doc.clientHeight >= doc.scrollHeight - 2) {
        setActive(sectionIds[sectionIds.length - 1]);
        return;
      }

      // Otherwise pick the topmost visible section
      let best: string | null = null;
      let bestTop = Infinity;
      for (const [id, top] of visibleMap.current) {
        if (top < bestTop) {
          bestTop = top;
          best = id;
        }
      }
      if (best) setActive(best);
    };

    const observer = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            visibleMap.current.set(e.target.id, e.boundingClientRect.top);
          } else {
            visibleMap.current.delete(e.target.id);
          }
        }
        pickActive();
      },
      { rootMargin: "-48px 0px -35% 0px", threshold: 0 }
    );

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

    // Also listen to scroll for bottom-of-page detection
    window.addEventListener("scroll", pickActive, { passive: true });

    return () => {
      observer.disconnect();
      window.removeEventListener("scroll", pickActive);
    };
  }, [sectionIds]);

  return active;
}
