<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vertical Bar Chart</title>
    <script src="https://d3js.org/d3.v7.js"></script>
  </head>

  <body>
<!-- Add three buttons here to add a bar, remove a bar (right),
and remove a bar (left) -->

    <br><br>

    <script>
      // Create svg and initial bars
      const w = 500;
      const h = 400;
      const margin = { top: 25, right: 0, bottom: 25, left: 25 };
      const innerWidth = w - margin.left - margin.right;
      const innerHeight = h - margin.top - margin.bottom;

      const svg = d3.select("body")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

      svg.append("rect")
        .attr("x", 0)
        .attr("y", 0)
        .attr("width", w)
        .attr("height", h)
        .attr("fill", "lightblue");

      const bardata = [300, 100, 150, 220, 70, 270];

      const xScale = d3.scaleBand()
        .domain(d3.range(bardata.length))
        .range([0, innerWidth])
        .paddingInner(0.1);

      const yScale = d3.scaleLinear()
        .domain([0, 400])
        .range([innerHeight, 0]);

      const xAxis = d3.axisBottom()
        .scale(xScale);

      const yAxis = d3.axisLeft()
        .scale(yScale);

      const bars = svg.append("g")
        .attr("id", "plot")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
        .selectAll("rect")
        .data(bardata);

      bars.enter().append("rect")
        .attr("x", (d, i) => xScale(i))
        .attr("y", d => yScale(d))
        .attr("width", xScale.bandwidth())
        .attr("height", d => innerHeight - yScale(d))
        .attr("fill", "blue");

      svg.append("g")
        .attr("class", "xAxis")
        .attr("transform", `translate(${margin.left}, ${h - margin.bottom})`)
        .call(xAxis);

      svg.append("g")
        .attr("class", "yAxis")
        .attr("transform", `translate(${margin.left}, ${margin.top})`)
        .call(yAxis);

      // General Update Pattern
      function update(data) {
        xScale.domain(d3.range(data.length));

        const bars = svg.select("#plot")
          .selectAll("rect")
          .data(data);

        bars.enter().append("rect")
          .merge(bars)
          .attr("x", (d, i) => xScale(i))
          .attr("y", d => yScale(d))
          .attr("width", xScale.bandwidth())
          .attr("height", d => innerHeight - yScale(d))
          .attr("fill", "blue");

        bars.exit().remove();

        svg.select(".xAxis")
          .call(xAxis);
      }

      function add() {
        const newValue = Math.floor(Math.random() * 400);
        bardata.push(newValue);
        update(bardata);
      }

      function remove_right() {
        bardata.pop();
        update(bardata);
      }

      function remove_left() {
        bardata.shift(); // To remove from left, use shift instead of pop
        update(bardata);
      }
    </script>
  </body>
</html>