import { useState } from 'react' import { redirectToStripeCheckout } from '../stripe' interface Props { url: string csrfToken: string characters: string[] price: string label: string /** nombre del campo POST del personaje (por defecto "character") */ field?: string /** clase CSS del botón (por defecto "rename-button") */ buttonClass?: string } /** * Formulario reutilizable para los servicios de personaje de pago: selector de * personaje + botón con precio. Al enviar, la vista devuelve un session_id de * Stripe y redirige al Checkout. Sirve para rename/customize/race/faction/level/ * gold/transfer/... cambiando solo los data-* de la plantilla. */ export function CharacterPurchaseForm({ url, csrfToken, characters, price, label, field = 'character', buttonClass = 'rename-button', }: Props) { const [character, setCharacter] = useState('') const [busy, setBusy] = useState(false) const [message, setMessage] = useState<{ ok: boolean; html: string } | null>(null) async function handleSubmit(e: React.FormEvent) { e.preventDefault() if (busy) return setBusy(true) setMessage(null) const body = new URLSearchParams() body.set(field, character) body.set('csrfmiddlewaretoken', csrfToken) try { const resp = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': csrfToken, Accept: 'application/json', }, credentials: 'same-origin', body: body.toString(), }) if (!resp.ok) throw new Error(`HTTP ${resp.status}`) const data: { success?: boolean message?: string session_id?: string stripe_public_key?: string } = await resp.json() if (data.success && data.session_id && data.stripe_public_key) { await redirectToStripeCheckout(data.stripe_public_key, data.session_id) return // redirigiendo a Stripe } setMessage({ ok: !!data.success, html: data.message || '' }) setBusy(false) } catch { setMessage({ ok: false, html: 'Error al iniciar el pago. Inténtalo más tarde.', }) setBusy(false) } } return (
Escoge el personaje