<div class="chart">
  <canvas id="<%= chart_id %>" width="<%= canvas_width %>" height="<%= canvas_height %>"></canvas>
</div>
<script>
new Chart(document.getElementById('<%= chart_id %>').getContext('2d'), {
  type: 'scatter',
  data: {
    datasets: <%= JSON.generate(data_sets) %>
  },
  options: {
    title: {
      display: true,
      text: "Cycletime Scatterplot"
    },
    responsive: <%= canvas_responsive? %>, // If responsive is true then it fills the screen
    scales: {
      x: {
        type: "time",
        scaleLabel: {
          display: true,
          labelString: 'Date Completed'
        },
        grid: {
          color: <%= CssVariable['--grid-line-color'].to_json %>
        },
        min: "<%= date_range.begin.to_s %>",
        max: "<%= (date_range.end + 1).to_s %>"
      },
      y: {
        scaleLabel: {
          display: true,
          labelString: 'Days',
          min: 0,
          max: <%= @highest_cycletime %>
        },
        title: {
          display: true,
          text: 'Cycle time in days'
        },
        grid: {
          color: <%= CssVariable['--grid-line-color'].to_json %>
        },
      }
    },
    plugins: {
      tooltip: {
        callbacks: {
          label: function(context) {
            return context.dataset.data[context.dataIndex].title
          }
        }
      },
      autocolors: false,
      annotation: {
        annotations: {
          <%= working_days_annotation %>

          <% @percentage_lines.each_with_index do |args, index| %>
          <%   percent, color = args %>
          line<%= index %>: {
            type: 'line',
            yMin: <%= percent %>,
            yMax: <%= percent %>,
            borderColor: <%= color.to_json %>,
            borderWidth: 1,
            drawTime: 'beforeDraw'
          },
          <% end %>
        }
      },
      legend: {
        onClick: (evt, legendItem, legend) => {
          // Find the datasetMeta that corresponds to the item clicked
          var i = 0
          while(legendItem.text != legend.chart.getDatasetMeta(i).label) {
            i++;
          }
          nextVisibility = !!legend.chart.getDatasetMeta(i).hidden;

          // Hide/show the 85% line for that dataset
          legend.chart.options.plugins.annotation.annotations["line"+(i/2)].display = nextVisibility;

          // Hide/show the trendline for this dataset, if they were enabled. The trendline is always
          // there but not always visible.
          legend.chart.setDatasetVisibility(i+1, <%= !!@show_trend_lines %> && nextVisibility);

          // Still run the default behaviour
          Chart.defaults.plugins.legend.onClick(evt, legendItem, legend);
        },
        labels: {
          filter: function(item, chart) {
            // Logic to remove a particular legend item goes here
            return !item.text.includes('Trendline');
          }
        }
      }
    }
  }
});
</script>
