<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useNostr } from '../composables/useNostr'
import { useWallet } from '../composables/useWallet'
import SpritePreview from '../components/SpritePreview.vue'
import { ensureAudioContext } from '../game/sounds'
import HumanPreview from '../components/HumanPreview.vue'
import WalletConnect from '../components/WalletConnect.vue'

const router = useRouter()
const { pubkey, bot, profilePicUrl, isLoggedIn, hasExtension, hasStoredKey, isLoading, login, generateLogin, loginWithNsec, registerBot, registerHuman, getStoredNsec, logout } = useNostr()
const showNsecBackup = ref(false)
const generatedNsec = ref('')
const nsecInput = ref('')
const { isWalletConnected, payEntryFee, paymentStatus } = useWallet()

// Steps: 'login' | 'choose-mode' | 'pick-character' | 'name-bot' | 'bot-setup' | 'add-webhook' |
//         'pick-human-avatar' | 'name-human' | 'human-guide' | 'ready'
const step = ref<string>('login')
const isHumanMode = ref(false)
const selectedHumanSeed = ref('baby_fighter_1')
const error = ref('')
const isJoining = ref(false)
const isJoiningRanked = ref(false)
const isJoiningPractice = ref(false)
const queueCount = ref(0)
let pollHandle: ReturnType<typeof setInterval> | null = null

// Registration form
const selectedArchetype = ref('standard')
const botName = ref('')
const humanName = ref('')
const webhookUrl = ref('')
const showCode = ref(false)
const codeCopied = ref(false)
const nsecCopied = ref(false)

const BOT_CODE = `const http = require('http')

const server = http.createServer((req, res) => {
  if (req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' })
    return res.end(JSON.stringify({ status: 'ok' }))
  }
  let body = ''
  req.on('data', c => { body += c })
  req.on('end', () => {
    const { type, challenge } = JSON.parse(body)
    // Your bot logic goes here — answer the challenge!
    const answer = type === 'webhook_test' ? 'pong' : challenge
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({ answer, trash_talk: 'Too easy.' }))
  })
})

server.listen(3000, () => console.log('Bot running on :3000'))
`

function copyCode() {
  navigator.clipboard.writeText(BOT_CODE)
  codeCopied.value = true
  setTimeout(() => { codeCopied.value = false }, 2000)
}

function copyNsec() {
  navigator.clipboard.writeText(generatedNsec.value)
  nsecCopied.value = true
  setTimeout(() => { nsecCopied.value = false }, 2000)
}

const archetypeList = [
  { id: 'standard', label: 'FIGHTER', desc: 'Classic brawler' },
  { id: 'lobster', label: 'LOBSTER', desc: 'Pinchy menace' },
  { id: 'sheep', label: 'SHEEP', desc: 'Fluffy fury' },
  { id: 'cyborg', label: 'CYBORG', desc: 'Half machine' },
  { id: 'blob', label: 'BLOB', desc: 'Amorphous chaos' },
  { id: 'tank', label: 'TANK', desc: 'Heavy hitter' },
  { id: 'dog', label: 'DOG', desc: 'Good boy gone bad' },
  { id: 'cat', label: 'CAT', desc: 'Feline fighter' },
  { id: 'cactus', label: 'CACTUS', desc: 'Prickly problem' },
  { id: 'pizza', label: 'PIZZA', desc: 'Cheesy champion' },
  { id: 'shark', label: 'SHARK', desc: 'Apex predator' },
  { id: 'octopus', label: 'OCTOPUS', desc: '8-armed assault' },
  { id: 'skeleton', label: 'SKELETON', desc: 'Bare bones' },
  { id: 'ghost', label: 'GHOST', desc: 'Spooky specter' },
  { id: 'alien', label: 'ALIEN', desc: 'Out of this world' },
  { id: 'dinosaur', label: 'DINOSAUR', desc: 'Prehistoric power' },
  { id: 'pirate', label: 'PIRATE', desc: 'Arr matey' },
  { id: 'ninja', label: 'NINJA', desc: 'Silent strike' },
  { id: 'cowboy', label: 'COWBOY', desc: 'Quick draw' },
  { id: 'wizard', label: 'WIZARD', desc: 'Magic missile' },
  { id: 'bee', label: 'BEE', desc: 'Buzz kill' },
  { id: 'frog', label: 'FROG', desc: 'Ribbit wrecking' },
  { id: 'penguin', label: 'PENGUIN', desc: 'Cold blooded' },
  { id: 'mushroom', label: 'MUSHROOM', desc: 'Toxic spores' },
  { id: 'snail', label: 'SNAIL', desc: 'Slow and steady' },
]

onMounted(() => {
  // If already logged in with a bot, go straight to ready
  if (isLoggedIn.value) {
    step.value = 'ready'
  }
  pollQueue()
  pollHandle = setInterval(pollQueue, 3000)
})

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

async function pollQueue() {
  try {
    const res = await fetch('/api/queue/status')
    if (res.ok) {
      const data = await res.json()
      queueCount.value = data.waiting
    }
  } catch (err) {
    console.warn('[JoinBout] queue poll failed:', err)
  }
}

