// app/(app)/worlds/page.tsx  
// Shows world generation stats from worlds.blackroad.io
// Server component with 10s revalidation

async function getWorldStats() {
  try {
    const res = await fetch('https://worlds.blackroad.io/stats', { next: { revalidate: 10 } })
    if (!res.ok) return null
    return await res.json()
  } catch { return null }
}

async function getRecentWorlds() {
  try {
    const res = await fetch('https://blackroad-agents-status.amundsonalexa.workers.dev/worlds?limit=10', 
      { next: { revalidate: 10 } })
    if (!res.ok) return []
    const data = await res.json()
    return data.worlds || []
  } catch { return [] }
}

export default async function WorldsPage() {
  const stats = await getWorldStats()
  const worlds = await getRecentWorlds()
  
  const total = stats?.total || 0
  const nodes = stats?.by_node || {}
  
  return (
    <div className="p-8 max-w-5xl">
      <h1 className="text-3xl font-bold mb-2">🌍 World Generator</h1>
      <p className="text-muted-foreground mb-8">
        Autonomous AI worlds generated by BlackRoad Pi fleet
      </p>
      
      {/* Stats row */}
      <div className="grid grid-cols-3 gap-4 mb-8">
        <div className="rounded-xl border p-5 text-center">
          <div className="text-4xl font-bold text-green-500">{total}</div>
          <div className="text-sm text-muted-foreground mt-1">Total Worlds</div>
        </div>
        <div className="rounded-xl border p-5 text-center">
          <div className="text-4xl font-bold text-blue-500">{nodes.aria64 || '—'}</div>
          <div className="text-sm text-muted-foreground mt-1">aria64 Node</div>
        </div>
        <div className="rounded-xl border p-5 text-center">
          <div className="text-4xl font-bold text-purple-500">{nodes.alice || '—'}</div>
          <div className="text-sm text-muted-foreground mt-1">alice Node</div>
        </div>
      </div>
      
      {/* Type breakdown */}
      {stats?.by_type && (
        <div className="mb-8">
          <h2 className="text-lg font-semibold mb-3">By Type</h2>
          <div className="flex gap-3 flex-wrap">
            {Object.entries(stats.by_type).map(([type, count]: [string, any]) => {
              const emojis: Record<string, string> = { lore: '📜', world: '🌍', code: '💻', story: '✨', tech: '🔧' }
              return (
                <div key={type} className="rounded-lg border px-4 py-2 flex items-center gap-2">
                  <span>{emojis[type] || '📄'}</span>
                  <span className="font-mono text-sm">{type}</span>
                  <span className="text-muted-foreground text-sm">{count}</span>
                </div>
              )
            })}
          </div>
        </div>
      )}
      
      <p className="text-sm text-muted-foreground">
        ⚡ Generating ~2 worlds/min · Live RSS: <a href="https://worlds-feed.blackroad.io/feed.rss" className="underline">worlds-feed.blackroad.io</a>
      </p>
    </div>
  )
}
