import { useState, useEffect, useRef } from 'react';

export function useCountUp(end: number, duration = 800) {
  const [count, setCount] = useState(0);
  const prevEnd = useRef(end);

  useEffect(() => {
    if (end === prevEnd.current && count > 0) return;
    prevEnd.current = end;
    if (end === 0) { setCount(0); return; }

    const startTime = performance.now();
    function tick(now: number) {
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setCount(Math.round(end * eased));
      if (progress < 1) requestAnimationFrame(tick);
    }
    requestAnimationFrame(tick);
  }, [end, duration]);

  return count;
}
