<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { RouterLink } from 'vue-router'
import { graphApi } from '@/api/graph'
import { Network, RefreshCw, Info, Hexagon, ExternalLink, Cpu, Sparkles } from 'lucide-vue-next'
import type { KGNode, KGEdge } from '@/api/graph'

const props = withDefaults(defineProps<{
  fullscreen?: boolean
  showOpenFullView?: boolean
}>(), {
  fullscreen: false,
  showOpenFullView: false,
})

const nodes = ref<KGNode[]>([])
const edges = ref<KGEdge[]>([])
const stats = ref({ node_count: 0, edge_count: 0 })
const isLoading = ref(false)
const selectedEntity = ref<KGNode | null>(null)
const entityContext = ref('')
const isBuilding = ref(false)
const buildStatus = ref<'idle' | 'running' | 'success' | 'error'>('idle')
const buildTitle = ref('')
const buildMessage = ref('')
const projectionSubtitle = ref('Knowledge brain memory/tag projection')
const chartRef = ref<HTMLDivElement>()
let buildPollTimer: ReturnType<typeof setTimeout> | null = null
let resizeHandler: (() => void) | null = null
let chartInstance: any = null

const typeColors: Record<string, string> = {
  person: '#ff7b7b',
  concept: '#5da9ff',
  topic: '#a78bfa',
  task: '#fbbf24',
  event: '#fb923c',
  document: '#cbd5e1',
  memory: '#00f5d4',
  tag: '#38bdf8',
  default: '#64748b',
}

function getColor(type: string) {
  return typeColors[type] || typeColors.default
}

function getNodeWeight(node: KGNode) {
  return node.importance || 0.5
}

function getNodeTier(node: KGNode) {
  const weight = getNodeWeight(node)
  if (node.type === 'memory' || weight >= 0.82) return 'core'
  if (node.type === 'tag' || weight >= 0.62) return 'relay'
  return 'leaf'
}

function getNodeSize(node: KGNode) {
  const weight = getNodeWeight(node)
  const tier = getNodeTier(node)
  if (tier === 'core') return 34 + weight * 34
  if (tier === 'relay') return 24 + weight * 24
  return 16 + weight * 18
}

function getNodeOpacity(node: KGNode) {
  return getNodeTier(node) === 'leaf' ? 0.78 : 0.96
}

function clearBuildPoll() {
  if (buildPollTimer) {
    clearTimeout(buildPollTimer)
    buildPollTimer = null
  }
}

function getErrorMessage(error: unknown) {
  const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
  if (typeof detail === 'string' && detail) return detail
  return 'Unable to rebuild the brain graph projection right now.'
}

async function loadGraph() {
  isLoading.value = true
  try {
    const response = await graphApi.get()
    nodes.value = response.data.nodes
    edges.value = response.data.edges
    stats.value = response.data.stats
    await nextTick()
    renderChart()
  } catch (e) {
    console.error('加载图谱失败:', e)
  }
  isLoading.value = false
}

async function pollGraphBuild(previousNodeCount: number, previousEdgeCount: number, attempts = 0) {
  clearBuildPoll()
  buildPollTimer = setTimeout(async () => {
    try {
      const response = await graphApi.get()
      nodes.value = response.data.nodes
      edges.value = response.data.edges
      stats.value = response.data.stats
      await nextTick()
      renderChart()

      const hasChanged = response.data.stats.node_count !== previousNodeCount || response.data.stats.edge_count !== previousEdgeCount
      if (hasChanged) {
        isBuilding.value = false
        buildStatus.value = 'success'
        buildTitle.value = 'PROJECTION REBUILT'
        buildMessage.value = `Projection updated to ${response.data.stats.node_count} nodes and ${response.data.stats.edge_count} relations.`
        clearBuildPoll()
        return
      }

      if (attempts >= 14) {
        isBuilding.value = false
        buildStatus.value = 'running'
        buildTitle.value = 'BUILDING IN BACKGROUND'
        buildMessage.value = 'The rebuild task is still running. The brain graph projection will appear here as soon as the backend finishes processing memories and tags.'
        clearBuildPoll()
        return
      }

      buildTitle.value = 'REBUILDING PROJECTION'
      buildMessage.value = `Processing knowledge links... ${attempts + 1}/15`
      await pollGraphBuild(previousNodeCount, previousEdgeCount, attempts + 1)
    } catch (error) {
      isBuilding.value = false
      buildStatus.value = 'error'
      buildMessage.value = getErrorMessage(error)
      clearBuildPoll()
    }
  }, 2000)
}

