<template>
  <div class="agent-view scanlines">
    <!-- Background -->
    <div class="bg-grid"></div>
    <div class="bg-glow"></div>
    <div class="bg-particles">
      <span v-for="p in bgParticles" :key="p.id" class="bg-particle" :style="p.style"></span>
    </div>

    <!-- Header -->
    <div class="view-header">
      <div class="header-title">
        <span class="title-bracket">[</span>
        <span class="title-text">AGENT COMMAND CENTER</span>
        <span class="title-bracket">]</span>
      </div>
      <div class="header-actions">
        <button class="btn-icon" @click="refreshStats" :class="{ spinning: loading }" title="刷新状态">
          <RefreshCw :size="14" />
        </button>
        <button class="btn-add" @click="addModalOpen = true">
          <Plus :size="14" />
          <span>新增智能体</span>
        </button>
        <div class="status-bar">
          <span class="status-dot" :class="connectionStatus"></span>
          <span class="status-label">{{ connectionLabel }}</span>
        </div>
      </div>
    </div>

    <!-- Nodes Canvas -->
    <div class="nodes-canvas" ref="canvasRef">
      <!-- SVG for connection lines (dynamically sized to canvas) -->
      <svg class="conn-svg" ref="svgRef">
        <defs>
          <filter id="lineGlow">
            <feGaussianBlur stdDeviation="3" result="blur"/>
            <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
        </defs>
        <path
          v-for="sub in subAgents"
          :key="`line-${sub.id}`"
          :d="getLinePath(sub.id)"
          class="conn-path"
          :class="{ active: activeLine === sub.id }"
        />
        <circle r="5" class="pulse-dot">
          <animateMotion
            v-if="firingLine"
            :dur="pulseDuration + 'ms'"
            :path="getLinePath(firingLine)"
            fill="freeze"
            @end="onPulseEnd"
          />
        </circle>
      </svg>

      <!-- Master node -->
      <div
        ref="masterCardRef"
        class="node-card node-master"
        :class="{ selected: selectedAgentId === 'master' }"
        :style="masterNodeStyle"
        @click="selectAgent('master')"
      >
        <div class="node-inner">
          <div class="node-corner tl"></div>
          <div class="node-corner tr"></div>
          <div class="node-corner bl"></div>
          <div class="node-corner br"></div>
          <div class="node-status" :class="getStatusClass('master')">
            <span class="status-ring"></span>
          </div>
          <div class="node-label">MASTER CORE</div>
          <div class="node-name">{{ getAgentName('master') }}</div>
          <div class="node-role">{{ getAgentRole('master') }}</div>
          <div class="node-desc">{{ getAgentDesc('master') }}</div>
          <div class="node-footer">
            <span class="node-stat">
              <span class="stat-label">调用</span>
              <span class="stat-val">{{ agentData['master']?.callCount || 0 }}</span>
            </span>
            <span v-if="agentData['master']?.currentTask" class="node-task-tag">
              {{ agentData['master'].currentTask }}
            </span>
          </div>
        </div>
      </div>

      <!-- Sub-agent nodes -->
      <div
        v-for="sub in subAgents"
        :key="sub.id"
        :ref="el => setSubRef(sub.id, el as HTMLElement)"
        class="node-card node-sub"
        :class="{ selected: selectedAgentId === sub.id, disabled: !sub.enabled }"
        :style="getSubNodeStyle(sub)"
        @click="selectAgent(sub.id)"
      >
        <div class="node-inner">
          <div class="node-corner tl"></div>
          <div class="node-corner tr"></div>
          <div class="node-corner bl"></div>
          <div class="node-corner br"></div>
          <div class="node-status" :class="getStatusClass(sub.id)">
            <span class="status-ring"></span>
          </div>
          <div class="node-label">{{ sub.name }}</div>
          <div class="node-role">{{ sub.role }}</div>
          <div class="node-desc">{{ sub.description }}</div>
          <div class="node-footer">
            <span class="node-stat">
              <span class="stat-label">调用</span>
              <span class="stat-val">{{ agentData[sub.id]?.callCount || 0 }}</span>
            </span>
            <span v-if="agentData[sub.id]?.currentTask" class="node-task-tag">
              {{ agentData[sub.id].currentTask }}
            </span>
            <span v-else class="node-idle">待机中</span>
          </div>
          <div class="rel-label">{{ sub.relLabel }}</div>
        </div>
      </div>

    </div>

    <!-- Right Drawer -->
    <Transition :css="false" @enter="animateIn" @leave="animateOut">
      <div v-if="drawerOpen" class="config-drawer">
        <div class="drawer-header">
          <span class="drawer-title">// AGENT CONFIGURATION</span>
          <button class="btn-close" @click="drawerOpen = false"><X :size="16" /></button>
        </div>
        <div class="drawer-body" v-if="editAgent">
          <div class="form-group">
            <label class="form-label">// AGENT NAME</label>
            <input v-model="editAgent.name" type="text" class="form-input" />
          </div>
          <div class="form-group">
            <label class="form-label">// ROLE</label>
            <input v-model="editAgent.role" type="text" class="form-input" />
          </div>
          <div class="form-group">
            <label class="form-label">// DESCRIPTION</label>
            <textarea v-model="editAgent.description" class="form-textarea" rows="2"></textarea>
          </div>
          <div class="form-group flex-1">
            <label class="form-label">// SYSTEM PROMPT</label>
            <textarea v-model="editAgent.systemPrompt" class="form-textarea code-textarea" rows="10"></textarea>
          </div>
          <div class="form-group">
            <label class="form-label">// STATUS</label>
            <div class="toggle-row">
              <span class="toggle-label" :class="{ dim: editAgent.enabled }">DISABLED</span>
              <button class="toggle-btn" :class="{ active: editAgent.enabled }" @click="editAgent.enabled = !editAgent.enabled">
                <span class="toggle-knob"></span>
              </button>
              <span class="toggle-label" :class="{ dim: !editAgent.enabled }">ENABLED</span>
            </div>
          </div>
          <div class="drawer-actions">
            <button class="btn-secondary" @click="resetConfig">重置</button>
            <button class="btn-primary" @click="saveConfig" :disabled="saving">
              <span v-if="saving" class="btn-loader"></span>
              {{ saving ? '保存中...' : '保存配置' }}
            </button>
          </div>
        </div>
      </div>
    </Transition>

    <!-- Add Modal -->
    <Transition :css="false" @enter="animateIn" @leave="animateOut">
      <div v-if="addModalOpen" class="modal-overlay" @click.self="addModalOpen = false">
        <div class="modal-card">
          <div class="modal-header">
            <span class="modal-title">// ADD NEW AGENT</span>
            <button class="btn-close" @click="addModalOpen = false"><X :size="16" /></button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label class="form-label">// AGENT NAME</label>
              <input v-model="newAgent.name" type="text" class="form-input" placeholder="例如: CODER" />
            </div>
            <div class="form-group">
              <label class="form-label">// ROLE KEY (英文唯一标识)</label>
              <input v-model="newAgent.roleKey" type="text" class="form-input" placeholder="例如: coder" />
            </div>
            <div class="form-group">
              <label class="form-label">// ROLE</label>
              <input v-model="newAgent.role" type="text" class="form-input" placeholder="中文角色名" />
            </div>
            <div class="form-group">
              <label class="form-label">// DESCRIPTION</label>
              <textarea v-model="newAgent.description" class="form-textarea" rows="2" placeholder="描述此 Agent 的职责..."></textarea>
            </div>
            <div class="form-group flex-1">
              <label class="form-label">// SYSTEM PROMPT</label>
              <textarea v-model="newAgent.systemPrompt" class="form-textarea code-textarea" rows="6" placeholder="输入系统提示词..."></textarea>
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn-secondary" @click="addModalOpen = false">取消</button>
            <button class="btn-primary" @click="addAgent" :disabled="!newAgent.name || !newAgent.roleKey">创建智能体</button>
          </div>
        </div>
      </div>
    </Transition>

    <Transition :css="false" @enter="fadeIn" @leave="fadeOut">
      <div v-if="drawerOpen" class="drawer-backdrop" @click="drawerOpen = false"></div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { animate, type AnimationControls } from 'motion'
