<script setup lang="ts">
import { onMounted, onUnmounted, watch } from 'vue'
import { useAgentsStore, CATEGORY_META, formatSize } from '../stores/agents'
import type { AgentTab } from '../stores/agents'
import ToolsManager from '../components/agents/ToolsManager.vue'
import McpManager from '../components/agents/McpManager.vue'
import PluginsManager from '../components/agents/PluginsManager.vue'
import HooksManager from '../components/agents/HooksManager.vue'
import SkillsManager from '../components/agents/SkillsManager.vue'

const store = useAgentsStore()

const tabs: { key: AgentTab; label: string; icon: string }[] = [
  { key: 'files', label: 'Files', icon: 'M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z|M14 2v6h6' },
  { key: 'tools', label: 'Tools', icon: 'M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z' },
  { key: 'mcps', label: 'MCPs', icon: 'M22 12h-4l-3 9L9 3l-3 9H2' },
  { key: 'plugins', label: 'Plugins', icon: 'M12 2L2 7l10 5 10-5-10-5z|M2 17l10 5 10-5|M2 12l10 5 10-5' },
  { key: 'hooks', label: 'Hooks', icon: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71|M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71' },
  { key: 'skills', label: 'Skills', icon: 'M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z|M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z' }
]

function handleKeydown(e: KeyboardEvent) {
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault()
    if (store.activeTab === 'files' && store.isDirty) store.saveFile()
    else if (store.activeTab === 'tools' && store.configDirty) store.savePermissions()
    else if (store.activeTab === 'hooks') store.saveHooks()
    else if (store.activeTab === 'mcps') store.saveMcpServers()
  }
}

function switchTab(tab: AgentTab) {
  store.activeTab = tab
  if (tab !== 'files') {
    store.loadTabData()
  }
}

function shortPath(path: string): string {
  const parts = path.split('/')
  if (parts.length <= 2) return parts[parts.length - 1]
  return parts.slice(1).join('/')
}