async function buildGraph() {
  if (isBuilding.value) return

  isBuilding.value = true
  buildStatus.value = 'running'
  buildTitle.value = 'PROJECTION REQUEST ACCEPTED'
  buildMessage.value = 'The backend has started rebuilding your brain graph projection. Waiting for fresh memory and tag nodes...'
  const previousNodeCount = stats.value.node_count
  const previousEdgeCount = stats.value.edge_count

  try {
    const response = await graphApi.build()
    buildTitle.value = 'PROJECTION REQUEST ACCEPTED'
    buildMessage.value = response.data?.message || 'The backend has started rebuilding your brain graph projection. Waiting for fresh memory and tag nodes...'
    await pollGraphBuild(previousNodeCount, previousEdgeCount)
  } catch (error) {
    console.error('构建失败:', error)
    isBuilding.value = false
    buildStatus.value = 'error'
    buildTitle.value = 'BUILD FAILED'
    buildMessage.value = getErrorMessage(error)
    clearBuildPoll()
  }
}

async function selectEntity(node: KGNode) {
  selectedEntity.value = node
  entityContext.value = 'LOADING...'
  try {
    const response = await graphApi.getEntityContext(node.name)
    entityContext.value = response.data.context
  } catch (_e) {
    entityContext.value = 'Failed to load context'
  }
}

function disposeChart() {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
}

function renderChart() {
  if (!chartRef.value) return
  // @ts-ignore
  if (!window.echarts) return
  // @ts-ignore
  const echarts = window.echarts

  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value, 'dark')

  chartInstance.setOption({
    backgroundColor: 'transparent',
    animationDuration: 700,
    animationEasingUpdate: 'quarticOut',
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(6, 10, 18, 0.96)',
      borderColor: 'rgba(0, 245, 212, 0.28)',
      borderWidth: 1,
      textStyle: { color: '#e8f4f8', fontFamily: 'JetBrains Mono, monospace', fontSize: 12 },
      formatter: (params: any) => {
        if (params.dataType === 'node') {
          return `<b style="color:${params.data.color}">${params.data.name}</b><br/><span style="color:#7eb8c9">Type: ${params.data.type || 'unknown'}</span><br/><span style="color:#9dd6e3">Tier: ${params.data.tier}</span>`
        }
        return `<span style="color:#7eb8c9">${params.data.sourceName}</span> → <span style="color:#a78bfa">${params.data.relation}</span> → <span style="color:#7eb8c9">${params.data.targetName}</span>`
      },
    },
    series: [{
      type: 'graph',
      layout: 'force',
      roam: true,
      draggable: true,
      symbol: 'circle',
      symbolKeepAspect: true,
      symbolSize: (_val: unknown, params: any) => getNodeSize(params.data.rawNode),
      label: {
        show: true,
        position: 'right',
        distance: 8,
        fontSize: 10,
        color: '#d6f8ff',
        fontFamily: 'JetBrains Mono, monospace',
        formatter: (params: any) => {
          const maxLength = params.data.tier === 'core' ? 18 : 14
          return params.data.name?.substring(0, maxLength) || ''
        },
      },
      labelLayout: {
        hideOverlap: true,
      },
      lineStyle: {
        color: 'source',
        curveness: 0.15,
        opacity: 0.6,
        width: 1.6,
      },
      emphasis: {
        focus: 'adjacency',
        scale: 1.12,
        lineStyle: {
          width: 3.2,
          opacity: 0.95,
        },
        label: {
          color: '#ffffff',
          fontSize: 11,
        },
      },
      edgeSymbol: ['circle', 'arrow'],
      edgeSymbolSize: [4, 8],
      data: nodes.value.map((node) => {
        const color = getColor(node.type)
        const tier = getNodeTier(node)
        const isCore = tier === 'core'
        return {
          id: node.id,
          name: node.name,
          type: node.type,
          tier,
          color,
          rawNode: node,
          itemStyle: {
            color,
            opacity: getNodeOpacity(node),
            borderColor: isCore ? '#dafeff' : color,
            borderWidth: isCore ? 3 : 2,
            shadowColor: color,
            shadowBlur: isCore ? 28 : 16,
          },
        }
      }),
      links: edges.value.map((edge) => {
        const sourceNode = nodes.value.find((node) => node.id === edge.source)
        const targetNode = nodes.value.find((node) => node.id === edge.target)
        const sourceColor = getColor(sourceNode?.type || 'default')
        const targetColor = getColor(targetNode?.type || 'default')
        return {
          source: edge.source,
          target: edge.target,
          sourceName: sourceNode?.name || '',
          targetName: targetNode?.name || '',
          relation: edge.relation,
          lineStyle: {
            color: sourceColor,
            opacity: 0.28,
            width: sourceNode && getNodeTier(sourceNode) === 'core' ? 2.6 : 1.4,
          },
          emphasis: {
            lineStyle: {
              color: targetColor,
            },
          },
        }
      }),
      force: {
        repulsion: 240,
        gravity: 0.03,
        edgeLength: [70, 220],
        friction: 0.08,
        layoutAnimation: true,
      },
    }],
  })

  chartInstance.off('click')
  chartInstance.on('click', (params: any) => {
    if (params.dataType === 'node') {
      const node = nodes.value.find((item) => item.id === params.data.id)
      if (node) selectEntity(node)
    }
  })
}

