<script setup lang="ts">
import { ref, onMounted, computed } from "vue"

// ─── State ──────────────────────────────────────────────────────────

const loading = ref(true)
const error = ref("")

// n8n detection
const isN8nPage = ref(false)
const workflowId = ref("")
const workflowName = ref("")
const n8nBaseUrl = ref("")
const workflowLoaded = ref(false)

// MCP connection
const mcpConnected = ref(false)

// Platform selection
const selectedPlatform = ref<string | null>(null)
const launching = ref(false)

// ─── Computed ───────────────────────────────────────────────────────

const canLaunch = computed(() => isN8nPage.value && workflowLoaded.value && mcpConnected.value)

const statusText = computed(() => {
  if (!mcpConnected.value) return "⚠️ MCP Server chưa kết nối"
  if (!isN8nPage.value) return "📋 Mở một workflow trên n8n để bắt đầu"
  if (!workflowLoaded.value) return "⏳ Đang tải workflow..."
  return `✅ Sẵn sàng chỉnh sửa "${workflowName.value}"`
})

const statusClass = computed(() => {
  if (!mcpConnected.value) return "status-warning"
  if (!isN8nPage.value) return "status-info"
  if (!workflowLoaded.value) return "status-loading"
  return "status-ready"
})

// ─── Platforms ──────────────────────────────────────────────────────

const platforms = [
  { id: "chatgpt", name: "ChatGPT", url: "https://chatgpt.com", icon: "🤖", color: "#10a37f" },
  { id: "gemini", name: "Gemini", url: "https://gemini.google.com/app", icon: "✨", color: "#4285f4" },
  { id: "deepseek", name: "DeepSeek", url: "https://chat.deepseek.com", icon: "🔮", color: "#6366f1" },
  { id: "grok", name: "Grok", url: "https://grok.com", icon: "⚡", color: "#1da1f2" },
]

// ─── Lifecycle ──────────────────────────────────────────────────────

onMounted(async () => {
  try {
    // 1. Check MCP connection
    const mcpStatus = await sendMessage({ type: "n8n-mcp:status" })
    mcpConnected.value = mcpStatus?.connected || false

    // 2. Check active tab
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
    if (tab?.url) {
      detectN8nWorkflow(tab)
    }
  } catch (err: any) {
    error.value = err.message
  } finally {
    loading.value = false
  }
})

// ─── n8n Detection ──────────────────────────────────────────────────

async function detectN8nWorkflow(tab: chrome.tabs.Tab) {
  if (!tab.url) return

  // Try to extract workflow ID from URL
  const patterns = [
    /\/workflow\/([a-zA-Z0-9_-]+)/,
    /\/workflows\/([a-zA-Z0-9_-]+)/,
  ]

  let id: string | null = null
  for (const pattern of patterns) {
    const match = tab.url.match(pattern)
    if (match?.[1]) {
      id = match[1]
      break
    }
  }

  if (!id) return

  isN8nPage.value = true
  workflowId.value = id

  const parsed = new URL(tab.url)
  n8nBaseUrl.value = `${parsed.protocol}//${parsed.host}`

  // Fetch workflow details via MCP
  try {
    const result = await sendMessage({
      type: "n8n-context:fetch-workflow",
      workflowId: id,
    })

    if (result?.success && result.workflow) {
      const wf = typeof result.workflow === "string" ? JSON.parse(result.workflow) : result.workflow
      workflowName.value = wf?.name || `Workflow ${id}`

      // Build summary
      const nodes = wf?.nodes || []
      const summary = nodes.map((n: any) => `- ${n.name} (${n.type})`).join("\n")

      // Save context to background
      await sendMessage({
        type: "n8n-context:set",
        context: {
          workflowId: id,
          workflowName: workflowName.value,
          workflowSummary: `Workflow: "${workflowName.value}"\nNodes (${nodes.length}):\n${summary}`,
          workflowJson: wf,
          n8nBaseUrl: n8nBaseUrl.value,
          capturedAt: Date.now(),
          sourceTabId: tab.id!,
        },
      })

      workflowLoaded.value = true
    } else {
      // MCP not available — still allow with basic info
      workflowName.value = `Workflow ${id}`
      workflowLoaded.value = true

      await sendMessage({
        type: "n8n-context:set",
        context: {
          workflowId: id,
          workflowName: workflowName.value,
          workflowSummary: `Workflow ID: ${id} (details unavailable — MCP not connected)`,
          n8nBaseUrl: n8nBaseUrl.value,
          capturedAt: Date.now(),
          sourceTabId: tab.id!,
        },
      })
    }
  } catch (err: any) {
    // Fallback: use basic info
    workflowName.value = `Workflow ${id}`
    workflowLoaded.value = true
  }
}

// ─── Launch Platform ────────────────────────────────────────────────

async function launchPlatform(platform: typeof platforms[0]) {
  if (!canLaunch.value) return

  launching.value = true
  selectedPlatform.value = platform.id

  try {
    // Open new tab with the AI platform
    const newTab = await chrome.tabs.create({ url: platform.url })

    // The content script (superassistant/index.ts) on the new tab will
    // automatically fetch context from background and inject it into chat

    // Close popup
    setTimeout(() => window.close(), 300)
  } catch (err: any) {
    error.value = `Failed to open ${platform.name}: ${err.message}`
    launching.value = false
    selectedPlatform.value = null
  }
}

