'use client' import { useState } from 'react' import { useTranslations } from 'next-intl' import { Turnstile } from '@/components/Turnstile' const ERROR_KEYS = ['invalidEmail', 'invalidUsername', 'captchaFailed'] as const type RecoverType = 'password' | 'accountname' | 'securitytoken' | 'activation' export function RecoverForm() { const t = useTranslations('Recover') const [type, setType] = useState('password') const [value, setValue] = useState('') const [captcha, setCaptcha] = useState('') const [captchaKey, setCaptchaKey] = useState(0) // remonta el widget para pedir un token nuevo const [busy, setBusy] = useState(false) const [sent, setSent] = useState(false) const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null) const usesUsername = type === 'password' function changeType(newType: RecoverType) { setType(newType) setValue('') setMessage(null) setSent(false) setCaptcha('') setCaptchaKey((k) => k + 1) } function resetCaptcha() { setCaptcha('') setCaptchaKey((k) => k + 1) } async function handleSubmit(e: React.FormEvent) { e.preventDefault() if (busy || sent) return setBusy(true) setMessage(null) try { const res = await fetch('/api/auth/recover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type, value: value.trim(), turnstileToken: captcha }), }) const data: { success?: boolean; error?: string } = await res.json() if (data.success) { setMessage({ ok: true, text: t('success') }) setSent(true) // Como el original: tras 5 s se restaura el botón y se limpia el formulario. setTimeout(() => { setSent(false) setValue('') setMessage(null) resetCaptcha() }, 5000) } else { const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError' setMessage({ ok: false, text: t(key) }) setTimeout(() => { setMessage(null) resetCaptcha() }, 5000) } } catch { setMessage({ ok: false, text: t('genericError') }) } finally { setBusy(false) } } return ( <>

{t('prompt')}


{usesUsername ? ( setValue(e.target.value)} /> ) : ( setValue(e.target.value)} /> )}

{message && {message.text}}

) }