import { getTranslations, setRequestLocale } from 'next-intl/server'
import { redirect, Link } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getRealmName, realmSlug } from '@/lib/realm'
import { gameAccountDisplayName } from '@/lib/bnet'
import { getAccountDashboard, getAccountRank } from '@/lib/account'
import { reconcileSumUpCheckouts } from '@/lib/sumup'
import { getGameAccounts } from '@/lib/auth'
import { isAdmin } from '@/lib/admin'
import { PageShell } from '@/components/PageShell'
import { AccountTools } from '@/components/AccountTools'
import { GameAccountSwitcher } from '@/components/GameAccountSwitcher'

export const dynamic = 'force-dynamic'

// Enmascara el correo (siempre en minúsculas): primeros caracteres + dominio.
function maskEmail(e: string): string {
  if (!e) return ''
  e = e.toLowerCase()
  const [local, domain] = e.split('@')
  if (!domain) return e
  const visible = local.slice(0, Math.min(6, Math.max(1, local.length - 2)))
  return `${visible}***@${domain}`
}

const ICONS = '/ns-themes/ns-ryu/ns-images/ns-icons'

export default async function AccountPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params
  setRequestLocale(locale)
  const t = await getTranslations('Account')

  const session = await getSession()
  if (!session.bnetId) redirect({ href: '/log-in', locale })
  if (!session.username) redirect({ href: '/select-account', locale })

  // Acredita cualquier pago SumUp pendiente de esta cuenta (SumUp no tiene
  // webhooks) antes de leer el saldo de PD, para que se muestre actualizado.
  if (session.accountId) await reconcileSumUpCheckouts({ accountId: session.accountId }).catch(() => {})

  const data = await getAccountDashboard(session, locale)
  const admin = await isAdmin(session)
  // El rango se basa en el TOTAL DONADO (Stripe + SumUp, sin bajar al gastar);
  // se usa el máximo con el saldo actual para no rebajar el rango a nadie.
  const rank = getAccountRank(Math.max(data.donatedPD, data.dp))
  // Cuentas de juego de la Battle.net (para el selector si hay más de una).
  const games = await getGameAccounts(session.bnetId ?? 0)

  return (
    <PageShell title={t('title')}>
      {/* Información: dos fieldsets como en Django */}
      <div className="box-content">
        <div className="title-box-content">
          <h2>{t('infoTitle')}</h2>
        </div>
        <div className="body-box-content">
          <fieldset className="account-fieldset">
            <legend>{t('basicData')}</legend>
            <div className="separate account-info">
              <p><i className="fa-solid fa-user account-ficon third-brown"></i> {t('accountName')}:{' '}
                <GameAccountSwitcher
                  accounts={games}
                  currentId={session.accountId ?? 0}
                  currentLabel={gameAccountDisplayName(data.gameAccount)}
                />
              </p>
              <p><i className="fa-solid fa-at account-ficon third-brown"></i> {t('regMail')}: <span>{maskEmail(data.regMail)}</span></p>
              <p><i className="fa-solid fa-at account-ficon third-brown"></i> {t('currentMail')}: <span>{maskEmail(data.email)}</span></p>
              <p><i className="fa-solid fa-calendar-days account-ficon third-brown"></i> {t('joindate')}: <span>{data.joindate}</span></p>
              <p><i className="fa-solid fa-globe account-ficon third-brown"></i> {t('lastIpWeb')}: <span>{data.lastIp}</span></p>
              <p><i className="fa-solid fa-globe account-ficon third-brown"></i> {t('lastIpServer')}: <span>{data.lastAttemptIp}</span></p>
            </div>
          </fieldset>

          <fieldset className="account-fieldset">
            <legend>{t('accountState')}</legend>
            <div className="separate account-info">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={rank.image} className="ns-rank" alt={`${t('level')} ${rank.level}`} title={`${t('level')} ${rank.level}`} />
              <p><i className="fa-solid fa-coins account-ficon third-brown"></i> <span className="dp-color">{t('dp')}</span>: <span>{data.dp}</span> | <span className="vp-color">{t('vp')}</span>: <span>{data.vp}</span></p>
              <p><i className="fa-solid fa-shield-halved account-ficon third-brown"></i> {t('securityToken')}: <span>{data.securityTokenDate ? t('requested') : t('notRequested')}</span></p>
              <p><i className="fa-solid fa-lock-open red-info account-ficon"></i> {t('twofaLabel')}: <span> {t('twofaOff')}</span></p>
              <p><i className="fa-solid fa-gavel account-ficon third-brown"></i> {t('banned')}: <span>{data.isBanned ? t('yes') : t('no')}</span> (<Link href="/ban-history">{t('banHistoryLink')}</Link>)</p>
              <p><i className="fa-solid fa-handshake account-ficon third-brown"></i> {t('recruited')}: <span>{data.isRecruited ? t('yes') : t('no')}</span></p>
              <p><i className="fa-solid fa-user-group account-ficon third-brown"></i> {t('recruitedFriends')}: <span>{data.recruitedCount}</span></p>
            </div>
          </fieldset>
        </div>
      </div>

      {/* Mis personajes: rejilla con char-box como en Django */}
      {data.characters.length > 0 && (
        <div className="box-content">
          <div className="title-box-content">
            <h2>{t('characters')}</h2>
          </div>
          <div className="characters-grid body-box-content">
            {data.characters.map((c) => (
              <div className={`char-box char-box-${c.classCss}`} key={c.name}>
                <div className="char-text">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img className="img-small-icon char-icon" src={c.imageUrl} alt={c.name} height={64} loading="lazy" />
                  <p className={`${c.classCss} big-font`}>{c.name}</p>
                  <p><span>{t('level')} {c.level}</span></p>
                  <p className="second-brown">{c.zone}</p>
                  <p>
                    <span>
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      {c.gold}<img className="img-align" src={`${ICONS}/money-gold.gif`} width={10} alt="g" />{' '}
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      {c.silver}<img className="img-align" src={`${ICONS}/money-silver.webp`} width={10} alt="s" />{' '}
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      {c.copper}<img className="img-align" src={`${ICONS}/money-copper.gif`} width={10} alt="c" />
                    </span>
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Utilidades y Herramientas: paneles plegables como en Django */}
      <div className="box-content">
        <div className="title-box-content">
          <h2>{t('toolsTitle')}</h2>
        </div>
        <AccountTools isAdmin={admin} storeHref={`/store-${realmSlug(await getRealmName())}`} />
      </div>
    </PageShell>
  )
}
