"use client";

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

interface UseCountUpOptions {
  /** Starting value (default: 0) */
  start?: number;
  /** Target value to count to */
  end: number;
  /** Animation duration in ms (default: 300) */
  duration?: number;
  /** Delay before starting animation in ms (default: 0) */
  delay?: number;
  /** Whether animation is enabled (default: true) */
  enabled?: boolean;
}

/**
 * Animated counter hook for stats and numbers
 * Uses requestAnimationFrame for smooth 60fps animation
 */
export function useCountUp({
  start = 0,
  end,
  duration = 300,
  delay = 0,
  enabled = true,
}: UseCountUpOptions): number {
  const [count, setCount] = useState(start);
  const frameRef = useRef<number | undefined>(undefined);
  const startTimeRef = useRef<number | undefined>(undefined);

  useEffect(() => {
    // If disabled or reduced motion preferred, show final value immediately
    if (!enabled || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      setCount(end);
      return;
    }

    const timeout = setTimeout(() => {
      const animate = (timestamp: number) => {
        if (!startTimeRef.current) {
          startTimeRef.current = timestamp;
        }

        const progress = Math.min((timestamp - startTimeRef.current) / duration, 1);
        // Ease-out cubic for smooth deceleration
        const eased = 1 - Math.pow(1 - progress, 3);
        const current = Math.round(start + (end - start) * eased);

        setCount(current);

        if (progress < 1) {
          frameRef.current = requestAnimationFrame(animate);
        }
      };

      frameRef.current = requestAnimationFrame(animate);
    }, delay);

    return () => {
      clearTimeout(timeout);
      if (frameRef.current) {
        cancelAnimationFrame(frameRef.current);
      }
    };
  }, [start, end, duration, delay, enabled]);

  return count;
}