onMounted(() => {
  loadGraph()

  resizeHandler = () => {
    chartInstance?.resize()
  }
  window.addEventListener('resize', resizeHandler)

  // @ts-ignore
  if (window.echarts) {
    renderChart()
    return
  }

  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js'
  script.onload = () => renderChart()
  document.head.appendChild(script)
})

onBeforeUnmount(() => {
  clearBuildPoll()
  disposeChart()
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler)
  }
})
</script>

<template>
  <div class="graph-projection" :class="{ fullscreen }">
    <div class="projection-shell">
      <div class="shell-grid shell-grid-a"></div>
      <div class="shell-grid shell-grid-b"></div>
      <div class="shell-orb orb-a"></div>
      <div class="shell-orb orb-b"></div>

      <div class="page-header">
        <div class="header-left">
          <div class="header-icon"><Hexagon :size="20" /></div>
          <div class="header-text">
            <div class="eyebrow">NEURAL CIRCUIT MAP</div>
            <h1>BRAIN GRAPH PROJECTION</h1>
            <span class="header-sub">{{ projectionSubtitle }} · {{ stats.node_count }} nodes · {{ stats.edge_count }} relations</span>
          </div>
        </div>

        <div class="header-actions">
          <RouterLink v-if="showOpenFullView" class="open-full-btn" to="/graph">
            <ExternalLink :size="14" />
            Open full view
          </RouterLink>
          <button class="build-btn" @click="buildGraph" :disabled="isBuilding">
            <RefreshCw :size="14" :class="{ spin: isBuilding }" />
            {{ isBuilding ? 'BUILDING PROJECTION...' : 'REBUILD PROJECTION' }}
          </button>
        </div>
      </div>

      <div v-if="buildStatus !== 'idle'" class="build-alert" :class="`is-${buildStatus}`">
        <div class="build-alert-grid">
          <div class="build-alert-signal">
            <div class="signal-core"></div>
            <div class="signal-ring ring-1"></div>
            <div class="signal-ring ring-2"></div>
          </div>
          <div class="build-alert-copy">
            <div class="build-alert-title">{{ buildTitle }}</div>
            <div class="build-alert-message">{{ buildMessage }}</div>
          </div>
        </div>
      </div>

      <div class="telemetry-strip">
        <div class="telemetry-card">
          <Cpu :size="15" />
          <div>
            <span class="telemetry-label">Core memories</span>
            <strong>{{ stats.node_count }}</strong>
          </div>
        </div>
        <div class="telemetry-card">
          <Sparkles :size="15" />
          <div>
            <span class="telemetry-label">Signal paths</span>
            <strong>{{ stats.edge_count }}</strong>
          </div>
        </div>
        <div class="type-legend">
          <div v-for="(color, type) in typeColors" :key="type" class="legend-item">
            <div class="legend-dot" :style="{ background: color, boxShadow: `0 0 10px ${color}` }"></div>
            <span>{{ type.toUpperCase() }}</span>
          </div>
        </div>
      </div>

      <div class="main-area">
        <div class="graph-container">
          <div class="circuit-overlay">
            <span class="circuit-line line-a"></span>
            <span class="circuit-line line-b"></span>
            <span class="circuit-line line-c"></span>
            <span class="circuit-line line-d"></span>
            <span class="circuit-node node-a"></span>
            <span class="circuit-node node-b"></span>
            <span class="circuit-node node-c"></span>
          </div>

          <div class="graph-hud top-left">
            <span class="hud-label">SYSTEM</span>
            <strong>{{ nodes.length > 0 ? 'ONLINE' : 'STANDBY' }}</strong>
          </div>
          <div class="graph-hud top-right">
            <span class="hud-label">FOCUS</span>
            <strong>{{ selectedEntity?.name || 'AUTO' }}</strong>
          </div>

          <div v-if="nodes.length === 0 && !isLoading" class="empty-state">
            <div class="empty-icon">
              <div class="e-ring r1"></div>
              <div class="e-ring r2"></div>
              <Network :size="32" />
            </div>
            <div class="empty-title">NO PROJECTION DATA</div>
            <div class="empty-sub">Run brain learning or rebuild the projection graph</div>
          </div>

          <div ref="chartRef" v-show="nodes.length > 0" class="chart-canvas"></div>
        </div>

        <div class="entity-panel" v-if="selectedEntity">
          <div class="panel-title">
            <Info :size="14" />
            <span>ENTITY DETAIL</span>
            <button class="close-panel" @click="selectedEntity = null" aria-label="Close entity panel">×</button>
          </div>

          <div class="entity-header-glow"></div>
          <div class="entity-name" :style="{ color: getColor(selectedEntity.type) }">
            {{ selectedEntity.name }}
          </div>
          <div class="entity-type-tag" :style="{ color: getColor(selectedEntity.type), borderColor: getColor(selectedEntity.type) + '40' }">
            {{ (selectedEntity.type || 'unknown').toUpperCase() }} · {{ getNodeTier(selectedEntity).toUpperCase() }}
          </div>
          <div class="entity-context">{{ entityContext }}</div>
        </div>
      </div>

      <div class="relations-section" v-if="edges.length > 0">
        <div class="section-label">// RELATIONS ({{ edges.length }})</div>
        <div class="relations-scroll">
          <div v-for="edge in edges" :key="edge.id" class="rel-item">
            <span class="rel-node">{{ nodes.find((node) => node.id === edge.source)?.name?.slice(0, 16) || edge.source.slice(0, 8) }}</span>
            <div class="rel-arrow">
              <div class="arrow-line"></div>
              <span class="rel-type-badge">{{ edge.relation }}</span>
            </div>
            <span class="rel-node">{{ nodes.find((node) => node.id === edge.target)?.name?.slice(0, 16) || edge.target.slice(0, 8) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.graph-projection {
  position: relative;
  min-height: 100%;
  padding: 18px;
  overflow: hidden;
  background:
    radial-gradient(circle at top left, rgba(0, 245, 212, 0.08), transparent 24%),
    radial-gradient(circle at top right, rgba(56, 189, 248, 0.08), transparent 28%),
    linear-gradient(180deg, #030712 0%, #040a14 52%, #02050b 100%);
}

.graph-projection.fullscreen {
  min-height: calc(100vh - 48px);
}

.projection-shell {
  position: relative;
  min-height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  border: 1px solid rgba(90, 185, 255, 0.16);
  border-radius: 28px;
  background:
    linear-gradient(180deg, rgba(5, 10, 18, 0.94), rgba(3, 8, 16, 0.98)),
    radial-gradient(circle at center, rgba(0, 245, 212, 0.04), transparent 40%);
  box-shadow:
    inset 0 0 0 1px rgba(255, 255, 255, 0.02),
    0 0 0 1px rgba(0, 245, 212, 0.04),
    0 30px 80px rgba(0, 0, 0, 0.5);
}

.shell-grid,
.shell-orb {
  position: absolute;
  pointer-events: none;
}

.shell-grid {
  inset: 0;
  border-radius: inherit;
  opacity: 0.18;
}

.shell-grid-a {
  background-image:
    linear-gradient(rgba(0, 245, 212, 0.08) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 245, 212, 0.08) 1px, transparent 1px);
  background-size: 48px 48px;
  mask-image: linear-gradient(180deg, rgba(0, 0, 0, 0.7), transparent 100%);
}

.shell-grid-b {
  inset: 18px;
  border: 1px solid rgba(0, 245, 212, 0.08);
  opacity: 0.4;
}

.shell-orb {
  width: 260px;
  height: 260px;
  border-radius: 50%;
  filter: blur(56px);
  opacity: 0.24;
}

.orb-a {
  top: -80px;
  right: -60px;
  background: rgba(0, 245, 212, 0.3);
}

.orb-b {
  bottom: -120px;
  left: -50px;
  background: rgba(56, 189, 248, 0.28);
}

.page-header,
.telemetry-strip,
.main-area,
.relations-section,
.build-alert {
  position: relative;
  z-index: 1;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.header-left,
.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-text {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.eyebrow {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.24em;
  color: rgba(125, 211, 252, 0.78);
}

.header-icon {
  display: grid;
  place-items: center;
  width: 42px;
  height: 42px;
  border-radius: 14px;
  color: var(--accent-cyan);
  background: rgba(0, 245, 212, 0.08);
  border: 1px solid rgba(0, 245, 212, 0.18);
  box-shadow: 0 0 18px rgba(0, 245, 212, 0.18);
}

h1 {
  margin: 0;
  font-family: var(--font-display);
  font-size: 24px;
  font-weight: 700;
  letter-spacing: 0.18em;
  color: #edf9ff;
}

.header-sub {
  font-family: var(--font-mono);
  font-size: 11px;
  color: rgba(191, 219, 254, 0.72);
  letter-spacing: 0.12em;
}

.build-btn,
.open-full-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-height: 44px;
  padding: 0 16px;
  border-radius: 14px;
  border: 1px solid rgba(0, 245, 212, 0.2);
  background: linear-gradient(180deg, rgba(7, 18, 28, 0.92), rgba(5, 10, 18, 0.96));
  color: var(--accent-cyan);
  font-family: var(--font-display);
  font-size: 10px;
  letter-spacing: 0.14em;
  text-decoration: none;
  transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease, color 0.2s ease;
  cursor: pointer;
}

.build-btn:hover,
.open-full-btn:hover,
.build-btn:focus-visible,
.open-full-btn:focus-visible {
  border-color: rgba(0, 245, 212, 0.45);
  box-shadow: 0 0 0 1px rgba(0, 245, 212, 0.16), 0 0 24px rgba(0, 245, 212, 0.12);
  outline: none;
}

.build-btn:disabled {
  cursor: wait;
  opacity: 0.76;
}

.spin {
  animation: spin 1s linear infinite;
}

.build-alert {
  overflow: hidden;
  border-radius: 22px;
  border: 1px solid rgba(0, 245, 212, 0.16);
  background: linear-gradient(135deg, rgba(6, 12, 20, 0.96), rgba(7, 20, 32, 0.92));
}

.build-alert::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.05), transparent);
  transform: translateX(-100%);
  animation: scan 5.5s linear infinite;
}

