'use client' import { useState } from 'react' import { useTranslations } from 'next-intl' /** * Campo «Nombre de la cuenta»: muestra la cuenta de juego activa (WOW1) —como * desplegable si hay más de una— y un botón «+» para crear nuevas cuentas de * juego (WOW2, WOW3…) bajo la misma Battle.net. Cambiar o crear hace una * RECARGA COMPLETA para que todo /account opere sobre la cuenta correcta. */ export function GameAccountSwitcher({ accounts, currentId, currentLabel, }: { accounts: { id: number; index: number }[] currentId: number currentLabel: string }) { const t = useTranslations('Account') const [busy, setBusy] = useState(false) const [adding, setAdding] = useState(false) const [password, setPassword] = useState('') const [error, setError] = useState(null) async function onChange(e: React.ChangeEvent) { const id = Number(e.target.value) if (id === currentId || busy) return setBusy(true) try { const res = await fetch('/api/auth/select-account', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ accountId: id }), }) const d = await res.json() if (d.success) window.location.reload() else setBusy(false) } catch { setBusy(false) } } async function addAccount() { if (busy || !password) return setBusy(true) setError(null) try { const res = await fetch('/api/account/add-game-account', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ password }), }) const d: { success?: boolean; error?: string } = await res.json() if (d.success) { window.location.reload() return } setError( d.error === 'invalidPassword' ? t('addAccountBadPassword') : d.error === 'maxAccounts' ? t('addAccountMax') : t('addAccountError'), ) setBusy(false) } catch { setError(t('addAccountError')) setBusy(false) } } return ( {accounts.length > 1 ? ( ) : ( {currentLabel} )} {adding && ( setPassword(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addAccount() } }} className="account-select add-account-input" autoComplete="off" /> {error && {error}} )} ) }