<template>
  <div class="agent-view scanlines">
    <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>

    <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>

    <div
      class="nodes-canvas"
      ref="canvasRef"
      :class="{ panning: isPanning }"
      @mousedown="startPan"
      @wheel.prevent="handleWheel"
    >
      <div class="canvas-aura"></div>
      <div class="canvas-scan"></div>

      <div class="hud-panels">
        <div class="hud-panel commander-skills" data-testid="commander-skills">
          <div class="hud-title">指挥官技能</div>
          <div class="skill-list">
            <div
              v-for="skill in commanderSkills"
              :key="skill.id"
              class="skill-chip"
              :class="{ active: activeSkillId === skill.id }"
              :data-testid="`commander-skill-${skill.id}`"
            >
              <span class="skill-label">{{ skill.label }}</span>
              <span class="skill-title">{{ skill.title }}</span>
            </div>
          </div>
        </div>

        <div class="hud-panel route-telemetry" data-testid="route-telemetry">
          <div class="hud-title">ACTIVE ROUTE</div>
          <div class="route-main">{{ activeMainRouteLabel }}</div>
          <div class="route-child">{{ activeChildRouteLabel }}</div>
        </div>
      </div>

      <div class="nodes-viewport" :style="viewportStyle">
        <div class="nodes-stage" :style="stageStyle">
          <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="agent in mainAgents"
              :key="`bus-${agent.id}`"
              :d="getBusLinePath(agent.id)"
              class="conn-path"
              :class="{ energized: activeMainId === agent.id }"
              :data-testid="`bus-link-${agent.id}`"
            />
            <path
              v-for="agent in activeMainAgents"
              :key="`bus-current-${agent.id}`"
              :d="getBusLinePath(agent.id)"
              class="conn-current"
              :data-testid="`bus-current-${agent.id}`"
            />

            <path
              v-for="child in childAgents"
              :key="`sub-${child.id}`"
              :d="getSubLinePath(child.id)"
              class="conn-path conn-path-sub"
              :class="{ energized: activeChildId === child.id }"
              :data-testid="`sub-link-${child.id}`"
            />
            <path
              v-for="child in activeChildAgents"
              :key="`sub-current-${child.id}`"
              :d="getSubLinePath(child.id)"
              class="conn-current conn-current-sub"
              :data-testid="`sub-current-${child.id}`"
            />
          </svg>

          <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>

          <div
            v-for="agent in mainAgents"
            :key="agent.id"
            :ref="el => setNodeRef(agent.id, el as HTMLElement)"
            class="node-card node-sub"
            :class="{ selected: selectedAgentId === agent.id, disabled: !localAgents[agent.id]?.enabled }"
            :style="getMainNodeStyle(agent.id)"
            :data-testid="`agent-chip-${agent.id}`"
            @click="selectAgent(agent.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(agent.id)">
                <span class="status-ring"></span>
              </div>
              <div class="node-label">{{ getAgentName(agent.id) }}</div>
              <div class="node-role">{{ getAgentRole(agent.id) }}</div>
              <div class="node-desc">{{ getAgentDesc(agent.id) }}</div>
              <div class="node-footer">
                <span class="node-stat">
                  <span class="stat-label">调用</span>
                  <span class="stat-val">{{ agentData[agent.id]?.callCount || 0 }}</span>
                </span>
                <span v-if="agentData[agent.id]?.currentTask" class="node-task-tag">{{ agentData[agent.id]?.currentTask }}</span>
                <span v-else class="node-idle">待机中</span>
              </div>
              <div class="rel-label">{{ relationLabels[`master-${agent.id}`] }}</div>
            </div>
          </div>

          <div
            v-for="child in childAgents"
            :key="child.id"
            :ref="el => setNodeRef(child.id, el as HTMLElement)"
            class="node-card node-sub node-child"
            :class="{ selected: selectedAgentId === child.id, disabled: !localAgents[child.id]?.enabled }"
            :style="getChildNodeStyle(child.id)"
            :data-testid="`agent-chip-${child.id}`"
            @click="selectAgent(child.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(child.id)">
                <span class="status-ring"></span>
              </div>
              <div class="node-label">{{ child.name }}</div>
              <div class="node-role">{{ child.role }}</div>
              <div class="node-desc">{{ child.description }}</div>
              <div class="node-footer">
                <span class="node-stat">
                  <span class="stat-label">调用</span>
                  <span class="stat-val">{{ agentData[child.id]?.callCount || 0 }}</span>
                </span>
                <span v-if="agentData[child.id]?.currentTask" class="node-task-tag">{{ agentData[child.id]?.currentTask }}</span>
                <span v-else class="node-idle">待机中</span>
              </div>
              <div class="rel-label">{{ child.toolScopeLabel }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="canvas-controls">
        <button class="control-chip zoom-chip" @click="zoomOut" title="缩小视图">
          <span class="chip-symbol">−</span>
        </button>
        <button class="control-chip zoom-readout" @click="resetView" title="重置视图">
          <span class="chip-value">{{ zoomPercent }}</span>
        </button>
        <button class="control-chip zoom-chip" @click="zoomIn" title="放大视图">
          <span class="chip-symbol">+</span>
        </button>
      </div>
    </div>

    <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>

    <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 { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { RefreshCw, X, Plus } from 'lucide-vue-next'
import { COMMANDER_SKILLS, DEFAULT_AGENTS, MAIN_AGENT_ORDER, RELATION_LABELS, SUB_COMMANDERS } from '@/data/agents'
import type { Agent, MainAgentId, SubCommander } from '@/data/agents'
import { agentApi, type AgentHierarchyStats, type AgentStats } from '@/api/agent'

const NODE_W = 200
const NODE_H = 170
const CHILD_W = 140
const CHILD_H = 150
const MASTER_TOP = 48
const MAIN_TOP = 350
const CHILD_TOP = 640
const MAIN_XS: Record<Exclude<MainAgentId, 'master'>, number> = {
  planner: 12.5,
  executor: 37.5,
  librarian: 62.5,
  analyst: 87.5,
}
const CHILD_LANE_OFFSET = 6
const motionEnabled = typeof window !== 'undefined' && typeof window.matchMedia === 'function'
  ? window.matchMedia('(prefers-reduced-motion: no-preference)').matches
  : false
const MIN_ZOOM = 0.8
const MAX_ZOOM = 1.6
const ZOOM_STEP = 0.1
const CRISP_ZOOM_THRESHOLD = 1.12
const OFFLINE_ROUTE_INTERVAL = 1700

type PlaybackHandle = ReturnType<typeof window.setTimeout>
type PollHandle = ReturnType<typeof setInterval>
interface AgentRuntimeState {
  callCount: number
  currentTask: string | null
  status: string
}

const mainAgents = computed(() => MAIN_AGENT_ORDER.map(id => localAgents[id]))
const childAgents = SUB_COMMANDERS
const commanderSkills = COMMANDER_SKILLS
const relationLabels = RELATION_LABELS
const childLabelMap = Object.fromEntries(childAgents.map(child => [child.id, child.name])) as Record<string, string>
const childMetaMap = Object.fromEntries(childAgents.map(child => [child.id, child])) as Record<string, SubCommander>

const canvasRef = ref<HTMLElement | null>(null)
const svgRef = ref<SVGElement | null>(null)
const masterCardRef = ref<HTMLElement | null>(null)
const nodeRefs: Record<string, HTMLElement> = {}
const cleanupFns: Array<() => void> = []
const hoverResetTimers: Record<string, PlaybackHandle | null> = {}
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
let pollInterval: PollHandle | null = null
let demoInterval: PollHandle | 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 zoom = ref(1)
const pan = reactive({ x: 0, y: 0 })
const basePan = reactive({ x: 0, y: 0 })
const isPanning = ref(false)
const panStart = reactive({ x: 0, y: 0 })
const panOrigin = reactive({ x: 0, y: 0 })
const connectionStatus = ref<'connected' | 'disconnected'>('disconnected')
const connectionLabel = computed(() => connectionStatus.value === 'connected' ? '实时同步' : '离线模式')
const zoomPercent = computed(() => `${Math.round(zoom.value * 100)}%`)
const activeMainId = ref<string>('planner')
const activeChildId = ref<string>('planner_scope')
const agentData = reactive<Record<string, AgentRuntimeState>>({})

const localAgents = reactive<Record<string, Agent>>(
  Object.fromEntries([
    ...DEFAULT_AGENTS,
    ...SUB_COMMANDERS.map((child) => ({
      id: child.id,
      name: child.name,
      role: child.role,
      roleKey: child.id,
      description: child.description,
      systemPrompt: `${child.role}：${child.description}`,
      enabled: true,
    })),
  ].map(agent => [agent.id, { ...agent }]))
)

const layoutZoom = computed(() => Math.min(zoom.value, CRISP_ZOOM_THRESHOLD))
const stageScale = computed(() => zoom.value / layoutZoom.value)

const viewportStyle = computed(() => ({
  transform: `translate(${roundPx(basePan.x + pan.x)}px, ${roundPx(basePan.y + pan.y)}px)`,
}))

const stageStyle = computed(() => ({
  width: '100%',
  minHeight: `${roundPx((CHILD_TOP + CHILD_H + 120) * layoutZoom.value)}px`,
  left: '0px',
  transform: `scale(${stageScale.value})`,
  transformOrigin: '50% 0%',
  '--node-scale': String(layoutZoom.value),
}))

const activeSkillId = computed(() => {
  const current = activeChildId.value || activeMainId.value
  return commanderSkills.find(skill => skill.relatedAgentIds.includes(current) || skill.relatedAgentIds.includes(activeMainId.value))?.id ?? 'skill_orchestration'
})
const activeMainAgents = computed(() => mainAgents.value.filter(agent => agent.id === activeMainId.value))
const activeChildAgents = computed(() => childAgents.filter(child => child.id === activeChildId.value))
const activeMainRouteLabel = computed(() => (activeMainId.value || 'master').toUpperCase())
const activeChildRouteLabel = computed(() => childLabelMap[activeChildId.value] || 'STANDBY')

function roundPx(value: number) {
  return Math.round(value)
}

function getCanvasMetrics() {
  const canvas = canvasRef.value
  if (!canvas) return { width: 0, height: 0 }
  return { width: canvas.clientWidth, height: canvas.clientHeight }
}

function pxToSvg(pctX: number) {
  const canvas = canvasRef.value
  if (!canvas) return 0
  return (pctX / 100) * canvas.clientWidth
}

function updateBasePan() {
  const { width, height } = getCanvasMetrics()
  const scaledWidth = width * zoom.value
  const scaledHeight = height * zoom.value
  basePan.x = width ? roundPx((width - scaledWidth) / 2) : 0
  basePan.y = height ? roundPx((height - scaledHeight) / 2) : 0
}

function getNodeMetrics(width = NODE_W, height = NODE_H) {
  return {
    width: roundPx(width * layoutZoom.value),
    height: roundPx(height * layoutZoom.value),
    paddingX: roundPx(16 * layoutZoom.value),
    paddingY: roundPx(14 * layoutZoom.value),
    corner: Math.max(6, roundPx(10 * layoutZoom.value)),
    status: Math.max(8, roundPx(10 * layoutZoom.value)),
    statusRing: Math.max(6, roundPx(8 * layoutZoom.value)),
    relOffset: roundPx(-20 * layoutZoom.value),
  }
}

function buildNodeStyle(centerPct: number, top: number, width = NODE_W, height = NODE_H) {
  const x = pxToSvg(centerPct)
  const metrics = getNodeMetrics(width, height)
  return {
    left: `${roundPx(x - metrics.width / 2)}px`,
    top: `${roundPx(top)}px`,
    width: `${metrics.width}px`,
    height: `${metrics.height}px`,
    '--node-padding-x': `${metrics.paddingX}px`,
    '--node-padding-y': `${metrics.paddingY}px`,
    '--node-corner-size': `${metrics.corner}px`,
    '--node-status-size': `${metrics.status}px`,
    '--node-status-ring-size': `${metrics.statusRing}px`,
    '--node-rel-offset': `${metrics.relOffset}px`,
  }
}

const masterNodeStyle = computed(() => buildNodeStyle(50, MASTER_TOP, NODE_W, NODE_H))
function getMainNodeStyle(id: string) {
  return buildNodeStyle(MAIN_XS[id as keyof typeof MAIN_XS] ?? 50, MAIN_TOP, NODE_W, NODE_H)
}
function getChildNodeStyle(id: string) {
  const child = childMetaMap[id]
  const parentX = MAIN_XS[child.parentId]
  const siblingIndex = childAgents.filter(item => item.parentId === child.parentId).findIndex(item => item.id === id)
  const offset = siblingIndex === 0 ? -CHILD_LANE_OFFSET : CHILD_LANE_OFFSET
  return buildNodeStyle(parentX + offset, CHILD_TOP, CHILD_W, CHILD_H)
}

function getCurvePath(fromX: number, fromY: number, toX: number, toY: number) {
  const midY = (fromY + toY) / 2
  return `M ${roundPx(fromX)},${roundPx(fromY)} C ${roundPx(fromX)},${roundPx(midY)} ${roundPx(toX)},${roundPx(midY)} ${roundPx(toX)},${roundPx(toY)}`
}

function getBusLinePath(mainId: string) {
  const metrics = getNodeMetrics()
  return getCurvePath(pxToSvg(50), MASTER_TOP + metrics.height / 2, pxToSvg(MAIN_XS[mainId as keyof typeof MAIN_XS] ?? 50), MAIN_TOP + metrics.height / 2)
}

function getSubLinePath(childId: string) {
  const child = childMetaMap[childId]
  const mainMetrics = getNodeMetrics()
  const childMetrics = getNodeMetrics(CHILD_W, CHILD_H)
  const parentX = pxToSvg(MAIN_XS[child.parentId])
  const siblingIndex = childAgents.filter(item => item.parentId === child.parentId).findIndex(item => item.id === childId)
  const childX = pxToSvg(MAIN_XS[child.parentId] + (siblingIndex === 0 ? -CHILD_LANE_OFFSET : CHILD_LANE_OFFSET))
  return getCurvePath(parentX, MAIN_TOP + mainMetrics.height / 2, childX, CHILD_TOP + childMetrics.height / 2)
}

function updateSvgSize() {
  const canvas = canvasRef.value
  const svg = svgRef.value
  if (!canvas || !svg) return
  svg.setAttribute('width', String(canvas.clientWidth))
  svg.setAttribute('height', String(Math.max(canvas.clientHeight, CHILD_TOP + CHILD_H + 120)))
}

function setNodeRef(id: string, el: HTMLElement | null) {
  if (el) nodeRefs[id] = el
}

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 || id.toUpperCase() }
function getAgentRole(id: string) { return localAgents[id]?.role || '' }
function getAgentDesc(id: string) { return localAgents[id]?.description || '' }
function clampZoom(value: number) {
  return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Number(value.toFixed(2))))
}

