document.addEventListener("DOMContentLoaded", () => {
  const canvas = document.getElementById("statusChart");
  const dataEl = document.getElementById("stats-data");
  const legendEl = document.getElementById("custom-legend");

  if (!canvas || !dataEl || !legendEl) {
    console.error("❌ Chart, Daten oder Legende fehlen");
    return;
  }

  let data;

  try {
    data = JSON.parse(dataEl.textContent);
  } catch (err) {
    console.error("❌ JSON Fehler:", err);
    return;
  }

  console.log("📊 REPORT DATA:", data);

  // Labels & Werte vorbereiten
  const labels = data.map((d) => d.status.replace("_", " ").toUpperCase());

  const values = data.map((d) => Number(d.total));

  // Euro Format
  const formatEuro = (value) =>
    value.toLocaleString("de-DE", {
      style: "currency",
      currency: "EUR",
    });

  // Farben passend zu Status
  const colors = [
    "#ffc107", // open
    "#28a745", // paid
    "#dc3545", // cancelled
    "#6c757d", // credit
  ];

  // Chart erzeugen
  const chart = new Chart(canvas, {
    type: "pie",

    data: {
      labels,

      datasets: [
        {
          data: values,
          backgroundColor: colors,
        },
      ],
    },

    options: {
      responsive: true,

      plugins: {
        // ❗ Eigene Legende → Chart-Legende aus
        legend: {
          display: false,
        },

        tooltip: {
          callbacks: {
            label(context) {
              return formatEuro(context.parsed);
            },
          },
        },
      },
    },
  });

  // ----------------------------
  // Eigene Legende bauen (HTML)
  // ----------------------------

  legendEl.innerHTML = "";

  labels.forEach((label, i) => {
    const row = document.createElement("div");

    row.className = "legend-row";

    row.innerHTML = `
      <span
        class="legend-color"
        style="background:${colors[i]}"
      ></span>

      <span class="legend-text">
        ${label}: ${formatEuro(values[i])}
      </span>
    `;

    legendEl.appendChild(row);
  });
});
