<script setup lang="ts">
import { onBeforeUnmount } from 'vue'
import type { Agent, AgentStatusState } from '../../types/agent'

const props = defineProps<{
  agent: Agent
  status: AgentStatusState | undefined
  recording?: boolean
}>()

const emit = defineEmits<{
  click: [event: MouseEvent]
  hold: [el: HTMLElement]
  holdrelease: []
}>()

const HOLD_MS = 200
let holdTimer: number | null = null
let didHold = false
let holdTarget: HTMLElement | null = null

function onPointerDown(e: PointerEvent) {
  didHold = false
  holdTarget = e.currentTarget as HTMLElement
  holdTarget.setPointerCapture(e.pointerId)
  holdTimer = window.setTimeout(() => {
    didHold = true
    emit('hold', holdTarget!)
  }, HOLD_MS)
}

function onPointerUp(e: PointerEvent) {
  clearHold()
  if (didHold) {
    emit('holdrelease')
  } else {
    emit('click', e as unknown as MouseEvent)
  }
}

function onPointerCancel() {
  clearHold()
  if (didHold) {
    emit('holdrelease')
  }
}

function clearHold() {
  if (holdTimer) { clearTimeout(holdTimer); holdTimer = null }
}

onBeforeUnmount(clearHold)

function bubbleClasses() {
  const s = props.status
  const base: Record<string, boolean> = { recording: !!props.recording }
  if (!s) return base
  return {
    ...base,
    processing: s.isProcessing && !s.isReading && !s.isWriting && !s.awaitingPermission,
    reading: s.isReading,
    writing: s.isWriting,
    permission: s.awaitingPermission,
    notification: s.showNotification,
    'tool-flash': s.showToolFlash
  }
}

function bubbleStyle() {
  const c = props.agent.uiConfig?.color || '#6366f1'
  const s = props.status

  if (props.recording) {
    return {
      background: props.agent.uiConfig?.gradient || c,
      borderColor: 'rgba(239, 68, 68, 0.7)'
    }
  }

  if (s?.awaitingPermission) {
    return { background: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)' }
  }
  if (s?.isWriting) {
    return { background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)' }
  }
  if (s?.isReading) {
    return { background: 'linear-gradient(135deg, #06b6d4 0%, #0891b2 100%)' }
  }
  if (s?.isProcessing) {
    return { background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)' }
  }

  return {
    background: props.agent.uiConfig?.gradient || c,
    boxShadow: `0 4px 15px ${c}66, 0 8px 30px ${c}4D, inset 0 1px 0 rgba(255,255,255,0.2)`
  }
}

function bubbleHoverShadow() {
  const c = props.agent.uiConfig?.color || '#6366f1'
  return `0 8px 25px ${c}80, 0 15px 40px ${c}59, inset 0 1px 0 rgba(255,255,255,0.25)`
}

function isAnimating(): boolean {
  const s = props.status
  if (!s) return false
  return s.isProcessing || s.isReading || s.isWriting || s.awaitingPermission || s.showNotification || s.showToolFlash
}

function bubbleTitle() {
  const s = props.status
  const a = props.agent
  if (s?.awaitingPermission) {
    return `Permiso requerido: ${s.currentTool || 'herramienta'}`
  }
  if (s?.isProcessing) {
    return `${a.uiConfig?.label}: ${s.currentTool || 'processing'}`
  }
  return a.uiConfig?.label || a.name
}
</script>

