'use client'

import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import Navbar from '@/components/Navbar'
import Footer from '@/components/Footer'

export const dynamic = 'force-dynamic'

interface GameCategory {
  id: string
  name: string
  slug: string
  thumbnail?: string
  _count: { products: number }
}

export default function GamesPage() {
  const [games, setGames] = useState<GameCategory[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState(() => {
    if (typeof window !== 'undefined') {
      return new URLSearchParams(window.location.search).get('search') || ''
    }
    return ''
  })

  useEffect(() => {
    fetch(`/api/games${search ? `?search=${search}` : ''}`)
      .then(r => r.json())
      .then(d => { setGames(d.categories || []); setLoading(false) })
      .catch(() => setLoading(false))
  }, [search])

  const gameIcons: Record<string, string> = {
    'Mobile Legends': '⚔️', 'Free Fire': '🔥', 'PUBG Mobile': '🎯',
    'Genshin Impact': '⚡', 'Valorant': '💥', 'Honkai Star Rail': '🌟',
    'Clash of Clans': '🏰', 'Call of Duty': '🎖️', 'Arena of Valor': '🛡️',
    'Ragnarok': '🌈', 'Roblox': '🧱', 'Minecraft': '⛏️',
  }

  const gameColors: Record<string, string> = {
    'Mobile Legends': '#3b82f6', 'Free Fire': '#ef4444', 'PUBG Mobile': '#f59e0b',
    'Genshin Impact': '#8b5cf6', 'Valorant': '#ef4444', 'Honkai Star Rail': '#06b6d4',
  }

  return (
    <main style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <div style={{ paddingTop: '64px', flex: 1 }}>
        {/* Header */}
        <div style={{
          background: 'linear-gradient(135deg, rgba(245,158,11,0.06) 0%, rgba(139,92,246,0.04) 100%)',
          borderBottom: '1px solid rgba(255,255,255,0.06)',
          padding: '50px 24px',
        }}>
          <div style={{ maxWidth: '1280px', margin: '0 auto' }}>
            <h1 className="font-game" style={{ fontSize: '40px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
              🎮 Top Up <span className="gradient-text">Game</span>
            </h1>
            <p style={{ color: '#64748b', fontSize: '15px', marginBottom: '24px' }}>
              Pilih game favoritmu dan top up dengan harga terbaik
            </p>
            <input
              className="input"
              style={{ maxWidth: '400px' }}
              placeholder="🔍 Cari game..."
              value={search}
              onChange={e => setSearch(e.target.value)}
            />
          </div>
        </div>

        {/* Games Grid */}
        <div style={{ maxWidth: '1280px', margin: '0 auto', padding: '48px 24px' }}>
          {loading ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '20px' }}>
              {Array(12).fill(0).map((_, i) => (
                <div key={i} className="skeleton" style={{ height: '160px', borderRadius: '16px' }} />
              ))}
            </div>
          ) : games.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 20px', color: '#475569' }}>
              <div style={{ fontSize: '48px', marginBottom: '16px' }}>🎮</div>
              <p style={{ fontSize: '16px', marginBottom: '8px' }}>Belum ada produk game</p>
              <p style={{ fontSize: '14px' }}>Sync produk dari VIP Reseller di Admin Dashboard</p>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: '20px' }}>
              {games.map(game => {
                const icon = gameIcons[game.name] || '🎮'
                const color = gameColors[game.name] || '#f59e0b'
                return (
                  <Link key={game.id} href={`/games/${game.slug}`} style={{ textDecoration: 'none' }}>
                    <div className="card" style={{ padding: '28px 20px', textAlign: 'center', cursor: 'pointer' }}>
                      <div style={{
                        fontSize: '40px',
                        width: 64,
                        height: 64,
                        background: `${color}15`,
                        borderRadius: '16px',
                        border: `1px solid ${color}25`,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        margin: '0 auto 14px',
                      }}>{icon}</div>
                      <div style={{ fontSize: '14px', fontWeight: 600, color: '#e2e8f0', marginBottom: '6px', lineHeight: 1.3 }}>
                        {game.name}
                      </div>
                      <div style={{ fontSize: '12px', color: '#475569' }}>
                        {game._count?.products || 0} produk
                      </div>
                    </div>
                  </Link>
                )
              })}
            </div>
          )}
        </div>
      </div>
      <Footer />
    </main>
  )
}
