"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { getPageTopoPattern } from "@/content/topo-patterns";

function useRiftScroll() {
  useEffect(() => {
    let ticking = false;
    const update = () => {
      ticking = false;
      const max = Math.max(
        1,
        document.documentElement.scrollHeight - window.innerHeight
      );
      document.documentElement.style.setProperty(
        "--rift-scroll",
        String(window.scrollY / max)
      );
    };
    const onScroll = () => {
      if (!ticking) {
        ticking = true;
        requestAnimationFrame(update);
      }
    };

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

    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      document.documentElement.style.removeProperty("--rift-scroll");
    };
  }, []);
}

/** Solid page backdrop only — patterns live on each section */
export function RiftPageFlow() {
  const pathname = usePathname() ?? "/";

  useEffect(() => {
    document.documentElement.dataset.topoPattern = getPageTopoPattern(pathname);
    return () => {
      delete document.documentElement.dataset.topoPattern;
    };
  }, [pathname]);

  useRiftScroll();

  return (
    <div
      className="pointer-events-none absolute inset-0 z-0 bg-white"
      aria-hidden
    />
  );
}