<template>
  <button
    class="agent-bubble"
    :class="bubbleClasses()"
    :data-agent="agent.id"
    :style="bubbleStyle()"
    :title="bubbleTitle()"
    @pointerdown.prevent="onPointerDown"
    @pointerup="onPointerUp"
    @pointercancel="onPointerCancel"
    @touchstart.prevent
    @contextmenu.prevent
    @selectstart.prevent
    @dragstart.prevent
    @mouseenter="!isAnimating() && (($event.currentTarget as HTMLElement).style.boxShadow = bubbleHoverShadow())"
    @mouseleave="!isAnimating() && (($event.currentTarget as HTMLElement).style.boxShadow = bubbleStyle().boxShadow || '')"
  >
    <!-- Recording: audio bars -->
    <div v-if="recording" class="audio-bars">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
    </div>

    <!-- Permission alert icon -->
    <svg v-else-if="status?.awaitingPermission" class="bubble-status-icon permission-icon" xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
      <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
      <line x1="12" y1="9" x2="12" y2="13"/>
      <line x1="12" y1="17" x2="12.01" y2="17"/>
    </svg>

    <!-- Ejecutor processing: ember ring -->
    <div v-else-if="agent.id === 'ejecutor' && status?.isProcessing && !status?.isReading && !status?.isWriting" class="ember-ring">
      <span></span>
      <span></span>
    </div>

    <!-- Default processing: thinking dots -->
    <div v-else-if="status?.isProcessing && !status?.isReading && !status?.isWriting" class="thinking-dots">
      <span></span>
      <span></span>
      <span></span>
    </div>

    <!-- Reading icon (eye) -->
    <svg v-else-if="status?.isReading" class="bubble-status-icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
      <circle cx="12" cy="12" r="3"/>
    </svg>

    <!-- Writing icon (pencil) -->
    <svg v-else-if="status?.isWriting" class="bubble-status-icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <path d="M12 19l7-7 3 3-7 7-3-3z"/>
      <path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/>
      <path d="M2 2l7.586 7.586"/>
      <circle cx="11" cy="11" r="2"/>
    </svg>

    <!-- Default: agent label -->
    <span v-else class="bubble-label">{{ agent.uiConfig?.shortLabel }}</span>
  </button>
</template>

<style scoped>
.agent-bubble {
  pointer-events: auto;
  width: 58px;
  height: 58px;
  border-radius: 18px;
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.15);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
  overflow: visible;
  backdrop-filter: blur(10px);
  -webkit-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
  touch-action: none;
  position: relative;
}

/* Hover glow ring */
.agent-bubble::before {
  content: '';
  position: absolute;
  inset: -3px;
  border-radius: 21px;
  background: inherit;
  filter: blur(8px);
  z-index: -1;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.agent-bubble:hover {
  transform: translateY(-3px) scale(1.05);
}

.agent-bubble:hover::before {
  opacity: 0.4;
}

.agent-bubble:active {
  transform: scale(0.95);
  transition-duration: 0.1s;
}

/* ====================== RECORDING STATE ====================== */

.agent-bubble.recording {
  animation: rec-glow 1.5s ease-in-out infinite !important;
  border-color: rgba(239, 68, 68, 0.7) !important;
}

.audio-bars {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
  height: 22px;
}

.audio-bars span {
  width: 3px;
  border-radius: 2px;
  background: #fff;
  animation: audio-bar 1.2s ease-in-out infinite;
}

.audio-bars span:nth-child(1) { height: 8px;  animation-delay: 0s; }
.audio-bars span:nth-child(2) { height: 16px; animation-delay: 0.15s; }
.audio-bars span:nth-child(3) { height: 22px; animation-delay: 0.3s; }
.audio-bars span:nth-child(4) { height: 14px; animation-delay: 0.45s; }
.audio-bars span:nth-child(5) { height: 10px; animation-delay: 0.6s; }

@keyframes audio-bar {
  0%, 100% { transform: scaleY(0.4); opacity: 0.5; }
  50%      { transform: scaleY(1);   opacity: 1; }
}

@keyframes rec-glow {
  0%, 100% {
    box-shadow:
      0 0 0 0 rgba(239, 68, 68, 0.5),
      0 4px 15px rgba(239, 68, 68, 0.3) !important;
  }
  50% {
    box-shadow:
      0 0 0 8px rgba(239, 68, 68, 0),
      0 4px 25px rgba(239, 68, 68, 0.6) !important;
  }
}

/* ====================== STATUS ANIMATIONS (DEFAULT) ====================== */

.agent-bubble.processing,
.agent-bubble.reading,
.agent-bubble.writing,
.agent-bubble.permission,
.agent-bubble.notification {
  transition: background 0.3s ease !important;
}

.agent-bubble.processing {
  animation: ab-processing-pulse 2s ease-in-out infinite !important;
}

.agent-bubble.reading {
  animation: ab-reading-scan 1.5s ease-in-out infinite !important;
}

.agent-bubble.writing {
  animation: ab-writing-pulse 0.8s ease-in-out infinite !important;
}

.agent-bubble.permission {
  animation: ab-permission-pulse 1s ease-in-out infinite !important;
  transform: scale(1.1) !important;
  z-index: 10000;
}

.agent-bubble.notification {
  animation: ab-notification-bounce 0.5s ease-in-out 4 !important;
}

.agent-bubble.tool-flash::after {
  content: '';
  position: absolute;
  inset: -4px;
  border-radius: 22px;
  background: rgba(255, 255, 255, 0.4);
  animation: ab-tool-flash 0.5s ease-out forwards !important;
  pointer-events: none;
}

/* Thinking dots */
.thinking-dots {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.thinking-dots span {
  width: 5px;
  height: 5px;
  background: white;
  border-radius: 50%;
  animation: ab-thinking-dot 1.4s ease-in-out infinite;
}

.thinking-dots span:nth-child(1) { animation-delay: 0s; }
.thinking-dots span:nth-child(2) { animation-delay: 0.2s; }
.thinking-dots span:nth-child(3) { animation-delay: 0.4s; }

/* Status icons */
.bubble-status-icon {
  animation: ab-icon-breathe 1s ease-in-out infinite;
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3));
}

