// Minimal eingebettete Chart.js-Version (angepasst für VictoryTimer)
// Vertikaler Bar-Chart ohne Achsentitel und ohne Labels
// Feste Balkenhöhe: 20px + 10px Abstand unten, kein Abstand oben

class ChartWrapper {
  constructor(ctx, config) {
    this.ctx = ctx;
    this.config = config;
    this.render();
  }

  render() {
    const { datasets } = this.config.data;
    const data = datasets[0].data;

    this.ctx.canvas.width = this.ctx.canvas.clientWidth;
    this.ctx.canvas.height = this.ctx.canvas.clientHeight;

    const width = this.ctx.canvas.width;
    const height = this.ctx.canvas.height;

    const barHeight = 15;
    const spacing = 5;

    const max = 720; // 30 Tage = 720 Stunden

    this.ctx.clearRect(0, 0, width, height);

    const colors = [
      '#ff6f61', '#6a5acd', '#ffd700', '#40e0d0', '#ff69b4', '#87cefa', '#98fb98', '#ffa07a', '#dda0dd', '#f08080',
      '#00ced1', '#dc143c', '#7b68ee', '#00fa9a', '#ffc0cb', '#ba55d3', '#20b2aa', '#ff8c00', '#4682b4', '#9acd32'
    ];

    data.forEach((val, i) => {
      const y = i * (barHeight + spacing);
      const barWidth = (val / max) * width;
      this.ctx.fillStyle = colors[i % colors.length];
      this.ctx.fillRect(0, y, barWidth, barHeight);
    });
  }

  destroy() {
    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
  }
}

let chart;

export function drawChart() {
  const history = JSON.parse(localStorage.getItem("victorytimer_history") || "[]").slice(-20)
    .filter(seconds => seconds >= 300) // mindestens 5 Minuten
    .map(seconds => +(seconds / 3600).toFixed(1));

  const ctx = document.getElementById("historyChart").getContext("2d");
  if (chart) chart.destroy();

  chart = new ChartWrapper(ctx, {
    type: 'bar',
    data: {
      labels: [],
      datasets: [{
        label: 'Rauchfrei-Zeit (Stunden)',
        data: history
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: true,
          title: { display: false, text: "" }
        }
      }
    }
  });
}

