<script setup>
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue'
import * as d3 from 'd3'
import { GRID, GRID_STEP_X, GRID_STEP_Y, snapToGrid } from './gridConstants.js'

// ---------------------------------------------------------------------------
// Props & Emits
// ---------------------------------------------------------------------------

const props = defineProps({
    dimensions: { type: Object, default: () => ({}) },
    currentPath: { type: Array, default: () => [] },

    // Legacy flat-prop support
    nodes: { type: Array, default: () => [] },
    lines: { type: Array, default: () => [] },
    connections: { type: Array, default: () => [] },
    currentLevel: { type: Number, default: 1 },
})

const emit = defineEmits([
    'node-click',
    'node-hover',
    'node-leave',
    'dimension-change',
    'create-node',
    'edit-node',
    'delete-node',
    'zoom-change',
])

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const ZOOM_IN_THRESHOLD  = 2.5
const ZOOM_OUT_THRESHOLD = 0.6
const ZOOM_IN_COMMIT     = 4.0
const ZOOM_OUT_COMMIT    = 0.25
const NODE_PROXIMITY     = 250
const FIT_PADDING        = 80    // px padding around nodes for labels
const FIT_MARGIN         = 0.85  // use 85% of viewport
const FIT_SCALE_MIN      = 0.3
const FIT_SCALE_MAX      = 2.0

const LINE_COLORS = [
    '#00d2ff', '#e94560', '#00ff88', '#7b68ee',
    '#ff6b6b', '#ffd93d', '#6bcb77', '#4d96ff',
    '#ff8fab', '#a8dadc', '#e07a5f', '#81b29a',
]

// ---------------------------------------------------------------------------
// Refs
// ---------------------------------------------------------------------------

const svgRef       = ref(null)
const containerRef = ref(null)
const transform    = ref(d3.zoomIdentity)
const hoveredNode  = ref(null)

// Dimension stack
const dimensionStack = ref([])
const currentDimensionIndex = ref(0)

// Transition state
const transitionState = ref({
    active: false,
    direction: null,
    progress: 0,
    targetNode: null,
    childDimension: null,
})

// Tracks whether we're mid-commit (prevent re-entry)
let isCommitting = false

// Grid visibility (shown during branch handle interaction)
const gridVisible = ref(false)
let gridFadeTimer = null

// Line highlighting (set by FAB hover)
const highlightedLineId = ref(null)

// Context menu
const contextMenu = ref({
    show: false,
    x: 0, y: 0,
    type: null,
    node: null,
    canvasX: 0, canvasY: 0,
})

// D3 references
let svg, g, zoom

// ---------------------------------------------------------------------------
// Derived helpers
// ---------------------------------------------------------------------------

const getLineColor = (index) => LINE_COLORS[index % LINE_COLORS.length]

const currentDimensionData = computed(() => {
    return dimensionStack.value[currentDimensionIndex.value] ?? null
})

const currentNodes = computed(() => {
    return currentDimensionData.value?.nodes ?? []
})

const currentDepth = computed(() => currentDimensionIndex.value + 1)

/** Whether we're currently inside a child dimension (not root) */
const isInChildDimension = computed(() => currentDimensionIndex.value > 0)

/** The parent node we zoomed into (if in child dimension) */
const parentNode = computed(() => {
    if (!isInChildDimension.value) return null
    return currentDimensionData.value?.parentNodeId ?? null
})

// ---------------------------------------------------------------------------
// Bootstrap dimension stack from props
// ---------------------------------------------------------------------------

const buildRootDimension = () => {
    if (props.dimensions && (props.dimensions.nodes || props.dimensions.lines)) {
        return {
            id: 'root',
            parentNodeId: null,
            lines: props.dimensions.lines ?? [],
            nodes: props.dimensions.nodes ?? [],
            connections: props.dimensions.connections ?? [],
            opacity: 1,
        }
    }
    return {
        id: 'root',
        parentNodeId: null,
        lines: props.lines ?? [],
        nodes: props.nodes ?? [],
        connections: props.connections ?? [],
        opacity: 1,
    }
}

// ---------------------------------------------------------------------------
// Fit-to-view transform
// ---------------------------------------------------------------------------

/**
 * Compute a D3 zoom transform that fits all nodes of a dimension into the
 * viewport with padding, instead of always resetting to scale=1.
 */
const computeFitTransform = (dimData, w, h) => {
    const nodes = dimData?.nodes ?? []
    if (!nodes.length) {
        return d3.zoomIdentity.translate(w / 2, h / 2).scale(1)
    }

    const xMin = Math.min(...nodes.map(n => n.x)) - FIT_PADDING
    const xMax = Math.max(...nodes.map(n => n.x)) + FIT_PADDING
    const yMin = Math.min(...nodes.map(n => n.y)) - FIT_PADDING
    const yMax = Math.max(...nodes.map(n => n.y)) + FIT_PADDING

    // Guard against degenerate bbox (single node or co-linear)
    const bboxW = Math.max(xMax - xMin, 100)
    const bboxH = Math.max(yMax - yMin, 100)

    const scaleX = (w * FIT_MARGIN) / bboxW
    const scaleY = (h * FIT_MARGIN) / bboxH
    const scale  = Math.min(Math.max(Math.min(scaleX, scaleY), FIT_SCALE_MIN), FIT_SCALE_MAX)

    const bboxCenterX = (xMin + xMax) / 2
    const bboxCenterY = (yMin + yMax) / 2

    const tx = w / 2 - bboxCenterX * scale
    const ty = h / 2 - bboxCenterY * scale

    return d3.zoomIdentity.translate(tx, ty).scale(scale)
}

