<script setup>
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue'
import * as d3 from 'd3'

// ---------------------------------------------------------------------------
// 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   // commit at this scale (smoother range)
const ZOOM_OUT_COMMIT    = 0.25  // commit at this scale
const NODE_PROXIMITY     = 250   // how close to a node to trigger zoom-in

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

// 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,
    }
}

// ---------------------------------------------------------------------------
// 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,
        }
    })

    // Centre the initial view
    svg.call(
        zoom.transform,
        d3.zoomIdentity.translate(width / 2, height / 2).scale(1)
    )

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

    renderMap()
}

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

const handleZoom = (event) => {
    if (isCommitting) return

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

    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 back to the default zoom (scale=1, centered).
 * This prevents the jarring snap that a hard reset causes.
 */
const animateZoomReset = () => {
    if (!svg || !zoom) {
        isCommitting = false
        renderMap()
        return
    }

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

    // Temporarily disable the zoom handler to prevent re-entry during animation
    svg.on('.zoom', null)

    svg.transition()
        .duration(400)
        .ease(d3.easeCubicOut)
        .call(
            zoom.transform,
            d3.zoomIdentity.translate(w / 2, h / 2).scale(1)
        )
        .on('end', () => {
            // Re-enable zoom handler
            svg.call(zoom)
            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,
                }
            })
            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
}

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

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

        // Outer glow track
        group.append('path')
            .datum(lineNodes)
            .attr('d', lineGen)
            .attr('fill', 'none')
            .attr('stroke', color)
            .attr('stroke-width', 8)
            .attr('stroke-linecap', 'round')
            .attr('opacity', 0.15)

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

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

    // "[+]" label for nodes with children
    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('[+]')

    // Station label
    nodeGroups.append('text')
        .attr('x', 0)
        .attr('y', 28)
        .attr('text-anchor', 'middle')
        .attr('fill', '#e8e8e8')
        .attr('font-family', "'VT323', monospace")
        .attr('font-size', '14px')
        .text(d => d.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()
}

const handleContextAddChild = () => {
    if (contextMenu.value.node) {
        emit('create-node', {
            x: contextMenu.value.canvasX,
            y: contextMenu.value.canvasY,
            parentNodeId: contextMenu.value.node.id,
            parentEntityType: contextMenu.value.node.entityType ?? null,
            parentEntityId: contextMenu.value.node.entityId ?? null,
            dimensionId: contextMenu.value.node.id,
            depth: currentDepth.value + 1,
            addToNode: contextMenu.value.node,
        })
    }
    closeContextMenu()
}

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

defineExpose({
    zoomTo,
    handleFabCreate,
    currentDepth,
    currentDimensionData,
    isInChildDimension,
})
</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 + 30}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">
                        {{ currentDepth > 1 ? 'PROJECT' : 'CANVAS' }}
                    </div>
                    <button class="context-item" @click="handleContextCreate">
                        + {{ currentDepth > 1 ? 'New item here' : 'New node here' }}
                    </button>
                </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="handleContextAddChild"
                    >
                        + Add child node
                    </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;
}

/* -----------------------------------------------------------------------
   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>
