'use client' import { useState } from 'react' import { useRouter } from '@/i18n/navigation' function promoError(error?: string): string { switch (error) { case 'missingCode': return 'Escribe un código de promoción.' case 'notFound': return 'El código no existe o ya no está disponible.' case 'expired': return 'Este código ha caducado.' case 'exhausted': return 'Este código ya ha alcanzado su límite de usos.' case 'alreadyUsed': return 'Ya has canjeado este código.' case 'notAuthenticated': return 'Tu sesión ha expirado. Inicia sesión de nuevo.' default: return 'No se pudo canjear el código. Inténtalo de nuevo.' } } export function PromoCodeForm() { const router = useRouter() const [code, setCode] = useState('') 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 || !code.trim()) return setBusy(true) setMessage(null) try { const res = await fetch('/api/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ code: code.trim() }), }) const data: { success?: boolean; error?: string; pd?: number; pv?: number } = await res.json() if (data.success) { const parts: string[] = [] if (data.pd) parts.push(`${data.pd} PD`) if (data.pv) parts.push(`${data.pv} PV`) const reward = parts.length ? parts.join(' y ') : 'la recompensa' setMessage({ ok: true, text: `¡Código canjeado! Has recibido ${reward}.` }) setCode('') router.refresh() } else { setMessage({ ok: false, text: promoError(data.error) }) } } catch { setMessage({ ok: false, text: promoError() }) } finally { setBusy(false) } } return (

setCode(e.target.value)} required />

{message && {message.text}}
) }