import type { Metadata } from 'next'
import { setRequestLocale } from 'next-intl/server'
import { notFound } from 'next/navigation'
import { getRealmName, realmSlug } from '@/lib/realm'
import { RealmInfo } from '@/components/RealmInfo'
import { PlayersBoard } from '@/components/PlayersBoard'

export const dynamic = 'force-dynamic'

type Kind = 'realm' | 'players'

// Rutas dinámicas del reino (el slug viene de acore_auth.realmlist):
//   /<slug>-realm    → información del reino (Rates/Horarios)
//   /<slug>-players  → estadísticas de personajes (datos reales de la BD)
async function resolve(param: string): Promise<{ name: string; kind: Kind } | null> {
  const name = await getRealmName()
  const slug = realmSlug(name)
  if (param === `${slug}-realm`) return { name, kind: 'realm' }
  if (param === `${slug}-players`) return { name, kind: 'players' }
  return null
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ realm: string }>
}): Promise<Metadata> {
  const { realm } = await params
  const r = await resolve(realm)
  if (!r) return {}
  return { title: `${r.kind === 'players' ? 'Personajes' : 'Reino'} - ${r.name}` }
}

export default async function RealmPage({
  params,
}: {
  params: Promise<{ locale: string; realm: string }>
}) {
  const { locale, realm } = await params
  setRequestLocale(locale)
  const r = await resolve(realm)
  if (!r) notFound()

  const heading = r.kind === 'players' ? 'Personajes' : 'Reino'

  return (
    <div className="main-page">
      <div className="middle-content">
        <div className="body-content">
          <div className="title-content">
            <h1>{heading} - <span className="blue-info">{r.name.toUpperCase()}</span></h1>
          </div>
          {r.kind === 'realm' ? <RealmInfo /> : <PlayersBoard />}
        </div>
      </div>
    </div>
  )
}
