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

const props = defineProps({
    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', 'zoom-change'])

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

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

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

let svg, g, zoom

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)

    // Clear previous content
    svg.selectAll('*').remove()

    // Add defs for glow filter
    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')

    // Scanline pattern
    const scanlinePattern = defs.append('pattern')
        .attr('id', 'scanlines')
        .attr('patternUnits', 'userSpaceOnUse')
        .attr('width', 4)
        .attr('height', 4)

    scanlinePattern.append('line')
        .attr('x1', 0).attr('y1', 0)
        .attr('x2', 4).attr('y2', 0)
        .attr('stroke', 'rgba(0,0,0,0.08)')
        .attr('stroke-width', 1)

    // Main group for zoom/pan
    g = svg.append('g')

    // Setup zoom
    zoom = d3.zoom()
        .scaleExtent([0.3, 5])
        .on('zoom', (event) => {
            g.attr('transform', event.transform)
            transform.value = event.transform
            emit('zoom-change', {
                scale: event.transform.k,
                x: event.transform.x,
                y: event.transform.y,
            })
        })

    svg.call(zoom)

    // Center the view
    const initialTransform = d3.zoomIdentity
        .translate(width / 2, height / 2)
        .scale(1)

    svg.call(zoom.transform, initialTransform)

    renderMap()
}

const renderMap = () => {
    if (!g) return

    g.selectAll('*').remove()

    // Draw metro lines
    props.lines.forEach((line, lineIndex) => {
        const color = line.color || getLineColor(lineIndex)
        const lineNodes = props.nodes.filter(n => n.lineId === line.id)

        if (lineNodes.length < 2) return

        // Sort nodes by order
        lineNodes.sort((a, b) => a.order - b.order)

        // Draw the line path
        const lineGenerator = d3.line()
            .x(d => d.x)
            .y(d => d.y)
            .curve(d3.curveMonotoneX)

        g.append('path')
            .datum(lineNodes)
            .attr('d', lineGenerator)
            .attr('fill', 'none')
            .attr('stroke', color)
            .attr('stroke-width', 4)
            .attr('stroke-linecap', 'round')
            .attr('opacity', 0.7)

        // Line label — positioned well above the first station
        if (lineNodes.length > 0) {
            g.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.8)
                .text(line.name)
        }
    })

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

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

    // Draw station nodes
    const nodeGroups = g.selectAll('.station')
        .data(props.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)
        })

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

    // Station 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 = props.lines.find(l => l.id === d.lineId)
            return line?.color || getLineColor(props.lines.indexOf(line))
        })
        .attr('stroke-width', 2)

    // Station labels — positioned below the station dot to avoid line overlap
    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 — below the label
    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)
}

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

watch(() => [props.nodes, props.lines, props.connections], () => {
    renderMap()
}, { deep: true })

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

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

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

defineExpose({ zoomTo })
</script>

<template>
    <div ref="containerRef" class="metro-canvas-container">
        <svg ref="svgRef" class="metro-canvas"></svg>

        <!-- Hover tooltip -->
        <Transition name="fade">
            <div
                v-if="hoveredNode"
                class="node-tooltip"
                :style="{
                    left: `${hoveredNode.x + transform.x + 30}px`,
                    top: `${hoveredNode.y + 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 class="tooltip-hint">Click to zoom in</div>
            </div>
        </Transition>
    </div>
</template>

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

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

.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;
}

.fade-enter-active, .fade-leave-active {
    transition: opacity 0.15s;
}
.fade-enter-from, .fade-leave-to {
    opacity: 0;
}
</style>
