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

// Roadmap = read-only Übersichts-Graph: {knoten:[{id,title,text,prioritaet}],
// kanten:[{von,nach,typ}], richtung}. Layout via dagre, Knoten-Text via KaTeX.
const props = defineProps({
  graph: { type: Object, default: null },
  height: { type: String, default: '78vh' },
})

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

const nodes = ref([])
const edges = ref([])
const bereit = ref(false)
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: 'roadmap',
    position: { x: 0, y: 0 },
    data: {
      title: String(k.title || ''),
      text: String(k.text || ''),
      prioritaet: ['grund', 'kern', 'vertiefung'].includes(k.prioritaet) ? k.prioritaet : 'kern',
    },
  }))
  edges.value = (g.kanten || [])
    .filter((e) => ids.has(String(e.von)) && ids.has(String(e.nach)))
    .map((e, i) => {
      const optional = e.typ === 'optional'
      return {
        id: `e${i}`,
        source: String(e.von),
        target: String(e.nach),
        type: 'smoothstep',
        markerEnd: MarkerType.ArrowClosed,
        style: optional ? { strokeDasharray: '6 4', opacity: 0.7 } : {},
      }
    })
}

// Two-Pass: Vue Flow misst die Knoten, dann rechnet dagre das Layout.
function layout() {
  const g = new dagre.graphlib.Graph()
  g.setDefaultEdgeLabel(() => ({}))
  g.setGraph({ rankdir: richtung.value, nodesep: 50, ranksep: 70 })
  for (const n of nodes.value) {
    const dim = findNode(n.id)?.dimensions
    g.setNode(n.id, { width: dim?.width || 180, height: dim?.height || 56 })
  }
  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
  layout()
  bereit.value = true
  await nextTick()
  fitView({ padding: 0.2 })
})

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

<template>
  <div class="roadmap-view" :style="{ height }">
    <p v-if="fehler" class="rm-fallback">Roadmap nicht verfügbar — neu generieren.</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-roadmap="{ data }">
        <Handle type="target" :position="targetPos" />
        <div class="rm-node" :class="'prio-' + data.prioritaet">
          <div class="rm-title">{{ data.title }}</div>
          <div v-if="data.text" class="rm-text markdown" v-html="renderMarkdownInline(data.text)"></div>
        </div>
        <Handle type="source" :position="sourcePos" />
      </template>
    </VueFlow>
  </div>
</template>

<style scoped>
.roadmap-view { width: 100%; position: relative; }
.rm-fallback { color: var(--text-muted); font-size: 0.85rem; padding: 1rem 0; }
.rm-node {
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border-strong, #999);
  border-left: 4px solid var(--rm-accent, #8b5cf6);
  border-radius: 8px;
  background: color-mix(in srgb, var(--rm-accent, #8b5cf6) 7%, var(--panel, #fff));
  color: var(--text, #111);
  max-width: 260px;
  white-space: normal;
  overflow-wrap: anywhere;
}
.rm-title { font-weight: 600; font-size: 0.85rem; line-height: 1.25; }
.rm-text { font-size: 0.74rem; color: var(--text-muted, #555); line-height: 1.3; margin-top: 0.2rem; }
.rm-text :deep(.katex) { white-space: normal; }
/* Prioritäts-Farben: grund=grün (Fundament), kern=lila (Hauptstoff), vertiefung=grau (später). */
.prio-grund { --rm-accent: #22c55e; }
.prio-kern { --rm-accent: #8b5cf6; }
.prio-vertiefung { --rm-accent: #94a3b8; }
</style>
