import { getTranslations } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getGameCharacters } from '@/lib/characters'
import { getStoreBalances } from '@/lib/store'
import { wowheadWotlkHome } from '@/lib/wowhead'
import { PageShell } from '@/components/PageShell'
import { ServiceBox } from '@/components/ServiceBox'
import { StoreBrowser } from '@/components/StoreBrowser'
import { StoreNews } from '@/components/StoreNews'

/**
 * Contenido de la tienda. Vive aquí y no en una ruta propia porque la URL lleva
 * el reino (`/store-<slug>`, como el original) y eso lo resuelve la ruta
 * dinámica `[realm]`, igual que /<slug>-realm y /<slug>-players.
 */
export async function StorePage({ locale, realm }: { locale: string; realm: string }) {
  const session = await getSession()
  if (!session.bnetId) redirect({ href: '/log-in', locale })
  if (!session.username) redirect({ href: '/select-account', locale })

  const [chars, balances] = await Promise.all([
    getGameCharacters(session.accountId!),
    getStoreBalances(session.accountId!),
  ])

  const t = await getTranslations('Store')

  return (
    <PageShell title={<>{t('title')} - <span className="blue-info">{realm.toUpperCase()}</span></>}>
      <ServiceBox>
        <br />
        <p>{t('infoTooltip')}</p>
        <p>
          {t.rich('infoDb', {
            link: (c) => (
              <a href={wowheadWotlkHome(locale)} target="_blank" rel="noopener noreferrer">
                {c}
              </a>
            ),
          })}
        </p>
        <br />
        <StoreNews />
      </ServiceBox>

      <StoreBrowser
        characters={chars.map((c) => ({ name: c.name, classCss: c.classCss }))}
        dp={balances.dp}
        vp={balances.vp}
        realm={realm}
      />
    </PageShell>
  )
}
