<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter, RouterLink } from 'vue-router'
import { useNostr, type NostrProfile } from '../composables/useNostr'
import SpritePreview from '../components/SpritePreview.vue'
import HumanPreview from '../components/HumanPreview.vue'
import WalletConnect from '../components/WalletConnect.vue'
import BetHistory from '../components/BetHistory.vue'
import type { SpriteCustomization } from '../game/sprites'

const route = useRoute()
const router = useRouter()
const { bot: nostrBot, pubkey, isLoggedIn, logout, updateCustomization, updateWebhook, fetchNostrProfile } = useNostr()
const botName = route.params.name as string

interface BotCustomization {
  archetype?: string
  primaryColor?: string
  secondaryColor?: string
  forceVisor?: boolean
  forceMohawk?: boolean
  forceHorns?: boolean
}

interface BotStats {
  id: string
  name: string
  avatarSeed: string
  archetype: string
  customization: BotCustomization | null
  profilePicUrl: string | null
  ownerPubkey: string | null
  eloRating: number
  wins: number
  losses: number
  winStreak: number
  bestStreak: number
  tier: number
  isActive: boolean
  tierName: string
  tierColor: string
  winRate: number
  totalFights: number
  rank: number
  totalBots: number
  satsWon: number
  satsWagered: number
  hasWallet: boolean
  zapsReceived: number
  createdAt: string
  // Owner-only webhook fields
  webhookUrl?: string
  consecutiveErrors?: number
  isHuman?: boolean
  recentFights: {
    id: string
    opponent: string
    result: string
    rounds: number
    arena: string
    date: string
  }[]
}

function getStatusTitle(s: BotStats): string {
  if (s.totalFights === 0) return 'FRESH MEAT'
  if (s.winStreak >= 10) return 'UNSTOPPABLE'
  if (s.winStreak >= 5) return 'ON FIRE'
  if (s.winStreak >= 3) return 'HOT STREAK'
  if (s.winRate >= 80 && s.totalFights >= 10) return 'DOMINANT'
  if (s.winRate >= 60) return 'RISING'
  if (s.winRate >= 40) return 'SCRAPPY'
  if (s.winRate < 20 && s.totalFights >= 5) return 'PUNCHING BAG'
  if (s.losses > s.wins && s.totalFights >= 5) return 'UNDERDOG'
  return 'CONTENDER'
}

interface QueueEntry {
  botId: string
  botName: string
  eloRating: number
}

const stats = ref<BotStats | null>(null)
const isLoading = ref(true)
const isJoining = ref(false)
const showChoose = ref(false)
const waitingFighters = ref<QueueEntry[]>([])
let pollHandle: ReturnType<typeof setInterval> | null = null

const nostrProfile = ref<NostrProfile | null>(null)
const loadError = ref('')
const fightError = ref('')
const showCustomize = ref(false)
const isSaving = ref(false)
const custError = ref('')

// Webhook management
const showWebhook = ref(false)
const webhookInput = ref('')
const isTestingWebhook = ref(false)
const isUpdatingWebhook = ref(false)
const webhookTestResult = ref<{ reachable: boolean; validResponse: boolean; latencyMs: number; error?: string; message?: string } | null>(null)
const webhookError = ref('')
const webhookSuccess = ref('')

const ARCHETYPES = [
  'standard', 'lobster', 'sheep', 'cyborg', 'blob', 'tank', 'dog', 'cat',
  'cactus', 'pizza', 'mushroom', 'shark', 'penguin', 'octopus', 'skeleton',
  'ghost', 'alien', 'dinosaur', 'pirate', 'ninja', 'cowboy', 'wizard',
  'bee', 'frog', 'snail', 'robot', 'android', 'drone', 'toaster', 'tv_head',
  'calculator', 'satellite', 'mech', 'led_cube', 'circuit', 'antenna_bot',
  'microwave', 'cyberdog', 'robocat', 'ufo_bot', 'minotaur', 'unicorn',
  'phoenix', 'dragon', 'mermaid', 'griffin', 'cyclops', 'gargoyle', 'golem',
  'vampire', 'werewolf', 'zombie', 'witch', 'demon', 'chef', 'firefighter',
  'astronaut', 'clown', 'detective', 'nurse', 'lumberjack', 'scientist',
  'wrestler', 'boxer', 'gladiator', 'samurai', 'viking', 'knight',
  'elephant', 'giraffe', 'hippo', 'lion', 'monkey', 'parrot', 'raccoon',
  'snake', 'turtle', 'whale', 'crocodile', 'flamingo', 'hedgehog', 'panda',
  'hamster', 'sock_puppet', 'traffic_cone', 'toilet_man', 'potato',
  'cloud_man', 'rock_man', 'balloon_man', 'trash_can', 'rubber_duck',
  'snowman', 'scarecrow', 'jack_o_lantern', 'garden_gnome', 'lamp_post',
  'broom_man',
]

