"use client"; import { useState, useEffect } from "react"; import { authClient } from "@/lib/auth-client"; import Link from "next/link"; import { useRouter, useSearchParams } from "next/navigation"; import { toast } from "sonner"; import { useTranslations } from "next-intl"; import { Card, CardBody } from "@/design-system/base/card"; import { Input } from "@/design-system/base/input"; import { PrimaryButton, LinkButton } from "@/design-system/base/button"; import { VStack } from "@/design-system/layout/stack"; export default function LoginPage() { const t = useTranslations("auth"); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [loading, setLoading] = useState(false); const [resendLoading, setResendLoading] = useState(false); const [showResendOption, setShowResendOption] = useState(false); const [unverifiedEmail, setUnverifiedEmail] = useState(""); const searchParams = useSearchParams(); const redirectTo = searchParams.get("redirect"); const { data: session, isPending } = authClient.useSession(); const router = useRouter(); useEffect(() => { if (!isPending && session?.user?.username && !redirectTo) { router.push("/decks"); } }, [session, isPending, router, redirectTo]); const handleResendVerification = async () => { if (!unverifiedEmail) return; setResendLoading(true); try { const { error } = await authClient.sendVerificationEmail({ email: unverifiedEmail, callbackURL: "/login", }); if (error) { toast.error(t("resendFailed")); } else { toast.success(t("resendSuccess")); setShowResendOption(false); } } finally { setResendLoading(false); } }; const handleLogin = async () => { if (!username || !password) { toast.error(t("enterCredentials")); return; } setLoading(true); setShowResendOption(false); try { if (username.includes("@")) { const { error } = await authClient.signIn.email({ email: username, password: password, }); if (error) { if (error.status === 403) { setUnverifiedEmail(username); setShowResendOption(true); toast.error(t("emailNotVerified")); } else { toast.error(error.message ?? t("loginFailed")); } return; } } else { const { error } = await authClient.signIn.username({ username: username, password: password, }); if (error) { if (error.status === 403) { toast.error(t("emailNotVerified")); } else { toast.error(error.message ?? t("loginFailed")); } return; } } router.push(redirectTo ?? "/decks"); } finally { setLoading(false); } }; return (

{t("title")}

setUsername(e.target.value)} /> setPassword(e.target.value)} /> {t("forgotPassword")} {showResendOption && (

{t("emailNotVerifiedHint")}

{t("resendVerification")}
)} {t("confirm")} {t("noAccountLink")}
); }