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

interface AnimatedCounterProps {
  value: number;
  suffix?: string;
  duration?: number;
  className?: string;
}

const AnimatedCounter: React.FC<AnimatedCounterProps> = ({
  value,
  suffix = "",
  duration = 1.5,
  className = "",
}) => {
  const baseValue = useMotionValue(0);
  const springValue = useSpring(baseValue, {
    damping: 20,
    stiffness: 100,
  });
  const [displayValue, setDisplayValue] = useState(0);

  useEffect(() => {
    baseValue.set(value);
  }, [value, baseValue]);

  useEffect(() => {
    const unsubscribe = springValue.on("change", (latest) => {
      setDisplayValue(Math.round(latest));
    });

    return () => unsubscribe();
  }, [springValue]);

  return (
    <motion.span className={className}>
      {displayValue}
      {suffix}
    </motion.span>
  );
};

export default AnimatedCounter;
