'use client' import { useState } from 'react' import { useTranslations, useLocale } from 'next-intl' import type { GmGuild } from '@/lib/guild' import { PaymentMethodSelect, pdCostOf, type PayMethod } from '@/components/PaymentMethodSelect' function renameErrorKey(error?: string): string { switch (error) { case 'missingFields': case 'invalidName': case 'invalidToken': case 'notGuildMaster': case 'nameTaken': case 'soapError': case 'notAuthenticated': return error case 'insufficientPd': // pago con PD sin saldo -> mensaje específico de hermandad return 'insufficientPoints' case 'fulfillFailed': // el renombrado por SOAP no se aplicó (se reembolsó) return 'soapError' default: return 'generic' } } export function RenameGuildForm({ guilds, price, pdBalance }: { guilds: GmGuild[]; price: number; pdBalance: number }) { const t = useTranslations('Points') const tpay = useTranslations('Pay') const locale = useLocale() const renameError = (error?: string) => t(`renameGuild.errors.${renameErrorKey(error)}`) const [guildId, setGuildId] = useState('') const [newName, setNewName] = useState('') const [token, setToken] = useState('') const [showToken, setShowToken] = useState(false) const [method, setMethod] = useState(pdBalance >= pdCostOf(price) ? 'pd' : 'sumup') const [busy, setBusy] = useState(false) const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null) if (guilds.length === 0) { return (

{t('renameGuild.noGuilds')}
) } async function handleSubmit(e: React.FormEvent) { e.preventDefault() if (busy) return if (!guildId || !newName.trim() || !token.trim()) { setMessage({ ok: false, text: renameError('missingFields') }) return } const amount = method === 'pd' ? tpay('pdCost', { cost: pdCostOf(price) }) : tpay('eur', { price }) if (!window.confirm(tpay('confirm', { amount }))) return setBusy(true) setMessage(null) try { const res = await fetch('/api/guild/rename/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ guildId: Number(guildId), newName: newName.trim(), token: token.trim(), provider: method, locale }), }) const data: { success?: boolean; url?: string; error?: string } = await res.json() if (data.success && data.url) { window.location.href = data.url // éxito PD, o Checkout (Stripe/SumUp) return } setMessage({ ok: false, text: renameError(data.error) }) setBusy(false) } catch { setMessage({ ok: false, text: renameError() }) setBusy(false) } } return (
setNewName(e.target.value)} required />
setToken(e.target.value)} required />{' '} setShowToken((s) => !s)} />

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