import React from 'react';

type Props = {
  value: number;
  duration?: number;
};

export default function AnimatedCount({ value, duration = 700 }: Props) {
  const [displayValue, setDisplayValue] = React.useState(0);

  React.useEffect(() => {
    let frameId = 0;
    const startTime = performance.now();

    const tick = (currentTime: number) => {
      const progress = Math.min((currentTime - startTime) / duration, 1);
      const easedProgress = 1 - Math.pow(1 - progress, 3);
      setDisplayValue(Math.round(value * easedProgress));

      if (progress < 1) {
        frameId = requestAnimationFrame(tick);
      }
    };

    setDisplayValue(0);
    frameId = requestAnimationFrame(tick);

    return () => cancelAnimationFrame(frameId);
  }, [duration, value]);

  return <>{new Intl.NumberFormat().format(displayValue)}</>;
}
