<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FightViewer from '../components/FightViewer.vue'
import { useNostr } from '../composables/useNostr'

const route = useRoute()
const router = useRouter()
const { bot: myBot, isLoggedIn } = useNostr()
const fightId = route.params.fightId as string
const fight = ref<any>(null)
const isLoading = ref(true)
const isRequeueing = ref(false)
const isLive = ref(false)
const liveRounds = ref(0)
let pollHandle: ReturnType<typeof setInterval> | null = null

async function loadFight(): Promise<string | null> {
  try {
    const res = await fetch(`/api/fights/${fightId}`)
    if (res.ok) {
      const data = await res.json()
      liveRounds.value = data.rounds?.length || 0
      if (data.status === 'finished') {
        fight.value = data
      }
      return data.status
    }
  } catch { /* */ }
  return null
}

onMounted(async () => {
  const status = await loadFight()
  isLoading.value = false

  if (status !== 'finished') {
    isLive.value = true
    pollHandle = setInterval(async () => {
      const s = await loadFight()
      if (s === 'finished') {
        isLive.value = false
        if (pollHandle) { clearInterval(pollHandle); pollHandle = null }
      }
    }, 1500)
  }
})

onUnmounted(() => {
  if (pollHandle) clearInterval(pollHandle)
})

async function fightAgain(botId: string) {
  if (isRequeueing.value) return
  isRequeueing.value = true
  try {
    const res = await fetch(`/api/queue/join/${botId}`, { method: 'POST' })
    if (res.ok) {
      const data = await res.json()
      router.push(`/arena/${data.fightId}`)
    }
  } catch { /* */ }
  isRequeueing.value = false
}
</script>

<template>
  <div class="h-[calc(100vh-4rem)] flex flex-col px-2 sm:px-3 py-2 sm:py-3 overflow-hidden">
    <div v-if="isLoading" class="flex-1 flex items-center justify-center">
      <p class="font-display text-text-muted animate-pulse tracking-wider">LOADING FIGHT...</p>
    </div>

    <div v-else-if="isLive" class="flex-1 flex flex-col items-center justify-center gap-4">
      <div class="w-16 h-16 border-4 border-neon-pink/30 border-t-neon-pink rounded-full animate-spin" />
      <p class="font-display text-neon-pink text-xl tracking-widest animate-pulse glow-pink">FIGHT IN PROGRESS</p>
      <p class="font-mono text-text-muted text-xs">
        Round {{ liveRounds }} — webhooks being called...
      </p>
    </div>

    <div v-else-if="!fight" class="flex-1 flex items-center justify-center">
      <p class="font-display text-text-muted">Fight not found.</p>
    </div>

    <template v-else>
      <FightViewer :fight="fight" :autoplay="true" class="flex-1 min-h-0" />

      <!-- Big post-fight action bar -->
      <div v-if="fight.status === 'finished'" class="flex-shrink-0 pt-2 sm:pt-3">
        <div class="flex gap-2">
          <button
            v-if="fight.botA && isLoggedIn && myBot?.id === fight.botA.id"
            class="flex-1 py-3 sm:py-4 bg-neon-cyan/5 border-2 border-neon-cyan/50 text-neon-cyan
                   font-display font-black text-sm sm:text-base tracking-widest
                   hover:bg-neon-cyan/15 hover:border-neon-cyan transition-all neon-border-cyan
                   disabled:opacity-30 disabled:cursor-not-allowed"
            :disabled="isRequeueing"
            @click="fightAgain(fight.botA.id)"
          >
            {{ isRequeueing ? 'MATCHING...' : `FIGHT AGAIN` }}
            <span class="block font-mono text-[9px] sm:text-[10px] tracking-wider text-neon-cyan/60 mt-0.5">
              AS {{ fight.botA.name.toUpperCase() }}
            </span>
          </button>
          <button
            v-if="fight.botB && isLoggedIn && myBot?.id === fight.botB.id"
            class="flex-1 py-3 sm:py-4 bg-neon-pink/5 border-2 border-neon-pink/50 text-neon-pink
                   font-display font-black text-sm sm:text-base tracking-widest
                   hover:bg-neon-pink/15 hover:border-neon-pink transition-all neon-border-pink
                   disabled:opacity-30 disabled:cursor-not-allowed"
            :disabled="isRequeueing"
            @click="fightAgain(fight.botB.id)"
          >
            {{ isRequeueing ? 'MATCHING...' : `FIGHT AGAIN` }}
            <span class="block font-mono text-[9px] sm:text-[10px] tracking-wider text-neon-pink/60 mt-0.5">
              AS {{ fight.botB.name.toUpperCase() }}
            </span>
          </button>
        </div>
      </div>
    </template>
  </div>
</template>
