document.addEventListener("DOMContentLoaded", () => {
  const rows = document.querySelectorAll("table tbody tr");
  rows.forEach((r, i) => {
    r.style.opacity = "0";
    r.style.transform = "translateY(8px)";
    setTimeout(() => {
      r.style.transition = ".35s ease";
      r.style.opacity = "1";
      r.style.transform = "translateY(0)";
    }, i * 60);
  });

  initSalesChart();
});

function initSalesChart() {
  const canvas = document.getElementById("salesChart");
  const series = window.__SALES_SERIES__;
  if (!canvas || !Array.isArray(series) || !series.length) return;

  const ctx = canvas.getContext("2d");
  if (!ctx) return;

  const w = canvas.width;
  const h = canvas.height;
  const pad = 24;
  const values = series.map((x) => Number(x.total || 0));
  const max = Math.max(1, ...values);
  const stepX = (w - pad * 2) / Math.max(1, values.length - 1);

  ctx.clearRect(0, 0, w, h);
  ctx.fillStyle = "#fff";
  ctx.fillRect(0, 0, w, h);

  ctx.strokeStyle = "#ef4056";
  ctx.lineWidth = 2;
  ctx.beginPath();
  values.forEach((val, i) => {
    const x = pad + i * stepX;
    const y = h - pad - ((h - pad * 2) * (val / max));
    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  });
  ctx.stroke();

  ctx.fillStyle = "#3f4064";
  ctx.font = "12px sans-serif";
  values.forEach((val, i) => {
    const x = pad + i * stepX;
    const y = h - pad - ((h - pad * 2) * (val / max));
    ctx.beginPath();
    ctx.arc(x, y, 3, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillText(String(Math.round(val)), x - 10, y - 8);
  });
}