.permission-icon {
  animation: ab-permission-shake 0.5s ease-in-out infinite;
  filter: drop-shadow(0 0 8px rgba(255, 255, 255, 0.8));
}

/* ====================== EJECUTOR UNIQUE ANIMATIONS ====================== */

.agent-bubble[data-agent="ejecutor"].processing {
  animation: ej-heartbeat 1.2s ease-in-out infinite !important;
  border-color: rgba(255, 100, 50, 0.5) !important;
}

.agent-bubble[data-agent="ejecutor"].reading {
  animation: ej-infrared 1s linear infinite !important;
}

.agent-bubble[data-agent="ejecutor"].writing {
  animation: ej-forge 0.6s ease-in-out infinite !important;
  border-color: rgba(255, 200, 50, 0.6) !important;
}

.agent-bubble[data-agent="ejecutor"].notification {
  animation: ej-glitch 0.15s steps(2) 8 !important;
}

.agent-bubble[data-agent="ejecutor"].tool-flash::after {
  background: rgba(239, 68, 68, 0.5) !important;
  animation: ej-shockwave 0.6s ease-out forwards !important;
  border: 1px solid rgba(255, 100, 50, 0.8);
}

.agent-bubble[data-agent="ejecutor"].tool-flash::before {
  content: '' !important;
  position: absolute !important;
  inset: -2px !important;
  border-radius: 20px !important;
  background: rgba(255, 150, 50, 0.3) !important;
  filter: none !important;
  opacity: 1 !important;
  animation: ej-shockwave-inner 0.4s ease-out forwards !important;
  pointer-events: none !important;
  z-index: 1 !important;
}

/* Ember ring */
.ember-ring {
  position: relative;
  width: 24px;
  height: 24px;
}

.ember-ring span {
  position: absolute;
  inset: 0;
  border: 2px solid transparent;
  border-radius: 50%;
}

.ember-ring span:nth-child(1) {
  border-top-color: #fff;
  border-right-color: rgba(255, 200, 50, 0.8);
  animation: ej-ember-spin 0.8s linear infinite;
}

.ember-ring span:nth-child(2) {
  border-bottom-color: rgba(255, 100, 50, 0.9);
  border-left-color: rgba(255, 50, 50, 0.6);
  animation: ej-ember-spin 1.2s linear infinite reverse;
}

/* ====================== EJECUTOR KEYFRAMES ====================== */

@keyframes ej-heartbeat {
  0%   { transform: scale(1)    !important; box-shadow: 0 4px 20px rgba(239, 68, 68, 0.3)  !important; }
  14%  { transform: scale(1.15) !important; box-shadow: 0 4px 35px rgba(239, 68, 68, 0.7)  !important; }
  28%  { transform: scale(1)    !important; box-shadow: 0 4px 20px rgba(239, 68, 68, 0.3)  !important; }
  42%  { transform: scale(1.22) !important; box-shadow: 0 4px 45px rgba(255, 100, 50, 0.8) !important; }
  70%  { transform: scale(1)    !important; box-shadow: 0 4px 15px rgba(239, 68, 68, 0.2)  !important; }
  100% { transform: scale(1)    !important; box-shadow: 0 4px 20px rgba(239, 68, 68, 0.3)  !important; }
}

@keyframes ej-infrared {
  0% {
    box-shadow: 0 -8px 20px rgba(239, 68, 68, 0.6), 0 8px 20px rgba(239, 68, 68, 0.1) !important;
    transform: rotate(0deg) !important;
  }
  25% {
    box-shadow: 8px 0 20px rgba(239, 68, 68, 0.6), -8px 0 20px rgba(239, 68, 68, 0.1) !important;
  }
  50% {
    box-shadow: 0 8px 20px rgba(239, 68, 68, 0.6), 0 -8px 20px rgba(239, 68, 68, 0.1) !important;
  }
  75% {
    box-shadow: -8px 0 20px rgba(239, 68, 68, 0.6), 8px 0 20px rgba(239, 68, 68, 0.1) !important;
  }
  100% {
    box-shadow: 0 -8px 20px rgba(239, 68, 68, 0.6), 0 8px 20px rgba(239, 68, 68, 0.1) !important;
  }
}