function applyZoom(nextZoom: number, anchorX?: number, anchorY?: number) {
  const clamped = clampZoom(nextZoom)
  const canvas = canvasRef.value
  const previousZoom = zoom.value

  if (!canvas || clamped === previousZoom) {
    zoom.value = clamped
    updateBasePan()
    return
  }

  const rect = canvas.getBoundingClientRect()
  const localX = anchorX ?? rect.width / 2
  const localY = anchorY ?? rect.height / 2
  const contentX = (localX - (basePan.x + pan.x)) / previousZoom
  const contentY = (localY - (basePan.y + pan.y)) / previousZoom

  zoom.value = clamped
  updateBasePan()

  pan.x = roundPx(localX - basePan.x - contentX * zoom.value)
  pan.y = roundPx(localY - basePan.y - contentY * zoom.value)
}

function zoomIn() {
  applyZoom(zoom.value + ZOOM_STEP)
}
function zoomOut() {
  applyZoom(zoom.value - ZOOM_STEP)
}
function resetView() {
  zoom.value = 1
  pan.x = 0
  pan.y = 0
  updateBasePan()
}
function handleWheel(event: WheelEvent) {
  const delta = event.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP
  const canvas = canvasRef.value
  if (!canvas) {
    applyZoom(zoom.value + delta)
    return
  }
  const rect = canvas.getBoundingClientRect()
  applyZoom(zoom.value + delta, event.clientX - rect.left, event.clientY - rect.top)
}
function startPan(event: MouseEvent) {
  const target = event.target as HTMLElement | null
  if (!target || target.closest('.node-card') || target.closest('.canvas-controls') || target.closest('.hud-panel')) return
  isPanning.value = true
  panStart.x = event.clientX
  panStart.y = event.clientY
  panOrigin.x = pan.x
  panOrigin.y = pan.y
  window.addEventListener('mousemove', movePan)
  window.addEventListener('mouseup', endPan, { once: true })
}
function movePan(event: MouseEvent) {
  if (!isPanning.value) return
  pan.x = panOrigin.x + event.clientX - panStart.x
  pan.y = panOrigin.y + event.clientY - panStart.y
}
function endPan() {
  isPanning.value = false
  window.removeEventListener('mousemove', movePan)
}

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 = localAgents[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
}

