"use client";

import { usePathname } from "next/navigation";
import { useEffect } from "react";

/** Observes `[data-reveal]` elements and adds `.is-in` when they enter view. */
export function ScrollReveal() {
  const pathname = usePathname();

  useEffect(() => {
    const root = document.documentElement;
    const revealEls = Array.from(document.querySelectorAll<HTMLElement>("[data-reveal]"));
    if (!revealEls.length) return;

    const isNearViewport = (el: HTMLElement) => {
      const rect = el.getBoundingClientRect();
      return rect.top < window.innerHeight * 0.96;
    };

    // Keep above-the-fold items visible before animation is enabled.
    revealEls.forEach((el) => {
      if (isNearViewport(el)) el.classList.add("is-in");
    });

    root.classList.add("reveal-on");

    const showAll = () => {
      revealEls.forEach((el) => el.classList.add("is-in"));
    };

    // Safety net: never leave content hidden if observers fail to fire.
    const failSafeId = setTimeout(showAll, 1400);

    if (!("IntersectionObserver" in window)) {
      showAll();
      clearTimeout(failSafeId);
      return () => {
        root.classList.remove("reveal-on");
      };
    }

    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((en) => {
          if (!en.isIntersecting) return;
          const target = en.target as HTMLElement;
          const sibs = target.closest(".bento, .steps, .flist, .plans, .road, .tiles");
          if (sibs) {
            const list = Array.from(sibs.querySelectorAll("[data-reveal]"));
            target.style.transitionDelay = `${Math.min(list.indexOf(target), 5) * 70}ms`;
          }
          target.classList.add("is-in");
          io.unobserve(target);
        });
      },
      { rootMargin: "0px 0px -8% 0px", threshold: 0.1 },
    );

    revealEls.forEach((el) => {
      if (el.classList.contains("is-in")) return;
      io.observe(el);
    });

    return () => {
      clearTimeout(failSafeId);
      io.disconnect();
      root.classList.remove("reveal-on");
    };
  }, [pathname]);

  return null;
}