// ---------------------------------------------------------------------------
// Canvas init
// ---------------------------------------------------------------------------

const initCanvas = () => {
    if (!svgRef.value) return

    const width  = containerRef.value.clientWidth
    const height = containerRef.value.clientHeight

    svg = d3.select(svgRef.value)
        .attr('width', width)
        .attr('height', height)

    svg.selectAll('*').remove()

    // --- Defs ---
    const defs = svg.append('defs')

    const glowFilter = defs.append('filter')
        .attr('id', 'glow')
        .attr('x', '-50%').attr('y', '-50%')
        .attr('width', '200%').attr('height', '200%')

    glowFilter.append('feGaussianBlur')
        .attr('stdDeviation', '4')
        .attr('result', 'coloredBlur')

    const feMerge = glowFilter.append('feMerge')
    feMerge.append('feMergeNode').attr('in', 'coloredBlur')
    feMerge.append('feMergeNode').attr('in', 'SourceGraphic')

    const childGlowFilter = defs.append('filter')
        .attr('id', 'childGlow')
        .attr('x', '-100%').attr('y', '-100%')
        .attr('width', '300%').attr('height', '300%')

    childGlowFilter.append('feGaussianBlur')
        .attr('stdDeviation', '2')
        .attr('result', 'coloredBlur')

    const feMerge2 = childGlowFilter.append('feMerge')
    feMerge2.append('feMergeNode').attr('in', 'coloredBlur')
    feMerge2.append('feMergeNode').attr('in', 'SourceGraphic')

    // Main panning/zooming group
    g = svg.append('g')

    // --- Zoom ---
    zoom = d3.zoom()
        .scaleExtent([0.15, 6])
        .on('zoom', handleZoom)

    svg.call(zoom)

    // Right-click context menu
    svg.on('contextmenu', (event) => {
        event.preventDefault()
        const [x, y] = d3.pointer(event, g.node())
        const clickedNode = findNodeAt(x, y)
        contextMenu.value = {
            show: true,
            x: event.clientX,
            y: event.clientY,
            type: clickedNode ? 'node' : 'canvas',
            node: clickedNode,
            canvasX: x,
            canvasY: y,
        }
    })

    // Seed the dimension stack with root data
    dimensionStack.value = [buildRootDimension()]
    currentDimensionIndex.value = 0

    // Fit initial view to the data instead of hardcoded scale=1
    const rootDim = dimensionStack.value[0]
    svg.call(zoom.transform, computeFitTransform(rootDim, width, height))

    renderMap()
}

// ---------------------------------------------------------------------------
// Zoom handler
// ---------------------------------------------------------------------------

const handleZoom = (event) => {
    const t = event.transform
    g.attr('transform', t)
    transform.value = t

    // During commit animation, just apply the visual transform — skip threshold logic
    if (isCommitting) return

    emit('zoom-change', { scale: t.k, x: t.x, y: t.y })

    const w  = containerRef.value?.clientWidth  ?? 800
    const h  = containerRef.value?.clientHeight ?? 600
    const cx = (w / 2 - t.x) / t.k
    const cy = (h / 2 - t.y) / t.k
    const nearest = findNearestNode(cx, cy)

    // --- Zoom-in transition ---
    if (t.k > ZOOM_IN_THRESHOLD &&
        nearest &&
        nearest.node.children &&
        nearest.distance < NODE_PROXIMITY)
    {
        const range = ZOOM_IN_COMMIT - ZOOM_IN_THRESHOLD
        const progress = Math.min(1, Math.max(0, (t.k - ZOOM_IN_THRESHOLD) / range))

        transitionState.value = {
            active: true,
            direction: 'in',
            progress,
            targetNode: nearest.node,
            childDimension: nearest.node.children,
        }

        renderWithTransition()

        if (progress >= 1) {
            commitDimensionChange('in', nearest.node)
        }
        return
    }

    // --- Zoom-out transition ---
    if (t.k < ZOOM_OUT_THRESHOLD && dimensionStack.value.length > 1) {
        const range = ZOOM_OUT_THRESHOLD - ZOOM_OUT_COMMIT
        const progress = Math.min(1, Math.max(0, (ZOOM_OUT_THRESHOLD - t.k) / range))

        transitionState.value = {
            active: true,
            direction: 'out',
            progress,
            targetNode: null,
            childDimension: null,
        }

        renderWithTransition()

        if (progress >= 1) {
            commitDimensionChange('out', null)
        }
        return
    }

    // --- Normal range: cancel any ongoing transition ---
    if (transitionState.value.active) {
        transitionState.value.active = false
    }
    renderMap()
}

