'use client';
import { useCallback, useEffect, useRef, useState } from 'react';

/**
 * A one-shot seconds countdown for the OTP resend timer. Exactly one interval runs at a time —
 * `start(n)` restarts it, it stops itself at zero, and it is cleared on unmount, so no interval
 * leaks (which would cause re-render storms). State is kept local to the OTP component.
 */
export function useCountdown() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const stop = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }, []);

  const start = useCallback(
    (from: number) => {
      stop();
      const initial = Math.max(0, Math.floor(from));
      setSeconds(initial);
      if (initial === 0) return;
      intervalRef.current = setInterval(() => {
        setSeconds((prev) => {
          if (prev <= 1) {
            stop();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    },
    [stop],
  );

  useEffect(() => stop, [stop]);

  return { seconds, isActive: seconds > 0, start, stop };
}
