class Spoom::Coverage::D3::Timeline::Stacked

def line(y:, color: "strictnessColor(d.key)", curve: "curveCatmullRom.alpha(1)")

def line(y:, color: "strictnessColor(d.key)", curve: "curveCatmullRom.alpha(1)")
  <<~JS
    var area_#{id} = d3.area()
      .x((d) => xScale_#{id}(parseDate(#{y})))
      .y0((d) => yScale_#{id}(d[0]))
      .y1((d) => yScale_#{id}(d[1]))
      .curve(d3.#{curve});
    var layer = svg_#{id}.selectAll(".layer")
      .data(layers_#{id})
      .enter().append("g")
        .attr("class", "layer")
        .attr("fill", (d, i) => #{color})
    layer.append("path")
      .attr("class", "area")
      .attr("d", area_#{id})
      .attr("fill", (d) => #{color})
    svg_#{id}.selectAll("circle")
      .data(points_#{id})
      .enter()
        .append("circle")
        .attr("class", "dot")
        .attr("cx", (d) => xScale_#{id}(parseDate(#{y})))
        .attr("cy", (d, i) => yScale_#{id}(d[1]))
        .on("mouseover", (d) => tooltip.style("opacity", 1))
        .on("mousemove", tooltip_#{id})
        .on("mouseleave", (d) => tooltip.style("opacity", 0));
  JS
end

def plot

def plot
  <<~JS
    #{x_scale}
    #{y_scale(min: "0", max: "100", ticks: "tickValues([0, 25, 50, 75, 100])")}
    #{line(y: "d.data.timestamp")}
    #{x_ticks}
    #{y_ticks(ticks: "tickValues([25, 50, 75])", format: "d + '%'", padding: 30)}
  JS
end

def script

def script
  <<~JS
    #{tooltip}
    var data_#{id} = #{@data.to_json};
    var keys_#{id} = #{T.unsafe(@keys).to_json};
    var stack_#{id} = d3.stack()
      .keys(keys_#{id})
      .value((d, key) => toPercent(d.values[key], d.total));
    var layers_#{id} = stack_#{id}(data_#{id});
    var points_#{id} = []
    layers_#{id}.forEach(function(d) {
      d.forEach(function(p) {
        p.key = d.key
        points_#{id}.push(p);
      });
    })
    function draw_#{id}() {
      var width_#{id} = document.getElementById("#{id}").clientWidth;
      var height_#{id} = 200;
      d3.select("##{id}").selectAll("*").remove()
      var svg_#{id} = d3.select("##{id}")
        .attr("class", "inverted")
        .attr("width", width_#{id})
        .attr("height", height_#{id});
      #{plot}
    }
    draw_#{id}();
    window.addEventListener("resize", draw_#{id});
  JS
end