// ---------------------------------------------------------------------------
// Dimension commit
// ---------------------------------------------------------------------------

const commitDimensionChange = (direction, node) => {
    if (isCommitting) return
    isCommitting = true

    if (direction === 'in' && node) {
        const children = node.children
        const child = {
            id: node.id,
            parentNodeId: node.id,
            // Prefer metadata from backend, fall back to node's own entity info
            parentEntityType: children.parentEntityType ?? node.entityType ?? null,
            parentEntityId: children.parentEntityId ?? node.entityId ?? null,
            parentName: children.parentName ?? node.name ?? null,
            lines: children.lines ?? [],
            nodes: children.nodes ?? [],
            connections: children.connections ?? [],
            opacity: 1,
        }
        dimensionStack.value.push(child)
        currentDimensionIndex.value++

        animateZoomReset()

        transitionState.value.active = false
        emit('dimension-change', {
            direction: 'in',
            node,
            depth: dimensionStack.value.length,
            dimension: child,
        })
    } else if (direction === 'out') {
        dimensionStack.value.pop()
        currentDimensionIndex.value = Math.max(0, currentDimensionIndex.value - 1)

        animateZoomReset()

        transitionState.value.active = false
        emit('dimension-change', {
            direction: 'out',
            depth: dimensionStack.value.length,
            dimension: currentDimensionData.value,
        })
    }
}

/**
 * Smoothly animate to a fit-to-view transform for the current dimension.
 * Calculates bounding box of all nodes and zooms to fit them in the viewport.
 * The zoom handler stays active but isCommitting guards against threshold logic.
 */
const animateZoomReset = () => {
    if (!svg || !zoom) {
        isCommitting = false
        renderMap()
        return
    }

    const w = containerRef.value?.clientWidth  ?? 800
    const h = containerRef.value?.clientHeight ?? 600

    const targetDim = currentDimensionData.value
    const targetTransform = computeFitTransform(targetDim, w, h)

    // Render the new dimension immediately so the animation shows correct content
    renderMap()

    svg.transition()
        .duration(400)
        .ease(d3.easeCubicOut)
        .call(zoom.transform, targetTransform)
        .on('end', () => {
            isCommitting = false
            renderMap()
        })
}

// ---------------------------------------------------------------------------
// Node finders
// ---------------------------------------------------------------------------

const findNearestNode = (x, y) => {
    const nodes = currentNodes.value
    if (!nodes.length) return null
    let nearest = null
    let minDist  = Infinity
    for (const node of nodes) {
        const dist = Math.sqrt((node.x - x) ** 2 + (node.y - y) ** 2)
        if (dist < minDist) {
            minDist = dist
            nearest = { node, distance: dist }
        }
    }
    return nearest
}

const findNodeAt = (x, y, dimData = null) => {
    const nodes = dimData?.nodes ?? currentNodes.value
    return nodes.find(n => Math.sqrt((n.x - x) ** 2 + (n.y - y) ** 2) < 15) ?? null
}

// ---------------------------------------------------------------------------
// Grid rendering (shown on interaction only)
// ---------------------------------------------------------------------------

const renderGrid = (dimData, parentGroup) => {
    const nodes = dimData?.nodes ?? []
    if (!nodes.length) return

    const gridGroup = parentGroup.append('g')
        .attr('class', 'grid-layer')
        .attr('opacity', gridVisible.value ? 0.6 : 0)
        .style('transition', 'opacity 0.3s ease')

    const margin = 300
    const xMin = Math.min(...nodes.map(n => n.x)) - margin
    const xMax = Math.max(...nodes.map(n => n.x)) + margin
    const yMin = Math.min(...nodes.map(n => n.y)) - margin
    const yMax = Math.max(...nodes.map(n => n.y)) + margin

    for (let x = snapToGrid(xMin); x <= xMax; x += GRID_STEP_X) {
        gridGroup.append('line')
            .attr('x1', x).attr('y1', yMin)
            .attr('x2', x).attr('y2', yMax)
            .attr('stroke', 'rgba(0, 210, 255, 0.06)')
            .attr('stroke-width', 0.5)
            .attr('stroke-dasharray', '2,6')
    }
    for (let y = snapToGrid(yMin); y <= yMax; y += GRID_STEP_Y) {
        gridGroup.append('line')
            .attr('x1', xMin).attr('y1', y)
            .attr('x2', xMax).attr('y2', y)
            .attr('stroke', 'rgba(0, 210, 255, 0.06)')
            .attr('stroke-width', 0.5)
            .attr('stroke-dasharray', '2,6')
    }
}

const showGrid = () => {
    clearTimeout(gridFadeTimer)
    gridVisible.value = true
    if (g) g.select('.grid-layer').transition().duration(200).attr('opacity', 0.6)
}

const hideGrid = () => {
    gridFadeTimer = setTimeout(() => {
        gridVisible.value = false
        if (g) g.select('.grid-layer').transition().duration(300).attr('opacity', 0)
    }, 400)
}

// ---------------------------------------------------------------------------
// Branch handles
// ---------------------------------------------------------------------------

