"use client"; import React, { useEffect, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { AuthUser, TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth"; import { useSearchParams } from "next/navigation"; import Link from "next/link"; import { errorMessage } from "@/lib/utils"; // Matches the backend's minimum gap between code sends. const RESEND_COOLDOWN_SECONDS = 60; export function LoginForm() { const { login, verifyTwoFactor, resendTwoFactor } = useAuth(); const searchParams = useSearchParams(); const raw = searchParams.get("redirect") || ""; const hasExplicitRedirect = raw.startsWith("/") && !raw.startsWith("//"); const redirectTo = hasExplicitRedirect ? raw : "/dashboard"; const registerHref = redirectTo !== "/dashboard" ? `/register?redirect=${encodeURIComponent(redirectTo)}` : "/register"; const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [showPassword, setShowPassword] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); // Two-factor step — set once the password is accepted for an account with 2FA on. const [challenge, setChallenge] = useState(null); const [code, setCode] = useState(""); // 2.3.0: a recovery code instead of the 6-digit code (xxxxx-xxxxx, single use). const [useRecovery, setUseRecovery] = useState(false); const [rememberDevice, setRememberDevice] = useState(false); const [resendIn, setResendIn] = useState(0); useEffect(() => { if (resendIn <= 0) return; const t = setTimeout(() => setResendIn((s) => s - 1), 1000); return () => clearTimeout(t); }, [resendIn]); // Skip the generic /dashboard hop (which just redirects again once the role is known) // and go straight to the role-specific dashboard, unless the caller asked for a specific // page back (e.g. returning to a registration flow after login). const goToDashboard = (loggedInUser: AuthUser) => { window.location.href = hasExplicitRedirect ? redirectTo : `/dashboard/${loggedInUser.role || "user"}`; }; const getErrorMessage = (err: unknown) => { const msg = errorMessage(err); if (!msg) return "Login failed"; // Handle case where message is accidentally a JSON string try { const parsed = JSON.parse(msg); return parsed?.message || msg; } catch { return msg; } }; const onSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); setLoading(true); try { const result = await login(email, password); if (isTwoFactorChallenge(result)) { // Password was right, but the account has two-factor on — show the code step. setChallenge(result); setCode(""); setResendIn(RESEND_COOLDOWN_SECONDS); return; } goToDashboard(result); } catch (err) { setError(getErrorMessage(err) || "Login failed. Please try again."); } finally { setLoading(false); } }; const onSubmitCode = async (e: React.FormEvent) => { e.preventDefault(); if (!challenge) return; setError(null); setLoading(true); try { goToDashboard(await verifyTwoFactor(challenge.challengeId, code, rememberDevice)); } catch (err) { setError(getErrorMessage(err) || "Verification failed. Please try again."); } finally { setLoading(false); } }; const onResend = async () => { if (!challenge || resendIn > 0) return; setError(null); try { // The resend response doesn't repeat `enrolling`, so carry it over. const next = await resendTwoFactor(challenge.challengeId); setChallenge({ ...next, enrolling: challenge.enrolling }); setCode(""); setResendIn(RESEND_COOLDOWN_SECONDS); } catch (err) { setError(getErrorMessage(err) || "Couldn't send a new code. Please try again."); } }; const backToPassword = () => { setChallenge(null); setCode(""); setUseRecovery(false); setPassword(""); setError(null); }; if (challenge) { return (

Enter your verification code

{challenge.enrolling && (

Two-factor authentication is required for your role. Entering this code turns it on for your account.

)}

{useRecovery ? "Enter one of the recovery codes you saved when you turned on two-factor. Each works once." : challenge.method === "authenticator" ? "Open your authenticator app and enter the 6-digit code it shows for this site." : <>We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes.}

setCode(useRecovery ? e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "") : e.target.value.replace(/\D/g, ""))} className="w-full border rounded px-3 py-2 text-lg tracking-widest" autoFocus required />
{error &&

{error}

}
{!challenge.enrolling && ( )} {challenge.method !== "authenticator" && !useRecovery && ( )}
); } return (
{searchParams.get("reason") === "2fa" && (

Two-factor authentication is now required for your role. Log in again to set it up — we'll send you a code.

)}
setEmail(e.target.value)} className="w-full border rounded px-3 py-2" required />
setPassword(e.target.value)} className="w-full border rounded px-3 py-2 pr-20" required />
Forgot your password?
Don't have an account? Sign up here.
{error && (

{error}

{error.toLowerCase().includes('not yet active') && (

Check your inbox for an activation email. If you didn't receive it, try logging in again to resend it.

)}
)}

By signing in, you acknowledge that you’ve read and agree to our{" "} Terms of Use {" "} and{" "} Privacy Policy .

); }