import { useThree } from "@react-three/fiber";
import { useLayoutEffect } from "react";
import { useSceneStore } from "../../../store/scene/useSceneStore";

function FPSLimiter() {
    const { advance, set, frameloop } = useThree();
    const { fps, limitFps } = useSceneStore();

    useLayoutEffect(() => {
        let then = 0;
        let raf: number;

        if (limitFps) {
            const interval = 1000 / fps;

            function tick(t: number) {
                raf = requestAnimationFrame(tick);
                const elapsed = t - then;

                if (elapsed > interval) {
                    advance(t, true);
                    then = t - (elapsed % interval);
                }
            }

            set({ frameloop: "never" });
            raf = requestAnimationFrame(tick);

            return () => {
                cancelAnimationFrame(raf);
                set({ frameloop });
            };
        } else {
            set({ frameloop: "always" });
        }
    }, [fps, limitFps, advance, set, frameloop]);

    return null;
}

export default FPSLimiter;
