<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chord Diagram</title>
    
    <script>
        {{D3_MIN}}
    </script>
    
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            margin: 0 auto;
        }
        
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        
        #chord {
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
            display: block;
            margin: 0 auto;
        }
        
        .group-arc {
            cursor: pointer;
        }
        
        .chord {
            cursor: pointer;
            fill-opacity: 0.67;
            stroke: #000;
            stroke-width: 0.5px;
        }
        
        .chord:hover {
            fill-opacity: 0.9;
        }
        
        .group-label {
            font-size: 12px;
            font-weight: bold;
            text-anchor: middle;
            pointer-events: none;
        }
        
        .tooltip {
            position: absolute;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px;
            border-radius: 4px;
            font-size: 12px;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.3s;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div class="container">
        <svg id="chord"></svg>
        <div class="tooltip" id="tooltip"></div>
    </div>

    <script>
        // Data will be injected here
        const chordData = {{CHORD_DATA}};

        // Chord variables
        let svg, chord, arc, ribbon, tooltip;
        const width = 500;
        const height = 500;
        const outerRadius = Math.min(width, height) * 0.4;
        const innerRadius = outerRadius - 25;

        // Color scale
        const colors = d3.scaleOrdinal(d3.schemeCategory10);

        // Initialize SVG
        function initializeSVG() {
            svg = d3.select("#chord")
                .attr("width", width)
                .attr("height", height);
            
            svg.selectAll("*").remove();
            
            const g = svg.append("g")
                .attr("transform", `translate(${width / 2},${height / 2})`);
            
            chord = d3.chord()
                .padAngle(0.05)
                .sortSubgroups(d3.descending);
            
            arc = d3.arc()
                .innerRadius(innerRadius)
                .outerRadius(outerRadius);
            
            ribbon = d3.ribbon()
                .radius(innerRadius);
            
            tooltip = d3.select("#tooltip");
            
            return g;
        }

        // Draw the Chord diagram
        function drawChord(g, data) {
            const chords = chord(data.matrix);
            
            // Draw the groups (arcs around the circle)
            const group = g.append("g")
                .selectAll("g")
                .data(chords.groups)
                .enter().append("g")
                .attr("class", "group");

            group.append("path")
                .attr("class", "group-arc")
                .style("fill", d => colors(d.index))
                .style("stroke", d => d3.rgb(colors(d.index)).darker())
                .attr("d", arc)
                .on("mouseover", function(event, d) {
                    fadeChords(d.index, 0.1);
                    showGroupTooltip(event, d, data.labels);
                })
                .on("mouseout", function() {
                    fadeChords(null, 1);
                    hideTooltip();
                });

            // Add group labels
            group.append("text")
                .attr("class", "group-label")
                .each(d => { d.angle = (d.startAngle + d.endAngle) / 2; })
                .attr("dy", ".35em")
                .attr("transform", d => `
                    rotate(${(d.angle * 180 / Math.PI - 90)})
                    translate(${outerRadius + 10})
                    ${d.angle > Math.PI ? "rotate(180)" : ""}
                `)
                .style("text-anchor", d => d.angle > Math.PI ? "end" : null)
                .text(d => data.labels[d.index]);

            // Draw the chords (ribbons between groups)
            g.append("g")
                .selectAll("path")
                .data(chords)
                .enter().append("path")
                .attr("class", "chord")
                .style("fill", d => colors(d.source.index))
                .attr("d", ribbon)
                .on("mouseover", function(event, d) {
                    d3.select(this).style("fill-opacity", 0.9);
                    showChordTooltip(event, d, data.labels, data.matrix);
                })
                .on("mouseout", function(event, d) {
                    d3.select(this).style("fill-opacity", 0.67);
                    hideTooltip();
                });
        }

        // Fade chords for highlighting
        function fadeChords(focusIndex, opacity) {
            svg.selectAll(".chord")
                .style("opacity", d => {
                    if (focusIndex === null) return 1;
                    return d.source.index === focusIndex || d.target.index === focusIndex ? 1 : opacity;
                });
            
            svg.selectAll(".group-arc")
                .style("opacity", d => {
                    if (focusIndex === null) return 1;
                    return d.index === focusIndex ? 1 : opacity;
                });
        }

        // Tooltip functions
        function showGroupTooltip(event, d, labels) {
            const totalOut = d.value;
            const groupName = labels[d.index];
            
            tooltip.style("opacity", 1)
                .html(`
                    <strong>${groupName}</strong><br/>
                    Total Flow: ${totalOut.toLocaleString()}<br/>
                    Index: ${d.index}
                `)
                .style("left", (event.pageX + 10) + "px")
                .style("top", (event.pageY - 10) + "px");
        }

        function showChordTooltip(event, d, labels, matrix) {
            const sourceName = labels[d.source.index];
            const targetName = labels[d.target.index];
            const sourceToTarget = matrix[d.source.index][d.target.index];
            const targetToSource = matrix[d.target.index][d.source.index];
            
            tooltip.style("opacity", 1)
                .html(`
                    <strong>Connection</strong><br/>
                    ${sourceName} → ${targetName}: ${sourceToTarget.toLocaleString()}<br/>
                    ${targetName} → ${sourceName}: ${targetToSource.toLocaleString()}<br/>
                    <strong>Total: ${(sourceToTarget + targetToSource).toLocaleString()}</strong>
                `)
                .style("left", (event.pageX + 10) + "px")
                .style("top", (event.pageY - 10) + "px");
        }

        function hideTooltip() {
            tooltip.style("opacity", 0);
        }

        // Function to measure and report content size for iframe auto-resizing
        function reportContentSize() {
            // Get the actual content height
            const contentHeight = Math.max(
                document.body.scrollHeight,
                document.body.offsetHeight,
                document.documentElement.clientHeight,
                document.documentElement.scrollHeight,
                document.documentElement.offsetHeight
            );
            
            // Send size change message to parent window (for MCP-UI iframe auto-resize)
            // The message format must match what the MCP-UI client expects
            if (window.parent !== window) {
                window.parent.postMessage({
                    type: 'ui-size-change',  // lowercase as expected by MCP-UI client
                    payload: {
                        height: contentHeight
                        // width is optional, we're not setting it to allow responsive design
                    }
                }, '*');
            }
        }

        // Initialize and render on load
        window.onload = function() {
            const g = initializeSVG();
            drawChord(g, chordData);
            
            // Report initial size
            setTimeout(reportContentSize, 100);
            
            // Watch for size changes using ResizeObserver if available
            if (typeof ResizeObserver !== 'undefined') {
                const resizeObserver = new ResizeObserver(() => {
                    reportContentSize();
                });
                resizeObserver.observe(document.body);
                resizeObserver.observe(document.documentElement);
            }
            
            // Fallback: also report on window resize
            window.addEventListener('resize', reportContentSize);
        };
    </script>
</body>
</html>