'use client' import { useMemo, useState } from 'react' import { useTranslations, useLocale } from 'next-intl' import type { GiftCategory, GiftItem } from '@/lib/gift' import { CharacterSelect, type CharOption } from '@/components/CharacterSelect' import { PaymentMethodSelect, type PayMethod } from '@/components/PaymentMethodSelect' // Tope de cantidad en la interfaz. El servidor lo revalida en priceCart (fuente de verdad). const MAX_QTY = 100 interface CartEntry { item: GiftItem qty: number } /** Campo con ojo para mostrar/ocultar el token de seguridad. */ function SecretInput({ value, onChange, placeholder, }: { value: string onChange: (v: string) => void placeholder: string }) { const [show, setShow] = useState(false) return ( <> onChange(e.target.value)} placeholder={placeholder} required />{' '} setShow((s) => !s)} /> ) } export function SendGiftForm({ characters, catalog, currency = '€', pdBalance = 0, }: { characters: CharOption[] catalog: GiftCategory[] currency?: string pdBalance?: number }) { const t = useTranslations('CharService') const tpay = useTranslations('Pay') const locale = useLocale() const [source, setSource] = useState('') const [destination, setDestination] = useState('') const [token, setToken] = useState('') const [cart, setCart] = useState>(new Map()) const [method, setMethod] = useState('pd') const [busy, setBusy] = useState(false) const [error, setError] = useState(null) const total = useMemo( () => Math.round([...cart.values()].reduce((s, e) => s + e.item.price * e.qty, 0) * 100) / 100, [cart], ) // Catálogo aplanado y paginado: 4 objetos por fila, 2 filas (8) por página. const PAGE_SIZE = 8 const allItems = useMemo( () => catalog.flatMap((c) => c.items.map((it) => ({ ...it, category: c.name }))), [catalog], ) const [page, setPage] = useState(1) const totalPages = Math.max(1, Math.ceil(allItems.length / PAGE_SIZE)) const currentPage = Math.min(page, totalPages) const pageItems = allItems.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE) function addItem(item: GiftItem) { setCart((prev) => { const next = new Map(prev) const cur = next.get(item.id) next.set(item.id, { item, qty: Math.min(MAX_QTY, (cur?.qty ?? 0) + 1) }) return next }) } function setQty(id: number, qty: number) { setCart((prev) => { const next = new Map(prev) const cur = next.get(id) if (!cur) return prev const q = Math.max(1, Math.min(MAX_QTY, Math.floor(qty) || 1)) next.set(id, { ...cur, qty: q }) return next }) } function removeItem(id: number) { setCart((prev) => { const next = new Map(prev) next.delete(id) return next }) } async function handleSubmit(e: React.FormEvent) { e.preventDefault() if (busy) return if (!source || !destination.trim() || !token.trim()) { setError(t('sendGift.errMissingFields')) return } if (cart.size === 0) { setError(t('sendGift.errEmptyCart')) return } if ( !window.confirm( t('sendGift.confirm', { destination: destination.trim(), total, currency }), ) ) return setBusy(true) setError(null) try { const res = await fetch('/api/gift/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ source, destination: destination.trim(), security_token: token.trim(), cart: [...cart.values()].map((e) => ({ id: e.item.id, qty: e.qty })), provider: method, locale, }), }) const data: { success?: boolean; url?: string; message?: string; error?: string } = await res.json() if (data.success && data.url) window.location.href = data.url else { const payErr = data.error && tpay.has(`errors.${data.error}`) ? tpay(`errors.${data.error}`) : undefined setError(data.message || payErr || t('sendGift.errPayment')) setBusy(false) } } catch { setError(t('sendGift.errUnexpected')) setBusy(false) } } if (characters.length === 0) return

{t('sendGift.noCharacters')}

if (catalog.length === 0) return

{t('sendGift.noItems')}

return (

{t('sendGift.sourcePrompt')}


{t('sendGift.destPrompt')}

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

{t('sendGift.tokenPrompt')}


{/* Catálogo de objetos: cuadrícula centrada de 4 por fila + paginación */}

{t('sendGift.availableItems')}

{pageItems.map((it) => (
{it.name}
{it.category}
{it.name}
{it.price} {currency}
))}
{totalPages > 1 && (
{Array.from({ length: totalPages }, (_, i) => i + 1).map((n) => ( ))}
)}
{/* Carrito */}

{t('sendGift.cart')}

{cart.size === 0 ? (

{t('sendGift.cartEmpty')}

) : ( {[...cart.values()].map((e) => ( ))}
{e.item.name} {e.item.name} setQty(e.item.id, Number(ev.target.value))} style={{ width: '4em' }} /> {Math.round(e.item.price * e.qty * 100) / 100} {currency}
)}

{t.rich('sendGift.total', { total, currency, s: (c) => {c} })}

{total > 0 && }

{error && {error}}
) }