"use client";

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

declare global {
  interface Window {
    __axReveal?: boolean;
  }
}

/** Inline boot script: hide reveal targets before first paint, with a failsafe if JS never hydrates. */
export const revealBootScript = `(function(){var d=document.documentElement;d.classList.add('js');setTimeout(function(){if(!window.__axReveal){d.classList.remove('js');d.setAttribute('data-reveal-off','')}},3500)})();`;

/** One IntersectionObserver for every [data-reveal] element on the current route. */
export function RevealObserver() {
  const pathname = usePathname();

  useLayoutEffect(() => {
    const root = document.documentElement;
    if (root.hasAttribute("data-reveal-off")) return;
    // Strict Mode in development can strip the class the boot script added.
    root.classList.add("js");
    window.__axReveal = true;
  }, []);

  useEffect(() => {
    const root = document.documentElement;
    const targets = Array.from(document.querySelectorAll<HTMLElement>("[data-reveal]:not(.is-revealed)"));
    if (root.hasAttribute("data-reveal-off") || !("IntersectionObserver" in window)) {
      targets.forEach((el) => el.classList.add("is-revealed"));
      return;
    }

    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (!entry.isIntersecting) continue;
          entry.target.classList.add("is-revealed");
          observer.unobserve(entry.target);
        }
      },
      { rootMargin: "0px 0px -6% 0px", threshold: 0.06 },
    );

    targets.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, [pathname]);

  return null;
}
