<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import type { TerminalSlot } from '@/types/transcript-debug'
import { useSessionState, type AgentStatus } from '@/stores/session-state'

const props = defineProps<{
  agent: string
  connected: boolean
  terminals: TerminalSlot[]
  activeSessionId: string | null
  model?: string
  version?: string
}>()

const sessionStore = useSessionState()

const STATUS_COLORS: Record<AgentStatus, string> = {
  idle:              '#6b7280',
  thinking:          '#60a5fa',
  reading:           '#22d3ee',
  writing:           '#4ade80',
  toolUse:           '#fbbf24',
  permissionRequest: '#fb923c',
  interrupted:       '#f87171',
  error:             '#f87171',
  sessionStart:      '#60a5fa',
  sessionEnd:        '#6b7280',
}

const agentStatusColor = computed(() => {
  const state = sessionStore.agents[props.agent]
  if (!state) return null
  return STATUS_COLORS[state.status] || '#6b7280'
})

const agentStatusClass = computed(() => {
  const state = sessionStore.agents[props.agent]
  return state?.status || 'idle'
})

const activeIndex = computed(() => {
  if (!props.activeSessionId) return -1
  return props.terminals.findIndex(t => t.sessionId === props.activeSessionId)
})

const activeSlot = computed(() =>
  activeIndex.value >= 0 ? props.terminals[activeIndex.value] : null
)

const emit = defineEmits<{
  'switch-terminal': [sessionId: string]
  'close-terminal': [sessionId: string]
}>()

const isOpen = ref(false)
const wrapperRef = ref<HTMLElement | null>(null)

function toggle(e: Event) {
  e.stopPropagation()
  isOpen.value = !isOpen.value
}

function onClickOutside(e: MouseEvent) {
  if (!isOpen.value) return
  if (wrapperRef.value && !wrapperRef.value.contains(e.target as Node)) {
    isOpen.value = false
  }
}

function handleSwitch(sessionId: string) {
  emit('switch-terminal', sessionId)
  isOpen.value = false
}

function handleClose(e: Event, sessionId: string) {
  e.stopPropagation()
  emit('close-terminal', sessionId)
}

function slotColor(t: TerminalSlot): string {
  if (!t.alive) return '#f87171'        // PTY dead → red
  if (t.clients > 0) return '#4ade80'   // alive + connected → green
  return '#fbbf24'                       // alive, no clients (parked) → orange
}

onMounted(() => document.addEventListener('mousedown', onClickOutside))
onBeforeUnmount(() => document.removeEventListener('mousedown', onClickOutside))
</script>

<template>
  <div ref="wrapperRef" class="agent-badge-wrapper" :class="{ connected }" @click="toggle">
    <span v-if="agentStatusColor" class="state-dot status-dot" :class="agentStatusClass" :style="{ background: agentStatusColor }" />
    <span v-else-if="activeSlot" class="state-dot badge-dot" :style="{ background: slotColor(activeSlot) }" />
    <span class="agent-label">{{ agent }}</span>
    <span v-if="terminals.length" class="term-count">{{ activeIndex >= 0 ? `${activeIndex + 1}/${terminals.length}` : terminals.length }}</span>
    <svg class="caret" :class="{ open: isOpen }" width="6" height="6" viewBox="0 0 6 6" shape-rendering="crispEdges">
      <rect x="2" y="4" width="2" height="2" fill="currentColor"/>
      <rect x="0" y="2" width="2" height="2" fill="currentColor"/>
      <rect x="4" y="2" width="2" height="2" fill="currentColor"/>
    </svg>
    <Transition name="dropdown">
      <div v-if="isOpen" class="dropdown">
        <div v-if="model || version" class="dropdown-meta">
          <span v-if="model" class="meta-model">{{ model }}</span>
          <span v-if="version" class="meta-version">v{{ version }}</span>
        </div>
        <div v-if="terminals.length === 0" class="dropdown-item empty">No terminals</div>
        <div
          v-for="(t, idx) in terminals"
          :key="t.sessionId"
          class="dropdown-item terminal-item"
          :class="{ active: t.sessionId === activeSessionId }"
          @click.stop="handleSwitch(t.sessionId)"
        >
          <span class="shortcut-key">{{ idx + 1 }}</span>
          <span class="state-dot" :style="{ background: slotColor(t) }" />
          <span class="terminal-label">{{ t.label }}</span>
          <button class="close-btn" @click="handleClose($event, t.sessionId)" title="Close terminal">
            <svg width="6" height="6" viewBox="0 0 6 6">
              <line x1="0" y1="0" x2="6" y2="6" stroke="currentColor" stroke-width="1.2"/>
              <line x1="6" y1="0" x2="0" y2="6" stroke="currentColor" stroke-width="1.2"/>
            </svg>
          </button>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.agent-badge-wrapper {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  user-select: none;
  padding: 3px 7px;
  border: 1px solid rgba(99, 102, 241, 0.3);
  background: rgba(99, 102, 241, 0.12);
  transition: background 0.15s, border-color 0.15s, box-shadow 0.2s;
}

.agent-badge-wrapper:hover {
  background: rgba(99, 102, 241, 0.2);
  border-color: rgba(99, 102, 241, 0.4);
}