function setRuntimeState(agentId: string, state: AgentStats) {
  agentData[agentId] = {
    callCount: state.call_count,
    currentTask: state.current_task,
    status: state.status,
  }
}

function applyHierarchyStats(stats: AgentHierarchyStats) {
  agentData.master = { callCount: 47, currentTask: '协调组织链路', status: 'active' }
  let nextMain = 'planner'
  let nextChild = 'planner_scope'

  for (const main of stats.main_agents) {
    setRuntimeState(main.agent_id, main)
    if (main.status === 'active') nextMain = main.agent_id

    for (const child of main.sub_commanders) {
      setRuntimeState(child.agent_id, child)
      if (child.status === 'active') {
        nextMain = main.agent_id
        nextChild = child.agent_id
      }
    }
  }

  activeMainId.value = nextMain
  activeChildId.value = nextChild
}

function stopDemoRouteCycle() {
  if (demoInterval) {
    clearInterval(demoInterval)
    demoInterval = null
  }
}

function startDemoRouteCycle() {
  stopDemoRouteCycle()
  const demoRoutes = childAgents.map(child => ({ mainId: child.parentId, childId: child.id }))
  let index = 0
  const applyRoute = () => {
    const route = demoRoutes[index]
    activeMainId.value = route.mainId
    activeChildId.value = route.childId
    index = (index + 1) % demoRoutes.length
  }
  applyRoute()
  demoInterval = setInterval(applyRoute, OFFLINE_ROUTE_INTERVAL)
}

