"use client";

import { useEffect, useState } from "react";

/**
 * Counts from 0 up to `target` once `start` becomes true (easeOutCubic).
 * Runs a single time — it never restarts. With reduced motion it lands on the final value immediately.
 */
export function useCountUp(target: number, start: boolean, duration = 1600) {
  const [value, setValue] = useState(0);

  useEffect(() => {
    if (!start) return;

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const length = reduced ? 1 : duration;
    let frame = 0;
    const startedAt = performance.now();

    function tick(now: number) {
      const t = Math.min((now - startedAt) / length, 1);
      setValue(Math.round(target * (1 - Math.pow(1 - t, 3))));
      if (t < 1) frame = requestAnimationFrame(tick);
    }
    frame = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frame);
  }, [start, target, duration]);

  return value;
}
