<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sankey Diagram</title>

    <script>
        {{D3_MIN}}
    </script>
    <script>
        {{D3_SANKY}}
    </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;
        }
        
        #sankey {
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
            display: block;
            margin: 0 auto;
        }
        
        .node rect {
            cursor: pointer;
            stroke: #000;
            stroke-width: 1px;
        }
        
        .node text {
            pointer-events: none;
            font-size: 12px;
            font-weight: bold;
        }
        
        .link {
            fill: none;
            stroke-opacity: 0.5;
            cursor: pointer;
        }
        
        .link:hover {
            stroke-opacity: 0.8;
        }
        
        .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="sankey"></svg>
        <div class="tooltip" id="tooltip"></div>
    </div>

    <script>
        // Data will be injected here
        const sankeyData = {{SANKEY_DATA}};

        // Sankey variables
        let svg, sankey, tooltip;
        const width = 500;
        const height = 400;
        const margin = { top: 20, right: 20, bottom: 20, left: 20 };

        // Color schemes for different categories
        const colorSchemes = {
            source: "#ff6b6b",
            income: "#4ecdc4",
            input: "#45b7d1",
            generation: "#f9ca24",
            process: "#f0932b",
            pool: "#6c5ce7",
            distribution: "#a29bfe",
            logistics: "#fd79a8",
            landing: "#00b894",
            page: "#00cec9",
            storage: "#fdcb6e",
            retail: "#e17055",
            consumption: "#74b9ff",
            expense: "#fd79a8",
            conversion: "#00b894",
            end: "#00b894",
            savings: "#55a3ff",
            loss: "#636e72",
            exit: "#636e72",
            reverse: "#ddd",
            waste: "#636e72",
            default: "#69b3a2"
        };

        // Initialize SVG
        function initializeSVG() {
            svg = d3.select("#sankey")
                .attr("width", width)
                .attr("height", height);
            
            svg.selectAll("*").remove();
            
            sankey = d3.sankey()
                .nodeWidth(20)
                .nodePadding(10)
                .extent([[margin.left, margin.top], [width - margin.right, height - margin.bottom]]);
            
            tooltip = d3.select("#tooltip");
        }

        // Draw the Sankey diagram
        function drawSankey(data) {
            // Create a map of node names to indices
            const nodeMap = new Map();
            data.nodes.forEach((node, index) => {
                nodeMap.set(node.name, index);
            });

            // Process data for D3 Sankey - convert node names to indices in links
            const processedLinks = data.links.map(link => ({
                source: nodeMap.get(link.source),
                target: nodeMap.get(link.target),
                value: link.value
            }));

            const graph = sankey({
                nodes: data.nodes.map(d => ({ ...d })),
                links: processedLinks
            });

            // Draw links
            svg.append("g")
                .selectAll("path")
                .data(graph.links)
                .enter().append("path")
                .attr("class", "link")
                .attr("d", d3.sankeyLinkHorizontal())
                .attr("stroke", d => {
                    const sourceCategory = d.source.category;
                    return colorSchemes[sourceCategory] || colorSchemes.default;
                })
                .attr("stroke-width", d => Math.max(1, d.width))
                .on("mouseover", function(event, d) {
                    showLinkTooltip(event, d);
                })
                .on("mouseout", hideTooltip);

            // Draw nodes
            const node = svg.append("g")
                .selectAll("g")
                .data(graph.nodes)
                .enter().append("g")
                .attr("class", "node");

            node.append("rect")
                .attr("x", d => d.x0)
                .attr("y", d => d.y0)
                .attr("height", d => d.y1 - d.y0)
                .attr("width", d => d.x1 - d.x0)
                .attr("fill", d => colorSchemes[d.category] || colorSchemes.default)
                .on("mouseover", function(event, d) {
                    showNodeTooltip(event, d);
                })
                .on("mouseout", hideTooltip);

            // Add node labels
            node.append("text")
                .attr("x", d => d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6)
                .attr("y", d => (d.y1 + d.y0) / 2)
                .attr("dy", "0.35em")
                .attr("text-anchor", d => d.x0 < width / 2 ? "start" : "end")
                .text(d => d.name)
                .style("font-size", "12px")
                .style("fill", "#333");
        }

        // Tooltip functions
        function showNodeTooltip(event, d) {
            const totalIn = d.targetLinks.reduce((sum, link) => sum + link.value, 0);
            const totalOut = d.sourceLinks.reduce((sum, link) => sum + link.value, 0);
            
            tooltip.style("opacity", 1)
                .html(`
                    <strong>${d.name}</strong><br/>
                    Category: ${d.category || 'N/A'}<br/>
                    Total In: ${totalIn.toLocaleString()}<br/>
                    Total Out: ${totalOut.toLocaleString()}<br/>
                    Net: ${(totalIn - totalOut).toLocaleString()}
                `)
                .style("left", (event.pageX + 10) + "px")
                .style("top", (event.pageY - 10) + "px");
        }

        function showLinkTooltip(event, d) {
            tooltip.style("opacity", 1)
                .html(`
                    <strong>Flow</strong><br/>
                    From: ${d.source.name}<br/>
                    To: ${d.target.name}<br/>
                    Value: ${d.value.toLocaleString()}<br/>
                    Width: ${d.width.toFixed(1)}px
                `)
                .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() {
            initializeSVG();
            drawSankey(sankeyData);
            
            // 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>