function buildOfflineStats() {
  return {
    main_agents: [
      {
        agent_id: 'planner',
        call_count: 12,
        current_task: null,
        status: 'active',
        sub_commanders: [
          { agent_id: 'planner_scope', call_count: 4, current_task: '收束需求', status: 'active' },
          { agent_id: 'planner_steps', call_count: 9, current_task: null, status: 'idle' },
        ],
      },
      {
        agent_id: 'executor',
        call_count: 8,
        current_task: '创建文档',
        status: 'idle',
        sub_commanders: [
          { agent_id: 'executor_tasks', call_count: 8, current_task: null, status: 'idle' },
          { agent_id: 'executor_forum', call_count: 4, current_task: null, status: 'idle' },
        ],
      },
      {
        agent_id: 'librarian',
        call_count: 5,
        current_task: null,
        status: 'idle',
        sub_commanders: [
          { agent_id: 'librarian_retrieval', call_count: 5, current_task: null, status: 'idle' },
          { agent_id: 'librarian_graph', call_count: 2, current_task: null, status: 'idle' },
        ],
      },
      {
        agent_id: 'analyst',
        call_count: 3,
        current_task: null,
        status: 'idle',
        sub_commanders: [
          { agent_id: 'analyst_progress', call_count: 2, current_task: null, status: 'idle' },
          { agent_id: 'analyst_insights', call_count: 3, current_task: null, status: 'idle' },
        ],
      },
    ],
  } satisfies AgentHierarchyStats
}