.build-alert-grid {
  position: relative;
  z-index: 1;
  display: grid;
  grid-template-columns: 56px minmax(0, 1fr);
  gap: 14px;
  align-items: center;
  min-height: 88px;
  padding: 16px 18px;
}

.build-alert-signal {
  position: relative;
  width: 42px;
  height: 42px;
  margin-inline: auto;
}

.signal-core {
  position: absolute;
  inset: 12px;
  border-radius: 50%;
  background: currentColor;
  box-shadow: 0 0 18px currentColor;
}

.signal-ring {
  position: absolute;
  inset: 0;
  border-radius: 50%;
  border: 1px solid currentColor;
  opacity: 0.28;
}

.ring-1 {
  animation: pulse-ring 1.8s ease-out infinite;
}

.ring-2 {
  animation: pulse-ring 1.8s ease-out infinite 0.45s;
}

.build-alert-copy {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 0;
}

.build-alert-title {
  font-family: var(--font-display);
  font-size: 15px;
  letter-spacing: 0.18em;
}

.build-alert-message {
  font-family: var(--font-mono);
  font-size: 13px;
  line-height: 1.6;
  color: rgba(216, 241, 252, 0.82);
}

.build-alert.is-running {
  color: var(--accent-cyan);
}

.build-alert.is-success {
  color: #7fffd4;
}

