"use client";

import * as React from "react";
import { Lenis } from "lenis/react";
import "lenis/dist/lenis.css";

type Props = { children: React.ReactNode };

/** Smooth inertia scrolling; disabled automatically for `prefers-reduced-motion`. */
export function SmoothScroll({ children }: Props) {
  const [useLenis, setUseLenis] = React.useState(false);

  React.useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    if (mq.matches) return;

    setUseLenis(true);

    const onChange = () => {
      setUseLenis(!mq.matches);
    };

    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, []);

  if (!useLenis) {
    return <>{children}</>;
  }

  return (
    <Lenis
      root
      options={{
        smoothWheel: true,
        wheelMultiplier: 0.92,
        lerp: 0.068,
        autoRaf: true,
      }}
    >
      {children}
    </Lenis>
  );
}