import { RefreshCw, X, Plus } from 'lucide-vue-next'
import { DEFAULT_AGENTS, RELATION_LABELS } from '@/data/agents'
import type { Agent } from '@/data/agents'
import { agentApi } from '@/api/agent'

// ── Node dimensions ──────────────────────────────────────────────
const NODE_W = 200
const NODE_H = 170
const MASTER_TOP = 48       // px from top
const SUB_TOP = 350         // px from top
// Horizontal percentages: master=50%, subs=12.5/37.5/62.5/87.5%
const SUB_XS = [12.5, 37.5, 62.5, 87.5]

// ── Sub-agent static data ────────────────────────────────────────
const subAgents = [
  { id: 'planner',   name: 'PLANNER',   role: '规划者', description: '制定任务计划，拆解复杂目标为可执行步骤', relLabel: RELATION_LABELS['master-planner'] },
  { id: 'executor',  name: 'EXECUTOR',  role: '执行者', description: '调用工具执行具体操作，创建/更新/删除系统资源', relLabel: RELATION_LABELS['master-executor'] },
  { id: 'librarian', name: 'LIBRARIAN', role: '知识官', description: '管理知识库和知识图谱，检索相关信息，更新记忆', relLabel: RELATION_LABELS['master-librarian'] },
  { id: 'analyst',   name: 'ANALYST',   role: '分析师', description: '分析工作数据，生成统计报告，提供洞察建议', relLabel: RELATION_LABELS['master-analyst'] },
]