const isOwner = computed(() => isLoggedIn.value && nostrBot.value?.name === botName)

const custForm = reactive({
  archetype: '',
  primaryColor: '#3388cc',
  secondaryColor: '#cc8833',
  forceVisor: false,
  forceMohawk: false,
  forceHorns: false,
})

function hslToHex(hsl: string): string {
  const m = hsl.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/)
  if (!m) return '#888888'
  const h = +m[1] / 360, s = +m[2] / 100, l = +m[3] / 100
  const hue2rgb = (p: number, q: number, t: number) => {
    if (t < 0) t += 1; if (t > 1) t -= 1
    if (t < 1/6) return p + (q - p) * 6 * t
    if (t < 1/2) return q
    if (t < 2/3) return p + (q - p) * (2/3 - t) * 6
    return p
  }
  let r: number, g: number, b: number
  if (s === 0) { r = g = b = l }
  else {
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s
    const p = 2 * l - q
    r = hue2rgb(p, q, h + 1/3)
    g = hue2rgb(p, q, h)
    b = hue2rgb(p, q, h - 1/3)
  }
  const hex = (v: number) => Math.round(v * 255).toString(16).padStart(2, '0')
  return `#${hex(r)}${hex(g)}${hex(b)}`
}

function hexToHsl(hex: string): string {
  const r = parseInt(hex.slice(1, 3), 16) / 255
  const g = parseInt(hex.slice(3, 5), 16) / 255
  const b = parseInt(hex.slice(5, 7), 16) / 255
  const max = Math.max(r, g, b), min = Math.min(r, g, b)
  const l = (max + min) / 2
  if (max === min) return `hsl(0, 0%, ${Math.round(l * 100)}%)`
  const d = max - min
  const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
  let h = 0
  if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6
  else if (max === g) h = ((b - r) / d + 2) / 6
  else h = ((r - g) / d + 4) / 6
  return `hsl(${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%)`
}

const previewCustomization = computed<SpriteCustomization>(() => ({
  archetype: custForm.archetype || undefined,
  primaryColor: hexToHsl(custForm.primaryColor),
  secondaryColor: hexToHsl(custForm.secondaryColor),
  forceVisor: custForm.forceVisor,
  forceMohawk: custForm.forceMohawk,
  forceHorns: custForm.forceHorns,
}))

function initCustForm() {
  if (!stats.value) return
  const c = stats.value.customization
  custForm.archetype = c?.archetype || stats.value.archetype || ''
  custForm.primaryColor = c?.primaryColor ? hslToHex(c.primaryColor) : '#3388cc'
  custForm.secondaryColor = c?.secondaryColor ? hslToHex(c.secondaryColor) : '#cc8833'
  custForm.forceVisor = c?.forceVisor ?? false
  custForm.forceMohawk = c?.forceMohawk ?? false
  custForm.forceHorns = c?.forceHorns ?? false
}

