// ══════════════════════════════════════════════
// RRB Admin — Module: dashboard
// ══════════════════════════════════════════════

// ══════════════════════════════════════════════
let _chartVentas12 = null;
let _chartDist6    = null;
let _chartDonut    = null;
let _dashLoaded    = false;

const MESES_SHORT = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];

// fmtPts() está en core.js

async function cargarDashboard() {
  if (_dashLoaded) return;
  const loading = document.getElementById('dash-loading');
  const content = document.getElementById('dash-content');
  loading.style.display = 'flex';
  content.style.display = 'none';

  try {
    const data = await api('GET', 'api/dashboard.php');
    if (!data.success) throw new Error(data.error || 'Error al cargar dashboard');
    renderDashboard(data.data);
    _dashLoaded = true;
  } catch(err) {
    loading.innerHTML = '<span style="color:var(--error)">Error al cargar métricas: ' + err.message + '</span>';
  }
}

function renderDashboard(d) {
  const loading = document.getElementById('dash-loading');
  const content = document.getElementById('dash-content');

  // ─ Cabecera período
  const mesNombre = MESES_SHORT[(d.periodo.mes - 1)] || '';
  document.getElementById('dash-periodo-label').textContent =
    'Período: ' + mesNombre + ' ' + d.periodo.anio + '  •  Última actualización: hace un momento';

  // ─ KPI: Ventas del mes vs hace 3 meses
  const vMes  = d.ventas_mes_actual;
  const v3m   = d.ventas_mes_3atras;
  document.getElementById('kpi-ventas-mes').textContent = fmtMXN(vMes);
  const cmpEl = document.getElementById('kpi-ventas-compare');
  if (v3m > 0) {
    const pct = ((vMes - v3m) / v3m * 100).toFixed(1);
    const up  = vMes >= v3m;
    cmpEl.className = 'kpi-compare ' + (up ? 'up' : 'down');
    cmpEl.innerHTML = (up ? '↑' : '↓') + ' ' + Math.abs(pct) + '% vs hace 3 meses';
  } else {
    cmpEl.className = 'kpi-compare neutral';
    cmpEl.textContent = 'Sin datos del período anterior';
  }
  // Barra: % del máx de los 12 meses
  const maxV12 = Math.max(...Object.values(d.ventas_12meses), 1);
  const barPct = Math.min(100, Math.round((vMes / maxV12) * 100));
  document.getElementById('kpi-ventas-bar').style.width = barPct + '%';

  // ─ KPI: Órdenes pendientes
  document.getElementById('kpi-ordenes').textContent = d.ordenes_pendientes;

  // ─ KPI: Regalías
  const regPag = d.regalias_mes.pagadas;
  const regPP  = d.regalias_mes.por_pagar;
  const regTot = d.regalias_mes.total;
  document.getElementById('kpi-reg-pagadas').textContent  = fmtMXN(regPag);
  document.getElementById('kpi-reg-porpagar').textContent = fmtMXN(regPP);

  const pctPag = regTot > 0 ? Math.round((regPag / regTot) * 100) : 0;
  const pctPP  = regTot > 0 ? Math.round((regPP  / regTot) * 100) : 0;
  document.getElementById('kpi-reg-pagadas-pct').className  = 'kpi-compare ' + (pctPag > 50 ? 'up' : 'neutral');
  document.getElementById('kpi-reg-pagadas-pct').textContent = pctPag + '% del total del mes';
  document.getElementById('kpi-reg-porpagar-pct').className  = 'kpi-compare ' + (pctPP > 50 ? 'down' : 'neutral');
  document.getElementById('kpi-reg-porpagar-pct').textContent = pctPP + '% del total del mes';

  // ─ Tarjeta regalías detalle
  document.getElementById('reg-pagadas-val').textContent  = fmtMXN(regPag);
  document.getElementById('reg-porpagar-val').textContent = fmtMXN(regPP);
  document.getElementById('reg-total-val').textContent    = fmtMXN(regTot);
  document.getElementById('reg-pct-label').textContent    = pctPag + '%';
  document.getElementById('reg-progress-bar').style.width = pctPag + '%';

  // ─ Gráfica: Ventas 12 meses
  const v12Keys  = Object.keys(d.ventas_12meses);
  const v12Vals  = Object.values(d.ventas_12meses);
  const v12Labels = v12Keys.map(k => {
    const [y, m] = k.split('-');
    return MESES_SHORT[parseInt(m) - 1] + ' ' + y.slice(2);
  });

  if (_chartVentas12) _chartVentas12.destroy();
  _chartVentas12 = new Chart(document.getElementById('chart-ventas-12'), {
    type: 'bar',
    data: {
      labels: v12Labels,
      datasets: [{
        label: 'Puntos',
        data: v12Vals,
        backgroundColor: v12Vals.map((_, i) => i === v12Vals.length - 1 ? '#1a3a5c' : 'rgba(26,58,92,.25)'),
        borderColor:     v12Vals.map((_, i) => i === v12Vals.length - 1 ? '#1a3a5c' : 'rgba(26,58,92,.5)'),
        borderWidth: 1,
        borderRadius: 4,
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: ctx => ' ' + Number(ctx.raw).toLocaleString('es-MX', {style:'currency',currency:'MXN'})
          }
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: { callback: v => fmtMXN(v), font: { size: 11 } },
          grid: { color: '#f0f4f8' }
        },
        x: { ticks: { font: { size: 11 } }, grid: { display: false } }
      }
    }
  });

  // ─ Gráfica: Distribuidores 6 meses
  const d6Keys   = Object.keys(d.distribuidores_6m);
  const d6Vals   = Object.values(d.distribuidores_6m);
  const d6Labels = d6Keys.map(k => {
    const [y, m] = k.split('-');
    return MESES_SHORT[parseInt(m) - 1] + ' ' + y.slice(2);
  });

  if (_chartDist6) _chartDist6.destroy();
  _chartDist6 = new Chart(document.getElementById('chart-dist-6'), {
    type: 'bar',
    data: {
      labels: d6Labels,
      datasets: [{
        label: 'Nuevos distribuidores',
        data: d6Vals,
        backgroundColor: d6Vals.map((_, i) => i === d6Vals.length - 1 ? '#e8a020' : 'rgba(232,160,32,.35)'),
        borderColor:     d6Vals.map((_, i) => i === d6Vals.length - 1 ? '#b45309' : 'rgba(180,83,9,.5)'),
        borderWidth: 1,
        borderRadius: 4,
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: false },
        tooltip: { callbacks: { label: ctx => ' ' + ctx.raw + ' distribuidores' } }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: { stepSize: 1, font: { size: 11 } },
          grid: { color: '#f0f4f8' }
        },
        x: { ticks: { font: { size: 11 } }, grid: { display: false } }
      }
    }
  });

  // ─ Donut: Regalías
  if (_chartDonut) _chartDonut.destroy();
  _chartDonut = new Chart(document.getElementById('chart-regalias-donut'), {
    type: 'doughnut',
    data: {
      labels: ['Pagadas', 'Por Pagar'],
      datasets: [{
        data: [regPag || 0.001, regPP || 0.001],
        backgroundColor: ['#15803d', '#f59e0b'],
        borderColor: ['#fff','#fff'],
        borderWidth: 3,
        hoverOffset: 6
      }]
    },
    options: {
      responsive: true,
      cutout: '68%',
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: ctx => ' ' + fmtMXN(ctx.raw)
          }
        }
      }
    }
  });

  // Leyenda donut
  document.getElementById('donut-legend').innerHTML =
    '<span style="display:flex;align-items:center;gap:5px"><span style="width:10px;height:10px;border-radius:50%;background:#15803d;display:inline-block"></span>Pagadas</span>' +
    '<span style="display:flex;align-items:center;gap:5px"><span style="width:10px;height:10px;border-radius:50%;background:#f59e0b;display:inline-block"></span>Por Pagar</span>';

  // Mostrar contenido
  loading.style.display = 'none';
  content.style.display = 'block';
}

