"use client"; import * as React from "react"; import { authClient } from "@/lib/auth-client"; import { Button } from "@/components/ui/button"; import { toast } from "@/components/ui/toast"; import { humanAuthError, type AuthClientError } from "./auth-errors"; export const RESEND_COOLDOWN_S = 30; /** Ticks a cooldown down to zero. `start(seconds)` resets it. */ export function useCooldown(initial = 0) { const [left, setLeft] = React.useState(initial); React.useEffect(() => { if (left <= 0) return; const t = setTimeout(() => setLeft((v) => Math.max(0, v - 1)), 1000); return () => clearTimeout(t); }, [left]); return { left, start: (s: number) => setLeft(s) }; } export function ResendVerification({ email, initialCooldown = 0, variant = "outline", className }: { email: string; initialCooldown?: number; variant?: "outline" | "ghost" | "primary" | "link"; className?: string }) { const { left, start } = useCooldown(initialCooldown); const [loading, setLoading] = React.useState(false); async function resend() { if (!email || loading || left > 0) return; setLoading(true); try { const { error } = await authClient.sendVerificationEmail({ email, callbackURL: "/verify-email" }); if (error) { const e = error as AuthClientError; if (e.status === 429) { toast.error("Slow down", "Too many emails requested. Please wait a minute before trying again."); start(60); } else { toast.error("Couldn't send the email", humanAuthError(e, "verify")); } return; } toast.success("Verification email sent", `Check ${email} — the link is valid for 24 hours.`); start(RESEND_COOLDOWN_S); } catch { toast.error("Couldn't send the email", "Check your connection and try again."); } finally { setLoading(false); } } return ( ); }