import { notFound } from 'next/navigation'
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { Link } from '@/i18n/navigation'
import { getCharacter, getCharacterEquipment } from '@/lib/armory'
import { raceName, className, classColor, factionOf, EQUIP_SLOTS } from '@/lib/wow-data'
import { wowheadUrl, wowheadData } from '@/lib/wowhead'
import { PageShell } from '@/components/PageShell'
import { WowheadRefresh } from '@/components/WowheadRefresh'
import { ArmoryModel3D } from '@/components/ArmoryModel3D'

export const dynamic = 'force-dynamic'

export default async function CharacterPage({
  params,
}: {
  params: Promise<{ locale: string; guid: string }>
}) {
  const { locale, guid } = await params
  setRequestLocale(locale)
  const t = await getTranslations('Armory')

  const id = Number(guid)
  const character = await getCharacter(id)
  if (!character) notFound()
  const equipment = await getCharacterEquipment(id, locale)
  const bySlot = new Map(equipment.map((e) => [e.slot, e]))

  const faction = factionOf(character.race)
  const factionLabel = faction === 'alliance' ? t('alliance') : faction === 'horde' ? t('horde') : ''

  // Modelo 3D: raza, género y equipo (entry + display; transmog si lo hay).
  const modelEquip = equipment
    .map((e) => ({
      slot: e.slot,
      entry: e.transmogEntry ?? e.entry,
      displayid: e.transmogDisplayId ?? e.displayId ?? 0,
    }))
    .filter((e) => e.displayid > 0)

  return (
    <PageShell title={character.name}>
      <div className="main-wide">
        <WowheadRefresh dep={`char-${id}`} />
        <p className="forum-path">
          <Link href="/armory">← {t('backToArmory')}</Link>
        </p>

        <div className="armory-char">
          {/* Columna izquierda: identidad + modelo 3D */}
          <div className="armory-char-left">
            <h1 className="armory-char-name" style={{ color: classColor(character.class) }}>
              {character.name}
            </h1>
            <div className="armory-char-sub">
              {t('level')} {character.level} · {raceName(character.race, locale)} ·{' '}
              <span style={{ color: classColor(character.class) }}>{className(character.class, locale)}</span>
            </div>
            <div className="armory-char-tags">
              {factionLabel && <span className={`armory-faction ${faction}`}>{factionLabel}</span>}
              <span className={`armory-status ${character.online ? 'online' : 'offline'}`}>
                {character.online ? t('online') : t('offline')}
              </span>
              {character.guildName && character.guildId && (
                <Link href={`/armory/guild/${character.guildId}`} className="armory-guild-tag">
                  &lt;{character.guildName}&gt;
                </Link>
              )}
            </div>
            <ArmoryModel3D
              race={character.race}
              gender={character.gender}
              equip={modelEquip}
              labels={{ loading: t('modelLoading'), unavailable: t('modelUnavailable') }}
            />
          </div>

          {/* Columna derecha: equipo */}
          <div className="armory-char-right">
            <h2 className="armory-section-title">{t('equipment')}</h2>
            {equipment.length === 0 ? (
              <p className="armory-hint">{t('noEquipment')}</p>
            ) : (
              <div className="armory-equip">
                {EQUIP_SLOTS.map(({ slot, es, en }) => {
                  const item = bySlot.get(slot)
                  const slotName = locale === 'en' ? en : es
                  if (!item) {
                    return (
                      <div key={slot} className="armory-equip-slot empty">
                        <span className="armory-slot-name">{slotName}</span>
                      </div>
                    )
                  }
                  return (
                    <div key={slot} className="armory-equip-slot">
                      <a
                        href={wowheadUrl('item', item.entry, locale)}
                        data-wowhead={wowheadData('item', item.entry, locale)}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={`armory-item q${item.quality}`}
                      >
                        {item.name}
                      </a>
                      <span className="armory-slot-name">
                        {slotName}
                        {item.itemLevel ? ` · ${item.itemLevel}` : ''}
                      </span>
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </PageShell>
  )
}