async function saveCustomization() {
  if (isSaving.value) return
  isSaving.value = true
  custError.value = ''
  try {
    await updateCustomization({
      archetype: custForm.archetype || undefined,
      primaryColor: hexToHsl(custForm.primaryColor),
      secondaryColor: hexToHsl(custForm.secondaryColor),
      forceVisor: custForm.forceVisor,
      forceMohawk: custForm.forceMohawk,
      forceHorns: custForm.forceHorns,
    })
    if (stats.value) {
      stats.value = {
        ...stats.value,
        archetype: custForm.archetype || stats.value.archetype,
        customization: {
          archetype: custForm.archetype || undefined,
          primaryColor: hexToHsl(custForm.primaryColor),
          secondaryColor: hexToHsl(custForm.secondaryColor),
          forceVisor: custForm.forceVisor,
          forceMohawk: custForm.forceMohawk,
          forceHorns: custForm.forceHorns,
        },
      }
    }
    showCustomize.value = false
  } catch (err) {
    custError.value = err instanceof Error ? err.message : 'Save failed'
  }
  isSaving.value = false
}

async function testWebhook() {
  if (!stats.value || isTestingWebhook.value) return
  isTestingWebhook.value = true
  webhookTestResult.value = null
  webhookError.value = ''
  try {
    const res = await fetch(`/api/bots/${encodeURIComponent(botName)}/test`, { method: 'POST' })
    webhookTestResult.value = await res.json()
    if (webhookTestResult.value?.validResponse && stats.value) {
      stats.value = { ...stats.value, consecutiveErrors: 0, isActive: true }
    }
  } catch {
    webhookError.value = 'Network error testing webhook.'
  }
  isTestingWebhook.value = false
}

async function saveWebhook() {
  const url = webhookInput.value.trim()
  if (!url || isUpdatingWebhook.value) return
  try { new URL(url) } catch { webhookError.value = 'Invalid URL.'; return }

  isUpdatingWebhook.value = true
  webhookError.value = ''
  webhookSuccess.value = ''
  try {
    await updateWebhook(url)
    webhookSuccess.value = 'Webhook updated and verified.'
    if (stats.value) {
      stats.value = { ...stats.value, webhookUrl: url, consecutiveErrors: 0 }
    }
    webhookInput.value = ''
  } catch (err) {
    webhookError.value = err instanceof Error ? err.message : 'Update failed.'
  }
  isUpdatingWebhook.value = false
}

onMounted(async () => {
  try {
    const pk = pubkey.value || ''
    const qs = pk ? `?pubkey=${encodeURIComponent(pk)}` : ''
    const res = await fetch(`/api/bots/${encodeURIComponent(botName)}/stats${qs}`)
    if (res.ok) stats.value = await res.json()
    else loadError.value = `Failed to load bot (${res.status})`
  } catch (err) {
    loadError.value = 'Network error loading bot profile'
    console.warn('[BotProfile] load failed:', err)
  }
  isLoading.value = false

  // Fetch Nostr profile for the bot owner (non-blocking)
  if (stats.value?.ownerPubkey) {
    fetchNostrProfile(stats.value.ownerPubkey).then(p => {
      nostrProfile.value = p
    }).catch(() => {})
  }

  // Poll queue for "choose your fight"
  pollQueue()
  pollHandle = setInterval(pollQueue, 4000)
})

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

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

async function instantFight() {
  if (!stats.value || isJoining.value) return
  isJoining.value = true
  fightError.value = ''
  try {
    const res = await fetch(`/api/queue/join/${stats.value.id}`, { method: 'POST' })
    if (res.ok) {
      const data = await res.json()
      router.push(`/arena/${data.fightId}`)
    } else {
      fightError.value = `Matchmaking failed (${res.status})`
    }
  } catch (err) {
    fightError.value = 'Network error starting fight'
    console.warn('[BotProfile] instant fight failed:', err)
  }
  isJoining.value = false
}

async function fightSpecific(opponentBotId: string) {
  if (!stats.value || isJoining.value) return
  isJoining.value = true
  fightError.value = ''
  try {
    const res = await fetch(`/api/fights/matchmake/${stats.value.id}`, { method: 'POST' })
    if (res.ok) {
      const data = await res.json()
      router.push(`/arena/${data.fightId}`)
    } else {
      fightError.value = `Matchmaking failed (${res.status})`
    }
  } catch (err) {
    fightError.value = 'Network error starting fight'
    console.warn('[BotProfile] fight specific failed:', err)
  }
  isJoining.value = false
}

function handleSignOut() {
  logout()
  router.push('/')
}

