export const OTP_VALID_SECONDS = 3 * 60;
const OTP_SENT_AT_KEY = "otp_sent_at";

export function markOtpSent(): void {
  if (typeof window === "undefined") return;
  sessionStorage.setItem(OTP_SENT_AT_KEY, Date.now().toString());
}

export function getOtpRemainingSeconds(): number {
  if (typeof window === "undefined") return OTP_VALID_SECONDS;

  const sent = sessionStorage.getItem(OTP_SENT_AT_KEY);
  if (!sent) return OTP_VALID_SECONDS;

  const elapsed = Math.floor((Date.now() - Number(sent)) / 1000);
  return Math.max(0, OTP_VALID_SECONDS - elapsed);
}

export function formatOtpCountdown(totalSeconds: number): string {
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return `${minutes}:${seconds.toString().padStart(2, "0")}`;
}
