// Animated odometer-style number ticker for currency values
function NumberTicker({ value, decimals = 2, className = "" }) {
  const [display, setDisplay] = React.useState(value);
  const fromRef = React.useRef(value);
  const startRef = React.useRef(performance.now());
  const rafRef = React.useRef(null);

  React.useEffect(() => {
    cancelAnimationFrame(rafRef.current);
    fromRef.current = display;
    startRef.current = performance.now();
    const target = value;
    const from = display;
    const dur = 650;

    const tick = (now) => {
      const t = Math.min(1, (now - startRef.current) / dur);
      // easeOutExpo
      const eased = t === 1 ? 1 : 1 - Math.pow(2, -10 * t);
      const next = from + (target - from) * eased;
      setDisplay(next);
      if (t < 1) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
    // eslint-disable-next-line
  }, [value]);

  // Format with thousands separators
  const safe = isFinite(display) ? display : 0;
  const fixed = safe.toFixed(decimals);
  const [intPart, decPart] = fixed.split(".");
  const withCommas = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

  // Render each character so we can animate per-digit shimmer
  const chars = (decPart !== undefined ? `${withCommas}.${decPart}` : withCommas).split("");

  return (
    <span className={`ticker ${className}`}>
      {chars.map((ch, i) => (
        <span
          key={i}
          className={`ticker__ch ${/\d/.test(ch) ? "digit" : "sep"}`}
        >
          {ch}
        </span>
      ))}
    </span>
  );
}

window.NumberTicker = NumberTicker;