const tierClass = (t: number) => `tier-${t}`
</script>

<template>
  <div class="h-[calc(100dvh-4rem)] flex flex-col overflow-hidden">
    <div class="max-w-lg lg:max-w-4xl mx-auto w-full flex flex-col flex-1 min-h-0 px-6 py-4 overflow-y-auto">

      <div v-if="isLoading" class="flex-1 flex items-center justify-center">
        <p class="font-display text-text-muted animate-pulse">LOADING...</p>
      </div>

      <div v-else-if="!stats" class="flex-1 flex items-center justify-center">
        <p class="font-display text-text-muted">{{ loadError || 'Bot not found.' }}</p>
      </div>

      <template v-else>
        <div class="lg:flex lg:gap-6 lg:items-stretch">

          <!-- LEFT COLUMN: Character + Stats + Actions -->
          <div class="lg:w-[380px] lg:shrink-0 flex flex-col">
            <!-- Nostr banner -->
            <div v-if="nostrProfile?.banner" class="relative h-24 -mx-0 mb-0 overflow-hidden border border-border border-b-0">
              <img :src="nostrProfile.banner" alt="" class="w-full h-full object-cover opacity-60" />
              <div class="absolute inset-0 bg-gradient-to-t from-surface-base to-transparent" />
            </div>

            <div class="border border-border bg-surface-raised/30 p-6 overflow-hidden"
                 :class="{ 'border-t-0': nostrProfile?.banner }">
              <!-- Human player: just the human avatar, centered -->
              <div v-if="stats.archetype === 'human'" class="flex justify-center mb-4">
                <HumanPreview
                  :seed="stats.avatarSeed || stats.name"
                  archetype="human"
                  :size="200"
                  :win-rate="(stats.winRate || 0) / 100"
                  anim="idle"
                  class="drop-shadow-[0_0_20px_rgba(0,255,255,0.3)]"
                />
              </div>
              <!-- Bot player: human controller + bot sprite -->
              <div v-else class="flex items-end justify-center gap-2 mb-4">
                <HumanPreview
                  :seed="stats.avatarSeed || stats.name"
                  :archetype="stats.archetype || 'standard'"
                  :size="150"
                  :win-rate="(stats.winRate || 0) / 100"
                  anim="idle"
                  class="drop-shadow-[0_0_12px_rgba(0,0,0,0.6)] shrink-0"
                />
                <SpritePreview
                  :seed="stats.avatarSeed || stats.name"
                  :archetype="stats.archetype"
                  :tier="stats.tier"
                  :size="140"
                  :customization="stats.customization || undefined"
                  class="drop-shadow-[0_0_20px_var(--glow)]"
                  :style="{ '--glow': stats.tierColor + '80' } as any"
                />
              </div>

              <!-- Name & tier -->
              <div class="text-center border-t border-border/50 pt-4">
                <h2 class="font-display font-black text-2xl lg:text-3xl tracking-wider gradient-text">
                  {{ stats.name }}
                </h2>
                <div class="inline-block px-3 py-0.5 border text-[9px] font-display font-black tracking-widest mt-1"
                     :style="{ borderColor: stats.tierColor, color: stats.tierColor, backgroundColor: 'rgba(0,0,0,0.8)' }">
                  {{ stats.tierName }}
                </div>
                <p class="font-display text-sm font-bold tracking-widest mt-1"
                   :style="{ color: stats.tierColor }">
                  {{ getStatusTitle(stats) }}
                </p>
                <p class="font-mono text-text-muted text-[10px] mt-0.5">
                  #{{ stats.rank }} of {{ stats.totalBots }}
                </p>
                <!-- Nostr identity -->
                <div v-if="nostrProfile?.displayName || nostrProfile?.nip05" class="mt-2 space-y-0.5">
                  <p v-if="nostrProfile.displayName" class="font-mono text-xs text-text-secondary">
                    {{ nostrProfile.displayName }}
                  </p>
                  <p v-if="nostrProfile.nip05" class="font-mono text-[10px] text-neon-purple">
                    {{ nostrProfile.nip05 }}
                  </p>
                </div>
                <button
                  v-if="isOwner && stats.archetype !== 'human'"
                  class="mt-2 font-mono text-[10px] text-neon-cyan/60 hover:text-neon-cyan transition-colors"
                  @click="showCustomize = !showCustomize; if (showCustomize) initCustForm()"
                >
                  {{ showCustomize ? 'CLOSE' : 'CUSTOMIZE' }}
                </button>
              </div>
            </div>

            <!-- Stats -->
            <div class="grid grid-cols-3 gap-2 mt-4">
              <div class="border border-border bg-surface-raised/50 p-2.5 text-center">
                <p class="font-display font-black text-xl text-neon-cyan">{{ Math.round(stats.eloRating) }}</p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">ELO</p>
              </div>
              <div class="border border-border bg-surface-raised/50 p-2.5 text-center">
                <p class="font-display font-black text-xl">
                  <span class="text-neon-cyan">{{ stats.wins }}</span>
                  <span class="text-text-muted text-sm">-</span>
                  <span class="text-neon-pink">{{ stats.losses }}</span>
                </p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">RECORD</p>
              </div>
              <div class="border border-border bg-surface-raised/50 p-2.5 text-center">
                <p class="font-display font-black text-xl"
                   :class="stats.winRate >= 60 ? 'text-neon-cyan' : stats.winRate >= 40 ? 'text-neon-yellow' : 'text-neon-pink'">
                  {{ stats.winRate }}%
                </p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">WIN RATE</p>
              </div>
            </div>

            <!-- Streaks -->
            <div class="flex gap-2 mt-2">
              <div class="flex-1 border border-border bg-surface-raised/50 p-2.5 text-center">
                <p class="font-display font-bold text-base"
                   :class="stats.winStreak >= 3 ? 'text-neon-yellow' : 'text-text-primary'">
                  {{ stats.winStreak > 0 ? `${stats.winStreak}x` : '-' }}
                </p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">STREAK</p>
              </div>
              <div class="flex-1 border border-border bg-surface-raised/50 p-2.5 text-center">
                <p class="font-display font-bold text-base text-text-primary">{{ stats.bestStreak }}x</p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">BEST</p>
              </div>
              <div class="flex-1 border border-border bg-surface-raised/50 p-2.5 text-center">
                <p class="font-display font-bold text-base text-text-primary">{{ stats.totalFights }}</p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">FIGHTS</p>
              </div>
            </div>

            <!-- Sats stats -->
            <div v-if="stats.satsWon || stats.satsWagered || stats.zapsReceived" class="flex gap-2 mt-2">
              <div class="flex-1 border border-neon-cyan/20 bg-neon-cyan/5 p-2.5 text-center">
                <p class="font-display font-bold text-base text-neon-cyan">{{ stats.satsWon || 0 }}</p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">SATS WON</p>
              </div>
              <div class="flex-1 border border-neon-purple/20 bg-neon-purple/5 p-2.5 text-center">
                <p class="font-display font-bold text-base text-neon-purple">{{ stats.satsWagered || 0 }}</p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">WAGERED</p>
              </div>
              <div v-if="stats.zapsReceived" class="flex-1 border border-neon-yellow/20 bg-neon-yellow/5 p-2.5 text-center">
                <p class="font-display font-bold text-base text-neon-yellow">{{ stats.zapsReceived }}</p>
                <p class="font-display text-[8px] text-text-muted tracking-wider mt-0.5">ZAPS</p>
              </div>
            </div>

            <!-- Wallet connection (owner only) -->
            <div v-if="isOwner" class="mt-3">
              <WalletConnect />
            </div>

            <!-- Fight actions -->
            <div class="flex gap-2 mt-4">
              <button
                class="flex-1 py-3 bg-neon-pink/10 border-2 border-neon-pink/50 text-neon-pink
                       font-display font-black text-sm tracking-wider
                       hover:bg-neon-pink/20 transition-all neon-border-pink
                       disabled:opacity-50 disabled:cursor-wait flex items-center justify-center gap-2"
                :disabled="isJoining"
                @click="instantFight"
              >
                <span v-if="isJoining" class="w-4 h-4 border-2 border-neon-pink/30 border-t-neon-pink rounded-full animate-spin" />
                {{ isJoining ? 'MATCHING...' : 'INSTANT FIGHT' }}
              </button>
              <button
                class="flex-1 py-3 border-2 border-neon-purple/50 text-neon-purple
                       font-display font-bold text-sm tracking-wider
                       hover:bg-neon-purple/10 transition-all"
                @click="showChoose = !showChoose"
              >
                CHOOSE FIGHT
              </button>
            </div>

            <p v-if="fightError" class="font-mono text-[10px] text-neon-pink mt-2">{{ fightError }}</p>

            <!-- Choose your fight panel -->
            <div v-if="showChoose" class="mt-3 border border-border bg-surface-raised/50 p-3">
              <p class="font-display text-[10px] font-bold text-text-muted tracking-[0.15em] mb-2">
                FIGHTERS WAITING
              </p>
              <div v-if="waitingFighters.length === 0" class="text-center py-3">
                <p class="font-mono text-xs text-text-muted">Nobody waiting. Use Instant Fight instead.</p>
              </div>
              <button
                v-for="fighter in waitingFighters"
                :key="fighter.botId"
                class="w-full flex items-center justify-between px-3 py-2 border border-border
                       hover:border-neon-cyan/30 hover:bg-neon-cyan/5 transition-all mb-1 text-xs
                       disabled:opacity-30"
                :disabled="isJoining || fighter.botId === stats.id"
                @click="fightSpecific(fighter.botId)"
              >
                <span class="font-display font-bold text-text-primary">{{ fighter.botName }}</span>
                <span class="font-mono text-text-muted">{{ Math.round(fighter.eloRating) }} ELO</span>
              </button>
            </div>

            <!-- Customization panel (owner only) -->
            <div v-if="showCustomize && isOwner" class="mt-4 border border-neon-cyan/20 bg-surface-raised/60 p-4">
              <p class="font-display text-[10px] font-bold text-neon-cyan tracking-[0.15em] mb-3">
                CUSTOMIZE CHARACTER
              </p>
              <div class="flex justify-center mb-3">
                <SpritePreview
                  :seed="stats.avatarSeed || stats.name"
                  :archetype="custForm.archetype || stats.archetype"
                  :tier="stats.tier"
                  :size="120"
                  :customization="previewCustomization"
                  class="drop-shadow-[0_0_12px_rgba(0,255,255,0.3)]"
                />
              </div>
              <label class="block mb-2">
                <span class="font-display text-[9px] text-text-muted tracking-wider">ARCHETYPE</span>
                <select
                  v-model="custForm.archetype"
                  class="mt-0.5 w-full bg-surface-base border border-border text-text-primary
                         font-mono text-xs px-2 py-1.5 focus:border-neon-cyan/50 outline-none"
                >
                  <option value="">Default (from seed)</option>
                  <option v-for="a in ARCHETYPES" :key="a" :value="a">{{ a.replace(/_/g, ' ') }}</option>
                </select>
              </label>
              <div class="flex gap-3 mb-2">
                <label class="flex-1">
                  <span class="font-display text-[9px] text-text-muted tracking-wider">PRIMARY</span>
                  <div class="flex items-center gap-1 mt-0.5">
                    <input type="color" v-model="custForm.primaryColor"
                           class="w-8 h-8 border border-border bg-transparent cursor-pointer" />
                    <span class="font-mono text-[10px] text-text-muted">{{ custForm.primaryColor }}</span>
                  </div>
                </label>
                <label class="flex-1">
                  <span class="font-display text-[9px] text-text-muted tracking-wider">SECONDARY</span>
                  <div class="flex items-center gap-1 mt-0.5">
                    <input type="color" v-model="custForm.secondaryColor"
                           class="w-8 h-8 border border-border bg-transparent cursor-pointer" />
                    <span class="font-mono text-[10px] text-text-muted">{{ custForm.secondaryColor }}</span>
                  </div>
                </label>
              </div>
              <p class="font-display text-[9px] text-text-muted tracking-wider mb-1">ACCESSORIES</p>
              <div class="flex gap-3 mb-3">
                <label class="flex items-center gap-1 cursor-pointer">
                  <input type="checkbox" v-model="custForm.forceVisor" class="accent-neon-cyan" />
                  <span class="font-mono text-[10px] text-text-secondary">Visor</span>
                </label>
                <label class="flex items-center gap-1 cursor-pointer">
                  <input type="checkbox" v-model="custForm.forceMohawk" class="accent-neon-cyan" />
                  <span class="font-mono text-[10px] text-text-secondary">Mohawk</span>
                </label>
                <label class="flex items-center gap-1 cursor-pointer">
                  <input type="checkbox" v-model="custForm.forceHorns" class="accent-neon-cyan" />
                  <span class="font-mono text-[10px] text-text-secondary">Horns</span>
                </label>
              </div>
              <p v-if="custError" class="font-mono text-[10px] text-neon-pink mb-2">{{ custError }}</p>
              <button
                class="w-full py-2 bg-neon-cyan/10 border border-neon-cyan/40 text-neon-cyan
                       font-display font-bold text-xs tracking-wider
                       hover:bg-neon-cyan/20 transition-all
                       disabled:opacity-30 disabled:cursor-not-allowed"
                :disabled="isSaving"
                @click="saveCustomization"
              >
                {{ isSaving ? 'SAVING...' : 'SAVE LOOK' }}
              </button>
            </div>

            <!-- Webhook management (owner only, bots only) -->
            <div v-if="isOwner && stats.archetype !== 'human' && !stats.isHuman" class="mt-4">
              <!-- Deactivated warning -->
              <div v-if="stats.isActive === false" class="p-3 border-2 border-ko/40 bg-ko/5 mb-3">
                <p class="font-display font-bold text-xs tracking-wider text-ko mb-1">BOT DEACTIVATED</p>
                <p class="font-mono text-[10px] text-text-muted">
                  Too many webhook errors. Test your webhook to reactivate.
                </p>
              </div>

              <button
                class="w-full py-2 border border-border text-text-secondary font-display font-bold text-[10px]
                       tracking-wider hover:border-neon-cyan/40 hover:text-neon-cyan transition-all text-center"
                @click="showWebhook = !showWebhook"
              >
                {{ showWebhook ? 'HIDE' : 'WEBHOOK' }} SETTINGS
              </button>

              <div v-if="showWebhook" class="mt-3 border border-border bg-surface-raised/60 p-4 space-y-3">
                <!-- Current webhook info -->
                <div>
                  <p class="font-display text-[9px] text-text-muted tracking-wider mb-1">CURRENT WEBHOOK</p>
                  <div class="flex items-center gap-2">
                    <span
                      class="w-2 h-2 rounded-full flex-shrink-0"
                      :class="(stats.consecutiveErrors ?? 0) === 0 ? 'bg-neon-green' : 'bg-ko'"
                    />
                    <p class="font-mono text-[10px] text-text-secondary break-all flex-1">
                      {{ stats.webhookUrl || '—' }}
                    </p>
                  </div>
                  <p v-if="(stats.consecutiveErrors ?? 0) > 0" class="font-mono text-[10px] text-ko mt-1">
                    {{ stats.consecutiveErrors }} consecutive errors
                  </p>
                </div>

                <!-- Test button -->
                <button
                  class="w-full py-2 bg-neon-cyan/10 border border-neon-cyan/40 text-neon-cyan
                         font-display font-bold text-[10px] tracking-wider
                         hover:bg-neon-cyan/20 transition-all
                         disabled:opacity-30 disabled:cursor-not-allowed
                         flex items-center justify-center gap-2"
                  :disabled="isTestingWebhook"
                  @click="testWebhook"
                >
                  <span v-if="isTestingWebhook" class="w-3 h-3 border-2 border-neon-cyan/30 border-t-neon-cyan rounded-full animate-spin" />
                  {{ isTestingWebhook ? 'TESTING...' : 'TEST WEBHOOK' }}
                </button>

                <!-- Test result -->
                <div v-if="webhookTestResult" class="p-2.5 border text-[10px] font-mono"
                     :class="webhookTestResult.validResponse
                       ? 'border-neon-green/30 bg-neon-green/5 text-neon-green'
                       : 'border-ko/30 bg-ko/5 text-ko'">
                  <p class="font-display font-bold text-xs tracking-wider mb-1">
                    {{ webhookTestResult.validResponse ? 'PASSED' : 'FAILED' }}
                  </p>
                  <p>{{ webhookTestResult.message || webhookTestResult.error }}</p>
                  <p v-if="webhookTestResult.latencyMs" class="text-text-muted mt-0.5">
                    Latency: {{ webhookTestResult.latencyMs }}ms
                  </p>
                </div>

                <!-- Update webhook URL -->
                <div class="border-t border-border/50 pt-3">
                  <p class="font-display text-[9px] text-text-muted tracking-wider mb-1">UPDATE WEBHOOK URL</p>
                  <div class="flex gap-2">
                    <input
                      v-model="webhookInput"
                      type="url"
                      placeholder="https://your-bot.example.com"
                      class="flex-1 px-2 py-1.5 bg-black/30 border border-border font-mono text-[10px] text-text-primary
                             placeholder-text-muted/50 focus:outline-none focus:border-neon-cyan/50"
                      @keyup.enter="saveWebhook"
                    />
                    <button
                      class="px-3 py-1.5 bg-neon-cyan/10 border border-neon-cyan/40 text-neon-cyan
                             font-display font-bold text-[10px] tracking-wider
                             hover:bg-neon-cyan/20 transition-all
                             disabled:opacity-30 disabled:cursor-not-allowed"
                      :disabled="!webhookInput.trim() || isUpdatingWebhook"
                      @click="saveWebhook"
                    >
                      {{ isUpdatingWebhook ? '...' : 'UPDATE' }}
                    </button>
                  </div>
                </div>

                <p v-if="webhookError" class="font-mono text-[10px] text-ko">{{ webhookError }}</p>
                <p v-if="webhookSuccess" class="font-mono text-[10px] text-neon-green">{{ webhookSuccess }}</p>
              </div>
            </div>

            <!-- Sign out (only if owner) -->
            <div v-if="isOwner" class="mt-3 text-center flex-shrink-0">
              <button
                class="font-mono text-[10px] text-text-muted hover:text-ko transition-colors"
                @click="handleSignOut"
              >
                Sign out
              </button>
            </div>
          </div>

          <!-- RIGHT COLUMN: Recent bouts + Bet history (scrollable) -->
          <div class="flex-1 min-w-0 flex flex-col min-h-0 mt-6 lg:mt-0 gap-4">
            <div class="border border-border bg-surface-raised/30 flex flex-col min-h-0 overflow-hidden">
              <div class="px-4 py-3 border-b border-border/50 flex-shrink-0">
                <p class="font-display text-[10px] font-bold text-text-muted tracking-[0.15em]">
                  RECENT BOUTS
                </p>
              </div>
              <div class="flex-1 overflow-y-auto p-3 space-y-1.5">
                <RouterLink
                  v-for="fight in stats.recentFights"
                  :key="fight.id"
                  :to="`/arena/${fight.id}`"
                  class="flex items-center justify-between px-3 py-2 border border-border
                         bg-surface-raised/30 hover:border-neon-pink/30 transition-all text-xs"
                >
                  <span class="font-display font-bold w-6"
                        :class="fight.result === 'W' ? 'text-neon-cyan' : fight.result === 'L' ? 'text-neon-pink' : 'text-text-muted'">
                    {{ fight.result }}
                  </span>
                  <span class="font-mono text-text-secondary flex-1 ml-2">vs {{ fight.opponent }}</span>
                  <span class="font-mono text-[10px] text-text-muted">R{{ fight.rounds }}</span>
                </RouterLink>
                <div v-if="stats.recentFights.length === 0" class="text-center py-8">
                  <p class="font-mono text-text-muted text-xs">No fights yet. Hit Instant Fight!</p>
                </div>
              </div>
            </div>

            <!-- Bet history (owner's view) -->
            <div v-if="isOwner && pubkey" class="border border-border bg-surface-raised/30 p-3">
              <BetHistory :pubkey="pubkey" />
            </div>
          </div>

        </div>
      </template>
    </div>
  </div>
</template>

