import { useEffect, useRef, useState } from "react";
import { useInView, useReducedMotion, animate } from "framer-motion";

interface AnimatedCounterProps {
  to: number;
  suffix?: string;
  duration?: number;
  className?: string;
  testId?: string;
  suffixClassName?: string;
}

/** Counts up from 0 to `to` when scrolled into view. Pass suffix="+" for "10+". */
export default function AnimatedCounter({ to, suffix = "", duration = 1.6, className = "", testId, suffixClassName = "text-ember" }: AnimatedCounterProps) {
  const ref = useRef<HTMLSpanElement>(null);
  const inView = useInView(ref, { once: true, amount: 0.4 });
  const reduce = useReducedMotion();
  const [val, setVal] = useState(0);

  useEffect(() => {
    if (!inView) return;
    if (reduce) {
      setVal(to);
      return;
    }
    const controls = animate(0, to, {
      duration,
      ease: [0.22, 1, 0.36, 1],
      onUpdate: (v) => setVal(Math.round(v)),
    });
    return () => controls.stop();
  }, [inView, to, duration, reduce]);

  return (
    <span ref={ref} className={className} data-testid={testId}>
      {val}
      {suffix && <span className={suffixClassName}>{suffix}</span>}
    </span>
  );
}