// ── Refs ────────────────────────────────────────────────────────
const canvasRef = ref<HTMLElement>()
const svgRef = ref<SVGElement>()
const masterCardRef = ref<HTMLElement>()
const subRefs: Record<string, HTMLElement> = {}
const masterAnim = ref<AnimationControls | null>(null)
const subAnims: Record<string, AnimationControls> = {}
const hoverAnims: Record<string, AnimationControls | null> = {}
// Background particles
const bgParticles = Array.from({ length: 60 }, (_, i) => {
  const d = 3 + Math.random() * 5
  const delay = Math.random() * 4
  const o = 0.25 + Math.random() * 0.5
  const size = 1 + Math.random() * 2.5
  return {
    id: i,
    style: {
      left: `${Math.random() * 98}%`,
      top: `${Math.random() * 95}%`,
      width: `${size}px`,
      height: `${size}px`,
      '--d': `${d}s`,
      '--delay': `${delay}s`,
      '--o': String(o),
      opacity: o,
    },
  }
})

let resizeObserver: ResizeObserver | null = null

const selectedAgentId = ref<string | null>(null)
const drawerOpen = ref(false)
const addModalOpen = ref(false)
const editAgent = ref<{ name: string; role: string; description: string; systemPrompt: string; enabled: boolean } | null>(null)
const newAgent = reactive({ name: '', roleKey: '', role: '', description: '', systemPrompt: '' })
const saving = ref(false)
const loading = ref(false)
const connectionStatus = ref<'connected' | 'disconnected'>('disconnected')
const connectionLabel = computed(() => connectionStatus.value === 'connected' ? '实时同步' : '离线模式')

const agentData = reactive<Record<string, { callCount: number; currentTask: string | null; status: string }>>({})
const activeLine = ref<string | null>(null)
const firingLine = ref<string | null>(null)
const pulseDuration = 600

const localAgents = reactive<Record<string, Agent>>(
  Object.fromEntries(DEFAULT_AGENTS.map(a => [a.id, { ...a }]))
)

let pollInterval: ReturnType<typeof setInterval> | null = null

// ── Layout ─────────────────────────────────────────────────────
function pxToSvg(pctX: number, top: number) {
  const canvas = canvasRef.value
  if (!canvas) return { x: 0, y: top }
  return {
    x: (pctX / 100) * canvas.clientWidth,
    y: top,
  }
}

const masterNodeStyle = computed(() => {
  const { x } = pxToSvg(50, MASTER_TOP)
  return {
    left: `${x - NODE_W / 2}px`,
    top: `${MASTER_TOP}px`,
    width: `${NODE_W}px`,
  }
})