async function refreshStats() {
  loading.value = true
  try {
    const stats = await agentApi.getHierarchyStats()
    applyHierarchyStats(stats)
    connectionStatus.value = 'connected'
    stopDemoRouteCycle()
  } catch {
    connectionStatus.value = 'disconnected'
    applyHierarchyStats(buildOfflineStats())
    startDemoRouteCycle()
  } finally {
    loading.value = false
  }
}

function stopTimer(timer: PlaybackHandle | null) {
  if (timer) window.clearTimeout(timer)
}

function runTransition(el: Element, keyframes: Keyframe[], options: KeyframeAnimationOptions, done?: () => void) {
  const target = el as HTMLElement
  if (typeof target.animate !== 'function') {
    done?.()
    return null
  }
  const animation = target.animate(keyframes, { fill: 'forwards', ...options })
  const finish = () => done?.()
  animation.addEventListener('finish', finish, { once: true })
  cleanupFns.push(() => animation.cancel())
  return animation
}

function animateIn(el: Element, done: () => void) {
  runTransition(el, [{ opacity: 0, transform: 'translateX(80px)' }, { opacity: 1, transform: 'translateX(0)' }], { duration: 350, easing: 'cubic-bezier(0.4, 0, 0.2, 1)' }, done)
}
function animateOut(el: Element, done: () => void) {
  runTransition(el, [{ opacity: 1, transform: 'translateX(0)' }, { opacity: 0, transform: 'translateX(80px)' }], { duration: 250, easing: 'cubic-bezier(0.4, 0, 1, 1)' }, done)
}
function fadeIn(el: Element, done: () => void) {
  runTransition(el, [{ opacity: 0 }, { opacity: 1 }], { duration: 250 }, done)
}
function fadeOut(el: Element, done: () => void) {
  runTransition(el, [{ opacity: 1 }, { opacity: 0 }], { duration: 200 }, done)
}

function playEntranceAnimations() {
  if (!motionEnabled) return
  if (masterCardRef.value) {
    runTransition(masterCardRef.value, [
      { opacity: 0, transform: 'translateY(14px) scale(0.99)', filter: 'brightness(0.86)' },
      { opacity: 1, transform: 'translateY(0) scale(1)', filter: 'brightness(1)' },
    ], { duration: 680, easing: 'cubic-bezier(0.16, 1, 0.3, 1)' })
  }

  ;[...mainAgents.value.map(agent => agent.id), ...childAgents.map(child => child.id)].forEach((id, idx) => {
    const el = nodeRefs[id]
    if (!el) return
    runTransition(el, [
      { opacity: 0, transform: 'translateY(12px) scale(0.99)', filter: 'brightness(0.82)' },
      { opacity: 1, transform: 'translateY(0) scale(1)', filter: 'brightness(1)' },
    ], { duration: 500, delay: 210 + idx * 55, easing: 'cubic-bezier(0.16, 1, 0.3, 1)' })

    const handleMouseEnter = () => {
      if (!localAgents[id]?.enabled) return
      stopTimer(hoverResetTimers[id] ?? null)
      el.style.transform = 'translateY(-2px)'
    }
    const handleMouseLeave = () => {
      stopTimer(hoverResetTimers[id] ?? null)
      hoverResetTimers[id] = window.setTimeout(() => {
        el.style.transform = ''
        hoverResetTimers[id] = null
      }, 180)
    }

    el.addEventListener('mouseenter', handleMouseEnter)
    el.addEventListener('mouseleave', handleMouseLeave)
    cleanupFns.push(() => {
      stopTimer(hoverResetTimers[id] ?? null)
      el.removeEventListener('mouseenter', handleMouseEnter)
      el.removeEventListener('mouseleave', handleMouseLeave)
    })
  })
}

