<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { VueFlow, useVueFlow, Handle, Position, MarkerType } from '@vue-flow/core'
import '@vue-flow/core/dist/style.css'
import dagre from '@dagrejs/dagre'
import { renderMarkdownInline } from '../markdown.js'

// Grafik = {knoten:[{id,text}], kanten:[{von,nach,text?}], richtung:'TB'|'LR'}.
// KI liefert nur die Semantik; Layout macht dagre, Mathe rendert KaTeX im Knoten.
const props = defineProps({
  graph: { type: Object, default: null },
  height: { type: String, default: '380px' },
})

let _seq = 0
const flowId = `gv-${++_seq}-${Math.floor(performance.now())}`
const { findNode, fitView, onNodesInitialized } = useVueFlow(flowId)

const nodes = ref([])
const edges = ref([])
const bereit = ref(false)   // erst nach dem Layout sichtbar (sonst kurz bei 0,0 gestapelt)
const fehler = ref(false)

const richtung = computed(() => (props.graph?.richtung === 'LR' ? 'LR' : 'TB'))
const istLR = computed(() => richtung.value === 'LR')
const targetPos = computed(() => (istLR.value ? Position.Left : Position.Top))
const sourcePos = computed(() => (istLR.value ? Position.Right : Position.Bottom))

function build() {
  bereit.value = false
  const g = props.graph
  const kn = g && Array.isArray(g.knoten) ? g.knoten : []
  if (!kn.length) {
    fehler.value = true
    nodes.value = []
    edges.value = []
    return
  }
  fehler.value = false
  const ids = new Set(kn.map((k) => String(k.id)))
  nodes.value = kn.map((k) => ({
    id: String(k.id),
    type: 'math',
    position: { x: 0, y: 0 },
    data: { text: String(k.text || '') },
  }))
  edges.value = (g.kanten || [])
    .filter((e) => ids.has(String(e.von)) && ids.has(String(e.nach)))
    .map((e, i) => ({
      id: `e${i}`,
      source: String(e.von),
      target: String(e.nach),
      label: e.text ? String(e.text) : undefined,
      type: 'smoothstep',
      markerEnd: MarkerType.ArrowClosed,
    }))
}

// Two-Pass: Vue Flow misst die Knoten (KaTeX!), erst dann rechnet dagre das Layout.
function layout() {
  const g = new dagre.graphlib.Graph()
  g.setDefaultEdgeLabel(() => ({}))
  g.setGraph({ rankdir: richtung.value, nodesep: 40, ranksep: 55 })
  for (const n of nodes.value) {
    const dim = findNode(n.id)?.dimensions
    g.setNode(n.id, { width: dim?.width || 160, height: dim?.height || 40 })
  }
  for (const e of edges.value) g.setEdge(e.source, e.target)
  dagre.layout(g)
  nodes.value = nodes.value.map((n) => {
    const p = g.node(n.id)
    return { ...n, position: { x: p.x - p.width / 2, y: p.y - p.height / 2 } }
  })
}

onNodesInitialized(async () => {
  if (!nodes.value.length) return
  await document.fonts.ready  // sonst misst der Browser Fallback-Font → falsche Breite
  layout()
  bereit.value = true
  await nextTick()
  fitView({ padding: 0.2 })
})

watch(() => props.graph, build, { immediate: true })
</script>

<template>
  <div class="graph-view" :style="{ height }">
    <p v-if="fehler" class="graph-fallback">Grafik nicht verfügbar — Bausteine ab „Grafiken" neu bauen.</p>
    <VueFlow
      v-else
      :id="flowId"
      :nodes="nodes"
      :edges="edges"
      :style="{ opacity: bereit ? 1 : 0 }"
      :nodes-draggable="false"
      :nodes-connectable="false"
      :elements-selectable="false"
      :zoom-on-scroll="false"
      :zoom-on-double-click="false"
      :min-zoom="0.2"
      :max-zoom="2"
      fit-view-on-init
    >
      <template #node-math="{ data }">
        <Handle type="target" :position="targetPos" />
        <div class="gv-node markdown" v-html="renderMarkdownInline(data.text)"></div>
        <Handle type="source" :position="sourcePos" />
      </template>
    </VueFlow>
  </div>
</template>

<style scoped>
.graph-view { width: 100%; position: relative; }
.graph-fallback { color: var(--text-muted); font-size: 0.85rem; padding: 1rem 0; }
.gv-node {
  padding: 0.4rem 0.65rem;
  border: 1px solid var(--border-strong, #999);
  border-radius: 8px;
  background: var(--panel, #fff);
  color: var(--text, #111);
  font-size: 0.8rem;
  line-height: 1.35;
  text-align: center;
  max-width: 300px;
  /* Langer Text/Formel umbricht, statt im Knoten abgeschnitten zu werden. */
  white-space: normal;
  overflow-wrap: anywhere;
}
/* KaTeX im Knoten umbrechen lassen + geerbtes Klippen (markdown .katex-display) neutralisieren. */
.gv-node :deep(.katex) { white-space: normal; }
.gv-node :deep(.katex-display) { overflow: visible; margin: 0; }
.graph-view :deep(.vue-flow__edge-text) { font-size: 0.72rem; fill: var(--text-muted, #666); }
.graph-view :deep(.vue-flow__edge-textbg) { fill: var(--panel, #fff); }
</style>
