import { useEffect, useState } from "react";
import { getTenderSectionScrollOffset } from "../scroll-to-section";

export function useTenderSectionScrollSpy(sectionIds: string[]) {
  const [activeId, setActiveId] = useState(sectionIds[0] ?? "");

  useEffect(() => {
    if (sectionIds.length === 0) {
      setActiveId("");
      return;
    }
    setActiveId((prev) =>
      sectionIds.includes(prev) ? prev : (sectionIds[0] ?? ""),
    );
  }, [sectionIds]);

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

    const pickActive = () => {
      const offset = getTenderSectionScrollOffset();
      const scrollY = window.scrollY;
      const viewportHeight = window.innerHeight;
      const documentHeight = Math.max(
        document.documentElement.scrollHeight,
        document.body.scrollHeight,
      );
      const maxScroll = Math.max(1, documentHeight - viewportHeight);

      if (scrollY + viewportHeight >= documentHeight - 2) {
        const last = sectionIds[sectionIds.length - 1] ?? "";
        setActiveId((prev) => (prev === last ? prev : last));
        return;
      }

      const naturalScrolls = sectionIds.map((id) => {
        const el = document.getElementById(id);
        if (!el) return Number.POSITIVE_INFINITY;
        return Math.max(0, el.getBoundingClientRect().top + scrollY - offset);
      });

      const activations: number[] = [];
      let prevAdjusted = 0;
      for (let i = 0; i < naturalScrolls.length; i++) {
        const natural = naturalScrolls[i];
        if (natural <= maxScroll) {
          activations.push(natural);
          prevAdjusted = natural;
          continue;
        }
        const remaining = naturalScrolls.length - i;
        const range = Math.max(0, maxScroll - prevAdjusted);
        const step = range / remaining;
        for (let j = 0; j < remaining; j++) {
          activations.push(prevAdjusted + step * (j + 1));
        }
        break;
      }

      let current = sectionIds[0] ?? "";
      for (let i = 0; i < activations.length; i++) {
        if (activations[i] <= scrollY) current = sectionIds[i];
      }
      setActiveId((prev) => (prev === current ? prev : current));
    };

    pickActive();
    window.addEventListener("scroll", pickActive, { passive: true });
    window.addEventListener("resize", pickActive, { passive: true });

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

  return activeId;
}