onMounted(() => {
  store.fetchAgents()
  window.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<template>
  <div class="agents-page">
    <!-- Top bar: agent selector + main tabs -->
    <div class="agents-topbar">
      <div class="agent-tabs">
        <button
          v-for="agent in store.agents"
          :key="agent.id"
          class="agent-tab"
          :class="{ active: store.selectedAgentId === agent.id }"
          @click="store.selectAgent(agent.id)"
        >
          <span class="agent-tab-name">{{ agent.name }}</span>
          <span class="agent-tab-count">{{ agent.files.length }}</span>
        </button>
      </div>

      <nav class="main-tabs">
        <button
          v-for="tab in tabs"
          :key="tab.key"
          class="main-tab"
          :class="{ active: store.activeTab === tab.key }"
          @click="switchTab(tab.key)"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24"
            fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
          >
            <path v-for="(d, i) in tab.icon.split('|')" :key="i" :d="d"/>
          </svg>
          <span>{{ tab.label }}</span>
        </button>
      </nav>
    </div>

    <!-- Files tab: sidebar + editor -->
    <div v-if="store.activeTab === 'files'" class="files-layout">
      <aside class="agents-sidebar">
        <!-- Loading -->
        <div v-if="store.loading" class="sidebar-loading">Loading agents...</div>

        <!-- Category groups -->
        <div v-else-if="store.selectedAgent" class="category-list">
          <div v-for="cat in store.groupedFiles" :key="cat.key" class="category-group">
            <button class="category-header" @click="store.toggleCategory(cat.key)">
              <svg
                class="category-icon"
                xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"
                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                :style="{ color: cat.color }"
              >
                <path v-for="(d, i) in cat.icon.split('|')" :key="i" :d="d"/>
              </svg>
              <span class="category-label">{{ cat.label }}</span>
              <span class="category-count" :style="{ background: cat.color + '18', color: cat.color }">{{ cat.files.length }}</span>
              <svg
                class="category-chevron"
                :class="{ collapsed: store.collapsedCategories.has(cat.key) }"
                xmlns="http://www.w3.org/2000/svg" width="12" height="12" 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="!store.collapsedCategories.has(cat.key)" class="category-files">
              <button
                v-for="file in cat.files"
                :key="file.path"
                class="file-row"
                :class="{ active: store.openFile?.path === file.path }"
                @click="store.loadFile(store.selectedAgentId!, file)"
                :title="file.path"
              >
                <span class="file-type-dot" :style="{ background: cat.color }"></span>
                <span class="file-label">{{ shortPath(file.path) }}</span>
                <span class="file-size">{{ formatSize(file.size) }}</span>
                <span v-if="store.openFile?.path === file.path && store.isDirty" class="unsaved-dot"></span>
              </button>
            </div>
          </div>

          <div v-if="!store.groupedFiles.length" class="sidebar-empty">No files found</div>
        </div>
      </aside>

      <main class="editor-panel">
        <template v-if="store.openFile">
          <div class="editor-header">
            <div class="editor-title">
              <span
                class="editor-cat-dot"
                :style="{ background: CATEGORY_META[store.openFile.category]?.color }"
              ></span>
              <span class="editor-path">{{ store.openFile.path }}</span>
              <span v-if="store.isDirty" class="unsaved-badge">Unsaved</span>
            </div>
            <div class="editor-actions">
              <button
                class="btn btn-secondary"
                :disabled="!store.isDirty"
                @click="store.revertFile()"
              >Revert</button>
              <button
                class="btn btn-primary"
                :disabled="!store.isDirty || store.saving"
                @click="store.saveFile()"
              >{{ store.saving ? 'Saving...' : 'Save' }}</button>
            </div>
          </div>

          <div v-if="store.error" class="editor-error">{{ store.error }}</div>

          <textarea
            class="editor-textarea"
            v-model="store.openFile.content"
            spellcheck="false"
          ></textarea>
        </template>

        <div v-else class="editor-empty">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/>
            <polyline points="14 2 14 8 20 8"/>
          </svg>
          <p>Select a file to view or edit</p>
          <span class="editor-hint">Ctrl+S to save</span>
        </div>
      </main>
    </div>

    <!-- Other tabs: full-width components -->
    <div v-if="store.activeTab !== 'files'" class="tab-content">
      <ToolsManager v-if="store.activeTab === 'tools'" />
      <McpManager v-if="store.activeTab === 'mcps'" />
      <PluginsManager v-if="store.activeTab === 'plugins'" />
      <HooksManager v-if="store.activeTab === 'hooks'" />
      <SkillsManager v-if="store.activeTab === 'skills'" />
    </div>
  </div>
</template>

<style scoped>
.agents-page {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

/* ── Top bar ── */
.agents-topbar {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.5rem 0.75rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  flex-shrink: 0;
}

.agent-tabs {
  display: flex;
  gap: 2px;
  overflow-x: auto;
  flex-shrink: 0;
}

.agent-tab {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.375rem 0.625rem;
  background: transparent;
  border: 1px solid transparent;
  border-radius: 6px;
  color: var(--text-muted);
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.15s;
}

.agent-tab:hover {
  color: var(--text-primary);
  background: var(--bg-hover);
}

.agent-tab.active {
  color: var(--text-primary);
  background: var(--bg-primary);
  border-color: var(--border-color);
  font-weight: 600;
}

.agent-tab-name {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.agent-tab-count {
  font-size: 0.625rem;
  padding: 0.0625rem 0.375rem;
  background: var(--bg-hover);
  border-radius: 999px;
  color: var(--text-muted);
}

.agent-tab.active .agent-tab-count {
  background: rgba(99, 102, 241, 0.15);
  color: #6366f1;
}

/* Main tabs */
.main-tabs {
  display: flex;
  gap: 2px;
  margin-left: auto;
  border-left: 1px solid var(--border-color);
  padding-left: 0.75rem;
}

.main-tab {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.375rem 0.625rem;
  background: transparent;
  border: 1px solid transparent;
  border-radius: 6px;
  color: var(--text-muted);
  font-size: 0.6875rem;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.15s;
}

.main-tab:hover {
  color: var(--text-primary);
  background: var(--bg-hover);
}

.main-tab.active {
  color: #6366f1;
  background: rgba(99, 102, 241, 0.08);
  border-color: rgba(99, 102, 241, 0.2);
  font-weight: 600;
}

.main-tab svg {
  flex-shrink: 0;
}

/* ── Files layout ── */
.files-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.agents-sidebar {
  width: 320px;
  min-width: 320px;
  background: var(--bg-secondary);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Category list */
.category-list {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem 0;
}

.category-group {
  margin-bottom: 2px;
}

.category-header {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.875rem;
  background: none;
  border: none;
  color: var(--text-primary);
  font-size: 0.75rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.15s;
}

.category-header:hover {
  background: var(--bg-hover);
}

.category-icon {
  flex-shrink: 0;
}

.category-label {
  flex: 1;
  text-align: left;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  font-size: 0.6875rem;
}

.category-count {
  font-size: 0.625rem;
  font-weight: 600;
  padding: 0.0625rem 0.4375rem;
  border-radius: 999px;
}

.category-chevron {
  color: var(--text-muted);
  transition: transform 0.2s;
  flex-shrink: 0;
}

.category-chevron.collapsed {
  transform: rotate(-90deg);
}

/* File rows */
.category-files {
  padding: 0 0 0.25rem;
}

.file-row {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.3125rem 0.875rem 0.3125rem 2rem;
  background: none;
  border: none;
  color: var(--text-secondary);
  font-size: 0.75rem;
  cursor: pointer;
  transition: all 0.12s;
  text-align: left;
}

.file-row:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.file-row.active {
  background: rgba(99, 102, 241, 0.08);
  color: #6366f1;
}

.file-type-dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  flex-shrink: 0;
  opacity: 0.6;
}

.file-row.active .file-type-dot {
  opacity: 1;
}

.file-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 0.6875rem;
}

.file-size {
  font-size: 0.625rem;
  color: var(--text-muted);
  flex-shrink: 0;
}

.unsaved-dot {
  width: 6px;
  height: 6px;
  background: #f59e0b;
  border-radius: 50%;
  flex-shrink: 0;
}

.sidebar-loading,
.sidebar-empty {
  padding: 2rem;
  text-align: center;
  color: var(--text-muted);
  font-size: 0.8125rem;
}

/* ── Editor ── */
.editor-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--bg-primary);
}

.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.625rem 1.25rem;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-secondary);
  gap: 1rem;
}