function getSubNodeStyle(sub: (typeof subAgents)[0]) {
  const idx = subAgents.findIndex(s => s.id === sub.id)
  const pct = SUB_XS[idx] ?? 50
  const { x } = pxToSvg(pct, SUB_TOP)
  return {
    left: `${x - NODE_W / 2}px`,
    top: `${SUB_TOP}px`,
    width: `${NODE_W}px`,
  }
}

function getLinePath(subId: string) {
  const canvas = canvasRef.value
  if (!canvas) return ''
  const w = canvas.clientWidth
  const idx = subAgents.findIndex(s => s.id === subId)
  const subPct = SUB_XS[idx] ?? 50
  const masterX = (50 / 100) * w
  const masterY = MASTER_TOP + NODE_H / 2
  const subX = (subPct / 100) * w
  const subY = SUB_TOP + NODE_H / 2
  const midY = (masterY + subY) / 2
  return `M ${masterX},${masterY} C ${masterX},${midY} ${subX},${midY} ${subX},${subY}`
}

// ── SVG sizing ──────────────────────────────────────────────────
function updateSvgSize() {
  const canvas = canvasRef.value
  const svg = svgRef.value
  if (!canvas || !svg) return
  svg.setAttribute('width', String(canvas.clientWidth))
  svg.setAttribute('height', String(canvas.clientHeight))
}

// ── Ref helpers ──────────────────────────────────────────────────
function setSubRef(id: string, el: HTMLElement | null) {
  if (el) subRefs[id] = el
}

// ── Status / data ────────────────────────────────────────────────
function getStatusClass(agentId: string) {
  const data = agentData[agentId]
  const agent = localAgents[agentId]
  if (!agent?.enabled) return 'disabled'
  if (!data) return 'idle'
  return data.status === 'active' ? 'active' : 'idle'
}
function getAgentName(id: string) { return localAgents[id]?.name || DEFAULT_AGENTS.find(a => a.id === id)?.name || id.toUpperCase() }
function getAgentRole(id: string) { return localAgents[id]?.role || DEFAULT_AGENTS.find(a => a.id === id)?.role || '' }
function getAgentDesc(id: string) { return localAgents[id]?.description || DEFAULT_AGENTS.find(a => a.id === id)?.description || '' }

// ── Actions ───────────────────────────────────────────────────────
function selectAgent(id: string) {
  const agent = localAgents[id]
  if (!agent) return
  selectedAgentId.value = id
  editAgent.value = { name: agent.name, role: agent.role, description: agent.description, systemPrompt: agent.systemPrompt, enabled: agent.enabled }
  drawerOpen.value = true
}

function resetConfig() {
  const original = DEFAULT_AGENTS.find(a => a.id === selectedAgentId.value)
  if (original && editAgent.value) Object.assign(editAgent.value, { name: original.name, role: original.role, description: original.description, systemPrompt: original.systemPrompt, enabled: original.enabled })
}

async function saveConfig() {
  if (!editAgent.value || !selectedAgentId.value) return
  saving.value = true
  try {
    if (localAgents[selectedAgentId.value]) Object.assign(localAgents[selectedAgentId.value], editAgent.value)
    try {
      await agentApi.updateConfig(selectedAgentId.value, { name: editAgent.value!.name, description: editAgent.value!.description, system_prompt: editAgent.value!.systemPrompt, enabled: editAgent.value!.enabled })
    } catch { /* local only */ }
    drawerOpen.value = false
  } finally { saving.value = false }
}

function addAgent() {
  if (!newAgent.name || !newAgent.roleKey) return
  const id = newAgent.roleKey.toLowerCase().replace(/\s+/g, '_')
  if (localAgents[id]) return
  localAgents[id] = { id, name: newAgent.name.toUpperCase(), role: newAgent.role, roleKey: id, description: newAgent.description, systemPrompt: newAgent.systemPrompt, enabled: true }
  addModalOpen.value = false
}

