"use client"; import Link from "next/link"; import { useCallback, useState, useId, useTransition } from "react"; import { devLoginAction } from "@/actions/auth-actions"; type LoginClientProps = { error: string | null; }; const REDIRECT_URL = "/admin"; // Development mode detection const isDev = process.env.NODE_ENV !== "production"; export default function LoginClient({ error }: LoginClientProps) { const emailId = useId(); const passwordId = useId(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [loading, setLoading] = useState(false); const [googleLoading, setGoogleLoading] = useState(false); const [localError, setLocalError] = useState(null); const [, startDevLoginTransition] = useTransition(); async function handleSignIn(e: React.FormEvent) { e.preventDefault(); if (!email || !password) { setLocalError("Email and password are required."); return; } setLocalError(null); setLoading(true); try { const res = await fetch("/api/auth/sign-in", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: email.trim().toLowerCase(), password: password.trim() }), }); const data = await res.json(); if (!res.ok || data.error) { setLocalError(data.message ?? "Sign-in failed. Please check your email and password."); setLoading(false); return; } // Cookie is set server-side via next/headers — just redirect on success. window.location.href = REDIRECT_URL; } catch { setLocalError("Sign-in failed. Please try again."); setLoading(false); } } async function handleGoogleSignIn() { setGoogleLoading(true); setLocalError(null); try { const { signInWithGoogleAction } = await import("@/actions/auth-actions"); const result = await signInWithGoogleAction({ callbackURL: REDIRECT_URL }); if (result.error || !result.url) { setLocalError( result.error ?? "Google sign-in is not available. Contact your administrator or sign in with email + password.", ); setGoogleLoading(false); return; } window.location.href = result.url; } catch { setLocalError("Google sign-in failed. Please try again."); setGoogleLoading(false); } } const handleDevLogin = useCallback((role: string) => { // Server action sets the dev_session cookie with httpOnly + sameSite // so it's safe against XSS-driven theft. The action is a no-op in // production, so this is only a dev escape hatch. startDevLoginTransition(async () => { await devLoginAction(role); window.location.assign(REDIRECT_URL); }); }, []); const displayError = error ?? localError; return (
{/* Decorative grain layer */}
); }