<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { RouterLink } from 'vue-router'
import SpritePreview from '../components/SpritePreview.vue'

interface Season {
  id: string
  number: number
  startDate: string
  endDate: string
  name: string
}

interface LeaderboardEntry {
  botId: string
  botName: string
  archetype: string
  avatarSeed?: string
  tier: number
  wins: number
  losses: number
  eloRating: number
  winStreak?: number
}

const entries = ref<LeaderboardEntry[]>([])
const season = ref<Season | null>(null)
const isLoading = ref(true)
const viewMode = ref<'season' | 'alltime'>('season')
const countdown = ref('')
let countdownHandle: ReturnType<typeof setInterval> | null = null

function updateCountdown() {
  if (!season.value) { countdown.value = ''; return }
  const endMs = new Date(season.value.endDate).getTime()
  const diff = endMs - Date.now()
  if (diff <= 0) { countdown.value = 'Season ended'; return }
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  countdown.value = days > 0 ? `${days}d ${hours}h ${mins}m` : `${hours}h ${mins}m`
}

async function fetchLeaderboard() {
  isLoading.value = true
  try {
    const qs = viewMode.value === 'season' ? '?season=current' : ''
    const res = await fetch(`/api/bots/leaderboard${qs}`)
    if (res.ok) {
      const data = await res.json()
      entries.value = data.entries || []
      season.value = data.season || null
      updateCountdown()
    }
  } catch (err) {
    console.warn('[Leaderboard] load failed:', err)
  }
  isLoading.value = false
}

function toggleView(mode: 'season' | 'alltime') {
  if (viewMode.value === mode) return
  viewMode.value = mode
  fetchLeaderboard()
}

const tierName = (t: number) => ['BABY', 'BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'DIAMOND', 'LEGEND'][t] || '???'
const tierClass = (t: number) => `tier-${t}`

onMounted(() => {
  fetchLeaderboard()
  countdownHandle = setInterval(updateCountdown, 60_000)
})

onUnmounted(() => {
  if (countdownHandle) clearInterval(countdownHandle)
})
</script>

<template>
  <div class="h-full flex flex-col px-6 py-6 overflow-hidden">
    <div class="max-w-4xl mx-auto w-full flex flex-col flex-1 min-h-0">

      <!-- Header -->
      <div class="mb-4">
        <div class="flex items-baseline justify-between mb-3">
          <h2 class="font-display font-black text-3xl sm:text-4xl tracking-wider">
            <span class="gradient-text">RANKINGS</span>
          </h2>
          <span class="font-mono text-text-muted text-xs">
            {{ entries.length }} fighters
          </span>
        </div>

        <!-- View toggle + season info -->
        <div class="flex items-center gap-3 flex-wrap">
          <div class="flex gap-1">
            <button
              class="px-3 py-1.5 font-pixel text-[10px] tracking-wider border rounded-md transition-all"
              :class="viewMode === 'season'
                ? 'border-neon-cyan bg-neon-cyan/15 text-neon-cyan'
                : 'border-border text-text-muted hover:border-white/20'"
              @click="toggleView('season')"
            >
              THIS SEASON
            </button>
            <button
              class="px-3 py-1.5 font-pixel text-[10px] tracking-wider border rounded-md transition-all"
              :class="viewMode === 'alltime'
                ? 'border-neon-cyan bg-neon-cyan/15 text-neon-cyan'
                : 'border-border text-text-muted hover:border-white/20'"
              @click="toggleView('alltime')"
            >
              ALL TIME
            </button>
          </div>
          <div v-if="season && viewMode === 'season'" class="flex items-center gap-2">
            <span class="font-display font-bold text-xs text-neon-purple tracking-wider">{{ season.name }}</span>
            <span class="font-mono text-[10px] text-text-muted">{{ countdown }}</span>
          </div>
        </div>
      </div>

      <!-- Loading -->
      <div v-if="isLoading" class="flex-1 flex flex-col items-center justify-center gap-4">
        <SpritePreview seed="loading" archetype="standard" :size="80" class="animate-bounce" />
        <p class="font-display text-sm text-text-muted animate-pulse tracking-widest">LOADING FIGHTERS...</p>
      </div>

      <!-- Empty -->
      <div v-else-if="entries.length === 0" class="flex-1 flex items-center justify-center">
        <p class="font-display text-text-muted tracking-wider">
          {{ viewMode === 'season' ? 'No fights this season yet.' : 'No fighters registered.' }}
        </p>
      </div>

      <!-- Table -->
      <div v-else class="flex-1 min-h-0 overflow-y-auto border border-border rounded-lg bg-surface-raised/50">
        <table class="w-full">
          <thead class="sticky top-0 bg-surface-raised z-10">
            <tr class="border-b border-border text-text-muted font-display text-[10px] uppercase tracking-[0.15em]">
              <th class="text-center px-4 py-3 w-14">#</th>
              <th class="text-left px-4 py-3">Fighter</th>
              <th class="text-center px-4 py-3">Tier</th>
              <th class="text-right px-4 py-3">Elo</th>
              <th class="text-right px-4 py-3 hidden sm:table-cell">Record</th>
              <th class="text-right px-4 py-3 hidden sm:table-cell">Streak</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(entry, index) in entries"
              :key="entry.botId"
              class="border-b border-border/50 hover:bg-surface-overlay/30 transition-colors"
            >
              <td class="text-center px-4 py-3 font-display font-bold text-lg"
                  :class="index === 0 ? 'text-neon-yellow glow-cyan' : index < 3 ? 'text-neon-cyan' : 'text-text-muted'">
                <span v-if="index < 3">{{ ['[1st]', '[2nd]', '[3rd]'][index] }}</span>
                <span v-else>{{ index + 1 }}</span>
              </td>
              <td class="px-4 py-3">
                <RouterLink :to="`/bot/${entry.botName}`" class="flex items-center gap-2 hover:text-neon-cyan transition-colors">
                  <SpritePreview
                    :seed="entry.avatarSeed || entry.botName"
                    :archetype="entry.archetype || 'standard'"
                    :tier="entry.tier"
                    :size="24"
                    class="shrink-0"
                  />
                  <span class="font-display font-bold text-sm tracking-wide text-text-primary truncate">
                    {{ entry.botName }}
                  </span>
                </RouterLink>
              </td>
              <td class="text-center px-4 py-3">
                <span class="font-display text-[10px] font-bold tracking-wider" :class="tierClass(entry.tier)">
                  {{ tierName(entry.tier) }}
                </span>
              </td>
              <td class="text-right px-4 py-3 font-mono font-bold text-sm"
                  :class="entry.eloRating >= 1500 ? 'text-neon-cyan' : entry.eloRating >= 1300 ? 'text-text-primary' : 'text-text-secondary'">
                {{ Math.round(entry.eloRating) }}
              </td>
              <td class="text-right px-4 py-3 font-mono text-xs text-text-secondary hidden sm:table-cell">
                <span class="text-neon-cyan">{{ entry.wins }}W</span>
                <span class="text-text-muted"> - </span>
                <span class="text-neon-pink">{{ entry.losses }}L</span>
              </td>
              <td class="text-right px-4 py-3 font-mono text-xs hidden sm:table-cell"
                  :class="(entry.winStreak || 0) >= 3 ? 'text-neon-yellow' : 'text-text-muted'">
                {{ (entry.winStreak || 0) > 0 ? `${entry.winStreak}x` : '-' }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>
