import { useEffect, useState } from "react";

/** Seconds a user must wait before another OTP can be requested. */
const DEFAULT_COOLDOWN_SECONDS = 60;

/**
 * Countdown that gates the "Resend code" button. Ticks with setTimeout rather
 * than wall-clock arithmetic, so it needs no Date.now().
 */
export function useResendCooldown(seconds: number = DEFAULT_COOLDOWN_SECONDS) {
  const [secondsLeft, setSecondsLeft] = useState(0);

  useEffect(() => {
    if (secondsLeft <= 0) return;
    const t = setTimeout(() => setSecondsLeft((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [secondsLeft]);

  return {
    secondsLeft,
    start: () => setSecondsLeft(seconds),
    reset: () => setSecondsLeft(0),
  };
}