@keyframes ej-forge {
  0%, 100% {
    transform: scale(1) !important;
    box-shadow: 0 4px 20px rgba(239, 68, 68, 0.4) !important;
    filter: brightness(1);
  }
  50% {
    transform: scale(1.06) !important;
    box-shadow: 0 4px 30px rgba(255, 200, 50, 0.8), 0 0 15px rgba(255, 255, 255, 0.3) !important;
    filter: brightness(1.3);
  }
}

@keyframes ej-glitch {
  0%  { transform: translate(0, 0) skewX(0deg) !important; }
  25% { transform: translate(-3px, 1px) skewX(-4deg) !important; box-shadow: -3px 0 8px rgba(0, 255, 255, 0.4), 3px 0 8px rgba(255, 0, 50, 0.4) !important; }
  50% { transform: translate(2px, -2px) skewX(3deg) !important; box-shadow: 3px 0 8px rgba(0, 255, 255, 0.4), -3px 0 8px rgba(255, 0, 50, 0.4) !important; }
  75% { transform: translate(-1px, 2px) skewX(-2deg) !important; }
  100%{ transform: translate(0, 0) skewX(0deg) !important; box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4) !important; }
}

@keyframes ej-shockwave {
  0%   { opacity: 1; transform: scale(1); }
  100% { opacity: 0; transform: scale(1.6); }
}

@keyframes ej-shockwave-inner {
  0%   { opacity: 0.8; transform: scale(1); }
  100% { opacity: 0; transform: scale(1.3); }
}

@keyframes ej-ember-spin {
  from { transform: rotate(0deg); }
  to   { transform: rotate(360deg); }
}

/* ====================== DEFAULT KEYFRAMES ====================== */

@keyframes ab-processing-pulse {
  0%, 100% { box-shadow: 0 8px 24px rgba(245, 158, 11, 0.4) !important; }
  50% { box-shadow: 0 8px 40px rgba(245, 158, 11, 0.8) !important; }
}

@keyframes ab-reading-scan {
  0%, 100% {
    box-shadow: 0 8px 24px rgba(6, 182, 212, 0.4) !important;
    transform: rotate(0deg) !important;
  }
  25% { transform: rotate(-3deg) !important; }
  75% { transform: rotate(3deg) !important; }
  50% { box-shadow: 0 8px 40px rgba(6, 182, 212, 0.8) !important; }
}

@keyframes ab-writing-pulse {
  0%, 100% {
    transform: scale(1) !important;
    box-shadow: 0 8px 24px rgba(16, 185, 129, 0.4) !important;
  }
  50% {
    transform: scale(1.08) !important;
    box-shadow: 0 8px 32px rgba(16, 185, 129, 0.7) !important;
  }
}

@keyframes ab-permission-pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7) !important;
    transform: scale(1.1) !important;
  }
  70% {
    box-shadow: 0 0 0 15px rgba(239, 68, 68, 0) !important;
    transform: scale(1.05) !important;
  }
  100% {
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0) !important;
    transform: scale(1.1) !important;
  }
}

@keyframes ab-permission-shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-2px); }
  75% { transform: translateX(2px); }
}

@keyframes ab-notification-bounce {
  0%, 100% { transform: translateY(0) !important; }
  50% { transform: translateY(-10px) !important; }
}

@keyframes ab-tool-flash {
  0% { opacity: 1; transform: scale(1); }
  100% { opacity: 0; transform: scale(1.4); }
}

@keyframes ab-thinking-dot {
  0%, 80%, 100% { transform: scale(0.6); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

@keyframes ab-icon-breathe {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

/* Prevent touch selection on all children */
.agent-bubble * {
  -webkit-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
  pointer-events: none;
}

/* ====================== LABELS ====================== */

.bubble-label {
  font-weight: 800;
  font-size: 15px;
  letter-spacing: 0.5px;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
  line-height: 1;
}

/* Mobile */
@media (max-width: 768px) {
  .agent-bubble {
    width: 52px;
    height: 52px;
    border-radius: 16px;
  }

  .agent-bubble::before {
    border-radius: 19px;
  }

  .bubble-label {
    font-size: 13px;
  }
}
</style>