/**
 * Render branch handles on a hovered node.
 * 0° = extend line right, 45° = fork down-right, 315° = fork up-right.
 */
const renderBranchHandles = (nodeGroup, node, allNodes) => {
    // Remove any existing handles first
    nodeGroup.select('.branch-handles').remove()

    const handleGroup = nodeGroup.append('g').attr('class', 'branch-handles')
    const HANDLE_DIST = 30   // distance from node center to handle
    const HANDLE_R = 9       // handle circle radius

    const branches = [
        { deg: 0,   dx: GRID_STEP_X,  dy: 0,             label: '→' },   // extend right
        { deg: 90,  dx: 0,            dy: GRID_STEP_Y,   label: '↓' },   // extend down
        { deg: 180, dx: -GRID_STEP_X, dy: 0,             label: '←' },   // extend left
        { deg: 270, dx: 0,            dy: -GRID_STEP_Y,  label: '↑' },   // extend up
        { deg: 45,  dx: GRID_STEP_X,  dy: GRID_STEP_Y,   label: '↘' },   // fork down-right
        { deg: 315, dx: GRID_STEP_X,  dy: -GRID_STEP_Y,  label: '↗' },   // fork up-right
    ]

    branches.forEach(b => {
        const targetX = snapToGrid(node.x + b.dx)
        const targetY = snapToGrid(node.y + b.dy)

        // Allow branching to occupied positions — metro interchanges are valid
        const occupied = allNodes.some(n => n.x === targetX && n.y === targetY)

        const rad = (b.deg * Math.PI) / 180
        const hx = Math.cos(rad) * HANDLE_DIST
        const hy = Math.sin(rad) * HANDLE_DIST

        // Handle circle
        const handle = handleGroup.append('circle')
            .attr('cx', hx).attr('cy', hy)
            .attr('r', HANDLE_R)
            .attr('fill', 'rgba(0, 210, 255, 0.1)')
            .attr('stroke', '#00d2ff')
            .attr('stroke-width', 1.5)
            .attr('stroke-dasharray', '3,2')
            .attr('cursor', 'pointer')
            .attr('class', 'branch-handle')
            .attr('opacity', 0)
            .transition().duration(200)
            .attr('opacity', 0.8)

        // "+" text on handle
        handleGroup.append('text')
            .attr('x', hx).attr('y', hy + 4)
            .attr('text-anchor', 'middle')
            .attr('fill', '#00d2ff')
            .attr('font-family', "'VT323', monospace")
            .attr('font-size', '13px')
            .attr('pointer-events', 'none')
            .attr('opacity', 0)
            .transition().duration(200)
            .attr('opacity', 0.9)
            .text('+')

        // Invisible larger hit area for the handle
        handleGroup.append('circle')
            .attr('cx', hx).attr('cy', hy)
            .attr('r', HANDLE_R + 6)
            .attr('fill', 'transparent')
            .attr('cursor', 'pointer')
            .on('mouseenter', () => {
                // Ghost preview: dashed line + ghost circle at target
                handleGroup.selectAll('.ghost-preview').remove()
                handleGroup.append('line')
                    .attr('class', 'ghost-preview')
                    .attr('x1', 0).attr('y1', 0)
                    .attr('x2', b.dx).attr('y2', b.dy)
                    .attr('stroke', '#00d2ff')
                    .attr('stroke-width', 2)
                    .attr('stroke-dasharray', '6,4')
                    .attr('opacity', 0.4)
                handleGroup.append('circle')
                    .attr('class', 'ghost-preview')
                    .attr('cx', b.dx).attr('cy', b.dy)
                    .attr('r', 8)
                    .attr('fill', 'none')
                    .attr('stroke', '#00d2ff')
                    .attr('stroke-width', 1.5)
                    .attr('stroke-dasharray', '4,3')
                    .attr('opacity', 0.5)
                handleGroup.append('text')
                    .attr('class', 'ghost-preview')
                    .attr('x', b.dx).attr('y', b.dy + 28)
                    .attr('text-anchor', 'middle')
                    .attr('fill', '#00d2ff')
                    .attr('font-family', "'VT323', monospace")
                    .attr('font-size', '12px')
                    .attr('opacity', 0.5)
                    .text(occupied ? 'interchange' : ([90, 270].includes(b.deg) ? 'new track' : 'extend'))
            })
            .on('mouseleave', () => {
                handleGroup.selectAll('.ghost-preview').remove()
            })
            .on('click', (event) => {
                event.stopPropagation()
                emit('create-node', {
                    x: targetX,
                    y: targetY,
                    lineId: [90, 270].includes(b.deg) ? null : node.lineId, // only up/down = new track, everything else extends
                    afterNodeId: node.id,
                    branchAngle: b.deg,
                    parentNodeId: currentDimensionData.value?.parentNodeId ?? null,
                    parentEntityType: currentDimensionData.value?.parentEntityType ?? null,
                    parentEntityId: currentDimensionData.value?.parentEntityId ?? null,
                    dimensionId: currentDimensionData.value?.id ?? 'root',
                    depth: currentDepth.value,
                    sourceNode: node,
                })
            })
    })
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

const renderDimension = (dimData, opacity, parentGroup) => {
    if (!dimData) return

    const group = parentGroup.append('g')
        .attr('opacity', opacity)
        .attr('class', 'dimension-group')
        .style('transition', 'opacity 0.05s linear')

    // Grid layer (behind everything, only visible during interaction)
    renderGrid(dimData, group)

    const nodes       = dimData.nodes       ?? []
    const lines       = dimData.lines       ?? []
    const connections = dimData.connections ?? []

    // --- Metro lines ---
    lines.forEach((line, lineIndex) => {
        const color     = line.color || getLineColor(lineIndex)
        const isHighlighted = highlightedLineId.value === line.id
        const isAnyHighlighted = highlightedLineId.value !== null
        const lineNodes = nodes
            .filter(n => n.lineId === line.id)
            .sort((a, b) => a.order - b.order)

        if (lineNodes.length < 2) {
            // Still render a single node's line label
            if (lineNodes.length === 1) {
                group.append('text')
                    .attr('x', lineNodes[0].x - 10)
                    .attr('y', lineNodes[0].y - 35)
                    .attr('fill', color)
                    .attr('font-family', "'VT323', monospace")
                    .attr('font-size', '16px')
                    .attr('opacity', 0.85)
                    .text(line.name)
            }
            if (lineNodes.length < 2) return
        }

        const lineGen = d3.line()
            .x(d => d.x)
            .y(d => d.y)
            .curve(d3.curveMonotoneX)

        const trackOpacity = isAnyHighlighted ? (isHighlighted ? 1.0 : 0.2) : 0.75
        const glowOpacity = isAnyHighlighted ? (isHighlighted ? 0.3 : 0.05) : 0.15

        // Outer glow track
        group.append('path')
            .datum(lineNodes)
            .attr('d', lineGen)
            .attr('fill', 'none')
            .attr('stroke', color)
            .attr('stroke-width', isHighlighted ? 10 : 8)
            .attr('stroke-linecap', 'round')
            .attr('opacity', glowOpacity)
            .attr('filter', isHighlighted ? 'url(#glow)' : null)

        // Main track
        group.append('path')
            .datum(lineNodes)
            .attr('d', lineGen)
            .attr('fill', 'none')
            .attr('stroke', color)
            .attr('stroke-width', isHighlighted ? 5 : 4)
            .attr('stroke-linecap', 'round')
            .attr('opacity', trackOpacity)

        // Line label
        if (lineNodes.length > 0) {
            group.append('text')
                .attr('x', lineNodes[0].x - 10)
                .attr('y', lineNodes[0].y - 35)
                .attr('fill', color)
                .attr('font-family', "'VT323', monospace")
                .attr('font-size', '16px')
                .attr('opacity', 0.85)
                .text(line.name)
        }
    })

    // --- Dependency connections ---
    connections.forEach(conn => {
        const source = nodes.find(n => n.id === conn.from)
        const target = nodes.find(n => n.id === conn.to)
        if (!source || !target) return

        group.append('line')
            .attr('x1', source.x).attr('y1', source.y)
            .attr('x2', target.x).attr('y2', target.y)
            .attr('stroke', '#8892b0')
            .attr('stroke-width', 1.5)
            .attr('stroke-dasharray', '6,4')
            .attr('opacity', 0.4)
    })

    // --- Station nodes ---
    const nodeGroups = group.selectAll('.station')
        .data(nodes)
        .enter()
        .append('g')
        .attr('class', 'station')
        .attr('transform', d => `translate(${d.x}, ${d.y})`)
        .attr('cursor', 'pointer')
        .on('click', (event, d) => {
            event.stopPropagation()
            emit('node-click', d)
        })
        .on('mouseenter', (event, d) => {
            hoveredNode.value = d
            d3.select(event.currentTarget).select('.station-dot')
                .transition().duration(200)
                .attr('r', 12)
                .attr('filter', 'url(#glow)')

            // Show branch handles
            showGrid()
            renderBranchHandles(d3.select(event.currentTarget), d, nodes)

            emit('node-hover', d)
        })
        .on('mouseleave', (event, d) => {
            hoveredNode.value = null
            d3.select(event.currentTarget).select('.station-dot')
                .transition().duration(200)
                .attr('r', 8)
                .attr('filter', null)

            // Remove branch handles
            d3.select(event.currentTarget).select('.branch-handles').remove()
            hideGrid()

            emit('node-leave', d)
        })

    // Outer ring
    nodeGroups.append('circle')
        .attr('r', 11)
        .attr('fill', 'none')
        .attr('stroke', d => {
            const line = lines.find(l => l.id === d.lineId)
            return line?.color || getLineColor(lines.indexOf(line))
        })
        .attr('stroke-width', 2)

    // Inner dot
    nodeGroups.append('circle')
        .attr('class', 'station-dot')
        .attr('r', 8)
        .attr('fill', d => {
            if (d.status === 'afgerond' || d.status === 'completed') return '#00ff88'
            if (d.status === 'actief'   || d.status === 'active')    return '#00d2ff'
            if (d.status === 'geparkeerd')                            return '#ffd93d'
            if (d.status === 'gestopt')                               return '#e94560'
            return '#16213e'
        })
        .attr('stroke', d => {
            const line = lines.find(l => l.id === d.lineId)
            return line?.color || getLineColor(lines.indexOf(line))
        })
        .attr('stroke-width', 2)

    // Child-dimension indicator: populated dimension (has nodes inside)
    nodeGroups.filter(d => d.children && (d.children.nodes?.length ?? 0) > 0)
        .append('circle')
        .attr('r', 16)
        .attr('fill', 'none')
        .attr('stroke', '#00d2ff')
        .attr('stroke-width', 1)
        .attr('stroke-dasharray', '3,3')
        .attr('opacity', 0.5)
        .attr('filter', 'url(#childGlow)')

    nodeGroups.filter(d => d.children && (d.children.nodes?.length ?? 0) > 0)
        .append('text')
        .attr('x', 13)
        .attr('y', -13)
        .attr('fill', '#00d2ff')
        .attr('font-family', "'VT323', monospace")
        .attr('font-size', '11px')
        .attr('opacity', 0.8)
        .text('[+]')

    // Empty dimension indicator (dimension exists but no nodes yet)
    nodeGroups.filter(d => d.children && (d.children.nodes?.length ?? 0) === 0)
        .append('circle')
        .attr('r', 14)
        .attr('fill', 'none')
        .attr('stroke', '#8892b0')
        .attr('stroke-width', 0.8)
        .attr('stroke-dasharray', '2,4')
        .attr('opacity', 0.4)

    nodeGroups.filter(d => d.children && (d.children.nodes?.length ?? 0) === 0)
        .append('text')
        .attr('x', 13)
        .attr('y', -13)
        .attr('fill', '#8892b0')
        .attr('font-family', "'VT323', monospace")
        .attr('font-size', '10px')
        .attr('opacity', 0.5)
        .text('[○]')

    // Station label (truncated to prevent overlap, max ~20 chars)
    nodeGroups.append('text')
        .attr('x', 0)
        .attr('y', 28)
        .attr('text-anchor', 'middle')
        .attr('fill', '#e8e8e8')
        .attr('font-family', "'VT323', monospace")
        .attr('font-size', '13px')
        .text(d => {
            const name = d.name ?? ''
            const maxLen = Math.max(12, Math.floor(GRID_STEP_X / 10))
            return name.length > maxLen ? name.slice(0, maxLen - 1) + '…' : name
        })

    // Status badge
    nodeGroups.filter(d => d.badge)
        .append('text')
        .attr('x', 0)
        .attr('y', 42)
        .attr('text-anchor', 'middle')
        .attr('fill', '#8892b0')
        .attr('font-family', "'IBM Plex Mono', monospace")
        .attr('font-size', '10px')
        .text(d => d.badge)
}

/** Normal render */
const renderMap = () => {
    if (!g) return
    g.selectAll('*').remove()
    const dim = currentDimensionData.value
    if (dim) renderDimension(dim, 1, g)
}

/** Cross-fade render during a zoom transition */
const renderWithTransition = () => {
    if (!g) return
    g.selectAll('*').remove()

    const { progress, direction, childDimension } = transitionState.value
    const eased = d3.easeCubicInOut(progress)

    if (direction === 'in') {
        renderDimension(currentDimensionData.value, 1 - eased, g)
        if (childDimension) {
            renderDimension(
                {
                    lines: childDimension.lines ?? [],
                    nodes: childDimension.nodes ?? [],
                    connections: childDimension.connections ?? [],
                },
                eased,
                g
            )
        }
    } else if (direction === 'out' && dimensionStack.value.length > 1) {
        renderDimension(currentDimensionData.value, 1 - eased, g)
        const parentDim = dimensionStack.value[currentDimensionIndex.value - 1]
        if (parentDim) {
            renderDimension(parentDim, eased, g)
        }
    }
}

// ---------------------------------------------------------------------------
// Context menu handlers
// ---------------------------------------------------------------------------

const closeContextMenu = () => {
    contextMenu.value.show = false
}

const handleContextCreate = () => {
    emit('create-node', {
        x: contextMenu.value.canvasX,
        y: contextMenu.value.canvasY,
        parentNodeId: currentDimensionData.value?.parentNodeId ?? null,
        parentEntityType: currentDimensionData.value?.parentEntityType ?? null,
        parentEntityId: currentDimensionData.value?.parentEntityId ?? null,
        dimensionId: currentDimensionData.value?.id ?? 'root',
        depth: currentDepth.value,
    })
    closeContextMenu()
}

const handleContextEdit = () => {
    if (contextMenu.value.node) emit('edit-node', contextMenu.value.node)
    closeContextMenu()
}

/** "Add dimension" — attach an empty children object to a node, making it zoomable */
const handleContextAddDimension = () => {
    const node = contextMenu.value.node
    if (!node) { closeContextMenu(); return }

    // Create empty dimension structure on the node
    node.children = {
        lines: [],
        nodes: [],
        connections: [],
        parentEntityType: node.entityType ?? null,
        parentEntityId: node.entityId ?? null,
        parentName: node.name ?? null,
    }

    // Re-render to show the new [○] indicator
    renderMap()
    closeContextMenu()
}

/** "Open dimension" — zoom into a node that already has children */
const handleContextZoomIn = () => {
    const node = contextMenu.value.node
    if (!node?.children) { closeContextMenu(); return }

    closeContextMenu()
    commitDimensionChange('in', node)
}

const handleContextDelete = () => {
    if (contextMenu.value.node) emit('delete-node', contextMenu.value.node)
    closeContextMenu()
}

/** FAB creates a node in the current dimension */
const handleFabCreate = () => {
    emit('create-node', {
        x: 0, y: 0,
        parentNodeId: currentDimensionData.value?.parentNodeId ?? null,
        parentEntityType: currentDimensionData.value?.parentEntityType ?? null,
        parentEntityId: currentDimensionData.value?.parentEntityId ?? null,
        dimensionId: currentDimensionData.value?.id ?? 'root',
        depth: currentDepth.value,
    })
}

// ---------------------------------------------------------------------------
// Resize
// ---------------------------------------------------------------------------

const handleResize = () => {
    if (!svg || !containerRef.value) return
    svg.attr('width', containerRef.value.clientWidth)
       .attr('height', containerRef.value.clientHeight)
}

// ---------------------------------------------------------------------------
// Document click to close context menu
// ---------------------------------------------------------------------------

const onDocumentClick = (e) => {
    if (contextMenu.value.show) {
        closeContextMenu()
    }
}

// ---------------------------------------------------------------------------
// Watchers
// ---------------------------------------------------------------------------

watch(
    () => [props.nodes, props.lines, props.connections, props.dimensions],
    () => {
        if (dimensionStack.value.length > 0) {
            dimensionStack.value[0] = buildRootDimension()
        } else {
            dimensionStack.value = [buildRootDimension()]
        }
        if (!transitionState.value.active) {
            renderMap()
        }
    },
    { deep: true }
)

// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------

onMounted(() => {
    initCanvas()
    window.addEventListener('resize', handleResize)
    document.addEventListener('click', onDocumentClick)
})

onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    document.removeEventListener('click', onDocumentClick)
})

