<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useCanvasStore } from '../stores/canvas'
import { connectWithToken, getConnectionInfo } from '../services/webmcp'

const canvasStore = useCanvasStore()
const { isConnected, isReconnecting, connectionStatus, connectionInfo } = storeToRefs(canvasStore)

const isOpen = ref(false)
const tokenInput = ref('')
const isConnecting = ref(false)
const justConnected = ref(false)

// Watch for connection changes and trigger animation
watch(isConnected, (newValue, oldValue) => {
  if (newValue && !oldValue) {
    // Just connected - trigger animation
    justConnected.value = true
    setTimeout(() => {
      justConnected.value = false
    }, 2500) // Animation duration
  }
})

const statusText = computed(() => {
  if (isReconnecting.value) return 'Reconnecting...'
  if (isConnected.value) return 'Connected'
  return 'Disconnected'
})

const statusClass = computed(() => {
  if (isReconnecting.value) return 'warning'
  if (isConnected.value) return 'success'
  return 'error'
})

function toggleDropdown() {
  isOpen.value = !isOpen.value
}

function closeDropdown(e: MouseEvent) {
  const target = e.target as HTMLElement
  if (!target.closest('.connection-dropdown-container')) {
    isOpen.value = false
  }
}

async function handleConnect() {
  if (!tokenInput.value.trim()) return

  isConnecting.value = true
  try {
    const success = await connectWithToken(tokenInput.value.trim())
    if (success) {
      tokenInput.value = ''
      canvasStore.showNotification('Connecting to WebMCP...', 'info')
    } else {
      canvasStore.showNotification('Invalid token', 'error')
    }
  } catch (e: any) {
    canvasStore.showNotification(e.message || 'Connection failed', 'error')
  } finally {
    isConnecting.value = false
  }
}

async function handlePaste() {
  try {
    const text = await navigator.clipboard.readText()
    tokenInput.value = text
  } catch {
    // Clipboard access denied
  }
}

onMounted(() => {
  document.addEventListener('click', closeDropdown)
})

onUnmounted(() => {
  document.removeEventListener('click', closeDropdown)
})
</script>

<template>
  <div class="connection-dropdown-container">
    <button class="dropdown-trigger" :class="{ 'just-connected': justConnected }" @click.stop="toggleDropdown" title="WebMCP Connection">
      <span class="status-dot" :class="statusClass"></span>
      <span>MCP</span>
      <svg class="chevron" :class="{ open: isOpen }" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polyline points="6 9 12 15 18 9"/>
      </svg>
    </button>

    <div v-if="isOpen" class="dropdown-menu" @click.stop>
      <div class="dropdown-header">
        <span class="header-title">WebMCP</span>
        <span class="status-badge" :class="statusClass">{{ statusText }}</span>
      </div>

      <!-- Disconnected: Show token input -->
      <div v-if="!isConnected" class="connect-section">
        <p class="connect-hint">Paste the token from Claude Code:</p>
        <div class="token-input-group">
          <input
            v-model="tokenInput"
            type="text"
            placeholder="eyJ..."
            class="token-input"
            @keyup.enter="handleConnect"
          />
          <button class="paste-btn" @click="handlePaste" title="Paste from clipboard">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
              <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
            </svg>
          </button>
        </div>
        <button
          class="connect-btn"
          @click="handleConnect"
          :disabled="!tokenInput.trim() || isConnecting"
        >
          {{ isConnecting ? 'Connecting...' : 'Connect' }}
        </button>
      </div>

      <!-- Connected: Show connection info -->
      <div v-else class="info-section">
        <div v-if="connectionInfo" class="info-grid">
          <div class="info-item">
            <span class="info-label">Channel</span>
            <span class="info-value">{{ connectionInfo.channel || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">Server</span>
            <span class="info-value">{{ connectionInfo.server || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">Tools</span>
            <span class="info-value">{{ connectionInfo.tools?.length || 0 }} registered</span>
          </div>
        </div>
        <div v-else class="info-empty">
          Connection active
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.connection-dropdown-container {
  position: relative;
  overflow: visible;
}

.dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: var(--bg-hover);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  color: var(--text-secondary);
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s ease;
}

.dropdown-trigger:hover {
  background: var(--bg-tertiary, rgba(255,255,255,0.1));
  color: var(--text-primary);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.status-dot.success {
  background: #10b981;
  box-shadow: 0 0 6px rgba(16, 185, 129, 0.6);
}

.status-dot.warning {
  background: #f59e0b;
  animation: pulse 1.5s infinite;
}

.status-dot.error {
  background: #6b7280;
}

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

.chevron {
  transition: transform 0.2s ease;
}

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

.dropdown-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  min-width: 260px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
  z-index: 1000;
  overflow: hidden;
}

.dropdown-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--border-color);
}

.header-title {
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--text-secondary);
}

.status-badge {
  font-size: 0.7rem;
  font-weight: 500;
  padding: 0.2rem 0.5rem;
  border-radius: 9999px;
}

.status-badge.success {
  background: rgba(16, 185, 129, 0.15);
  color: #10b981;
}

.status-badge.warning {
  background: rgba(245, 158, 11, 0.15);
  color: #f59e0b;
}

.status-badge.error {
  background: rgba(107, 114, 128, 0.15);
  color: #9ca3af;
}

.connect-section {
  padding: 1rem;
}

.connect-hint {
  font-size: 0.8rem;
  color: var(--text-secondary);
  margin: 0 0 0.75rem 0;
}

.token-input-group {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.token-input {
  flex: 1;
  padding: 0.5rem 0.75rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
  font-size: 0.8rem;
  font-family: var(--font-mono);
}

.token-input:focus {
  outline: none;
  border-color: var(--accent);
}

.token-input::placeholder {
  color: var(--text-muted);
}

.paste-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.paste-btn:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
  border-color: var(--accent);
}

.connect-btn {
  width: 100%;
  padding: 0.6rem;
  background: var(--accent);
  border: none;
  border-radius: 6px;
  color: var(--accent-text);
  font-size: 0.8rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.connect-btn:hover:not(:disabled) {
  background: var(--accent-hover);
}

.connect-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.info-section {
  padding: 1rem;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.4rem 0;
}

.info-label {
  font-size: 0.75rem;
  color: var(--text-muted);
}

.info-value {
  font-size: 0.8rem;
  color: var(--text-primary);
  font-family: var(--font-mono);
}

.info-empty {
  font-size: 0.8rem;
  color: var(--text-secondary);
  text-align: center;
  padding: 0.5rem 0;
}

/* Connection animation - Smooth effect */
.dropdown-trigger.just-connected {
  animation: connectionPulse 2s ease-in-out;
}

@keyframes connectionPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
    border-color: var(--border-color);
  }
  15% {
    transform: scale(1.05);
    box-shadow: 0 0 8px rgba(16, 185, 129, 0.4),
                0 0 20px rgba(16, 185, 129, 0.2);
    border-color: #10b981;
  }
  30% {
    transform: scale(1);
    box-shadow: 0 0 12px rgba(16, 185, 129, 0.5),
                0 0 30px rgba(16, 185, 129, 0.25);
    border-color: #34d399;
  }
  50% {
    box-shadow: 0 0 15px rgba(16, 185, 129, 0.4),
                0 0 35px rgba(16, 185, 129, 0.2);
    border-color: #10b981;
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
    border-color: var(--border-color);
  }
}
</style>
