'use client';

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

export function AnimatedNumber({ value }: { value: number }) {
  const spring = useSpring(value, { stiffness: 50, damping: 20 });
  const display = useTransform(spring, (v) => Math.round(v).toLocaleString());
  const ref = useRef<HTMLSpanElement>(null);

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

  useEffect(() => {
    return display.on('change', (v) => {
      if (ref.current) ref.current.textContent = v;
    });
  }, [display]);

  return <span ref={ref}>{value.toLocaleString()}</span>;
}
