"use client";

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

interface UseCountUpOptions {
  start?: number;
  end: number;
  duration?: number;
  delay?: number;
  enabled?: boolean;
}

export function useCountUp({
  start = 0,
  end,
  duration = 300,
  delay = 0,
  enabled = true,
}: UseCountUpOptions): number {
  const [count, setCount] = useState(start);
  const prefersReducedMotion = useReducedMotion();

  useEffect(() => {
    if (!enabled) {
      setCount(start);
      return;
    }

    if (prefersReducedMotion) {
      setCount(end);
      return;
    }

    let controls: ReturnType<typeof animate> | undefined;

    const timeout = setTimeout(() => {
      controls = animate(start, end, {
        duration: duration / 1000,
        ease: [0, 0, 0.2, 1],
        onUpdate: value => {
          setCount(Math.round(value));
        },
      });
    }, delay);

    return () => {
      clearTimeout(timeout);
      controls?.stop();
    };
  }, [start, end, duration, delay, enabled, prefersReducedMotion]);

  return count;
}