.editor-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: 0;
}

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

.editor-path {
  font-size: 0.8125rem;
  font-weight: 500;
  color: var(--text-primary);
  font-family: 'Consolas', 'Monaco', monospace;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unsaved-badge {
  padding: 0.125rem 0.5rem;
  background: rgba(245, 158, 11, 0.15);
  color: #f59e0b;
  font-size: 0.6875rem;
  font-weight: 600;
  border-radius: 999px;
  flex-shrink: 0;
}

.editor-actions {
  display: flex;
  gap: 0.5rem;
  flex-shrink: 0;
}

.btn {
  padding: 0.3125rem 0.75rem;
  font-size: 0.75rem;
  font-weight: 500;
  border-radius: 6px;
  border: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.15s;
}

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

.btn-secondary {
  background: var(--bg-secondary);
  color: var(--text-secondary);
}

.btn-secondary:hover:not(:disabled) {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.btn-primary {
  background: #6366f1;
  color: white;
  border-color: #6366f1;
}

.btn-primary:hover:not(:disabled) {
  background: #4f46e5;
  border-color: #4f46e5;
}

.editor-error {
  padding: 0.625rem 1.25rem;
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
  font-size: 0.8125rem;
  border-bottom: 1px solid rgba(239, 68, 68, 0.2);
}

.editor-textarea {
  flex: 1;
  padding: 1rem 1.25rem;
  background: var(--bg-primary);
  color: var(--text-primary);
  border: none;
  outline: none;
  resize: none;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.8125rem;
  line-height: 1.6;
  tab-size: 2;
}

.editor-empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  color: var(--text-muted);
}

.editor-empty p {
  font-size: 0.875rem;
  margin: 0;
}

.editor-hint {
  font-size: 0.6875rem;
  opacity: 0.5;
}

/* ── Tab content ── */
.tab-content {
  flex: 1;
  overflow: hidden;
  display: flex;
}
</style>
