
    var margin = { top: 64, right: 130, bottom: 10, left: 40 },
      width = Math.max(320, document.querySelector("#graph_energy").clientWidth || 500) - margin.left - margin.right,
      height = 520 - margin.top - margin.bottom;

    var svg = d3.select("#graph_energy")
      .append("svg")
      .style("overflow", "visible")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

    var chartTitle = "EU average electricity generation by source in 2025";
    d3.select("#graph_energy svg").append("text")
      .attr("class", "chart-title")
      .attr("x", 0)
      .attr("y", 30)
      .attr("fill", "#1a1a1a")
      .style("font-family", "effra, sans-serif")
      .style("font-size", "1.8rem")
      .style("font-weight", 700)
      .text(chartTitle);
    (function () {
      var extra = window.wrapChartTitle(d3.select("#graph_energy .chart-title"), width + margin.left + margin.right);
      d3.select("#graph_energy svg").attr("height", height + margin.top + margin.bottom + extra);
      svg.attr("transform", "translate(" + margin.left + "," + (margin.top + extra) + ")");
    })();

    d3.csv("https://uploads.transportenvironment.org/production/datasets/electricity-generation.csv?v=" + Date.now(), d3.autoType).then(function (rows) {
      var order = ["Solar", "Wind", "Hydro", "Bioenergy", "Other renewables", "Nuclear", "Gas", "Coal", "Other fossil"];
      var data = rows.filter(function (d) { return d.series !== "Total generation"; })
        .sort(function (a, b) {
          var ia = order.indexOf(a.series), ib = order.indexOf(b.series);
          return (ia < 0 ? order.length : ia) - (ib < 0 ? order.length : ib);
        });
      var subgroups = data.map(function (d) { return d.series; });
      var shares = {};
      data.forEach(function (d) { shares[d.series] = d.generation_share_pct; });

      var x = d3.scaleBand()
        .domain(["Electricity generation"])
        .range([0, width])
        .padding([0.06])

      var y = d3.scaleLinear()
        .domain([0, 100])
        .range([height, 0]);
      svg.append("g")
        .attr("class", "axis axis-y")
        .style("font-size", "1rem")
        .call(d3.axisLeft(y).tickValues([0, 25, 50, 75, 100]).tickFormat(function (d) { return d + "%"; }))
        .call(function (g) { g.select(".domain").remove(); });
      svg.selectAll(".axis path, .axis line").attr("stroke", "#E5E5E5");
      svg.selectAll(".axis text").attr("fill", "#E5E5E5");

      var color = d3.scaleOrdinal()
        .domain(subgroups)
        .range(['#0A00E0', '#4D45FF', '#807AFF', '#B4D8F3', '#E0EFFA', '#F0DCCD', '#FF8754', '#772749', '#BABABA'])

      var stackedData = d3.stack()
        .keys(subgroups)
        ([Object.assign({ group: "Electricity generation" }, shares)])


      var glowUpTo = "Other renewables";
      var glowTop = stackedData.find(function (s) { return s.key === glowUpTo; })[0][1];
      d3.select("#graph_energy svg").append("defs")
        .append("filter").attr("id", "energy-glow")
        .attr("x", "-30%").attr("y", "-30%").attr("width", "160%").attr("height", "160%")
        .append("feDropShadow").attr("dx", 0).attr("dy", 0).attr("stdDeviation", 10)
        .attr("flood-color", "#4D45FF").attr("flood-opacity", 0.6);
      var glow = svg.append("rect")
        .attr("class", "renewables-glow")
        .attr("x", x("Electricity generation"))
        .attr("width", x.bandwidth())
        .attr("y", y(glowTop))
        .attr("height", y(0) - y(glowTop))
        .attr("fill", "#4D45FF")
        .attr("filter", "url(#energy-glow)")
        .style("opacity", 0);

      svg.append("g")
        .selectAll("g")
        .data(stackedData)
        .enter().append("g")
        .attr("fill", function (d) { return color(d.key); })
        .selectAll("rect")
        .data(function (d) { return d; })
        .enter().append("rect")
        .attr("x", function (d) { return x(d.data.group); })
        .attr("y", function (d) { return y(d[1]); })
        .attr("height", function (d) { return y(d[0]) - y(d[1]); })

        .attr("width", x.bandwidth())
        .attr("stroke", "#fff")
        .attr("stroke-width", 1)
        .attr("stroke-opacity", 0.8)
        .style("cursor", "pointer")


      var barRight = x(x.domain()[0]) + x.bandwidth();
      var gap = 15;
      var labelData = stackedData.map(function (s) {
        return { key: s.key, value: s[0][1] - s[0][0], mid: y((s[0][0] + s[0][1]) / 2) };
      });
      var pos = height + gap;
      labelData.forEach(function (d) { pos = Math.min(d.mid, pos - gap); d.ly = pos; });
      var labels = svg.append("g").attr("class", "segment-labels")
        .selectAll("g").data(labelData).enter().append("g")
        .style("opacity", 0)
        .style("cursor", "pointer");
      var labelText = labels.append("text")
        .attr("x", barRight + 10)
        .attr("y", function (d) { return d.ly; })
        .attr("dy", "0.35em")
        .style("font-size", "1rem")
        .style("font-family", "Roboto, sans-serif");
      labelText.append("tspan")
        .attr("fill", function (d) {
          var c = d3.hsl(color(d.key));
          return c.l > 0.75 ? c.darker(1.3).formatHex() : color(d.key);
        })
        .style("font-weight", 700)
        .text(function (d) { return d.key; });


      var tip = d3.select("body").append("div").attr("class", "graph-tooltip")
        .style("position", "fixed").style("z-index", 50).style("pointer-events", "none")
        .style("opacity", 0).style("transition", "opacity 0.15s ease")
        .style("background", "#fff").style("border", "1px solid #d9d9d9").style("border-radius", "6px")
        .style("box-shadow", "0 4px 14px rgba(0,0,0,0.12)").style("padding", "6px 10px")
        .style("font-family", "Roboto, sans-serif").style("font-size", "13px")
        .style("color", "#1a1a1a").style("white-space", "nowrap");
      var shareOf = function (key) { return shares[key].toFixed(1) + "%"; };
      function showTip(event, key) {
        tip.html("<strong style=\"color:" + color(key) + "\">\u25A0</strong> " + key + " <b>" + shareOf(key) + "</b>")
          .style("left", (event.clientX + 14) + "px")
          .style("top", (event.clientY - 12) + "px")
          .style("opacity", 1);
      }
      function hideTip() { tip.style("opacity", 0); }
      svg.selectAll("rect:not(.renewables-glow)")
        .on("mousemove", function (event) { showTip(event, d3.select(this.parentNode).datum().key); })
        .on("mouseleave", hideTip);
      labels
        .on("mousemove", function (event, d) { showTip(event, d.key); })
        .on("mouseleave", hideTip);

      var annotationValue = 50;
      var annotationText = "50%";
      var annotation = svg.append("g").attr("class", "annotation-50")
        .attr("transform", "translate(0," + y(annotationValue) + ")")
        .style("opacity", 0);
      annotation.append("line")
        .attr("x1", 0)
        .attr("x2", barRight)
        .attr("stroke", "#1a1a1a")
        .attr("stroke-width", 1.5)
        .attr("stroke-dasharray", "2 2");
      annotation.append("text")
        .attr("x", barRight - 6)
        .attr("y", -6)
        .attr("text-anchor", "end")
        .attr("fill", "#1a1a1a")
        .style("font-size", "12px")
        .style("font-weight", 700)
        .style("font-family", "Roboto, sans-serif")
        .text(annotationText);


      var rects = svg.selectAll("rect:not(.renewables-glow)");
      var segDur = 450;
      labels.style("opacity", 1);
      glow.style("opacity", 1);
      annotation.style("opacity", 1);
    })
