<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { VueFlow, useVueFlow, SmoothStepEdge, Handle, Position } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
import '@vue-flow/core/dist/style.css'
import '@vue-flow/controls/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import type { Connection } from '@vue-flow/core'
import { computePositions, savePosition } from '../composables/useLayout'
import { useEditorStore } from '../stores/editorStore'

const props = defineProps<{
  sceneNodes: { id: string; label: string }[]
  sceneEdges: { id: string; source: string; target: string; label?: string }[]
  startScene: string
  selectedNodeId: string | null
}>()

const emit = defineEmits<{
  selectNode: [id: string]
  addEdge: [source: string, target: string]
  testScene: [id: string]
  clearSelection: []
}>()

const store = useEditorStore()

const nodes = ref<any[]>([])
const edges = ref<any[]>([])
const { onNodeClick, onConnect, onNodeContextMenu, onNodeDragStop, onPaneClick, fitView } = useVueFlow()
const ctxMenuVisible = ref(false)
const ctxMenuX = ref(0)
const ctxMenuY = ref(0)
const ctxMenuNodeId = ref('')

function makeNodes() {
  const positions = computePositions(props.sceneNodes, props.sceneEdges, props.startScene)
  const changes = store.aiChanges
  return props.sceneNodes.map((n) => {
    const pos = positions.get(n.id) ?? { x: 0, y: 0 }
    let badge = ''
    if (changes) {
      if (changes.added.includes(n.id)) badge = 'NEW'
      else if (changes.modified.includes(n.id)) badge = 'MOD'
      else if (changes.deleted.includes(n.id)) badge = 'DEL'
    }
    return {
      id: n.id,
      type: 'default',
      position: pos,
      data: {
        label: n.id === props.startScene ? `\u25b6 ${n.label}` : n.label,
        badge,
      },
      style: n.id === props.startScene
        ? { background: '#1b5e20', color: '#fff', borderColor: '#388e3c' }
        : n.id === props.selectedNodeId
          ? { background: '#1565c0', color: '#fff', borderColor: '#1976d2' }
          : {},
      sourcePosition: 'right' as const,
      targetPosition: 'left' as const,
      connectable: true,
    }
  })
}

function makeEdges() {
  return props.sceneEdges.map((e) => {
    const isUp = props.selectedNodeId != null && e.target === props.selectedNodeId
    const isDown = props.selectedNodeId != null && e.source === props.selectedNodeId
    return {
      id: e.id,
      source: e.source,
      target: e.target,
      label: e.label ?? '',
      animated: isUp || isDown,
      style: isUp
        ? { stroke: '#ff9800', strokeWidth: 2 }
        : isDown
          ? { stroke: '#4fc3f7', strokeWidth: 2 }
          : undefined,
    }
  })
}

let prevNodeCount = -1
let prevEdgeCount = -1
let didFitView = false
let rebuildSeq = 0

async function structuralRebuild() {
  const seq = ++rebuildSeq
  edges.value = []
  await nextTick()
  if (seq !== rebuildSeq) return
  nodes.value = makeNodes()
  await nextTick()
  if (seq !== rebuildSeq) return
  edges.value = makeEdges()
  prevNodeCount = props.sceneNodes.length
  prevEdgeCount = props.sceneEdges.length
  if (!didFitView && nodes.value.length > 0) {
    didFitView = true
    setTimeout(() => fitView({ padding: 0.2 }), 80)
  }
}

function inlineRebuild() {
  nodes.value = makeNodes()
  edges.value = makeEdges()
}

watch(
  () => [props.sceneNodes, props.sceneEdges, props.startScene, props.selectedNodeId, store.aiChanges] as const,
  () => {
    const nc = props.sceneNodes.length
    const ec = props.sceneEdges.length
    if (nc !== prevNodeCount || ec !== prevEdgeCount) {
      structuralRebuild()
    } else {
      inlineRebuild()
    }
  },
  { immediate: true },
)

onNodeClick((ev) => emit('selectNode', ev.node.id))

onNodeContextMenu((ev) => {
  ev.event.preventDefault()
  ctxMenuNodeId.value = ev.node.id
  ctxMenuX.value = ev.event.clientX
  ctxMenuY.value = ev.event.clientY
  ctxMenuVisible.value = true
})

function testFromHere() {
  emit('testScene', ctxMenuNodeId.value)
  ctxMenuVisible.value = false
}

function closeMenu() {
  ctxMenuVisible.value = false
}

onNodeDragStop((ev) => {
  const pos = ev.node.position
  savePosition(ev.node.id, Math.round(pos.x), Math.round(pos.y))
})

onPaneClick(() => emit('clearSelection'))

onConnect((conn: Connection) => {
  if (conn.source && conn.target) emit('addEdge', conn.source, conn.target)
})
</script>

<template>
  <div class="scene-graph">
    <VueFlow
      :nodes="nodes"
      :edges="edges"
      :default-edge-type="SmoothStepEdge"
      :min-zoom="0.2"
      :max-zoom="2"
    >
      <template #node-default="nodeProps">
        <div class="custom-node">
          <Handle type="target" :position="Position.Left" />
          <div class="custom-node-label">{{ nodeProps.data.label }}</div>
          <span v-if="nodeProps.data.badge" class="diff-badge" :class="`diff-badge-${nodeProps.data.badge}`">
            {{ nodeProps.data.badge }}
          </span>
          <Handle type="source" :position="Position.Right" />
        </div>
      </template>
      <Background :gap="20" />
      <Controls />
    </VueFlow>

    <Teleport to="body">
      <div v-if="ctxMenuVisible" class="ctx-menu-overlay" @click="closeMenu">
        <div class="ctx-menu" :style="{ left: ctxMenuX + 'px', top: ctxMenuY + 'px' }">
          <button class="ctx-item" @click="testFromHere">🎬 从此场景开始测试</button>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<style scoped>
.scene-graph {
  width: 100%;
  height: 100%;
  background: #0d0d1a;
}

.ctx-menu-overlay {
  position: fixed;
  inset: 0;
  z-index: 1000;
}

.ctx-menu {
  position: absolute;
  background: #1a1a2e;
  border: 1px solid rgba(255,255,255,0.15);
  border-radius: 6px;
  padding: 4px;
  min-width: 160px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.5);
}

.ctx-item {
  display: block;
  width: 100%;
  padding: 8px 14px;
  font-size: 13px;
  color: #ccc;
  background: none;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  text-align: left;
  transition: background 0.1s;
}

.ctx-item:hover {
  background: rgba(100,200,255,0.12);
  color: #fff;
}

.custom-node {
  position: relative;
  padding: 8px 30px 8px 12px;
  min-width: 120px;
  font-size: 12px;
}

.custom-node-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.diff-badge {
  position: absolute;
  top: 2px;
  right: 4px;
  padding: 1px 5px;
  font-size: 9px;
  font-weight: 600;
  border-radius: 2px;
  line-height: 1.4;
}

.diff-badge-NEW {
  background: #2e7d32;
  color: #c8e6c9;
}

.diff-badge-MOD {
  background: #e65100;
  color: #ffe0b2;
}

.diff-badge-DEL {
  background: #c62828;
  color: #ffcdd2;
  text-decoration: line-through;
}
</style>