// ─── Helpers ────────────────────────────────────────────────────────

function sendMessage(msg: any): Promise<any> {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage(msg, (response) => {
      resolve(response || {})
    })
  })
}
</script>

<template>
  <div class="workflow-launcher">
    <!-- Status Bar -->
    <div class="status-bar" :class="statusClass">
      <span class="status-dot"></span>
      <span class="status-text">{{ statusText }}</span>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <span>Detecting workflow...</span>
    </div>

    <!-- Error -->
    <div v-else-if="error" class="error-state">
      <span class="error-icon">⚠️</span>
      <span>{{ error }}</span>
    </div>

    <!-- Not on n8n -->
    <div v-else-if="!isN8nPage" class="empty-state">
      <div class="empty-icon">🔗</div>
      <h3>Open a Workflow</h3>
      <p>Navigate to your n8n instance and open a workflow to start editing with AI.</p>
      <div class="hint">
        <code>https://your-n8n.com/workflow/abc123</code>
      </div>
    </div>

    <!-- Workflow Detected — Show Platforms -->
    <div v-else class="workflow-detected">
      <!-- Workflow Info Card -->
      <div class="workflow-card">
        <div class="workflow-icon">⚡</div>
        <div class="workflow-info">
          <div class="workflow-name">{{ workflowName }}</div>
          <div class="workflow-id">ID: {{ workflowId }}</div>
          <div class="workflow-url">{{ n8nBaseUrl }}</div>
        </div>
      </div>

      <!-- Platform Grid -->
      <div class="platform-section">
        <h4 class="section-title">Edit with AI</h4>
        <div class="platform-grid">
          <button
            v-for="p in platforms"
            :key="p.id"
            class="platform-btn"
            :class="{ selected: selectedPlatform === p.id, launching: launching && selectedPlatform === p.id }"
            :style="{ '--accent': p.color }"
            :disabled="!canLaunch || launching"
            @click="launchPlatform(p)"
          >
            <span class="platform-icon">{{ p.icon }}</span>
            <span class="platform-name">{{ p.name }}</span>
            <span v-if="launching && selectedPlatform === p.id" class="platform-spinner"></span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.workflow-launcher {
  width: 320px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: #e4e4e7;
}

/* ── Status Bar ── */
.status-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 8px;
  margin-bottom: 12px;
  font-size: 12px;
  font-weight: 500;
}

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

.status-info { background: rgba(59, 130, 246, 0.1); color: #93c5fd; }
.status-info .status-dot { background: #3b82f6; }

.status-warning { background: rgba(245, 158, 11, 0.1); color: #fbbf24; }
.status-warning .status-dot { background: #f59e0b; }

.status-loading { background: rgba(139, 92, 246, 0.1); color: #c4b5fd; }
.status-loading .status-dot { background: #8b5cf6; animation: pulse 1.5s infinite; }

.status-ready { background: rgba(34, 197, 94, 0.1); color: #86efac; }
.status-ready .status-dot { background: #22c55e; }

/* ── States ── */
.loading-state, .error-state {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  justify-content: center;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.5);
}

.empty-state {
  text-align: center;
  padding: 20px 16px;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.empty-state h3 {
  margin: 0 0 4px;
  font-size: 15px;
  font-weight: 600;
  color: #e4e4e7;
}

.empty-state p {
  margin: 0 0 12px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.5);
  line-height: 1.5;
}

.hint code {
  font-size: 11px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.06);
  border-radius: 4px;
  color: rgba(255, 255, 255, 0.4);
}

/* ── Workflow Card ── */
.workflow-card {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  background: rgba(255, 109, 90, 0.06);
  border: 1px solid rgba(255, 109, 90, 0.12);
  border-radius: 10px;
  margin-bottom: 14px;
}

.workflow-icon {
  font-size: 20px;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, rgba(255, 109, 90, 0.2), rgba(255, 154, 68, 0.2));
  border-radius: 8px;
  flex-shrink: 0;
}

.workflow-name {
  font-size: 13px;
  font-weight: 600;
  color: #ff8a65;
  margin-bottom: 2px;
}

.workflow-id {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.4);
  font-family: 'SF Mono', Monaco, Consolas, monospace;
}

.workflow-url {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.25);
  margin-top: 2px;
}

/* ── Platform Grid ── */
.section-title {
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: rgba(255, 255, 255, 0.4);
  margin: 0 0 8px;
}

.platform-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
}

.platform-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 10px;
  color: #e4e4e7;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.platform-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.08);
  border-color: var(--accent, rgba(255, 255, 255, 0.15));
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.platform-btn:active:not(:disabled) {
  transform: scale(0.97);
}

.platform-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.platform-btn.selected {
  border-color: var(--accent);
  background: rgba(255, 255, 255, 0.08);
}

.platform-icon {
  font-size: 18px;
}

.platform-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-top-color: var(--accent, #fff);
  border-radius: 50%;
  animation: spin 0.6s linear infinite;
  margin-left: auto;
}

/* ── Animations ── */
.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-top-color: #8b5cf6;
  border-radius: 50%;
  animation: spin 0.6s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}
</style>
