<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } 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' | '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)

// 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
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
)

onMounted(() => {
  if (!myBot.value) {
    router.push('/join')
    return
  }
  startPolling()
})

onUnmounted(() => {
  stopPolling()
  stopTimer()
  if (feedbackTimer.value) clearTimeout(feedbackTimer.value)
})

function startPolling() {
  pollForChallenge()
  pollHandle = setInterval(pollForChallenge, 600)
}

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

function startTimer(remainingMs: number) {
  stopTimer()
  remainingSeconds.value = Math.ceil(remainingMs / 1000)
  timerHandle = setInterval(() => {
    remainingSeconds.value--
    if (remainingSeconds.value <= 0) {
      stopTimer()
      if (phase.value === 'challenge') {
        phase.value = 'submitted'
        showFeedback('wrong')
      }
    }
  }, 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)
}

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.ok) return
    const data = await res.json()

    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'
        startTimer(data.remainingMs)
        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 = 'between'
    }
  } catch {
    // Network hiccup, keep polling
  }
}

function selectChoice(choice: string) {
  answer.value = choice
  submitAnswer()
}

async function submitAnswer() {
  if (!currentChallenge.value || phase.value !== 'challenge') return
  if (!answer.value.trim()) return

  stopTimer()
  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()
      // Show feedback if server tells us if answer was right
      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.'
  }
}

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-[calc(100dvh-4rem)] 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>

      <!-- 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 (type 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-1000 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">
            {{ currentChallenge.prompt }}
          </p>
        </div>

        <!-- Multiple choice buttons -->
        <div v-if="hasChoices" class="space-y-2 mb-3">
          <button
            v-for="(choice, i) in currentChallenge.choices"
            :key="i"
            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:bg-neon-cyan/10 active:border-neon-cyan
                   transition-all"
            @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>

        <!-- Free text input (for creative or when no choices) -->
        <template v-if="!hasChoices">
          <textarea
            ref="answerInput"
            v-model="answer"
            rows="4"
            placeholder="Type your answer..."
            class="w-full bg-surface border-2 border-border px-4 py-3 text-sm font-mono
                   text-text-primary placeholder-text-muted resize-none rounded
                   focus:outline-none focus:border-neon-pink/50 transition-colors mb-2"
            @keydown.ctrl.enter="submitAnswer"
            @keydown.meta.enter="submitAnswer"
          />

          <button
            v-if="!showTrashTalk"
            class="font-mono text-[10px] text-text-muted hover:text-neon-yellow transition-colors mb-2"
            @click="showTrashTalk = true"
          >
            + add trash talk
          </button>
          <input
            v-if="showTrashTalk"
            v-model="trashTalk"
            type="text"
            maxlength="200"
            placeholder="Talk smack to your opponent..."
            class="w-full bg-surface border border-border px-3 py-2 text-xs font-mono
                   text-neon-yellow placeholder-text-muted rounded
                   focus:outline-none focus:border-neon-yellow/50 transition-colors mb-2"
          />

          <button
            class="w-full min-h-[48px] py-4 bg-neon-pink/10 border-2 border-neon-pink text-neon-pink
                   font-display font-black text-lg tracking-[0.15em] rounded
                   hover:bg-neon-pink/20 transition-all neon-border-pink
                   disabled:opacity-30 disabled:cursor-not-allowed"
            :disabled="!answer.trim()"
            @click="submitAnswer"
          >
            SUBMIT ANSWER
          </button>
          <p class="font-mono text-[10px] text-text-muted text-center mt-1">
            Ctrl+Enter to submit
          </p>
        </template>
      </div>

      <!-- PHASE: SUBMITTED / BETWEEN ROUNDS -->
      <div v-else-if="phase === 'submitted' || 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">
          {{ phase === 'submitted' ? 'ANSWER SUBMITTED' : 'NEXT ROUND...' }}
        </p>
        <p class="font-mono text-text-muted text-xs">Waiting for round result</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">
        <div class="h-[calc(100dvh-8rem)] 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>
