<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { useNostr } from '../composables/useNostr'
import FightViewer from '../components/FightViewer.vue'
import type { FightData } from '../game/fight/types'

const route = useRoute()
const router = useRouter()
const { bot: myBot, isLoggedIn } = useNostr()

const fightId = ref(route.params.fightId as string)
const fight = ref<FightData | null>(null)
const phase = ref<'waiting' | 'challenge' | 'submitted' | 'timeout' | 'between' | 'finished' | 'replay' | 'error'>('waiting')
const error = ref('')

// Challenge state
const currentChallenge = ref<{
  type: string
  label: string
  prompt: string
  roundNumber: number
  timeoutMs: number
  remainingMs: number
  scoring: string
  choices: string[]
} | null>(null)
const answer = ref('')
const trashTalk = ref('')
const remainingSeconds = ref(45)
const showTrashTalk = ref(false)

// Feedback state
const feedback = ref<'correct' | 'wrong' | null>(null)
const feedbackTimer = ref<ReturnType<typeof setTimeout> | null>(null)

// Polling error tracking (BUG-4 fix)
const consecutivePollErrors = ref(0)
const connectionLost = ref(false)

// Round results tracking
const roundResults = ref<Array<{
  round: number
  won: boolean
  hpA: number
  hpB: number
}>>([])
const currentRound = ref(0)
const myHp = ref(200)
const enemyHp = ref(200)
const opponentName = ref('')

let pollHandle: ReturnType<typeof setInterval> | null = null
let timerHandle: ReturnType<typeof setInterval> | null = null
let timerDeadline = 0 // BUG-7: deadline-based timer
const answerInput = ref<HTMLTextAreaElement | null>(null)

const myBotId = computed(() => myBot.value?.id || '')
const isMyFight = computed(() => {
  if (!fight.value || !myBot.value) return false
  return fight.value.botAId === myBot.value.id || fight.value.botBId === myBot.value.id
})
const amSideA = computed(() => fight.value?.botAId === myBot.value?.id)

const timerColor = computed(() => {
  if (remainingSeconds.value <= 3) return 'text-ko'
  if (remainingSeconds.value <= 10) return 'text-neon-yellow'
  return 'text-neon-green'
})

const timerShake = computed(() => remainingSeconds.value <= 3 && remainingSeconds.value > 0)

const hasChoices = computed(() =>
  currentChallenge.value?.choices && currentChallenge.value.choices.length > 0
)

// Back-button guard — warn if fight is active
onBeforeRouteLeave((_to, _from, next) => {
  const isActive = phase.value === 'challenge' || phase.value === 'submitted' || phase.value === 'timeout' || phase.value === 'between' || phase.value === 'waiting'
  if (isActive && !window.confirm('Fight in progress! Leave and forfeit?')) {
    next(false)
    return
  }
  next()
})