// ---------------------------------------------------------------------------
// Exposed API
// ---------------------------------------------------------------------------

const zoomTo = (x, y, scale) => {
    if (!svg || !zoom) return
    svg.transition().duration(500).call(
        zoom.transform,
        d3.zoomIdentity.translate(x, y).scale(scale)
    )
}

const setHighlightedLine = (lineId) => {
    highlightedLineId.value = lineId
    renderMap()
}

defineExpose({
    zoomTo,
    handleFabCreate,
    currentDepth,
    currentDimensionData,
    isInChildDimension,
    setHighlightedLine,
    showGrid,
    hideGrid,
})
</script>

<template>
    <div ref="containerRef" class="metro-canvas-container" @click="closeContextMenu">

        <!-- Main SVG canvas -->
        <svg ref="svgRef" class="metro-canvas"></svg>

        <!-- Depth indicator -->
        <div class="depth-indicator">
            DEPTH:&nbsp;{{ currentDepth }}
            <span v-if="currentDepth > 1" class="depth-back" @click.stop="commitDimensionChange('out', null)">
                [&uarr; BACK]
            </span>
        </div>

        <!-- Transition progress bar -->
        <div
            v-if="transitionState.active"
            class="transition-bar"
            :style="{ width: (transitionState.progress * 100) + '%' }"
        ></div>

        <!-- Hover tooltip -->
        <Transition name="fade">
            <div
                v-if="hoveredNode"
                class="node-tooltip"
                :style="{
                    left: `${hoveredNode.x * transform.k + transform.x - 280}px`,
                    top:  `${hoveredNode.y * transform.k + transform.y - 20}px`,
                }"
            >
                <div class="tooltip-title">{{ hoveredNode.name }}</div>
                <div v-if="hoveredNode.description" class="tooltip-desc">{{ hoveredNode.description }}</div>
                <div v-if="hoveredNode.status" class="tooltip-status">{{ hoveredNode.status }}</div>
                <div v-if="hoveredNode.children && (hoveredNode.children.nodes?.length ?? 0) > 0" class="tooltip-hint">
                    Scroll to zoom in &rarr; child dimension
                </div>
                <div v-else class="tooltip-hint">Click to view details</div>
            </div>
        </Transition>

        <!-- Context menu -->
        <Transition name="menu-fade">
            <div
                v-if="contextMenu.show"
                class="context-menu"
                :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
                @click.stop
            >
                <template v-if="contextMenu.type === 'canvas'">
                    <div class="context-menu-header">CANVAS</div>
                    <div class="context-hint">Hover a station to branch</div>
                </template>
                <template v-else-if="contextMenu.type === 'node'">
                    <div class="context-menu-header">{{ contextMenu.node?.name ?? 'NODE' }}</div>
                    <button class="context-item" @click="handleContextEdit">Edit</button>
                    <button
                        v-if="contextMenu.node?.children"
                        class="context-item"
                        @click="handleContextZoomIn"
                    >
                        &gt; Open dimension
                    </button>
                    <button
                        v-if="!contextMenu.node?.children"
                        class="context-item"
                        @click="handleContextAddDimension"
                    >
                        + Add dimension
                    </button>
                    <button class="context-item danger" @click="handleContextDelete">Delete</button>
                </template>
            </div>
        </Transition>

    </div>
