"use client";

import { useEffect } from "react";
import Lenis from "lenis";

/**
 * Physics-based smooth scroll. Wraps the whole app.
 *
 * Lenis drives its own RAF loop; every scroll-driven canvas in this site reads
 * scroll position inside its own RAF, so no bridge between the two is needed.
 *
 * iOS Safari stutters on the default config — it gets a higher lerp and
 * syncTouch stays off so native touch momentum is left alone.
 */
export default function SmoothScrollProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  useEffect(() => {
    // Respect the OS-level reduced-motion preference: no smooth scroll at all.
    const prefersReduced = window.matchMedia(
      "(prefers-reduced-motion: reduce)",
    ).matches;
    if (prefersReduced) return;

    const isSafari =
      /^((?!chrome|android).)*safari/i.test(navigator.userAgent) ||
      /iPad|iPhone|iPod/.test(navigator.userAgent);

    // `lerp` and `duration`/`easing` are alternative modes in Lenis: when a
    // lerp is supplied it wins and the duration/easing pair is never consulted.
    // Carrying both meant two of these read as tuning knobs while only one did
    // anything. Keeping lerp alone leaves a single honest control — lower
    // values glide for longer, higher values track the wheel more tightly.
    const lenis = new Lenis({
      lerp: isSafari ? 0.1 : 0.07,
      smoothWheel: true,
      syncTouch: false, // never on iOS — it fights native momentum
      touchMultiplier: 1.5,
      wheelMultiplier: 1,
    });

    let rafId = 0;
    const raf = (time: number) => {
      lenis.raf(time);
      rafId = requestAnimationFrame(raf);
    };
    rafId = requestAnimationFrame(raf);

    return () => {
      cancelAnimationFrame(rafId);
      lenis.destroy();
    };
  }, []);

  return <>{children}</>;
}
