"use client";

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

export default function Counter({
  value,
  decimals = 0,
  className,
  suffix,
}: {
  value: number;
  decimals?: number;
  className?: string;
  suffix?: string;
}) {
  const ref = useRef<HTMLSpanElement>(null);
  const inView = useInView(ref, { once: true, amount: 0.6 });
  const reduced = useReducedMotion();

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (!inView) return;
    if (reduced) {
      el.textContent = value.toFixed(decimals);
      return;
    }
    let raf = 0;
    const t0 = performance.now();
    const dur = 1500;
    const step = (t: number) => {
      const p = Math.min((t - t0) / dur, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      el.textContent = (value * eased).toFixed(decimals);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [inView, value, decimals, reduced]);

  return (
    <span className={className}>
      <span ref={ref} className="tnum">
        {reduced ? value.toFixed(decimals) : "0"}
      </span>
      {suffix ? <span className="text-azure-bright">{suffix}</span> : null}
    </span>
  );
}