async function refreshStats() {
  loading.value = true
  try {
    const stats = await agentApi.getStats()
    for (const s of stats) {
      agentData[s.agent_id] = { callCount: s.call_count, currentTask: s.current_task, status: s.status }
      if (s.status === 'active' && s.agent_id !== 'master') { firingLine.value = s.agent_id; activeLine.value = s.agent_id }
    }
    connectionStatus.value = 'connected'
  } catch {
    connectionStatus.value = 'disconnected'
    agentData['master'] = { callCount: 47, currentTask: '协调子Agent工作', status: 'active' }
    agentData['planner'] = { callCount: 12, currentTask: null, status: 'idle' }
    agentData['executor'] = { callCount: 8, currentTask: '创建文档', status: 'active' }
    agentData['librarian'] = { callCount: 5, currentTask: null, status: 'idle' }
    agentData['analyst'] = { callCount: 3, currentTask: null, status: 'idle' }
    firingLine.value = 'executor'; activeLine.value = 'executor'
  }
  loading.value = false
}

function onPulseEnd() { firingLine.value = null; activeLine.value = null }

// ── Motion helpers ───────────────────────────────────────────────
function animateIn(el: Element) { animate(el, { opacity: [0, 1], x: [80, 0] }, { duration: 0.35, easing: [0.4, 0, 0.2, 1] }).play() }
function animateOut(el: Element) { animate(el, { opacity: [1, 0], x: [0, 80] }, { duration: 0.25, easing: [0.4, 0, 1, 1] }).play() }
function fadeIn(el: Element) { animate(el, { opacity: [0, 1] }, { duration: 0.25 }).play() }
function fadeOut(el: Element) { animate(el, { opacity: [1, 0] }, { duration: 0.2 }).play() }

function playEntranceAnimations() {
  if (masterCardRef.value) {
    masterAnim.value = animate(masterCardRef.value, { opacity: [0, 1], y: [20, 0] }, { duration: 0.6, easing: [0.16, 1, 0.3, 1] })
  }
  subAgents.forEach((sub, idx) => {
    const el = subRefs[sub.id]
    if (!el) return
    const anim = animate(el, { opacity: [0, 1], y: [20, 0] }, { duration: 0.5, delay: 0.15 + idx * 0.1, easing: [0.16, 1, 0.3, 1] })
    subAnims[sub.id] = anim
    const hoverAnim = animate(el, { y: [0, -4] }, { duration: 0.2, easing: [0.34, 1.56, 0.64, 1] })
    hoverAnim.pause()
    hoverAnims[sub.id] = hoverAnim
    el.addEventListener('mouseenter', () => {
      if (!localAgents[sub.id]?.enabled) return
      hoverAnim.direction = 'forward'; hoverAnim.play()
    })
    el.addEventListener('mouseleave', () => {
      hoverAnim.direction = 'reverse'; hoverAnim.play()
    })
  })
}

// ── Lifecycle ────────────────────────────────────────────────────
onMounted(async () => {
  await refreshStats()
  pollInterval = setInterval(refreshStats, 5000)

  requestAnimationFrame(() => {
    updateSvgSize()
    playEntranceAnimations()
  })

  resizeObserver = new ResizeObserver(() => {
    updateSvgSize()
  })
  if (canvasRef.value) resizeObserver.observe(canvasRef.value)
})

onUnmounted(() => {
  if (pollInterval) clearInterval(pollInterval)
  resizeObserver?.disconnect()
  masterAnim.value?.stop()
  Object.values(subAnims).forEach(a => a.stop())
  Object.values(hoverAnims).forEach(a => a?.stop())
})
</script>

<style scoped>
.agent-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  background: var(--bg-void);
}

.bg-grid {
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(0,245,212,0.04) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0,245,212,0.04) 1px, transparent 1px);
  background-size: 40px 40px;
  pointer-events: none;
  z-index: 0;
}
.bg-glow {
  position: absolute;
  inset: 0;
  background: radial-gradient(ellipse 80% 60% at 50% 40%, rgba(0,245,212,0.05) 0%, transparent 70%);
  pointer-events: none;
  z-index: 0;
}
.bg-particles {
  position: absolute;
  inset: 0;
  pointer-events: none;
  z-index: 0;
  overflow: hidden;
}
.bg-particle {
  position: absolute;
  border-radius: 50%;
  background: var(--accent-cyan);
  box-shadow: 0 0 4px rgba(0,245,212,0.6), 0 0 8px rgba(0,245,212,0.2);
  animation: star-twinkle var(--d, 4s) ease-in-out infinite var(--delay, 0s);
}
@keyframes star-twinkle {
  0%, 100% { opacity: var(--o, 0.4); transform: scale(1); }
  50% { opacity: calc(var(--o, 0.4) * 0.3); transform: scale(0.5); }
}

