import { StrictMode, useEffect, type PropsWithChildren } from "react";
import { createRoot } from "react-dom/client";
import { MotionConfig } from "framer-motion";
import Lenis from "lenis";
import { BrowserRouter } from "react-router-dom";

import App from "./App";
import "./index.css";

function SmoothScroll({ children }: PropsWithChildren) {
  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    const lenis = new Lenis({ lerp: 0.09, smoothWheel: true });
    let frame = 0;
    const update = (time: number) => {
      lenis.raf(time);
      frame = requestAnimationFrame(update);
    };

    frame = requestAnimationFrame(update);
    return () => {
      cancelAnimationFrame(frame);
      lenis.destroy();
    };
  }, []);

  return children;
}

createRoot(document.querySelector<HTMLDivElement>("#root")!).render(
  <StrictMode>
    <BrowserRouter>
      <MotionConfig reducedMotion="user">
        <SmoothScroll>
          <App />
        </SmoothScroll>
      </MotionConfig>
    </BrowserRouter>
  </StrictMode>,
);