onMounted(() => {
  if (!myBot.value) {
    router.push('/join')
    return
  }
  startPolling()
  window.addEventListener('keydown', handleKeyboard)
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

onUnmounted(() => {
  stopPolling()
  stopTimer()
  if (feedbackTimer.value) clearTimeout(feedbackTimer.value)
  window.removeEventListener('keydown', handleKeyboard)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})

// Tab switching — re-poll and re-sync timer when tab becomes visible
function handleVisibilityChange() {
  if (document.visibilityState === 'visible' && (phase.value === 'challenge' || phase.value === 'waiting' || phase.value === 'between')) {
    pollForChallenge()
  }
}

// BUG-5: Keyboard shortcuts for MC choices (A-D or 1-4)
function handleKeyboard(e: KeyboardEvent) {
  if (phase.value !== 'challenge' || !currentChallenge.value?.choices?.length) return
  const choices = currentChallenge.value.choices
  let idx = -1
  const key = e.key.toLowerCase()
  if (key >= 'a' && key <= 'd') idx = key.charCodeAt(0) - 97
  else if (key >= '1' && key <= '4') idx = parseInt(key) - 1
  if (idx >= 0 && idx < choices.length) {
    e.preventDefault()
    selectChoice(choices[idx])
  }
}

let pollBackoff = 0

function startPolling() {
  pollBackoff = 0
  pollForChallenge()
  pollHandle = setInterval(() => {
    if (pollBackoff > 0) { pollBackoff--; return }
    pollForChallenge()
  }, 800)
}

function stopPolling() {
  if (pollHandle) { clearInterval(pollHandle); pollHandle = null }
}

// BUG-7: Deadline-based timer instead of drift-prone setInterval counter
function startTimer(remainingMs: number) {
  stopTimer()
  timerDeadline = Date.now() + remainingMs
  updateTimerDisplay()
  timerHandle = setInterval(() => {
    updateTimerDisplay()
    if (remainingSeconds.value <= 0) {
      stopTimer()
      if (phase.value === 'challenge') {
        // BUG-2: Submit timeout to server so fight can proceed
        phase.value = 'timeout'
        showFeedback('wrong')
        submitTimeout()
      }
    }
  }, 250) // Check more frequently for precision
}

function updateTimerDisplay() {
  const remaining = Math.max(0, timerDeadline - Date.now())
  remainingSeconds.value = Math.ceil(remaining / 1000)
}

function stopTimer() {
  if (timerHandle) { clearInterval(timerHandle); timerHandle = null }
}

function showFeedback(type: 'correct' | 'wrong') {
  feedback.value = type
  if (feedbackTimer.value) clearTimeout(feedbackTimer.value)
  feedbackTimer.value = setTimeout(() => { feedback.value = null }, 1500)
}

// BUG-4: Track consecutive poll failures, show connection lost
async function pollForChallenge() {
  if (!myBotId.value || phase.value === 'finished' || phase.value === 'replay' || phase.value === 'error') return

  try {
    const res = await fetch(`/api/fights/${fightId.value}/challenge/${myBotId.value}`)
    if (res.status === 429) { pollBackoff = Math.min(pollBackoff + 2, 8); return }
    if (!res.ok) return
    pollBackoff = Math.max(0, pollBackoff - 1)
    const data = await res.json()

    // Reset error tracking on success
    consecutivePollErrors.value = 0
    connectionLost.value = false

    if (data.pending) {
      if (phase.value !== 'challenge' || currentChallenge.value?.roundNumber !== data.roundNumber) {
        currentChallenge.value = data
        currentRound.value = data.roundNumber
        answer.value = ''
        trashTalk.value = ''
        showTrashTalk.value = false
        feedback.value = null
        phase.value = 'challenge'
        // Cap timer for multiple choice — just tapping a button, not typing
        const timerMs = (data.choices?.length > 0) ? Math.min(data.remainingMs, 10000) : data.remainingMs
        startTimer(timerMs)
        await nextTick()
        if (!hasChoices.value) answerInput.value?.focus()
      }
    } else if (data.fightStatus === 'finished') {
      stopPolling()
      stopTimer()
      await loadFight()
      phase.value = 'finished'
    } else if (phase.value === 'submitted' || phase.value === 'timeout') {
      phase.value = 'between'
    }
  } catch {
    consecutivePollErrors.value++
    if (consecutivePollErrors.value >= 5) {
      connectionLost.value = true
    }
  }
}

// BUG-1: Prevent double-tap by checking phase before processing
function selectChoice(choice: string) {
  if (phase.value !== 'challenge') return
  // BUG-8: Validate choice is in current choices
  if (!currentChallenge.value?.choices?.includes(choice)) return
  answer.value = choice
  phase.value = 'submitted' // Immediately lock out further taps
  submitAnswer()
}

async function submitAnswer() {
  if (!currentChallenge.value) return
  if (!answer.value.trim()) return

  stopTimer()
  // Phase already set to 'submitted' in selectChoice for MC,
  // but set it here too for text input path
  if (phase.value === 'challenge') phase.value = 'submitted'

  try {
    const res = await fetch(`/api/fights/${fightId.value}/respond/${myBotId.value}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        answer: answer.value.trim(),
        trashTalk: trashTalk.value.trim() || undefined,
      }),
    })

    if (res.ok) {
      const data = await res.json()
      if (data.correct !== undefined) {
        showFeedback(data.correct ? 'correct' : 'wrong')
      }
    } else {
      const data = await res.json()
      error.value = data.error || 'Failed to submit.'
    }
  } catch {
    error.value = 'Network error submitting answer.'
  }
}

// BUG-2: Submit timeout notification to server
async function submitTimeout() {
  if (!currentChallenge.value || !myBotId.value) return
  try {
    await fetch(`/api/fights/${fightId.value}/respond/${myBotId.value}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ answer: '', timeout: true }),
    })
  } catch {
    // Server will time out on its own if this fails
  }
}

