const dashboard = window.AdminDashboard || {};

const ordersByDay = Array.isArray(dashboard.ordersByDay) ? dashboard.ordersByDay : [];
const statusCounts = dashboard.statusCounts || {};
const paymentSplit = dashboard.paymentSplit || {};
const brandColor = dashboard.brandColor || '#7367f0';

const ordersByDayChartEl = document.querySelector('#ordersByDayChart');
if (ordersByDayChartEl && window.ApexCharts) {
  const seriesData = ordersByDay.map(item => item.count || 0);
  const labels = ordersByDay.map(item => item.label || '');

  const ordersByDayChart = new ApexCharts(ordersByDayChartEl, {
    chart: {
      type: 'area',
      height: 300,
      toolbar: { show: false }
    },
    series: [{ name: 'Pedidos', data: seriesData }],
    xaxis: {
      categories: labels,
      labels: { style: { fontSize: '12px' } }
    },
    dataLabels: { enabled: false },
    stroke: { curve: 'smooth', width: 3 },
    fill: {
      type: 'gradient',
      gradient: { shadeIntensity: 1, opacityFrom: 0.35, opacityTo: 0.05 }
    },
    colors: [brandColor],
    grid: { strokeDashArray: 6 },
    tooltip: { y: { formatter: val => `${val} pedidos` } }
  });

  ordersByDayChart.render();
}

const ordersStatusChartEl = document.querySelector('#ordersStatusChart');
if (ordersStatusChartEl && window.ApexCharts) {
  const labels = Object.keys(statusCounts);
  const series = labels.map(label => statusCounts[label] || 0);

  const ordersStatusChart = new ApexCharts(ordersStatusChartEl, {
    chart: {
      type: 'donut',
      height: 300
    },
    labels,
    series,
    colors: ['#ff9f43', '#00cfe8', '#7367f0', '#6c757d', '#28c76f', '#ea5455'],
    legend: { position: 'bottom' },
    dataLabels: { enabled: true },
    tooltip: { y: { formatter: val => `${val} pedidos` } }
  });

  ordersStatusChart.render();
}

const paymentSplitChartEl = document.querySelector('#paymentSplitChart');
if (paymentSplitChartEl && window.ApexCharts) {
  const labels = Object.keys(paymentSplit);
  const series = labels.map(label => paymentSplit[label] || 0);

  const paymentSplitChart = new ApexCharts(paymentSplitChartEl, {
    chart: {
      type: 'donut',
      height: 300
    },
    labels,
    series,
    colors: [brandColor, '#00cfe8'],
    legend: { position: 'bottom' },
    dataLabels: { enabled: true },
    tooltip: { y: { formatter: val => `€${val.toFixed(2)}` } }
  });

  paymentSplitChart.render();
}