.build-alert.is-error {
  color: #f87171;
}

.telemetry-strip {
  display: flex;
  align-items: stretch;
  gap: 12px;
  flex-wrap: wrap;
}

.telemetry-card {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 170px;
  padding: 12px 14px;
  border-radius: 18px;
  border: 1px solid rgba(90, 185, 255, 0.14);
  background: rgba(6, 12, 22, 0.78);
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.02);
  color: #c8f7ff;
}

.telemetry-card strong {
  display: block;
  margin-top: 3px;
  font-family: var(--font-display);
  font-size: 18px;
  color: #f8fdff;
  letter-spacing: 0.06em;
}

.telemetry-label {
  display: block;
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.14em;
  color: rgba(148, 163, 184, 0.86);
}

.type-legend {
  display: flex;
  align-items: center;
  gap: 14px;
  flex: 1;
  flex-wrap: wrap;
  padding: 12px 14px;
  border-radius: 18px;
  border: 1px solid rgba(90, 185, 255, 0.14);
  background: rgba(6, 12, 22, 0.72);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.12em;
  color: rgba(191, 219, 254, 0.74);
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 999px;
}

.main-area {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 340px;
  gap: 16px;
  min-height: 720px;
}

.graph-container,
.entity-panel,
.relations-section {
  border-radius: 24px;
  border: 1px solid rgba(90, 185, 255, 0.16);
  background:
    linear-gradient(180deg, rgba(5, 10, 18, 0.96), rgba(4, 8, 16, 0.98)),
    radial-gradient(circle at center, rgba(0, 245, 212, 0.04), transparent 44%);
  box-shadow:
    inset 0 0 0 1px rgba(255, 255, 255, 0.02),
    0 20px 56px rgba(0, 0, 0, 0.35);
}