onMounted(async () => {
  await refreshStats()
  pollInterval = setInterval(refreshStats, 5000)
  requestAnimationFrame(() => {
    updateBasePan()
    updateSvgSize()
    playEntranceAnimations()
  })
  resizeObserver = new ResizeObserver(() => {
    updateBasePan()
    updateSvgSize()
  })
  if (canvasRef.value) resizeObserver.observe(canvasRef.value)
})

onUnmounted(() => {
  if (pollInterval) clearInterval(pollInterval)
  stopDemoRouteCycle()
  resizeObserver?.disconnect()
  window.removeEventListener('mousemove', movePan)
  window.removeEventListener('mouseup', endPan)
  cleanupFns.forEach(cleanup => cleanup())
})
</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); }
}
.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); animation: status-pulse-soft 2.6s ease-in-out infinite; }
.status-dot.disconnected { background: var(--text-dim); }
@keyframes status-pulse-soft {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.55; transform: scale(0.82); }
}
.nodes-canvas {
  flex: 1;
  position: relative;
  overflow: hidden;
  isolation: isolate;
  cursor: grab;
}
.nodes-canvas.panning {
  cursor: grabbing;
  user-select: none;
}
.hud-panels {
  position: absolute;
  top: 18px;
  right: 20px;
  z-index: 12;
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 260px;
}
.hud-panel {
  border: 1px solid rgba(0,245,212,0.12);
  border-radius: 16px;
  background: linear-gradient(180deg, rgba(8, 13, 22, 0.92), rgba(5, 9, 18, 0.86));
  backdrop-filter: blur(14px);
  box-shadow: 0 16px 36px rgba(0, 0, 0, 0.24), inset 0 1px 0 rgba(255,255,255,0.04);
  padding: 14px;
}
.hud-title {
  font-family: var(--font-display);
  font-size: 10px;
  letter-spacing: 0.16em;
  color: var(--accent-cyan);
  margin-bottom: 10px;
}
.skill-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.skill-chip {
  display: flex;
  align-items: center;
  gap: 8px;
  border: 1px solid rgba(0,245,212,0.1);
  border-radius: 10px;
  padding: 8px 10px;
  color: var(--text-secondary);
  background: rgba(11, 18, 30, 0.88);
}
.skill-chip.active {
  border-color: rgba(0,245,212,0.4);
  box-shadow: 0 0 16px rgba(0,245,212,0.12);
  color: var(--text-primary);
}
.skill-label {
  font-family: var(--font-display);
  font-size: 9px;
  letter-spacing: 0.14em;
  color: var(--accent-amber);
}
.skill-title {
  font-family: var(--font-mono);
  font-size: 11px;
}
.route-main {
  font-family: var(--font-display);
  font-size: 18px;
  letter-spacing: 0.08em;
  color: var(--text-primary);
}
.route-child {
  margin-top: 6px;
  font-family: var(--font-mono);
  font-size: 11px;
  color: var(--accent-cyan);
  letter-spacing: 0.08em;
}
.canvas-controls {
  position: absolute;
  right: 20px;
  bottom: 18px;
  z-index: 12;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border: 1px solid rgba(0,245,212,0.12);
  border-radius: 22px;
  background: linear-gradient(180deg, rgba(8, 13, 22, 0.92), rgba(5, 9, 18, 0.86));
  backdrop-filter: blur(14px);
  box-shadow: 0 16px 36px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255,255,255,0.04);
}
.control-chip {
  height: 36px;
  border: 1px solid rgba(0,245,212,0.12);
  background: rgba(9, 16, 28, 0.9);
  color: var(--text-secondary);
  border-radius: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.18s ease;
}
.control-chip:hover {
  border-color: rgba(0,245,212,0.3);
  color: var(--accent-cyan);
  box-shadow: 0 0 18px rgba(0,245,212,0.08);
}
.zoom-chip { width: 36px; flex-shrink: 0; }
.chip-symbol { font-family: var(--font-display); font-size: 18px; line-height: 1; }
.zoom-readout { min-width: 72px; padding: 0 14px; }
.chip-value { font-family: var(--font-display); font-size: 11px; letter-spacing: 0.08em; color: var(--text-primary); }
.nodes-viewport {
  position: absolute;
  inset: 0;
  z-index: 1;
  will-change: transform;
}
.nodes-stage {
  position: absolute;
  inset: 0;
  will-change: auto;
}
.canvas-aura,
.canvas-scan {
  position: absolute;
  inset: 0;
  pointer-events: none;
  z-index: 0;
}
.canvas-aura {
  background:
    radial-gradient(circle at 50% 18%, rgba(0,245,212,0.1) 0%, rgba(0,245,212,0.05) 20%, transparent 46%),
    radial-gradient(circle at 50% 62%, rgba(0,245,212,0.035) 0%, transparent 54%);
  filter: blur(12px);
  opacity: 0.72;
}
.canvas-scan {
  inset: -20% 0;
  background: linear-gradient(180deg, transparent 0%, rgba(0,245,212,0.018) 42%, rgba(0,245,212,0.045) 50%, rgba(0,245,212,0.018) 58%, transparent 100%);
  animation: canvas-scan 11s linear infinite;
  opacity: 0.5;
}
@keyframes canvas-scan {
  from { transform: translateY(-18%); }
  to { transform: translateY(18%); }
}
.conn-svg {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
  overflow: visible;
}
.conn-path {
  fill: none;
  stroke: rgba(0,245,212,0.22);
  stroke-width: 1.5;
  stroke-dasharray: 5 7;
  stroke-linecap: round;
  filter: drop-shadow(0 0 6px rgba(0,245,212,0.06));
  animation: dash-flow 5.5s linear infinite;
}
.conn-path-sub {
  stroke-width: 1.2;
  stroke-opacity: 0.7;
}
@keyframes dash-flow { to { stroke-dashoffset: -48; } }
.conn-path.energized {
  stroke: color-mix(in srgb, var(--accent-cyan) 72%, var(--accent-amber) 28%);
  stroke-opacity: 0.62;
  stroke-width: 1.9;
  stroke-dasharray: none;
  filter: url(#lineGlow) drop-shadow(0 0 8px rgba(0,245,212,0.16));
  animation: line-flare 2.2s ease-in-out infinite alternate;
}
.conn-current {
  fill: none;
  stroke: rgba(232, 255, 255, 0.98);
  stroke-width: 3.2;
  stroke-linecap: round;
  stroke-dasharray: 18 220;
  filter: drop-shadow(0 0 10px rgba(0,245,212,0.36)) drop-shadow(0 0 18px rgba(255,255,255,0.24));
  animation: current-flow 1.2s linear infinite;
}
.conn-current-sub {
  stroke-width: 2.6;
  stroke-dasharray: 14 180;
  animation-duration: 1s;
}
@keyframes line-flare {
  from { stroke-opacity: 0.38; }
  to { stroke-opacity: 0.72; }
}
@keyframes current-flow {
  from { stroke-dashoffset: 0; }
  to { stroke-dashoffset: -238; }
}
.node-card {
  position: absolute;
  z-index: 2;
  cursor: pointer;
  transition: transform 0.22s ease;
}
.node-sub.disabled { opacity: 0.35; cursor: not-allowed; }
.node-child { z-index: 2; }
.node-child .node-name,
.node-child .node-role,
.node-child .node-label {
  word-break: break-word;
}
.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: var(--node-padding-y, 14px) var(--node-padding-x, 16px);
  display: flex;
  flex-direction: column;
  gap: calc(3px * var(--node-scale, 1));
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(12px);
  transition: border-color 0.2s, box-shadow 0.2s, background 0.25s ease;
}
.node-inner::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(115deg, transparent 20%, rgba(255,255,255,0.045) 32%, transparent 44%);
  transform: translateX(-150%);
  opacity: 0;
  pointer-events: none;
}
.node-master .node-inner::after {
  content: '';
  position: absolute;
  inset: -18%;
  background: radial-gradient(circle, rgba(0,245,212,0.1) 0%, rgba(0,245,212,0.045) 28%, transparent 62%);
  opacity: 0.72;
  animation: core-breathe 5.6s ease-in-out infinite;
  pointer-events: none;
}
.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.3);
}
.node-card:hover .node-inner {
  border-color: rgba(0,245,212,0.42);
  box-shadow: 0 8px 28px rgba(0,245,212,0.11), 0 0 0 1px rgba(0,245,212,0.08);
}
.node-card:hover .node-inner::before {
  opacity: 0.9;
  animation: node-sheen 1.45s ease;
}
.node-card.selected .node-inner {
  border-color: var(--accent-cyan);
  box-shadow: 0 0 0 1px rgba(0,245,212,0.26), 0 0 18px rgba(0,245,212,0.14);
}
@keyframes node-sheen {
  0% { transform: translateX(-150%); }
  100% { transform: translateX(150%); }
}
@keyframes core-breathe {
  0%, 100% { opacity: 0.46; transform: scale(0.98); }
  50% { opacity: 0.8; transform: scale(1.01); }
}
.node-corner { position: absolute; width: var(--node-corner-size, 10px); height: var(--node-corner-size, 10px); opacity: 0.6; }
.node-corner.tl { top: calc(6px * var(--node-scale, 1)); left: calc(6px * var(--node-scale, 1)); border-top: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); border-left: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); }
.node-corner.tr { top: calc(6px * var(--node-scale, 1)); right: calc(6px * var(--node-scale, 1)); border-top: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); border-right: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); }
.node-corner.bl { bottom: calc(6px * var(--node-scale, 1)); left: calc(6px * var(--node-scale, 1)); border-bottom: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); border-left: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); }
.node-corner.br { bottom: calc(6px * var(--node-scale, 1)); right: calc(6px * var(--node-scale, 1)); border-bottom: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); border-right: calc(1.5px * var(--node-scale, 1)) solid var(--accent-cyan); }
.node-status { position: absolute; top: calc(10px * var(--node-scale, 1)); right: calc(10px * var(--node-scale, 1)); width: var(--node-status-size, 10px); height: var(--node-status-size, 10px); border-radius: 50%; display: flex; align-items: center; justify-content: center; }
.status-ring { width: var(--node-status-ring-size, 8px); height: var(--node-status-ring-size, 8px); border-radius: 50%; }
.node-status.active::before {
  content: '';
  position: absolute;
  inset: -6px;
  border: 1px solid rgba(0,245,212,0.22);
  border-radius: 999px;
  animation: status-orbit 2.3s ease-out infinite;
}
.node-status.active .status-ring { background: var(--accent-cyan); box-shadow: 0 0 8px var(--accent-cyan); animation: status-pulse 1.8s 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} }
@keyframes status-orbit {
  0% { transform: scale(0.5); opacity: 0.65; }
  100% { transform: scale(1.3); opacity: 0; }
}
.node-label { font-family: var(--font-display); font-size: calc(8px * var(--node-scale, 1)); 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: calc(15px * var(--node-scale, 1)); font-weight: 700; letter-spacing: 0.08em; color: var(--accent-cyan); line-height: 1.2; }
.node-master .node-name { font-size: calc(18px * var(--node-scale, 1)); }
.node-role { font-family: var(--font-mono); font-size: calc(10px * var(--node-scale, 1)); color: var(--accent-amber); letter-spacing: 0.05em; }
.node-desc {
  font-family: var(--font-mono); font-size: calc(10px * var(--node-scale, 1)); 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-child .node-desc { -webkit-line-clamp: 2; }
.node-footer { display: flex; align-items: center; gap: calc(8px * var(--node-scale, 1)); flex-wrap: wrap; margin-top: 2px; }
.node-stat { display: flex; align-items: center; gap: calc(4px * var(--node-scale, 1)); font-family: var(--font-mono); font-size: calc(9px * var(--node-scale, 1)); }
.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: calc(9px * var(--node-scale, 1)); color: var(--accent-amber);
  background: rgba(249,168,37,0.08); border: 1px solid rgba(249,168,37,0.18);
  border-radius: 3px; padding: calc(1px * var(--node-scale, 1)) calc(6px * var(--node-scale, 1)); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: calc(120px * var(--node-scale, 1));
  box-shadow: 0 0 10px rgba(249,168,37,0.05);
  animation: task-tag-glow 3.4s ease-in-out infinite;
}
.node-idle { font-family: var(--font-mono); font-size: calc(9px * var(--node-scale, 1)); color: var(--text-dim); font-style: italic; }
.rel-label {
  position: absolute; font-family: var(--font-mono); font-size: calc(8px * var(--node-scale, 1)); color: var(--text-dim);
  letter-spacing: 0.05em; pointer-events: none; left: 50%; transform: translateX(-50%);
  bottom: var(--node-rel-offset, -20px); white-space: nowrap;
}
@keyframes task-tag-glow {
  0%, 100% { box-shadow: 0 0 8px rgba(249,168,37,0.04); }
  50% { box-shadow: 0 0 14px rgba(249,168,37,0.1); }
}
.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-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>
