import React, { useEffect, useRef } from 'react';
import { motion, useInView, useSpring, useTransform } from 'framer-motion';

interface CounterProps {
    value: number;
}

const Counter: React.FC<CounterProps> = ({ value }) => {
    const ref = useRef(null);
    const isInView = useInView(ref, { once: true, margin: "-20%" });
    // Using slow/heavy physics as requested for premium feel
    const spring = useSpring(0, { mass: 3, stiffness: 75, damping: 30 });

    const display = useTransform(spring, (current) =>
        // formatting: if decimal exists in target, show 1 decimal, else integer
        value % 1 !== 0 ? current.toFixed(1) : Math.round(current).toLocaleString()
    );

    useEffect(() => {
        if (isInView) {
            spring.set(value);
        }
    }, [isInView, value, spring]);

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

export default Counter;
