'use client' import { useState } from 'react' import { useTranslations } from 'next-intl' import { useRouter } from '@/i18n/navigation' const ERROR_KEYS = ['invalidCredentials', 'missingFields', 'invalidRequest'] as const export function LoginForm() { const t = useTranslations('Login') const router = useRouter() const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [showPw, setShowPw] = useState(false) const [busy, setBusy] = useState(false) const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null) async function handleSubmit(e: React.FormEvent) { e.preventDefault() if (busy) return if (!email.trim() || !password) { setMessage({ ok: false, text: t('missingFields') }) return } setBusy(true) setMessage(null) try { const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ email: email.trim(), password }), }) const data: { success?: boolean; needsSelection?: boolean; error?: string } = await res.json() if (data.success) { setMessage({ ok: true, text: t('success') }) router.push(data.needsSelection ? '/select-account' : '/account') } else { const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError' setMessage({ ok: false, text: t(key) }) setBusy(false) } } catch { setMessage({ ok: false, text: t('genericError') }) setBusy(false) } } return (
{message.text}
)}