"use client";

import { useEffect, useRef } from "react";
import { gsap, ScrollSmoother, ScrollTrigger, prefersReducedMotion } from "./gsap-setup";

/**
 * Inertial scrolling for the landing page.
 *
 * ScrollSmoother translates #smooth-content inside #smooth-wrapper, which means
 * anything `position: fixed` must live OUTSIDE this component or it will be
 * dragged along by the transform. The HUD, the ambient canvas and the preloader
 * are all mounted as siblings in app.tsx for exactly that reason.
 *
 * It is deliberately not created for reduced-motion visitors or on touch
 * devices (`smoothTouch: 0` leaves native momentum scrolling alone), so those
 * visitors get the ordinary scroller with no hijacking.
 */
export default function SmoothScroll({ children }: { children: React.ReactNode }) {
  const wrapperRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (prefersReducedMotion()) return;

    const ctx = gsap.context(() => {
      ScrollSmoother.create({
        wrapper: "#smooth-wrapper",
        content: "#smooth-content",
        smooth: 1.1,
        smoothTouch: 0,
        // Enables data-speed / data-lag parallax on descendants.
        effects: true,
        normalizeScroll: false,
      });
    }, wrapperRef);

    // Late-loading images (the dashboard shots) change document height after
    // the triggers are measured; one refresh on window load re-syncs them.
    const refresh = () => ScrollTrigger.refresh();
    window.addEventListener("load", refresh);

    return () => {
      window.removeEventListener("load", refresh);
      ctx.revert();
    };
  }, []);

  return (
    <div id="smooth-wrapper" ref={wrapperRef}>
      <div id="smooth-content">{children}</div>
    </div>
  );
}