.agent-badge-wrapper.connected {
  border: 2px solid;
  border-image: conic-gradient(
    from var(--border-angle, 0deg),
    rgba(34, 211, 238, 1),
    rgba(99, 102, 241, 0.7),
    rgba(34, 211, 238, 0.15),
    rgba(99, 102, 241, 0.7),
    rgba(34, 211, 238, 1)
  ) 1;
  background: rgba(34, 197, 94, 0.08);
  box-shadow: 0 0 12px rgba(34, 211, 238, 0.3);
  animation: border-spin 3s linear infinite;
}

.agent-badge-wrapper.connected:hover {
  background: rgba(34, 197, 94, 0.15);
}

@property --border-angle {
  syntax: "<angle>";
  initial-value: 0deg;
  inherits: false;
}

@keyframes border-spin {
  to { --border-angle: 360deg; }
}

.agent-label {
  font-size: 10px;
  font-weight: 700;
  font-family: 'Courier New', monospace;
  color: #a5b4fc;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.connected .agent-label {
  color: #86efac;
}

.badge-dot,
.status-dot {
  width: 5px;
  height: 5px;
  flex-shrink: 0;
}

.status-dot.thinking {
  animation: pulse-badge 1.5s ease-in-out infinite;
}

@keyframes pulse-badge {
  0%, 100% { opacity: 0.5; }
  50% { opacity: 1; }
}

.term-count {
  font-size: 8px;
  font-weight: 700;
  font-family: 'Courier New', monospace;
  color: rgba(165, 180, 252, 0.6);
  background: rgba(99, 102, 241, 0.2);
  padding: 0 3px;
  min-width: 12px;
  text-align: center;
  line-height: 12px;
}

.connected .term-count {
  color: rgba(134, 239, 172, 0.6);
  background: rgba(34, 197, 94, 0.15);
}

.caret {
  color: rgba(165, 180, 252, 0.5);
  transition: transform 0.2s ease;
}

.connected .caret {
  color: rgba(134, 239, 172, 0.5);
}

.caret.open {
  transform: rotate(180deg);
}

.dropdown {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  min-width: 180px;
  max-width: 260px;
  max-height: 280px;
  overflow-y: auto;
  background: rgba(8, 8, 18, 0.95);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border: 1px solid rgba(99, 102, 241, 0.2);
  z-index: 100;
  padding: 3px 0;
}

.dropdown-meta {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px 3px;
  border-bottom: 1px solid rgba(99, 102, 241, 0.1);
  margin-bottom: 2px;
}

.meta-model {
  font-size: 8px;
  font-family: 'Courier New', monospace;
  color: rgba(165, 180, 252, 0.7);
  background: rgba(99, 102, 241, 0.12);
  padding: 0 4px;
  line-height: 14px;
}

.meta-version {
  font-size: 8px;
  font-family: 'Courier New', monospace;
  color: rgba(255, 255, 255, 0.3);
}

.dropdown-item {
  padding: 5px 10px;
  font-size: 9px;
  font-family: 'Courier New', monospace;
  color: rgba(255, 255, 255, 0.5);
  letter-spacing: 0.5px;
}

.dropdown-item.empty {
  color: rgba(255, 255, 255, 0.25);
  font-style: italic;
  text-align: center;
}

.dropdown-item.terminal-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 5px 8px;
  cursor: pointer;
  transition: background 0.1s;
}

.dropdown-item.terminal-item:hover {
  background: rgba(99, 102, 241, 0.12);
}

.dropdown-item.terminal-item.active {
  background: rgba(99, 102, 241, 0.18);
  color: rgba(255, 255, 255, 0.8);
}

.shortcut-key {
  font-size: 8px;
  font-weight: 700;
  font-family: 'Courier New', monospace;
  color: rgba(255, 255, 255, 0.2);
  min-width: 10px;
  text-align: center;
  flex-shrink: 0;
}

.dropdown-item.terminal-item.active .shortcut-key {
  color: rgba(165, 180, 252, 0.7);
}

.state-dot {
  width: 5px;
  height: 5px;
  flex-shrink: 0;
  border-radius: 0;
}

.terminal-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 9px;
}

.close-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  flex-shrink: 0;
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.2);
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.15s, color 0.15s, background 0.15s;
}

.dropdown-item.terminal-item:hover .close-btn {
  opacity: 1;
}

.close-btn:hover {
  color: #fca5a5;
  background: rgba(239, 68, 68, 0.2);
}

/* Transition */
.dropdown-enter-active {
  transition: opacity 0.15s ease, transform 0.15s ease;
}

.dropdown-leave-active {
  transition: opacity 0.1s ease, transform 0.1s ease;
}

.dropdown-enter-from,
.dropdown-leave-to {
  opacity: 0;
  transform: translateY(-4px);
}

/* Scrollbar */
.dropdown::-webkit-scrollbar {
  width: 4px;
}

.dropdown::-webkit-scrollbar-track {
  background: transparent;
}

.dropdown::-webkit-scrollbar-thumb {
  background: rgba(99, 102, 241, 0.2);
}
</style>