/* Header */
.view-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 24px;
  border-bottom: 1px solid var(--border-dim);
  position: relative;
  z-index: 10;
  background: rgba(5,8,16,0.6);
  backdrop-filter: blur(8px);
}
.header-title { font-family: var(--font-display); font-size: 13px; letter-spacing: 0.2em; color: var(--text-primary); }
.title-bracket { color: var(--accent-cyan); opacity: 0.6; }
.header-actions { display: flex; align-items: center; gap: 12px; }

.btn-icon {
  width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;
  background: var(--bg-card); border: 1px solid var(--border-mid); border-radius: var(--radius-sm);
  color: var(--text-secondary); cursor: pointer; transition: all var(--transition-fast);
}
.btn-icon:hover { border-color: var(--accent-cyan); color: var(--accent-cyan); box-shadow: var(--glow-cyan); }
.btn-icon.spinning svg { animation: spin 0.8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }

.btn-add {
  display: flex; align-items: center; gap: 6px; padding: 6px 14px;
  background: rgba(0,245,212,0.08); border: 1px solid rgba(0,245,212,0.3);
  border-radius: var(--radius-sm); color: var(--accent-cyan); font-family: var(--font-mono);
  font-size: 11px; letter-spacing: 0.1em; cursor: pointer; transition: all var(--transition-fast);
}
.btn-add:hover { background: rgba(0,245,212,0.15); border-color: var(--accent-cyan); box-shadow: var(--glow-cyan); }

.status-bar { display: flex; align-items: center; gap: 6px; font-size: 10px; color: var(--text-dim); letter-spacing: 0.1em; }
.status-dot { width: 6px; height: 6px; border-radius: 50%; }
.status-dot.connected { background: var(--accent-cyan); box-shadow: 0 0 6px var(--accent-cyan); }
.status-dot.disconnected { background: var(--text-dim); }

