<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { VueFlow, useVueFlow } 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 } from '../composables/useLayout'

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]
}>()

const nodes = ref<any[]>([])
const edges = ref<any[]>([])
const { onNodeClick, onConnect, fitView } = useVueFlow()

function makeNodes() {
  const positions = computePositions(props.sceneNodes, props.sceneEdges, props.startScene)
  return props.sceneNodes.map((n) => {
    const pos = positions.get(n.id) ?? { x: 0, y: 0 }
    return {
      id: n.id,
      type: 'default',
      position: pos,
      data: { label: n.id === props.startScene ? `\u25b6 ${n.label}` : n.label },
      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) => ({
    id: e.id,
    source: e.source,
    target: e.target,
    label: e.label ?? '',
    animated: true,
  }))
}

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

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"
      :min-zoom="0.2"
      :max-zoom="2"
    >
      <Background :gap="20" />
      <Controls />
    </VueFlow>
  </div>
</template>

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