"use client";

import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import Lenis from "lenis";
import RouteLoader from "./RouteLoader";

/** Lenis owns page scroll; Motion's useScroll reads the native scroll position it drives. */
export default function SmoothScroll({ children }: { children: React.ReactNode }) {
  const lenisRef = useRef<Lenis | null>(null);
  const pathname = usePathname();

  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const lenis = new Lenis({ lerp: 0.09, wheelMultiplier: 0.9, anchors: { offset: -72 } });
    lenisRef.current = lenis;
    let raf = 0;
    const tick = (t: number) => {
      lenis.raf(t);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(raf);
      lenis.destroy();
      lenisRef.current = null;
    };
  }, []);

  // Lenis keeps its own target across route changes. Next resets the native scroll,
  // so without this Lenis still eases from the previous page's position (often the footer) to the new one.
  useEffect(() => {
    const lenis = lenisRef.current;
    if (!lenis) return;
    const id = decodeURIComponent(window.location.hash.slice(1));
    const target = id ? document.getElementById(id) : null;
    lenis.scrollTo(target ?? 0, { immediate: true, force: true, offset: target ? -72 : 0 });
  }, [pathname]);

  return (
    <>
      {children}
      <RouteLoader />
    </>
  );
}