.graph-container {
  position: relative;
  overflow: hidden;
  min-height: 720px;
}

.graph-container::before {
  content: '';
  position: absolute;
  inset: 0;
  background:
    radial-gradient(circle at 50% 48%, rgba(0, 245, 212, 0.12), transparent 28%),
    linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 20%, transparent 80%, rgba(0, 245, 212, 0.03));
  pointer-events: none;
}

.circuit-overlay {
  position: absolute;
  inset: 0;
  pointer-events: none;
  opacity: 0.36;
}

.circuit-line,
.circuit-node {
  position: absolute;
}

.circuit-line {
  background: linear-gradient(90deg, transparent, rgba(0, 245, 212, 0.9), transparent);
  box-shadow: 0 0 12px rgba(0, 245, 212, 0.45);
}

.line-a {
  top: 11%;
  left: 6%;
  width: 40%;
  height: 1px;
}

.line-b {
  top: 66%;
  left: 14%;
  width: 52%;
  height: 1px;
}

.line-c {
  top: 18%;
  right: 11%;
  width: 1px;
  height: 52%;
  background: linear-gradient(180deg, transparent, rgba(56, 189, 248, 0.88), transparent);
  box-shadow: 0 0 12px rgba(56, 189, 248, 0.4);
}

.line-d {
  bottom: 20%;
  right: 18%;
  width: 24%;
  height: 1px;
}

.circuit-node {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #00f5d4;
  box-shadow: 0 0 16px rgba(0, 245, 212, 0.85);
}

.node-a {
  top: calc(11% - 5px);
  left: calc(46% - 5px);
}

.node-b {
  top: calc(66% - 5px);
  left: calc(14% - 5px);
}

.node-c {
  top: calc(44% - 5px);
  right: calc(11% - 5px);
}

.graph-hud {
  position: absolute;
  z-index: 2;
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 124px;
  padding: 10px 12px;
  border-radius: 14px;
  border: 1px solid rgba(0, 245, 212, 0.16);
  background: rgba(4, 9, 16, 0.82);
  backdrop-filter: blur(12px);
}

.graph-hud strong {
  font-family: var(--font-display);
  font-size: 12px;
  letter-spacing: 0.14em;
  color: #ecfeff;
}

