import { useInView, useMotionValue, useSpring } from "framer-motion";
import { useEffect, useRef, useState } from "react";

type AnimatedCounterProps = {
    value: number;
    /** Só anima na primeira vez que entra no ecrã (default: true) */
    once?: boolean;
};

const AnimatedCounter = ({ value, once = true }: AnimatedCounterProps) => {
    const ref = useRef<HTMLSpanElement>(null);
    const isInView = useInView(ref, { once, amount: 0.8 });
    const motionValue = useMotionValue(0);
    const spring = useSpring(motionValue, { stiffness: 60, damping: 20 });
    const [display, setDisplay] = useState(0);

    useEffect(() => {
        if (isInView) {
            motionValue.set(value);
        } else if (!once) {
            motionValue.set(0);
        }
    }, [isInView, value, motionValue, once]);

    useEffect(() => {
        const unsubscribe = spring.on("change", (v) => {
            setDisplay(Math.round(v));
        });
        return unsubscribe;
    }, [spring]);

    return <span ref={ref}>{display}</span>;
};

export default AnimatedCounter;