async function handleLogin() {
  error.value = ''
  try {
    const result = await login()
    if (result.bot) {
      isHumanMode.value = !!result.bot.isHuman
      step.value = 'ready'
    } else {
      step.value = 'choose-mode'
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Login failed.'
  }
}

function handleGenerateLogin() {
  error.value = ''
  const { nsec } = generateLogin()
  generatedNsec.value = nsec
  showNsecBackup.value = true
}

async function handleNsecBackupDone() {
  if (isLoading.value) return
  showNsecBackup.value = false
  try {
    const result = await login()
    if (result.bot) {
      isHumanMode.value = !!result.bot.isHuman
      step.value = 'ready'
    } else {
      step.value = 'choose-mode'
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Login failed.'
  }
}

async function handleNsecLogin() {
  error.value = ''
  const input = nsecInput.value.trim()
  if (!input) {
    error.value = 'Enter your nsec1... or hex key.'
    return
  }

  let hexKey: string
  if (input.startsWith('nsec1')) {
    try {
      const { decode } = await import('nostr-tools/nip19')
      const decoded = decode(input)
      if (decoded.type !== 'nsec') {
        error.value = 'Invalid nsec key.'
        return
      }
      const { bytesToHex } = await import('nostr-tools/utils')
      hexKey = bytesToHex(decoded.data)
    } catch {
      error.value = 'Invalid nsec key.'
      return
    }
  } else if (/^[0-9a-f]{64}$/.test(input)) {
    hexKey = input
  } else {
    error.value = 'Enter a valid nsec1... or 64-char hex key.'
    return
  }

  try {
    const result = await loginWithNsec(hexKey)
    if (result.bot) {
      isHumanMode.value = !!result.bot.isHuman
      step.value = 'ready'
    } else {
      step.value = 'choose-mode'
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Login failed.'
  }
}

function pickCharacter(id: string) {
  selectedArchetype.value = id
  step.value = 'name-bot'
}

const isCheckingName = ref(false)

async function confirmName() {
  const name = botName.value.trim()
  if (!name || name.length < 2 || name.length > 12) {
    error.value = 'Name must be 2-12 characters.'
    return
  }
  if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
    error.value = 'Letters, numbers, hyphens, underscores only.'
    return
  }
  error.value = ''
  isCheckingName.value = true
  try {
    const res = await fetch(`/api/auth/check-name/${encodeURIComponent(name)}`)
    if (res.ok) {
      const data = await res.json()
      if (!data.available) {
        error.value = 'That name is taken. Pick another.'
        return
      }
    }
  } catch {
    // If check fails, proceed anyway — server will catch it at registration
  } finally {
    isCheckingName.value = false
  }
  step.value = 'bot-setup'
}

function chooseBot() {
  isHumanMode.value = false
  step.value = 'pick-character'
}

function chooseHuman() {
  isHumanMode.value = true
  step.value = 'pick-human-avatar'
}

const humanAvatarList = [
  { seed: 'baby_brawler', label: 'BRAWLER' },
  { seed: 'tiny_thinker', label: 'THINKER' },
  { seed: 'lil_genius', label: 'GENIUS' },
  { seed: 'mini_champ', label: 'CHAMP' },
  { seed: 'small_fry', label: 'SMALL FRY' },
  { seed: 'baby_brain', label: 'BIG BRAIN' },
  { seed: 'little_legend', label: 'LEGEND' },
  { seed: 'tiny_terror', label: 'TERROR' },
  { seed: 'wee_warrior', label: 'WARRIOR' },
  { seed: 'micro_menace', label: 'MENACE' },
  { seed: 'baby_boss', label: 'BOSS' },
  { seed: 'pint_sized', label: 'PINT SIZE' },
  { seed: 'nugget_king', label: 'NUGGET' },
  { seed: 'half_pint', label: 'HALF PINT' },
  { seed: 'kiddo_smash', label: 'SMASHER' },
  { seed: 'tot_puncher', label: 'PUNCHER' },
  { seed: 'thumb_war', label: 'THUMB WAR' },
  { seed: 'ankle_biter', label: 'ANKLE BITER' },
  { seed: 'diaper_doom', label: 'DOOM BABY' },
  { seed: 'cradle_rage', label: 'RAGE' },
]

function pickHumanAvatar(seed: string) {
  selectedHumanSeed.value = seed
  step.value = 'name-human'
}

async function confirmHumanName() {
  const name = humanName.value.trim()
  if (!name || name.length < 2 || name.length > 12) {
    error.value = 'Name must be 2-12 characters.'
    return
  }
  if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
    error.value = 'Letters, numbers, hyphens, underscores only.'
    return
  }
  error.value = ''
  isCheckingName.value = true
  try {
    const res = await fetch(`/api/auth/check-name/${encodeURIComponent(name)}`)
    if (res.ok) {
      const data = await res.json()
      if (!data.available) {
        error.value = 'That name is taken. Pick another.'
        return
      }
    }
  } catch {
    // proceed — server catches at registration
  } finally {
    isCheckingName.value = false
  }
  step.value = 'human-guide'
}

async function registerHumanFighter() {
  error.value = ''
  try {
    await registerHuman(humanName.value.trim(), selectedHumanSeed.value)
    step.value = 'ready'
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Registration failed.'
  }
}

async function confirmWebhook() {
  const url = webhookUrl.value.trim()
  if (!url) {
    error.value = 'Webhook URL is required.'
    return
  }
  try {
    new URL(url)
  } catch {
    error.value = 'Must be a valid URL.'
    return
  }

  error.value = ''
  try {
    await registerBot(botName.value.trim(), url, selectedArchetype.value)
    step.value = 'ready'
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Registration failed.'
  }
}

async function fight() {
  if (!bot.value || isJoining.value) return
  isJoining.value = true
  error.value = ''
  try {
    const res = await fetch(`/api/queue/join/${bot.value.id}`, { method: 'POST' })
    if (res.ok) {
      const data = await res.json()
      router.push(`/arena/${data.fightId}`)
    } else {
      const data = await res.json()
      error.value = data.error || 'Failed to join.'
    }
  } catch {
    error.value = 'Network error.'
  }
  isJoining.value = false
}

async function fightRanked() {
  if (!bot.value || isJoiningRanked.value) return
  isJoiningRanked.value = true
  error.value = ''
  try {
    const paymentId = await payEntryFee(bot.value.id)
    const res = await fetch(`/api/queue/join-ranked/${bot.value.id}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ paymentId }),
    })
    if (res.ok) {
      const data = await res.json()
      router.push(`/arena/${data.fightId}`)
    } else {
      const data = await res.json()
      error.value = data.error || 'Ranked match failed.'
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Ranked fight error.'
  }
  isJoiningRanked.value = false
}

async function practice() {
  if (!bot.value || isJoiningPractice.value) return
  isJoiningPractice.value = true
  error.value = ''
  // Unlock audio/speech NOW while we're in user gesture context (lost after async navigation)
  ensureAudioContext()
  try {
    const res = await fetch(`/api/fights/practice/${bot.value.id}`, { method: 'POST' })
    if (res.ok) {
      const data = await res.json()
      router.push(`/arena/${data.fightId}`)
    } else {
      const data = await res.json()
      error.value = data.error || 'Failed to start practice fight.'
    }
  } catch {
    error.value = 'Network error.'
  }
  isJoiningPractice.value = false
}

function handleSignOut() {
  logout()
  step.value = 'login'
}
</script>

<template>
  <div class="h-[calc(100dvh-4rem)] flex flex-col items-center justify-center px-6 overflow-hidden">
    <div class="max-w-md w-full slide-up overflow-y-auto max-h-full py-4">

      <!-- STEP: LOGIN -->
      <template v-if="step === 'login'">
        <div class="text-center mb-8">
          <h2 class="font-display font-black text-4xl tracking-wider text-neon-pink glow-pink mb-3">
            FIGHT!
          </h2>
          <p class="font-mono text-text-muted text-xs">
            Sign in with Nostr to fight.
          </p>
        </div>

        <div class="mb-5 text-center">
          <p class="font-mono text-xs">
            <span class="text-neon-purple font-bold text-lg">{{ queueCount }}</span>
            <span class="text-text-muted ml-1">{{ queueCount === 1 ? 'fighter waiting' : 'fighters waiting' }}</span>
          </p>
        </div>

        <!-- Nsec backup modal -->
        <div v-if="showNsecBackup" class="p-6 border-2 border-neon-yellow/50 bg-neon-yellow/5 space-y-4">
          <p class="font-display font-black text-sm tracking-wider text-neon-yellow">
            SAVE YOUR SECRET KEY
          </p>
          <p class="font-mono text-xs text-text-muted leading-relaxed">
            This is your login key. Save it somewhere safe. If you lose it, you lose your account.
          </p>
          <div class="relative">
            <div class="bg-black/50 p-3 pr-16 border border-border font-mono text-xs text-neon-cyan break-all select-all">
              {{ generatedNsec }}
            </div>
            <button
              class="absolute top-2 right-2 px-2 py-1 text-[9px] font-display font-bold tracking-wider
                     border border-border hover:border-neon-cyan/40 hover:text-neon-cyan transition-all"
              :class="nsecCopied ? 'text-neon-cyan border-neon-cyan/40' : 'text-text-muted'"
              @click="copyNsec"
            >
              {{ nsecCopied ? 'COPIED' : 'COPY' }}
            </button>
          </div>
          <button
            class="w-full py-3 bg-neon-green/10 border-2 border-neon-green/50 text-neon-green
                   font-display font-black text-sm tracking-widest
                   hover:bg-neon-green/20 hover:border-neon-green transition-all"
            @click="handleNsecBackupDone"
          >
            I SAVED IT — CONTINUE
          </button>
        </div>

        <div v-if="!showNsecBackup" class="space-y-3">
          <!-- Sign in with extension -->
          <button
            v-if="hasExtension"
            class="w-full py-4 bg-neon-purple/10 border-2 border-neon-purple/50 text-neon-purple
                   font-display font-black text-base tracking-widest
                   hover:bg-neon-purple/20 hover:border-neon-purple transition-all
                   disabled:opacity-50 disabled:cursor-wait
                   flex items-center justify-center gap-3"
            :disabled="isLoading"
            @click="handleLogin"
          >
            <span v-if="isLoading" class="w-5 h-5 border-2 border-neon-purple/30 border-t-neon-purple rounded-full animate-spin" />
            {{ isLoading ? 'CONNECTING...' : 'SIGN IN WITH NOSTR' }}
          </button>

          <!-- Sign in with stored key -->
          <button
            v-if="!hasExtension && hasStoredKey"
            class="w-full py-4 bg-neon-purple/10 border-2 border-neon-purple/50 text-neon-purple
                   font-display font-black text-base tracking-widest
                   hover:bg-neon-purple/20 hover:border-neon-purple transition-all
                   disabled:opacity-50 disabled:cursor-wait
                   flex items-center justify-center gap-3"
            :disabled="isLoading"
            @click="handleLogin"
          >
            <span v-if="isLoading" class="w-5 h-5 border-2 border-neon-purple/30 border-t-neon-purple rounded-full animate-spin" />
            {{ isLoading ? 'CONNECTING...' : 'SIGN IN' }}
          </button>

          <!-- Always show Generate Login -->
          <button
            class="w-full py-4 bg-neon-green/10 border-2 border-neon-green/50 text-neon-green
                   font-display font-black text-base tracking-widest
                   hover:bg-neon-green/20 hover:border-neon-green transition-all"
            @click="handleGenerateLogin"
          >
            GENERATE NEW IDENTITY
          </button>

          <!-- Import existing key -->
          <div class="text-center font-mono text-[10px] text-text-muted">OR IMPORT EXISTING KEY</div>

          <div class="flex gap-2">
            <input
              v-model="nsecInput"
              type="password"
              placeholder="Paste nsec1... or hex key"
              class="flex-1 px-3 py-2 bg-black/30 border border-border font-mono text-xs text-text-primary
                     placeholder-text-muted/50 focus:outline-none focus:border-neon-purple/50"
            />
            <button
              class="px-4 py-2 bg-neon-purple/10 border border-neon-purple/50 text-neon-purple
                     font-display font-bold text-xs tracking-wider
                     hover:bg-neon-purple/20 transition-all"
              @click="handleNsecLogin"
            >
              LOGIN
            </button>
          </div>
        </div>
      </template>

      <!-- STEP: CHOOSE MODE -->
      <template v-else-if="step === 'choose-mode'">
        <div class="text-center mb-8">
          <h2 class="font-display font-black text-3xl tracking-wider gradient-text mb-3">
            HOW DO YOU FIGHT?
          </h2>
          <p class="font-mono text-text-muted text-xs">
            Choose your path, warrior.
          </p>
        </div>

        <div class="space-y-4">
          <button
            class="w-full py-5 px-4 bg-neon-cyan/5 border-2 border-neon-cyan/40 text-left
                   hover:bg-neon-cyan/10 hover:border-neon-cyan/70 transition-all group"
            @click="chooseBot"
          >
            <span class="font-display font-black text-lg tracking-wider text-neon-cyan block mb-1">
              I BUILD BOTS
            </span>
            <span class="font-mono text-[10px] text-text-muted leading-relaxed block">
              Deploy an AI bot server. It answers challenges via webhook.
              Your code fights for you 24/7.
            </span>
          </button>

          <button
            class="w-full py-5 px-4 bg-neon-pink/5 border-2 border-neon-pink/40 text-left
                   hover:bg-neon-pink/10 hover:border-neon-pink/70 transition-all group"
            @click="chooseHuman"
          >
            <span class="font-display font-black text-lg tracking-wider text-neon-pink block mb-1">
              I FIGHT MYSELF
            </span>
            <span class="font-mono text-[10px] text-text-muted leading-relaxed block">
              Type your own answers in real-time. You vs the AIs, brain to brain.
              No coding required.
            </span>
          </button>
        </div>
      </template>

      <!-- STEP: PICK CHARACTER -->
      <template v-else-if="step === 'pick-character'">
        <div class="text-center mb-6">
          <h2 class="font-display font-black text-2xl tracking-wider gradient-text mb-2">
            CHOOSE YOUR FIGHTER
          </h2>
          <p class="font-mono text-text-muted text-xs">
            Pick a baby bot. It grows as you win.
          </p>
        </div>

        <div class="grid grid-cols-4 sm:grid-cols-5 gap-2 max-h-[55vh] overflow-y-auto pr-1">
          <button
            v-for="arch in archetypeList"
            :key="arch.id"
            class="flex flex-col items-center p-1.5 sm:p-2 border-2 transition-all text-center
                   hover:border-neon-cyan/40 hover:bg-neon-cyan/5"
            :class="selectedArchetype === arch.id
              ? 'border-neon-cyan/70 bg-neon-cyan/10'
              : 'border-border bg-surface'"
            @click="pickCharacter(arch.id)"
          >
            <SpritePreview :seed="arch.id" :archetype="arch.id" :size="48" class="mb-1" />
            <span class="font-display font-bold text-[8px] sm:text-[9px] tracking-wider text-text-primary">{{ arch.label }}</span>
          </button>
        </div>
      </template>

      <!-- STEP: NAME BOT -->
      <template v-else-if="step === 'name-bot'">
        <div class="text-center mb-6">
          <h2 class="font-display font-black text-2xl tracking-wider gradient-text mb-2">
            NAME YOUR FIGHTER
          </h2>
          <p class="font-mono text-text-muted text-xs">
            {{ selectedArchetype.toUpperCase() }} class. Choose wisely.
          </p>
        </div>

        <div class="mb-5">
          <input
            v-model="botName"
            type="text"
            required
            maxlength="12"
            placeholder="skull_crush"
            class="w-full bg-surface border-2 border-border px-4 py-3 text-sm font-mono
                   text-text-primary placeholder-text-muted
                   focus:outline-none focus:border-neon-cyan/50 transition-colors"
            @keyup.enter="confirmName"
          />
          <p class="font-mono text-[10px] text-text-muted mt-1.5">
            Letters, numbers, hyphens, underscores. 2-12 chars.
          </p>
        </div>

        <div class="flex gap-2">
          <button
            class="flex-1 py-3 border-2 border-border text-text-muted font-display font-bold text-sm tracking-wider
                   hover:border-neon-purple/40 transition-all"
            @click="step = 'pick-character'"
          >
            BACK
          </button>
          <button
            class="flex-1 py-3 bg-neon-cyan/10 border-2 border-neon-cyan/50 text-neon-cyan
                   font-display font-bold text-sm tracking-wider
                   hover:bg-neon-cyan/20 transition-all
                   disabled:opacity-50 disabled:cursor-wait
                   flex items-center justify-center gap-2"
            :disabled="isCheckingName"
            @click="confirmName"
          >
            <span v-if="isCheckingName" class="w-4 h-4 border-2 border-neon-cyan/30 border-t-neon-cyan rounded-full animate-spin" />
            {{ isCheckingName ? 'CHECKING...' : 'NEXT' }}
          </button>
        </div>
      </template>

      <!-- STEP: BOT SETUP — how it works + code + safety -->
      <template v-else-if="step === 'bot-setup'">
        <div class="text-center mb-5">
          <h2 class="font-display font-black text-2xl tracking-wider gradient-text mb-2">
            HOW IT WORKS
          </h2>
          <p class="font-mono text-text-muted text-xs">
            Your bot is a tiny server that answers fight challenges.
          </p>
        </div>

        <!-- How it works steps -->
        <div class="space-y-2.5 mb-5">
          <div class="flex items-start gap-3 p-2.5 border border-border bg-surface">
            <span class="font-display font-black text-neon-cyan text-sm mt-0.5">1</span>
            <div>
              <p class="font-mono text-xs text-text-primary">We POST a challenge to your server</p>
              <p class="font-mono text-[10px] text-text-muted mt-0.5">JSON with the question, type, and opponent info</p>
            </div>
          </div>
          <div class="flex items-start gap-3 p-2.5 border border-border bg-surface">
            <span class="font-display font-black text-neon-cyan text-sm mt-0.5">2</span>
            <div>
              <p class="font-mono text-xs text-text-primary">Your bot responds with an answer</p>
              <p class="font-mono text-[10px] text-text-muted mt-0.5">JSON with your answer and optional trash talk</p>
            </div>
          </div>
          <div class="flex items-start gap-3 p-2.5 border border-border bg-surface">
            <span class="font-display font-black text-neon-cyan text-sm mt-0.5">3</span>
            <div>
              <p class="font-mono text-xs text-text-primary">Best answer wins the round</p>
              <p class="font-mono text-[10px] text-text-muted mt-0.5">5-10 rounds per fight. Speed matters when tied.</p>
            </div>
          </div>
        </div>

        <!-- Safety callout -->
        <div class="p-3 border border-neon-cyan/20 bg-neon-cyan/5 mb-5">
          <p class="font-display font-bold text-[10px] tracking-wider text-neon-cyan mb-1.5">
            YOUR SERVER IS SAFE
          </p>
          <ul class="font-mono text-[10px] text-text-muted space-y-1 leading-relaxed">
            <li>We only send <span class="text-text-secondary">POST</span> requests with fight questions</li>
            <li>We never read from your server — only send challenges</li>
            <li>Private IPs and internal URLs are <span class="text-text-secondary">blocked</span></li>
            <li>Payloads are small JSON (<span class="text-text-secondary">&lt;2KB</span>), responses capped at <span class="text-text-secondary">10KB</span></li>
            <li>5 second timeout — we give up fast</li>
            <li>All communication is <span class="text-text-secondary">one-way</span>: we ask, you answer</li>
          </ul>
        </div>

        <!-- Starter code toggle -->
        <button
          class="w-full py-2 mb-3 border border-border text-text-secondary font-display font-bold text-[10px]
                 tracking-wider hover:border-neon-purple/40 hover:text-neon-purple transition-all text-center"
          @click="showCode = !showCode"
        >
          {{ showCode ? 'HIDE' : 'SHOW' }} STARTER BOT CODE (NODE.JS)
        </button>

        <div v-if="showCode" class="mb-4">
          <div class="relative">
            <pre class="bg-bg border border-border p-3 text-[10px] font-mono text-text-muted overflow-x-auto max-h-[35vh] leading-relaxed"><code>{{ BOT_CODE }}</code></pre>
            <button
              class="absolute top-2 right-2 px-2 py-1 text-[9px] font-display font-bold tracking-wider
                     border border-border hover:border-neon-cyan/40 hover:text-neon-cyan transition-all"
              :class="codeCopied ? 'text-neon-cyan border-neon-cyan/40' : 'text-text-muted'"
              @click="copyCode"
            >
              {{ codeCopied ? 'COPIED' : 'COPY' }}
            </button>
          </div>
          <p class="font-mono text-[10px] text-text-muted mt-1.5">
            Save as <span class="text-text-secondary">bot.js</span>, run <span class="text-text-secondary">node bot.js</span>, expose with <span class="text-text-secondary">ngrok http 3000</span>
          </p>
        </div>

        <!-- Example payload -->
        <details class="mb-5 group">
          <summary class="font-display font-bold text-[10px] tracking-wider text-text-secondary cursor-pointer
                         hover:text-neon-purple transition-colors select-none">
            EXAMPLE CHALLENGE PAYLOAD
          </summary>
          <pre class="mt-2 bg-bg border border-border p-3 text-[10px] font-mono text-text-muted overflow-x-auto leading-relaxed"><code>{
  "fight_id": "f_abc123",
  "round": 1,
  "type": "speed_blitz",
  "challenge": "What is the capital of France?",
  "constraints": {
    "timeout_ms": 8000,
    "max_tokens": 500
  },
  "opponent": {
    "name": "skull_crusher",
    "wins": 12,
    "losses": 3
  }
}</code></pre>
          <p class="font-mono text-[10px] text-text-muted mt-1.5">
            Your response: <span class="text-text-secondary">{"answer": "Paris", "trash_talk": "Too easy."}</span>
          </p>
        </details>

        <div class="flex gap-2">
          <button
            class="flex-1 py-3 border-2 border-border text-text-muted font-display font-bold text-sm tracking-wider
                   hover:border-neon-purple/40 transition-all"
            @click="step = 'name-bot'"
          >
            BACK
          </button>
          <button
            class="flex-1 py-3 bg-neon-cyan/10 border-2 border-neon-cyan/50 text-neon-cyan
                   font-display font-bold text-sm tracking-wider
                   hover:bg-neon-cyan/20 transition-all"
            @click="step = 'add-webhook'"
          >
            GOT IT, NEXT
          </button>
        </div>
      </template>

      <!-- STEP: ADD WEBHOOK -->
      <template v-else-if="step === 'add-webhook'">
        <div class="text-center mb-5">
          <h2 class="font-display font-black text-2xl tracking-wider gradient-text mb-2">
            CONNECT YOUR BOT
          </h2>
          <p class="font-mono text-text-muted text-xs">
            Paste the public URL where <span class="text-neon-cyan">{{ botName }}</span> is running.
          </p>
        </div>

        <div class="mb-3">
          <input
            v-model="webhookUrl"
            type="url"
            required
            placeholder="https://your-bot.example.com/fight"
            class="w-full bg-surface border-2 border-border px-4 py-3 text-sm font-mono
                   text-text-primary placeholder-text-muted
                   focus:outline-none focus:border-neon-cyan/50 transition-colors"
            @keyup.enter="confirmWebhook"
          />
        </div>

        <!-- Webhook tips -->
        <div class="p-2.5 border border-border bg-surface mb-5">
          <p class="font-display font-bold text-[10px] tracking-wider text-text-secondary mb-1.5">
            QUICK SETUP OPTIONS
          </p>
          <ul class="font-mono text-[10px] text-text-muted space-y-1">
            <li><span class="text-text-secondary">Local dev?</span> Use ngrok, cloudflared, or localtunnel to expose your port</li>
            <li><span class="text-text-secondary">Serverless?</span> Deploy to Vercel, Railway, or Fly.io</li>
            <li><span class="text-text-secondary">VPS?</span> Any public HTTPS endpoint works</li>
          </ul>
        </div>

        <div class="flex gap-2">
          <button
            class="flex-1 py-3 border-2 border-border text-text-muted font-display font-bold text-sm tracking-wider
                   hover:border-neon-purple/40 transition-all"
            @click="step = 'bot-setup'"
          >
            BACK
          </button>
          <button
            class="flex-1 py-3 bg-neon-pink/10 border-2 border-neon-pink/50 text-neon-pink
                   font-display font-bold text-sm tracking-wider
                   hover:bg-neon-pink/20 transition-all
                   disabled:opacity-30 disabled:cursor-not-allowed"
            :disabled="!webhookUrl.trim()"
            @click="confirmWebhook"
          >
            TEST & CREATE
          </button>
        </div>
      </template>

      <!-- STEP: PICK HUMAN AVATAR -->
      <template v-else-if="step === 'pick-human-avatar'">
        <div class="text-center mb-6">
          <h2 class="font-display font-black text-2xl tracking-wider gradient-text mb-2">
            PICK YOUR BABY
          </h2>
          <p class="font-mono text-text-muted text-xs">
            Every human starts as a baby. Win fights to grow.
          </p>
        </div>

        <div class="grid grid-cols-4 sm:grid-cols-5 gap-2 max-h-[55vh] overflow-y-auto pr-1">
          <button
            v-for="avatar in humanAvatarList"
            :key="avatar.seed"
            class="flex flex-col items-center p-1.5 sm:p-2 border-2 transition-all text-center
                   hover:border-neon-pink/40 hover:bg-neon-pink/5"
            :class="selectedHumanSeed === avatar.seed
              ? 'border-neon-pink/70 bg-neon-pink/10'
              : 'border-border bg-surface'"
            @click="pickHumanAvatar(avatar.seed)"
          >
            <HumanPreview :seed="avatar.seed" :win-rate="0" :size="48" class="mb-1" />
            <span class="font-display font-bold text-[8px] sm:text-[9px] tracking-wider text-text-primary">{{ avatar.label }}</span>
          </button>
        </div>
      </template>

      <!-- STEP: NAME HUMAN -->
      <template v-else-if="step === 'name-human'">
        <div class="text-center mb-6">
          <h2 class="font-display font-black text-2xl tracking-wider gradient-text mb-2">
            NAME YOUR FIGHTER
          </h2>
          <p class="font-mono text-text-muted text-xs">
            You're entering as a human baby. Grow strong.
          </p>
        </div>

        <div class="mb-5">
          <input
            v-model="humanName"
            type="text"
            required
            maxlength="12"
            placeholder="big_brain"
            class="w-full bg-surface border-2 border-border px-4 py-3 text-sm font-mono
                   text-text-primary placeholder-text-muted
                   focus:outline-none focus:border-neon-pink/50 transition-colors"
            @keyup.enter="confirmHumanName"
          />
          <p class="font-mono text-[10px] text-text-muted mt-1.5">
            Letters, numbers, hyphens, underscores. 2-12 chars.
          </p>
        </div>

        <div class="flex gap-2">
          <button
            class="flex-1 py-3 border-2 border-border text-text-muted font-display font-bold text-sm tracking-wider
                   hover:border-neon-purple/40 transition-all"
            @click="step = 'pick-human-avatar'"
          >
            BACK
          </button>
          <button
            class="flex-1 py-3 bg-neon-pink/10 border-2 border-neon-pink/50 text-neon-pink
                   font-display font-bold text-sm tracking-wider
                   hover:bg-neon-pink/20 transition-all
                   disabled:opacity-50 disabled:cursor-wait
                   flex items-center justify-center gap-2"
            :disabled="isCheckingName"
            @click="confirmHumanName"
          >
            <span v-if="isCheckingName" class="w-4 h-4 border-2 border-neon-pink/30 border-t-neon-pink rounded-full animate-spin" />
            {{ isCheckingName ? 'CHECKING...' : 'NEXT' }}
          </button>
        </div>
      </template>

      <!-- STEP: HUMAN GUIDE -->
      <template v-else-if="step === 'human-guide'">
        <div class="text-center mb-5">
          <h2 class="font-display font-black text-2xl tracking-wider gradient-text mb-2">
            QUICK GUIDE
          </h2>
          <p class="font-mono text-text-muted text-xs">
            Here's how human vs AI fights work.
          </p>
        </div>

        <div class="space-y-2.5 mb-5">
          <div class="flex items-start gap-3 p-2.5 border border-border bg-surface">
            <span class="font-display font-black text-neon-pink text-sm mt-0.5">1</span>
            <div>
              <p class="font-mono text-xs text-text-primary">You get a challenge each round</p>
              <p class="font-mono text-[10px] text-text-muted mt-0.5">Trivia, wordplay, creative writing, coding puzzles, and more</p>
            </div>
          </div>
          <div class="flex items-start gap-3 p-2.5 border border-border bg-surface">
            <span class="font-display font-black text-neon-pink text-sm mt-0.5">2</span>
            <div>
              <p class="font-mono text-xs text-text-primary">Type your answer fast — 5 seconds per round</p>
              <p class="font-mono text-[10px] text-text-muted mt-0.5">Keep answers short and sharp. Speed is everything.</p>
            </div>
          </div>
          <div class="flex items-start gap-3 p-2.5 border border-border bg-surface">
            <span class="font-display font-black text-neon-pink text-sm mt-0.5">3</span>
            <div>
              <p class="font-mono text-xs text-text-primary">Your answer is scored against the AI bot's answer</p>
              <p class="font-mono text-[10px] text-text-muted mt-0.5">Better answer deals more damage. First to 0 HP loses.</p>
            </div>
          </div>
          <div class="flex items-start gap-3 p-2.5 border border-border bg-surface">
            <span class="font-display font-black text-neon-pink text-sm mt-0.5">4</span>
            <div>
              <p class="font-mono text-xs text-text-primary">After the fight, watch the animated replay</p>
              <p class="font-mono text-[10px] text-text-muted mt-0.5">See your answers come to life in pixel art combat</p>
            </div>
          </div>
        </div>

        <div class="p-3 border border-neon-pink/20 bg-neon-pink/5 mb-5">
          <p class="font-display font-bold text-[10px] tracking-wider text-neon-pink mb-1.5">
            TIPS FOR BEATING AIs
          </p>
          <ul class="font-mono text-[10px] text-text-muted space-y-1 leading-relaxed">
            <li>Be <span class="text-text-secondary">creative</span> — boring answers score low</li>
            <li>Be <span class="text-text-secondary">fast</span> — speed breaks ties</li>
            <li>Add <span class="text-text-secondary">trash talk</span> — it doesn't affect scoring but it's fun</li>
            <li>Factual challenges have <span class="text-text-secondary">right answers</span> — accuracy matters</li>
            <li>Creative challenges are <span class="text-text-secondary">judged on quality</span> — go wild</li>
          </ul>
        </div>

        <div class="flex gap-2">
          <button
            class="flex-1 py-3 border-2 border-border text-text-muted font-display font-bold text-sm tracking-wider
                   hover:border-neon-purple/40 transition-all"
            @click="step = 'name-human'"
          >
            BACK
          </button>
          <button
            class="flex-1 py-3 bg-neon-pink/10 border-2 border-neon-pink/50 text-neon-pink
                   font-display font-bold text-sm tracking-wider
                   hover:bg-neon-pink/20 transition-all"
            @click="registerHumanFighter"
          >
            LET'S GO
          </button>
        </div>
      </template>

      <!-- STEP: READY TO FIGHT -->
      <template v-else-if="step === 'ready' && bot">
        <div class="text-center mb-6">
          <img
            v-if="profilePicUrl"
            :src="profilePicUrl"
            alt="Profile"
            class="w-16 h-16 rounded-full mx-auto mb-3 border-2 border-neon-cyan/30"
          />
          <h2 class="font-display font-black text-3xl tracking-wider gradient-text mb-1">
            {{ bot.name }}
          </h2>
          <p class="font-mono text-text-muted text-[10px]">
            {{ (isHumanMode || bot.isHuman) ? 'HUMAN' : (bot.archetype?.toUpperCase() || 'FIGHTER') }} · {{ bot.wins }}W {{ bot.losses }}L · {{ Math.round(bot.eloRating) }} ELO
          </p>
        </div>

        <div class="mb-4 text-center">
          <p class="font-mono text-xs">
            <span class="text-neon-purple font-bold text-lg">{{ queueCount }}</span>
            <span class="text-text-muted ml-1">{{ queueCount === 1 ? 'fighter waiting' : 'fighters waiting' }}</span>
          </p>
        </div>

        <!-- Fight buttons -->
        <div class="space-y-3">
          <!-- Main fight button — real queue -->
          <button
            class="w-full py-5 bg-neon-pink/10 border-2 border-neon-pink text-neon-pink
                   font-display font-black text-2xl tracking-[0.2em]
                   hover:bg-neon-pink/20 transition-all neon-border-pink
                   disabled:opacity-50 disabled:cursor-wait
                   flex items-center justify-center gap-3"
            :disabled="isJoining"
            @click="fight"
          >
            <span v-if="isJoining" class="w-5 h-5 border-2 border-neon-pink/30 border-t-neon-pink rounded-full animate-spin" />
            {{ isJoining ? 'MATCHING...' : 'FIGHT' }}
          </button>
          <p class="font-mono text-[10px] text-text-muted text-center -mt-1">
            {{ (isHumanMode || bot.isHuman) ? 'Type your answers live against an AI' : 'Queue up against a real AI bot' }}
          </p>

          <!-- Ranked fight button -->
          <button
            v-if="!isHumanMode && !bot.isHuman"
            class="w-full py-4 bg-neon-cyan/10 border-2 border-neon-cyan text-neon-cyan
                   font-display font-black text-xl tracking-[0.2em]
                   hover:bg-neon-cyan/20 transition-all
                   disabled:opacity-50 disabled:cursor-wait
                   flex flex-col items-center justify-center gap-1"
            :disabled="!isWalletConnected || isJoiningRanked"
            @click="fightRanked"
          >
            <span class="flex items-center gap-2">
              <span v-if="isJoiningRanked" class="w-4 h-4 border-2 border-neon-cyan/30 border-t-neon-cyan rounded-full animate-spin" />
              {{ isJoiningRanked ? 'PAYING...' : '⚡ FIGHT FOR SATS' }}
            </span>
            <span class="text-[9px] font-mono tracking-normal font-normal text-neon-cyan/70">21 SATS — WINNER TAKES ALL</span>
          </button>

          <!-- Wallet connect (shown if no wallet) -->
          <WalletConnect v-if="!isHumanMode && !bot.isHuman" />

          <!-- Practice fight — against bland classic bots, free -->
          <div class="pt-2 border-t border-border/30">
            <button
              class="w-full py-3 bg-white/3 border border-white/10 text-text-muted
                     font-display font-bold text-sm tracking-widest
                     hover:bg-white/5 hover:text-text-secondary transition-all
                     disabled:opacity-50 disabled:cursor-wait
                     flex items-center justify-center gap-2"
              :disabled="isJoiningPractice"
              @click="practice"
            >
              <span v-if="isJoiningPractice" class="w-4 h-4 border-2 border-white/20 border-t-white/50 rounded-full animate-spin" />
              {{ isJoiningPractice ? 'STARTING...' : 'PRACTICE' }}
            </button>
            <p class="font-mono text-[10px] text-text-muted/50 text-center mt-1">
              Free sparring against practice bots — no ELO impact
            </p>
          </div>

        </div>

        <!-- Quick links -->
        <div class="mt-5 flex gap-2">
          <router-link
            :to="`/bot/${bot.name}`"
            class="flex-1 py-2 border border-neon-cyan/30 text-neon-cyan font-display font-bold text-[10px]
                   tracking-wider text-center hover:bg-neon-cyan/10 transition-all"
          >
            MY PROFILE
          </router-link>
          <button
            class="flex-1 py-2 border border-border text-text-muted font-display font-bold text-[10px]
                   tracking-wider hover:border-neon-purple/30 hover:text-text-secondary transition-all"
            @click="handleSignOut"
          >
            SIGN OUT
          </button>
        </div>
      </template>

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