</template>

<style scoped>
/* -----------------------------------------------------------------------
   Container & canvas
   ----------------------------------------------------------------------- */
.metro-canvas-container {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: #1a1a2e;
}

.metro-canvas {
    display: block;
    width: 100%;
    height: 100%;
}

/* -----------------------------------------------------------------------
   Depth indicator
   ----------------------------------------------------------------------- */
.depth-indicator {
    position: absolute;
    bottom: 16px;
    left: 16px;
    font-family: 'VT323', monospace;
    font-size: 14px;
    color: #00d2ff;
    background: rgba(22, 33, 62, 0.8);
    border: 1px solid rgba(0, 210, 255, 0.3);
    padding: 4px 10px;
    border-radius: 3px;
    letter-spacing: 0.1em;
    user-select: none;
    display: flex;
    align-items: center;
    gap: 8px;
}

.depth-back {
    color: #e94560;
    cursor: pointer;
    transition: color 0.15s;
}

.depth-back:hover {
    color: #ff8fab;
    text-shadow: 0 0 8px rgba(233, 69, 96, 0.6);
}

/* -----------------------------------------------------------------------
   Transition progress bar
   ----------------------------------------------------------------------- */
.transition-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 2px;
    background: linear-gradient(90deg, #00d2ff, #e94560);
    transition: width 0.05s linear;
    pointer-events: none;
    box-shadow: 0 0 8px rgba(0, 210, 255, 0.6);
}

