{% block head %}
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
{% endblock %}

{% block body %}
<div id="mynetwork" style="width: 100%; height: 800px;"></div>

<script type="text/javascript">
    const chart = echarts.init(document.getElementById('mynetwork'));

    const rawNodes = {{ chart_data['nodes'] | tojson }};
    const rawEdges = {{ chart_data['edges'] | tojson }};

    // Build DAG layout
    const layers = {};
    const nodeDepth = {};

    // Organize nodes into layers by hop count
    for (const edge of rawEdges) {
        const { source, target } = edge;
        if (!(source in nodeDepth)) nodeDepth[source] = 0;
        const nextDepth = nodeDepth[source] + 1;
        nodeDepth[target] = Math.max(nodeDepth[target] || 0, nextDepth);
    }

    for (const node of rawNodes) {
        const depth = nodeDepth[node.name] || 0;
        if (!(depth in layers)) layers[depth] = [];
        layers[depth].push(node);
    }

    // Position nodes manually
    const chartNodes = [];
    const layerKeys = Object.keys(layers).sort((a, b) => +a - +b);
    const verticalSpacing = 100;
    const horizontalSpacing = 180;

    layerKeys.forEach((depth, layerIndex) => {
        const layer = layers[depth];
        const y = layerIndex * verticalSpacing;
        const xStart = -(layer.length - 1) * horizontalSpacing / 2;
        layer.forEach((node, i) => {
            chartNodes.push({
                ...node,
                x: xStart + i * horizontalSpacing,
                y: y,
                itemStyle: {
                    color: '#dddddd',
                    borderColor: '#222',
                    borderWidth: 2,
                },
                label: {
                    show: true,
                    position: 'inside',
                    color: '#000',
                    fontSize: 12,
                    formatter: node.short_name || node.name,
                },
            });
        });
    });

    const chartEdges = rawEdges.map(edge => ({
        source: edge.source,
        target: edge.target,
        lineStyle: {
            color: edge.originalColor || '#ccc',
            width: 2,
            type: 'solid',
        },
    }));

    const option = {
        backgroundColor: '#fff',
        tooltip: {},
        animation: false,
        series: [{
            type: 'graph',
            layout: 'none',
            coordinateSystem: null,
            data: chartNodes,
            links: chartEdges,
            roam: true,
            edgeSymbol: ['none', 'arrow'],
            edgeSymbolSize: [0, 10],
            lineStyle: {
                curveness: 0,
            },
        }],
    };

    chart.setOption(option);
</script>
{% endblock %}
