import { useCallback, useEffect, useState } from 'react';

/** 與 Gateway Member.OTP.ResendCooldownSeconds 預設一致 */
export const RESEND_COOLDOWN_SECONDS = 60;

export function useResendCooldown(initialSeconds = 0) {
  const [secondsLeft, setSecondsLeft] = useState(initialSeconds);

  useEffect(() => {
    if (secondsLeft <= 0) return;
    const timer = window.setInterval(() => {
      setSecondsLeft((prev) => (prev <= 1 ? 0 : prev - 1));
    }, 1000);
    return () => window.clearInterval(timer);
  }, [secondsLeft]);

  const startCooldown = useCallback(() => {
    setSecondsLeft(RESEND_COOLDOWN_SECONDS);
  }, []);

  return {
    secondsLeft,
    canSend: secondsLeft <= 0,
    startCooldown,
  };
}