/* -----------------------------------------------------------------------
   Hover tooltip
   ----------------------------------------------------------------------- */
.node-tooltip {
    position: absolute;
    pointer-events: none;
    background: #16213e;
    border: 1px solid #00d2ff;
    border-radius: 4px;
    padding: 8px 12px;
    z-index: 100;
    box-shadow: 0 0 15px rgba(0, 210, 255, 0.2);
    max-width: 250px;
}

.tooltip-title {
    font-family: 'VT323', monospace;
    font-size: 16px;
    color: #00d2ff;
}

.tooltip-desc {
    font-family: 'IBM Plex Mono', monospace;
    font-size: 11px;
    color: #8892b0;
    margin-top: 4px;
}

.tooltip-status {
    font-family: 'VT323', monospace;
    font-size: 13px;
    color: #00ff88;
    margin-top: 4px;
}

.tooltip-hint {
    font-family: 'VT323', monospace;
    font-size: 11px;
    color: #8892b0;
    margin-top: 6px;
    opacity: 0.6;
}

/* -----------------------------------------------------------------------
   Context menu
   ----------------------------------------------------------------------- */
.context-menu {
    position: fixed;
    z-index: 200;
    min-width: 180px;
    background: #0d1b2a;
    border: 1px solid #00d2ff;
    border-radius: 4px;
    box-shadow: 0 0 20px rgba(0, 210, 255, 0.25), inset 0 0 40px rgba(0, 0, 0, 0.4);
    overflow: hidden;
    font-family: 'VT323', monospace;
}