/* Canvas */
.nodes-canvas {
  flex: 1;
  position: relative;
  overflow: hidden;
}
.conn-svg {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}
.conn-path {
  fill: none;
  stroke: rgba(0,245,212,0.25);
  stroke-width: 1.5;
  stroke-dasharray: 5 5;
  animation: dash-flow 4s linear infinite;
}
@keyframes dash-flow { to { stroke-dashoffset: -30; } }
.conn-path.active {
  stroke: var(--accent-amber);
  stroke-opacity: 0.7;
  stroke-dasharray: none;
  filter: url(#lineGlow);
  animation: none;
}
.pulse-dot { fill: var(--accent-amber); filter: drop-shadow(0 0 8px var(--accent-amber)); }

/* Node Cards */
.node-card {
  position: absolute;
  height: 170px;
  z-index: 2;
  cursor: pointer;
}
.node-sub.disabled { opacity: 0.35; cursor: not-allowed; }

.node-inner {
  width: 100%;
  height: 100%;
  background: rgba(13,21,37,0.92);
  border: 1px solid rgba(0,245,212,0.2);
  border-radius: var(--radius-md);
  padding: 14px 16px;
  display: flex;
  flex-direction: column;
  gap: 3px;
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(12px);
  transition: border-color 0.2s, box-shadow 0.2s;
}
.node-master .node-inner {
  background: linear-gradient(135deg, rgba(0,245,212,0.06) 0%, rgba(13,21,37,0.95) 100%);
  border-color: rgba(0,245,212,0.35);
}
.node-card:hover .node-inner {
  border-color: rgba(0,245,212,0.5);
  box-shadow: 0 8px 32px rgba(0,245,212,0.15), 0 0 0 1px rgba(0,245,212,0.1);
}
.node-card.selected .node-inner {
  border-color: var(--accent-cyan);
  box-shadow: 0 0 0 2px rgba(0,245,212,0.3), var(--glow-cyan);
}

.node-corner { position: absolute; width: 10px; height: 10px; opacity: 0.6; }
.node-corner.tl { top: 6px; left: 6px; border-top: 1.5px solid var(--accent-cyan); border-left: 1.5px solid var(--accent-cyan); }
.node-corner.tr { top: 6px; right: 6px; border-top: 1.5px solid var(--accent-cyan); border-right: 1.5px solid var(--accent-cyan); }
.node-corner.bl { bottom: 6px; left: 6px; border-bottom: 1.5px solid var(--accent-cyan); border-left: 1.5px solid var(--accent-cyan); }
.node-corner.br { bottom: 6px; right: 6px; border-bottom: 1.5px solid var(--accent-cyan); border-right: 1.5px solid var(--accent-cyan); }

.node-status { position: absolute; top: 10px; right: 10px; width: 10px; height: 10px; border-radius: 50%; display: flex; align-items: center; justify-content: center; }
.status-ring { width: 8px; height: 8px; border-radius: 50%; }
.node-status.active .status-ring { background: var(--accent-cyan); box-shadow: 0 0 8px var(--accent-cyan); animation: status-pulse 1.5s ease-in-out infinite; }
.node-status.idle .status-ring { background: var(--text-secondary); }
.node-status.disabled .status-ring { background: var(--text-dim); opacity: 0.4; }
@keyframes status-pulse { 0%,100%{opacity:1} 50%{opacity:0.4} }

.node-label { font-family: var(--font-display); font-size: 8px; letter-spacing: 0.2em; color: var(--text-dim); margin-bottom: 1px; }
.node-master .node-label { color: rgba(0,245,212,0.5); }
.node-name { font-family: var(--font-display); font-size: 15px; font-weight: 700; letter-spacing: 0.08em; color: var(--accent-cyan); line-height: 1.2; }
.node-master .node-name { font-size: 18px; }
.node-role { font-family: var(--font-mono); font-size: 10px; color: var(--accent-amber); letter-spacing: 0.05em; }
.node-desc {
  font-family: var(--font-mono); font-size: 10px; color: var(--text-secondary);
  line-height: 1.5; flex: 1; overflow: hidden; display: -webkit-box;
  -webkit-line-clamp: 3; -webkit-box-orient: vertical; text-overflow: ellipsis;
}
.node-footer { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 2px; }
.node-stat { display: flex; align-items: center; gap: 4px; font-family: var(--font-mono); font-size: 9px; }
.stat-label { color: var(--text-dim); }
.stat-val { color: var(--accent-cyan); font-weight: 600; }
.node-task-tag {
  font-family: var(--font-mono); font-size: 9px; color: var(--accent-amber);
  background: rgba(249,168,37,0.1); border: 1px solid rgba(249,168,37,0.2);
  border-radius: 3px; padding: 1px 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 120px;
}
.node-idle { font-family: var(--font-mono); font-size: 9px; color: var(--text-dim); font-style: italic; }
.rel-label {
  position: absolute; font-family: var(--font-mono); font-size: 8px; color: var(--text-dim);
  letter-spacing: 0.05em; pointer-events: none; left: 50%; transform: translateX(-50%);
  bottom: -20px; white-space: nowrap;
}
.particle { position: absolute; border-radius: 50%; background: var(--accent-cyan); pointer-events: none; }

/* Drawer */
.config-drawer {
  position: fixed; top: 0; right: 0; width: 420px; height: 100%;
  background: rgba(5,8,16,0.97); border-left: 1px solid var(--border-mid);
  backdrop-filter: blur(20px); z-index: 100; display: flex; flex-direction: column;
  box-shadow: -10px 0 40px rgba(0,0,0,0.5);
}
.drawer-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 99; }
.drawer-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid var(--border-dim); }
.drawer-title { font-family: var(--font-display); font-size: 11px; letter-spacing: 0.15em; color: var(--accent-cyan); }
.btn-close {
  width: 28px; height: 28px; display: flex; align-items: center; justify-content: center;
  background: transparent; border: 1px solid var(--border-dim); border-radius: var(--radius-sm);
  color: var(--text-dim); cursor: pointer; transition: all var(--transition-fast);
}
.btn-close:hover { border-color: var(--accent-red); color: var(--accent-red); }
.drawer-body { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 16px; }
.drawer-body::-webkit-scrollbar { width: 4px; }
.drawer-body::-webkit-scrollbar-thumb { background: var(--border-mid); border-radius: 2px; }
.form-group { display: flex; flex-direction: column; gap: 6px; }
.form-group.flex-1 { flex: 1; display: flex; flex-direction: column; }
.form-label { font-family: var(--font-mono); font-size: 9px; letter-spacing: 0.15em; color: var(--text-dim); }
.form-input {
  background: var(--bg-card); border: 1px solid var(--border-mid); border-radius: var(--radius-sm);
  padding: 10px 12px; color: var(--text-primary); font-family: var(--font-mono); font-size: 12px; outline: none;
  transition: border-color var(--transition-fast);
}
.form-input:focus { border-color: var(--accent-cyan); box-shadow: 0 0 0 1px rgba(0,245,212,.1); }
.form-textarea {
  background: var(--bg-card); border: 1px solid var(--border-mid); border-radius: var(--radius-sm);
  padding: 10px 12px; color: var(--text-primary); font-family: var(--font-mono); font-size: 11px;
  outline: none; resize: none; line-height: 1.5; transition: border-color var(--transition-fast);
}
.form-textarea:focus { border-color: var(--accent-cyan); box-shadow: 0 0 0 1px rgba(0,245,212,.1); }
.code-textarea { font-size: 10px; flex: 1; }
.toggle-row { display: flex; align-items: center; gap: 12px; }
.toggle-label { font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.1em; color: var(--accent-cyan); transition: color .2s; }
.toggle-label.dim { color: var(--text-dim); }
.toggle-btn { width: 44px; height: 22px; background: var(--bg-card); border: 1px solid var(--border-mid); border-radius: 11px; padding: 2px; cursor: pointer; transition: all .25s; }
.toggle-btn.active { background: rgba(0,245,212,.15); border-color: var(--accent-cyan); }
.toggle-knob { display: block; width: 16px; height: 16px; border-radius: 50%; background: var(--text-dim); transition: all .25s; }
.toggle-btn.active .toggle-knob { background: var(--accent-cyan); box-shadow: 0 0 8px var(--accent-cyan); transform: translateX(22px); }
.drawer-actions { display: flex; gap: 12px; padding-top: 8px; }
.btn-secondary,.btn-primary {
  flex: 1; padding: 10px 16px; border-radius: var(--radius-sm); font-family: var(--font-mono);
  font-size: 11px; letter-spacing: 0.1em; cursor: pointer; transition: all var(--transition-fast);
  display: flex; align-items: center; justify-content: center; gap: 6px;
}
.btn-secondary { background: transparent; border: 1px solid var(--border-mid); color: var(--text-secondary); }
.btn-secondary:hover { border-color: var(--accent-cyan); color: var(--accent-cyan); }
.btn-primary { background: rgba(0,245,212,.1); border: 1px solid var(--accent-cyan); color: var(--accent-cyan); }
.btn-primary:hover { background: rgba(0,245,212,.2); box-shadow: var(--glow-cyan); }
.btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-loader { width: 12px; height: 12px; border: 1.5px solid transparent; border-top-color: var(--accent-cyan); border-radius: 50%; animation: spin .6s linear infinite; }

/* Modal */
.modal-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,.7); backdrop-filter: blur(4px);
  z-index: 200; display: flex; align-items: center; justify-content: center;
}
.modal-card {
  width: 480px; max-height: 80vh; background: rgba(10,15,26,.98); border: 1px solid var(--border-mid);
  border-radius: var(--radius-lg); display: flex; flex-direction: column;
  box-shadow: 0 20px 60px rgba(0,0,0,.6), 0 0 0 1px rgba(0,245,212,.05);
}
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid var(--border-dim); }
.modal-title { font-family: var(--font-display); font-size: 11px; letter-spacing: 0.15em; color: var(--accent-cyan); }
.modal-body { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 14px; }
.modal-body::-webkit-scrollbar { width: 4px; }
.modal-body::-webkit-scrollbar-thumb { background: var(--border-mid); border-radius: 2px; }
.modal-footer { display: flex; gap: 12px; padding: 16px 20px; border-top: 1px solid var(--border-dim); }
</style>