async function loadFight() {
  try {
    const res = await fetch(`/api/fights/${fightId.value}`)
    if (res.ok) {
      const data = await res.json()
      fight.value = data
      if (data.botA && data.botB) {
        const enemy = amSideA.value ? data.botB : data.botA
        opponentName.value = enemy?.name || 'Unknown'
      }
      if (data.rounds) {
        roundResults.value = data.rounds.map((r: { roundNumber: number; winnerId: string | null }) => {
          return { round: r.roundNumber, won: r.winnerId === myBotId.value, hpA: 0, hpB: 0 }
        })
        myHp.value = amSideA.value ? data.botAHp : data.botBHp
        enemyHp.value = amSideA.value ? data.botBHp : data.botAHp
      }
    }
  } catch (err) {
    console.warn('[HumanFight] poll failed:', err)
  }
}

function watchReplay() {
  phase.value = 'replay'
}

function fightAgain() {
  router.push('/join')
}

function goToArena() {
  router.push(`/arena/${fightId.value}`)
}
</script>

<template>
  <div class="h-full flex flex-col items-center px-4 overflow-hidden">
    <div class="max-w-lg w-full flex-1 min-h-0 overflow-y-auto py-4">

      <!-- Feedback flash overlay -->
      <Transition name="fade">
        <div
          v-if="feedback"
          class="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"
          :class="feedback === 'correct' ? 'bg-neon-green/10' : 'bg-ko/10'"
        >
          <span
            class="font-display font-black text-5xl tracking-widest"
            :class="feedback === 'correct' ? 'text-neon-green glow-green' : 'text-ko'"
          >
            {{ feedback === 'correct' ? 'CORRECT' : 'WRONG' }}
          </span>
        </div>
      </Transition>

      <!-- Connection lost banner (BUG-4) -->
      <div v-if="connectionLost" class="mb-3 p-2 border-2 border-neon-yellow/30 bg-neon-yellow/5 text-center rounded">
        <p class="font-mono text-xs text-neon-yellow">Connection lost — reconnecting...</p>
      </div>

      <!-- PHASE: WAITING -->
      <div v-if="phase === 'waiting'" class="flex flex-col items-center justify-center flex-1 gap-4">
        <div class="w-12 h-12 border-4 border-neon-pink/30 border-t-neon-pink rounded-full animate-spin" />
        <p class="font-display text-neon-pink text-lg tracking-widest animate-pulse glow-pink">
          FIGHT STARTING...
        </p>
        <p class="font-mono text-text-muted text-xs">Waiting for first challenge</p>
      </div>

      <!-- PHASE: CHALLENGE (pick your answer) -->
      <div v-else-if="phase === 'challenge' && currentChallenge" class="slide-up">
        <div class="flex items-center justify-between mb-3">
          <span class="font-display font-black text-sm tracking-wider text-neon-cyan">
            ROUND {{ currentChallenge.roundNumber }}
          </span>
          <span
            class="font-display font-black text-xl tracking-wider transition-colors"
            :class="[timerColor, { 'animate-shake': timerShake }]"
          >
            {{ remainingSeconds }}s
          </span>
        </div>

        <!-- Timer bar -->
        <div class="h-1 bg-white/5 rounded-full mb-3 overflow-hidden">
          <div
            class="h-full rounded-full transition-all duration-250 ease-linear"
            :class="{
              'bg-neon-green': remainingSeconds > 10,
              'bg-neon-yellow': remainingSeconds > 3 && remainingSeconds <= 10,
              'bg-ko': remainingSeconds <= 3,
            }"
            :style="{ width: (remainingSeconds / Math.ceil((currentChallenge.timeoutMs || 45000) / 1000)) * 100 + '%' }"
          />
        </div>

        <div class="p-3 border-2 border-neon-purple/30 bg-neon-purple/5 mb-3 rounded">
          <div class="flex items-center gap-2 mb-1.5">
            <span class="font-display font-bold text-[10px] tracking-wider text-neon-purple uppercase">
              {{ currentChallenge.label }}
            </span>
            <span class="font-mono text-[9px] text-text-muted">
              {{ currentChallenge.scoring === 'factual' ? 'FACTUAL' : 'CREATIVE' }}
            </span>
          </div>
          <p class="font-mono text-sm text-text-primary leading-relaxed whitespace-pre-wrap break-words">
            {{ currentChallenge.prompt }}
          </p>
        </div>

        <!-- Multiple choice buttons -->
        <!-- BUG-6: Use choice text as key instead of array index -->
        <!-- BUG-5: Keyboard hints shown via A/B/C/D labels -->
        <div v-if="currentChallenge?.choices?.length" class="space-y-2 mb-3">
          <button
            v-for="(choice, i) in currentChallenge.choices"
            :key="`${currentChallenge.roundNumber}-${choice}`"
            class="w-full min-h-[48px] px-4 py-3 text-left text-sm font-mono
                   border-2 border-border bg-surface/50 rounded
                   hover:border-neon-cyan/50 hover:bg-neon-cyan/5
                   active:scale-[0.97] active:bg-neon-cyan/10 active:border-neon-cyan
                   transition-all break-words"
            @click="selectChoice(choice)"
          >
            <span class="text-neon-cyan/50 font-display font-bold mr-2">{{ String.fromCharCode(65 + i) }}.</span>
            <span class="text-text-primary">{{ choice }}</span>
          </button>
        </div>

        <!-- Keyboard hint -->
        <p v-if="currentChallenge?.choices?.length" class="font-mono text-[9px] text-text-muted text-center">
          Press A-D or 1-4 to select
        </p>
      </div>

      <!-- PHASE: SUBMITTED (BUG-3: distinguish from timeout) -->
      <div v-else-if="phase === 'submitted'" class="flex flex-col items-center justify-center min-h-[60vh] gap-4">
        <div class="w-10 h-10 border-3 border-neon-cyan/30 border-t-neon-cyan rounded-full animate-spin" />
        <p class="font-display text-neon-cyan text-sm tracking-widest">ANSWER SUBMITTED</p>
        <p class="font-mono text-text-muted text-xs">Waiting for round result</p>
      </div>

      <!-- PHASE: TIMEOUT (BUG-3: distinct visual for timer expiry) -->
      <div v-else-if="phase === 'timeout'" class="flex flex-col items-center justify-center min-h-[60vh] gap-4">
        <div class="w-10 h-10 border-3 border-ko/30 border-t-ko rounded-full animate-spin" />
        <p class="font-display text-ko text-lg tracking-widest">TIME'S UP!</p>
        <p class="font-mono text-text-muted text-xs">Waiting for round result</p>
      </div>

      <!-- PHASE: BETWEEN ROUNDS -->
      <div v-else-if="phase === 'between'" class="flex flex-col items-center justify-center min-h-[60vh] gap-4">
        <div class="w-10 h-10 border-3 border-neon-cyan/30 border-t-neon-cyan rounded-full animate-spin" />
        <p class="font-display text-neon-cyan text-sm tracking-widest">NEXT ROUND...</p>
        <p class="font-mono text-text-muted text-xs">Preparing challenge</p>
      </div>

      <!-- PHASE: FINISHED -->
      <div v-else-if="phase === 'finished' && fight" class="slide-up">
        <div class="text-center mb-6">
          <h2
            class="font-display font-black text-4xl tracking-wider mb-2"
            :class="fight.winnerId === myBotId ? 'text-neon-cyan glow-cyan' : 'text-ko'"
          >
            {{ fight.winnerId === myBotId ? 'YOU WIN' : fight.winnerId ? 'YOU LOSE' : 'DRAW' }}
          </h2>
          <p class="font-mono text-text-muted text-xs">
            {{ fight.totalRounds }} rounds vs {{ opponentName || 'opponent' }}
          </p>
          <p class="font-mono text-xs mt-1">
            <span class="text-neon-cyan">{{ myHp }}/200 HP</span>
            <span class="text-text-muted mx-2">vs</span>
            <span class="text-neon-pink">{{ enemyHp }}/200 HP</span>
          </p>
        </div>

        <div class="space-y-2">
          <button
            class="w-full py-4 bg-neon-cyan/10 border-2 border-neon-cyan/50 text-neon-cyan
                   font-display font-black text-sm tracking-widest rounded
                   hover:bg-neon-cyan/20 transition-all neon-border-cyan"
            @click="watchReplay"
          >
            WATCH REPLAY
          </button>
          <button
            class="w-full py-3 bg-neon-pink/10 border-2 border-neon-pink/50 text-neon-pink
                   font-display font-bold text-sm tracking-wider rounded
                   hover:bg-neon-pink/20 transition-all"
            @click="fightAgain"
          >
            FIGHT AGAIN
          </button>
          <button
            class="w-full py-2 border border-border text-text-muted rounded
                   font-display font-bold text-xs tracking-wider
                   hover:border-neon-purple/30 transition-all"
            @click="goToArena"
          >
            VIEW IN ARENA
          </button>
        </div>
      </div>

      <!-- PHASE: REPLAY -->
      <div v-else-if="phase === 'replay' && fight" class="w-full flex-1 min-h-0 flex flex-col">
        <div class="flex-1 min-h-0 relative">
          <FightViewer :fight="fight" :autoplay="true" class="h-full" />
        </div>
        <div class="flex gap-2 mt-2">
          <button
            class="flex-1 py-2 border border-neon-pink/40 text-neon-pink font-display font-bold text-xs tracking-wider rounded
                   hover:bg-neon-pink/10 transition-all"
            @click="fightAgain"
          >
            FIGHT AGAIN
          </button>
          <button
            class="flex-1 py-2 border border-border text-text-muted font-display font-bold text-xs tracking-wider rounded
                   hover:border-neon-purple/30 transition-all"
            @click="phase = 'finished'"
          >
            BACK
          </button>
        </div>
      </div>

      <!-- ERROR -->
      <div v-if="error" class="mt-4 p-3 border-2 border-ko/30 bg-ko/5 text-center rounded">
        <p class="font-mono text-xs text-ko">{{ error }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.fade-enter-active { transition: opacity 0.15s ease; }
.fade-leave-active { transition: opacity 0.8s ease; }
.fade-enter-from, .fade-leave-to { opacity: 0; }

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  20% { transform: translateX(-3px); }
  40% { transform: translateX(3px); }
  60% { transform: translateX(-2px); }
  80% { transform: translateX(2px); }
}

.animate-shake {
  animation: shake 0.4s ease-in-out infinite;
}
</style>