.context-menu-header {
    padding: 6px 12px;
    font-size: 12px;
    color: #00d2ff;
    letter-spacing: 0.15em;
    background: rgba(0, 210, 255, 0.08);
    border-bottom: 1px solid rgba(0, 210, 255, 0.2);
    user-select: none;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

.context-item {
    display: block;
    width: 100%;
    padding: 8px 14px;
    text-align: left;
    background: none;
    border: none;
    color: #e8e8e8;
    font-family: 'VT323', monospace;
    font-size: 15px;
    cursor: pointer;
    letter-spacing: 0.05em;
    transition: background 0.12s, color 0.12s;
    border-bottom: 1px solid rgba(255, 255, 255, 0.04);
}

.context-item:last-child {
    border-bottom: none;
}

.context-item:hover {
    background: rgba(0, 210, 255, 0.12);
    color: #00d2ff;
}

.context-item.danger {
    color: #e94560;
}

.context-item.danger:hover {
    background: rgba(233, 69, 96, 0.12);
    color: #ff8fab;
}

.context-hint {
    padding: 8px 14px;
    color: #8892b0;
    font-family: 'VT323', monospace;
    font-size: 13px;
    opacity: 0.7;
}

/* -----------------------------------------------------------------------
   Transitions
   ----------------------------------------------------------------------- */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.15s;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

.menu-fade-enter-active {
    transition: opacity 0.1s, transform 0.1s;
}

.menu-fade-leave-active {
    transition: opacity 0.08s;
}

.menu-fade-enter-from {
    opacity: 0;
    transform: scale(0.95) translateY(-4px);
}

.menu-fade-leave-to {
    opacity: 0;
}
</style>