.hud-label {
  font-family: var(--font-mono);
  font-size: 9px;
  letter-spacing: 0.18em;
  color: rgba(125, 211, 252, 0.72);
}

.top-left {
  top: 16px;
  left: 16px;
}

.top-right {
  top: 16px;
  right: 16px;
  text-align: right;
}

.chart-canvas {
  position: relative;
  z-index: 1;
  width: 100%;
  height: 720px;
}

.empty-state {
  position: relative;
  z-index: 1;
  height: 100%;
  min-height: 720px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 12px;
  color: rgba(191, 219, 254, 0.68);
}

.empty-icon {
  position: relative;
  display: grid;
  place-items: center;
  width: 88px;
  height: 88px;
  color: var(--accent-cyan);
}

.e-ring {
  position: absolute;
  inset: 0;
  border: 1px solid rgba(0, 245, 212, 0.25);
  border-radius: 50%;
}

.empty-title {
  font-family: var(--font-display);
  letter-spacing: 0.18em;
  color: #f3fbff;
}

.empty-sub {
  font-family: var(--font-mono);
  font-size: 12px;
}

.entity-panel {
  position: relative;
  padding: 18px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow: hidden;
}

.entity-header-glow {
  position: absolute;
  top: -40px;
  right: -40px;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: rgba(0, 245, 212, 0.18);
  filter: blur(32px);
}

.panel-title {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  font-family: var(--font-display);
  letter-spacing: 0.12em;
  color: var(--accent-cyan);
}

.close-panel {
  margin-left: auto;
  min-width: 36px;
  min-height: 36px;
  border: 0;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.02);
  color: rgba(191, 219, 254, 0.68);
  font-size: 22px;
  cursor: pointer;
}

.close-panel:hover,
.close-panel:focus-visible {
  color: #ffffff;
  background: rgba(255, 255, 255, 0.06);
  outline: none;
}

.entity-name {
  position: relative;
  z-index: 1;
  font-size: 22px;
  font-family: var(--font-display);
  letter-spacing: 0.04em;
}

.entity-type-tag {
  position: relative;
  z-index: 1;
  width: fit-content;
  padding: 5px 10px;
  border: 1px solid;
  border-radius: 999px;
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.12em;
  background: rgba(255, 255, 255, 0.02);
}

.entity-context {
  position: relative;
  z-index: 1;
  color: rgba(226, 232, 240, 0.86);
  line-height: 1.7;
  white-space: pre-wrap;
}

.relations-section {
  padding: 16px;
}

.section-label {
  margin-bottom: 12px;
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.16em;
  color: var(--accent-cyan);
}

.relations-scroll {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.rel-item {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  gap: 12px;
  align-items: center;
  padding: 10px 12px;
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(148, 163, 184, 0.08);
}

.rel-node {
  color: rgba(226, 232, 240, 0.8);
  font-family: var(--font-mono);
  font-size: 12px;
}

.rel-arrow {
  display: flex;
  align-items: center;
  gap: 8px;
}

.arrow-line {
  width: 48px;
  height: 1px;
  background: linear-gradient(90deg, rgba(0, 245, 212, 0.1), rgba(0, 245, 212, 0.56), rgba(0, 245, 212, 0.1));
}

.rel-type-badge {
  color: var(--accent-cyan);
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.08em;
}

@keyframes pulse-ring {
  0% {
    transform: scale(0.85);
    opacity: 0.5;
  }
  100% {
    transform: scale(1.2);
    opacity: 0;
  }
}

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

@keyframes scan {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

@media (prefers-reduced-motion: reduce) {
  .spin,
  .ring-1,
  .ring-2,
  .build-alert::before,
  .r1,
  .r2 {
    animation: none;
  }
}

@media (max-width: 1200px) {
  .main-area {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 900px) {
  .graph-projection {
    padding: 12px;
  }

  .projection-shell {
    min-height: calc(100vh - 64px);
    padding: 14px;
    border-radius: 22px;
  }

  .page-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .telemetry-strip {
    flex-direction: column;
  }

  .type-legend {
    width: 100%;
  }

  .graph-container,
  .empty-state,
  .chart-canvas {
    min-height: 620px;
    height: 620px;
  }
}
</style>
