<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Formas de Pago — ARKHON</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
<style>
:root{
  --bg:#f7f8fc;--surface:#fff;--border:#eaecf4;
  --text:#111827;--text-2:#4b5563;--text-3:#9ca3af;
  --orange:#f97316;--orange-lt:rgba(249,115,22,.10);
  --green:#10b981;--green-lt:rgba(16,185,129,.10);
  --blue:#2563eb;--blue-lt:rgba(37,99,235,.10);
  --purple:#7c3aed;--purple-lt:rgba(124,58,237,.10);
  --red:#ef4444;--red-lt:rgba(239,68,68,.10);
  --shadow-sm:0 10px 28px rgba(17,24,39,.07);--r:10px;
}
*{margin:0;padding:0;box-sizing:border-box;}
html,body{font-family:'Plus Jakarta Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;font-size:13px;-webkit-font-smoothing:antialiased;}
button,input,select{font-family:'Plus Jakarta Sans',sans-serif;}
::-webkit-scrollbar{width:4px;}::-webkit-scrollbar-thumb{background:#d1d5db;border-radius:8px;}
@keyframes spin{to{transform:rotate(360deg);}}
@keyframes fadeUp{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}

.topbar{background:var(--surface);border-bottom:1px solid var(--border);height:58px;padding:0 20px;display:flex;align-items:center;gap:12px;box-shadow:var(--shadow-sm);position:sticky;top:0;z-index:20;}
.topbar-icon{width:34px;height:34px;border-radius:9px;flex-shrink:0;background:var(--blue);display:flex;align-items:center;justify-content:center;box-shadow:0 3px 10px rgba(37,99,235,.28);}
.topbar-icon svg{width:16px;height:16px;stroke:#fff;stroke-width:2.2;fill:none;}
.topbar h1{font-size:15px;font-weight:800;color:var(--text);letter-spacing:-.3px;flex:1;}
.topbar-meta{font-size:11px;color:var(--text-3);font-weight:600;}

.container{max-width:1200px;margin:0 auto;padding:18px 18px 40px;}

/* Filtros */
.filters-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);padding:16px 18px;margin-bottom:16px;display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap;}
.fg{display:flex;flex-direction:column;gap:3px;}
.fl{font-size:9px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:var(--text-3);}
input[type=date]{padding:7px 10px;border:1px solid var(--border);border-radius:8px;font-size:12px;font-weight:600;color:var(--text);outline:none;transition:.15s;background:var(--surface);}
input[type=date]:focus{border-color:var(--blue);}
select{padding:8px 10px;border:1px solid var(--border);border-radius:8px;font-size:12px;font-weight:600;color:var(--text);background:var(--surface);outline:none;}
.btn-primary{display:flex;align-items:center;gap:6px;padding:8px 18px;background:var(--blue);color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;box-shadow:0 2px 8px rgba(37,99,235,.28);transition:.15s;}
.btn-primary:hover{transform:translateY(-1px);}
.btn-primary svg{width:13px;height:13px;stroke:#fff;stroke-width:2.2;fill:none;}
.btn-secondary{display:flex;align-items:center;gap:6px;padding:8px 14px;background:var(--surface);color:var(--text-2);border:1px solid var(--border);border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;transition:.15s;}
.btn-secondary:hover{background:var(--bg);}

/* Stats */
.stats-row{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;margin-bottom:14px;}
@media(min-width:640px){.stats-row{grid-template-columns:repeat(4,1fr);}}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:14px 16px;box-shadow:var(--shadow-sm);animation:fadeUp .2s ease;}
.stat-label{font-size:10px;color:var(--text-3);font-weight:600;margin-bottom:4px;text-transform:uppercase;letter-spacing:.06em;}
.stat-val{font-size:20px;font-weight:800;letter-spacing:-.4px;color:var(--text);}
.stat-val.blue{color:var(--blue);}
.stat-val.green{color:var(--green);}
.stat-val.orange{color:var(--orange);}
.stat-sub{font-size:10px;color:var(--text-3);font-weight:600;margin-top:2px;}

/* Cards */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);overflow:hidden;margin-bottom:14px;animation:fadeUp .2s ease;}
.card-head{display:flex;align-items:center;justify-content:space-between;padding:13px 16px;border-bottom:1px solid var(--border);}
.card-title{font-size:12px;font-weight:800;color:var(--text);}
.card-badge{font-size:10px;font-weight:700;padding:2px 8px;border-radius:20px;background:var(--blue-lt);color:var(--blue);}
.card-body{padding:16px;}

/* Grid 2 col */
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px;}
@media(max-width:700px){.grid2{grid-template-columns:1fr;}}

/* Chart containers */
.chart-wrap{position:relative;height:280px;padding:6px 0;}
.chart-wrap-tall{position:relative;height:310px;padding:6px 0;}

/* Barras de formas de pago */
.fp-list{display:flex;flex-direction:column;gap:10px;}
.fp-item{display:flex;align-items:center;gap:10px;}
.fp-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0;}
.fp-name{font-size:12px;font-weight:700;color:var(--text);min-width:140px;}
.fp-track{flex:1;height:8px;background:var(--bg);border-radius:8px;overflow:hidden;}
.fp-fill{height:100%;border-radius:8px;transition:width .4s ease;}
.fp-val{font-size:12px;font-weight:800;color:var(--text);min-width:90px;text-align:right;}
.fp-pct{font-size:10px;font-weight:600;color:var(--text-3);min-width:38px;text-align:right;}

/* Tabla detalle */
.tbl-wrap{overflow-x:auto;}
table{width:100%;border-collapse:collapse;font-size:12px;}
th{padding:9px 12px;text-align:left;font-size:10px;font-weight:700;color:var(--text-3);text-transform:uppercase;letter-spacing:.07em;border-bottom:1px solid var(--border);background:var(--bg);white-space:nowrap;}
td{padding:9px 12px;border-bottom:1px solid var(--border);color:var(--text-2);}
tr:last-child td{border-bottom:none;}
tr:hover td{background:var(--bg);}
td.num{text-align:right;font-weight:700;color:var(--text);}
td.money{text-align:right;font-weight:700;color:var(--green);}
td.folio{font-weight:800;color:var(--blue);font-size:12px;}

/* Badge formas */
.fp-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:20px;font-size:10px;font-weight:700;}
.fp-ef   {background:#fef9c3;color:#854d0e;}
.fp-visa {background:#dbeafe;color:#1d4ed8;}
.fp-mc   {background:#fce7f3;color:#9d174d;}
.fp-tra  {background:#d1fae5;color:#065f46;}
.fp-val  {background:#ede9fe;color:#5b21b6;}
.fp-other{background:var(--bg);color:var(--text-3);}

/* Estado */
.badge-abierta{background:var(--orange-lt);color:var(--orange);padding:2px 7px;border-radius:20px;font-size:10px;font-weight:700;}
.badge-pagada {background:var(--green-lt);color:var(--green);padding:2px 7px;border-radius:20px;font-size:10px;font-weight:700;}

/* Paginación */
.pag-row{display:flex;justify-content:space-between;align-items:center;padding:10px 16px;border-top:1px solid var(--border);font-size:11px;color:var(--text-3);}
.pag-btns{display:flex;gap:6px;}
.pag-btn{padding:4px 10px;border:1px solid var(--border);border-radius:6px;background:var(--surface);font-size:11px;font-weight:600;cursor:pointer;color:var(--text-2);}
.pag-btn:hover{background:var(--bg);}
.pag-btn.active{background:var(--blue);color:#fff;border-color:var(--blue);}
.pag-btn:disabled{opacity:.4;cursor:default;}

.spinner{width:22px;height:22px;border:2.5px solid var(--border);border-top-color:var(--blue);border-radius:50%;animation:spin .7s linear infinite;margin:32px auto;display:block;}
.error-box{padding:14px 16px;background:var(--red-lt);border-radius:var(--r);color:var(--red);font-size:12px;font-weight:600;margin-bottom:12px;}
.empty{padding:36px;text-align:center;color:var(--text-3);font-size:12px;font-weight:600;}
</style>
<link rel="stylesheet" href="/css/responsive.css?v=406r"/>
</head>
<body>

<div class="topbar">
  <button onclick="window.location.href='/'" style="display:flex;align-items:center;gap:6px;padding:6px 12px;background:transparent;border:1px solid var(--border);border-radius:8px;font-size:12px;font-weight:600;color:var(--text-2);cursor:pointer;margin-right:4px;transition:.15s;" onmouseover="this.style.background='var(--bg)'" onmouseout="this.style.background='transparent'">
    <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2.5" fill="none"><polyline points="15 18 9 12 15 6"/></svg>
    Inicio
  </button>
  <div class="topbar-icon">
    <svg viewBox="0 0 24 24"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></svg>
  </div>
  <h1>Formas de Pago</h1>
  <span class="topbar-meta" id="topbar-meta"></span>
</div>

<div class="container">

  <!-- Filtros -->
  <div class="filters-card">
    <div class="fg">
      <div class="fl">Fecha inicio</div>
      <input type="date" id="f-ini"/>
    </div>
    <div class="fg">
      <div class="fl">Fecha fin</div>
      <input type="date" id="f-fin"/>
    </div>
    <div class="fg">
      <div class="fl">Turno (opcional)</div>
      <select id="f-turno">
        <option value="">Usar fechas</option>
      </select>
    </div>
    <button class="btn-primary" onclick="consultar()">
      <svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      Consultar
    </button>
    <button class="btn-secondary" onclick="exportarCSV()">
      <svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" stroke-width="2.2" fill="none"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
      Exportar CSV
    </button>
  </div>

  <div id="error-box" class="error-box" style="display:none;"></div>
  <div id="spinner" class="spinner" style="display:none;"></div>
  <div id="resultado"></div>

</div>

<script src="/js/arkhon-utils.js"></script>
<script>
var LOCAL_API_KEY = '';
let _datos = null;
let _pag = 1;
const PAGE_SIZE = 50;

// Paleta de colores por forma de pago
const COLORES = {
  EF:   '#f59e0b',
  VISA: '#2563eb',
  MC:   '#ec4899',
  TRA:  '#10b981',
  VAL:  '#7c3aed',
  TPY:  '#06b6d4',
  TRW:  '#14b8a6',
  MPY:  '#f97316',
  MRW:  '#ef4444',
};
const COLOR_DEFAULT = '#9ca3af';
const COLORES_ARR = ['#2563eb','#f59e0b','#10b981','#ec4899','#7c3aed','#f97316','#06b6d4','#ef4444','#14b8a6','#84cc16'];

function colorFP(id) { return COLORES[id] || COLOR_DEFAULT; }
function classFP(id) {
  const m = { EF:'fp-ef', VISA:'fp-visa', MC:'fp-mc', TRA:'fp-tra', VAL:'fp-val' };
  return m[id] || 'fp-other';
}
const percentLabelsPlugin = {
  id: 'fpPercentLabels',
  afterDatasetsDraw(chart, args, opts = {}) {
    const values = chart.data.datasets?.[0]?.data || [];
    const total = values.reduce((sum, value) => sum + Number(value || 0), 0);
    if (!total) return;
    const meta = chart.getDatasetMeta(0);
    const minPercent = opts.minPercent ?? 4;
    const { ctx } = chart;
    ctx.save();
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.font = '800 11px "Plus Jakarta Sans", sans-serif';
    meta.data.forEach((arc, index) => {
      const pct = Number(values[index] || 0) / total * 100;
      if (pct < minPercent) return;
      const pos = arc.tooltipPosition();
      const label = `${pct >= 10 ? pct.toFixed(0) : pct.toFixed(1)}%`;
      ctx.lineWidth = 3;
      ctx.strokeStyle = 'rgba(15,23,42,.34)';
      ctx.fillStyle = '#fff';
      ctx.strokeText(label, pos.x, pos.y);
      ctx.fillText(label, pos.x, pos.y);
    });
    ctx.restore();
  }
};

async function _getToken() {
  await _initAuth();
}


const fdt = s => { try{ return new Date(s).toLocaleString('es-MX',{dateStyle:'short',timeStyle:'short'}); }catch{return '—';} };


async function cargarTurnos() {
  try {
    const d = await api('/turnos/hoy');
    const sel = document.getElementById('f-turno');
    sel.innerHTML = '<option value="">Usar fechas</option>';
    (d||[]).forEach(t => {
      const hora = t.apertura ? new Date(t.apertura).toLocaleTimeString('es-MX',{hour:'2-digit',minute:'2-digit'}) : '';
      const estado = t.cierre ? 'Cerrado' : 'Activo';
      const opt = document.createElement('option');
      opt.value = t.idturno;
      opt.textContent = `${t.nombre_turno||'Turno'} #${t.idturno} — ${hora} (${estado})`;
      sel.appendChild(opt);
    });
  } catch(_) {}
}

async function consultar() {
  const ini    = document.getElementById('f-ini').value;
  const fin    = document.getElementById('f-fin').value;
  const idturno = document.getElementById('f-turno').value;

  document.getElementById('error-box').style.display = 'none';
  document.getElementById('resultado').innerHTML = '';
  document.getElementById('spinner').style.display = 'block';

  try {
    let ep;
    if (idturno) {
      ep = `/pagos?idturno=${idturno}`;
    } else {
      if (!ini||!fin) throw new Error('Selecciona un rango de fechas');
      ep = `/pagos?ini=${ini}&fin=${fin}`;
    }
    _datos = await api(ep);
    // api() puede retornar undefined si fue redirigido por 401 — proteger contra eso
    if (!_datos) throw new Error('Sesión expirada — recarga la página e inicia sesión de nuevo');
    _pag   = 1;
    const periodo = _datos?.periodo || {};
    document.getElementById('topbar-meta').textContent =
      periodo.tipo === 'turno'
        ? `Turno #${periodo.idturno}`
        : `${ini} — ${fin}`;
    renderResultado(_datos);
  } catch(e) {
    const eb = document.getElementById('error-box');
    eb.textContent = 'Error: ' + e.message;
    eb.style.display = 'block';
    // Asegurar que el resultado no quede vacío ni confuso
    document.getElementById('resultado').innerHTML = '';
  } finally {
    document.getElementById('spinner').style.display = 'none';
  }
}

// ─── Render principal ────────────────────────────────────────────────────────

let _charts = {};

function destroyCharts() {
  Object.values(_charts).forEach(c => { try { c.destroy(); } catch(_) {} });
  _charts = {};
}

function renderResultado(d) {
  destroyCharts();
  const res    = document.getElementById('resultado');
  if (!d) { res.innerHTML = '<div class="empty">Sin datos para este período</div>'; return; }
  const resumen = d.resumen || [];
  const totales = d.totales || {};
  const horas   = d.horas   || [];
  const detalle = d.detalle || [];

  if (!resumen.length) {
    res.innerHTML = '<div class="empty">Sin datos para este período</div>';
    return;
  }

  const totalImporte = resumen.reduce((a,r) => a + (r.importe_total||0), 0);

  // ── Stats ──
  let html = `
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-label">Total cobrado</div>
        <div class="stat-val blue">${fmt(totales.venta_total||0)}</div>
        <div class="stat-sub">${totales.total_folios||0} folios</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Formas usadas</div>
        <div class="stat-val">${resumen.length}</div>
        <div class="stat-sub">de ${totales.formas_usadas||resumen.length} distintas</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Propinas</div>
        <div class="stat-val green">${fmt(totales.propina_total||0)}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">Forma principal</div>
        <div class="stat-val orange" style="font-size:14px">${resumen[0]?.descripcion||'—'}</div>
        <div class="stat-sub">${fmt(resumen[0]?.importe_total||0)}</div>
      </div>
    </div>`;

  // ── Gráficas: dona + barras ──
  html += `<div class="grid2">
    <div class="card">
      <div class="card-head"><span class="card-title">% por forma de pago</span></div>
      <div class="card-body"><div class="chart-wrap"><canvas id="chart-dona"></canvas></div></div>
    </div>
    <div class="card">
      <div class="card-head"><span class="card-title">Importe por forma de pago</span></div>
      <div class="card-body"><div class="chart-wrap"><canvas id="chart-barras"></canvas></div></div>
    </div>
  </div>`;

  // ── Gráfica línea tendencia por hora ──
  html += `<div class="card">
    <div class="card-head"><span class="card-title">Tendencia por hora del día</span><span class="card-badge">importe acumulado</span></div>
    <div class="card-body"><div class="chart-wrap-tall"><canvas id="chart-linea"></canvas></div></div>
  </div>`;

  // ── Lista ranking formas de pago ──
  html += `<div class="card">
    <div class="card-head">
      <span class="card-title">Ranking formas de pago</span>
      <span class="card-badge">${resumen.length} formas</span>
    </div>
    <div class="card-body">
      <div class="fp-list">
        ${resumen.map(r => {
          const pct = totalImporte > 0 ? Math.round((r.importe_total/totalImporte)*100) : 0;
          const col = colorFP(r.idformadepago);
          return `<div class="fp-item">
            <div class="fp-dot" style="background:${col}"></div>
            <div class="fp-name">${r.descripcion}</div>
            <div class="fp-track"><div class="fp-fill" style="width:${pct}%;background:${col}"></div></div>
            <div class="fp-val">${fmt(r.importe_total)}</div>
            <div class="fp-pct">${pct}%</div>
          </div>`;
        }).join('')}
      </div>
    </div>
  </div>`;

  // ── Tabla detalle ──
  const totalPags = Math.ceil(detalle.length / PAGE_SIZE);
  html += `<div class="card" id="card-detalle">
    <div class="card-head">
      <span class="card-title">Detalle folio por folio</span>
      <span class="card-badge">${detalle.length} registros</span>
    </div>
    <div class="tbl-wrap" id="tbl-detalle"></div>
    <div class="pag-row" id="pag-row"></div>
  </div>`;

  res.innerHTML = html;

  // ── Renderizar charts ──
  requestAnimationFrame(() => {
    renderDona(resumen);
    renderBarras(resumen);
    renderLinea(horas, resumen.map(r => r.idformadepago));
    renderTabla(detalle, 1);
  });
}

// Dona
function renderDona(resumen) {
  const ctx = document.getElementById('chart-dona');
  if (!ctx) return;
  _charts.dona = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: resumen.map(r => r.descripcion),
      datasets: [{
        data:            resumen.map(r => r.importe_total),
        backgroundColor: resumen.map(r => colorFP(r.idformadepago)),
        borderWidth:     4,
        borderColor:     '#fff',
        hoverBorderColor:'#fff',
        hoverOffset:     10,
        spacing:         2,
        borderRadius:    8,
      }]
    },
    options: {
      responsive: true, maintainAspectRatio: false,
      plugins: {
        legend: { position:'right', labels:{ usePointStyle:true, pointStyle:'circle', font:{size:11,family:'Plus Jakarta Sans',weight:'700'}, boxWidth:8, padding:14, color:'#475569' } },
        tooltip: { backgroundColor:'rgba(15,23,42,.94)', padding:10, cornerRadius:8, callbacks: { label: ctx => ` ${ctx.label}: $${Number(ctx.raw).toLocaleString('es-MX',{minimumFractionDigits:2})}` } }
      },
      cutout: '62%',
      animation:{duration:700,easing:'easeOutQuart'},
    },
    plugins: [percentLabelsPlugin]
  });
}

// Barras
function renderBarras(resumen) {
  const ctx = document.getElementById('chart-barras');
  if (!ctx) return;
  _charts.barras = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: resumen.map(r => r.descripcion),
      datasets: [{
        label: 'Importe',
        data:            resumen.map(r => r.importe_total),
        backgroundColor: resumen.map(r => colorFP(r.idformadepago)),
        borderRadius:    9,
        borderSkipped:   false,
        maxBarThickness: 34,
      }]
    },
    options: {
      responsive: true, maintainAspectRatio: false,
      animation:{duration:700,easing:'easeOutQuart'},
      plugins: {
        legend: { display:false },
        tooltip: { backgroundColor:'rgba(15,23,42,.94)', padding:10, cornerRadius:8, callbacks: { label: ctx => ` $${Number(ctx.raw).toLocaleString('es-MX',{minimumFractionDigits:2})}` } }
      },
      scales: {
        x: { border:{display:false}, grid:{display:false}, ticks:{font:{size:10,family:'Plus Jakarta Sans',weight:'700'},color:'#64748b'} },
        y: { border:{display:false}, beginAtZero:true, grid:{color:'rgba(148,163,184,.14)',drawTicks:false}, ticks:{callback: v=>'$'+Number(v).toLocaleString('es-MX'), font:{size:10,weight:'700'},color:'#94a3b8'} }
      }
    }
  });
}

// Línea tendencia por hora
function renderLinea(horas, fpIds) {
  const ctx = document.getElementById('chart-linea');
  if (!ctx) return;

  // Construir horas únicas 0-23
  const horaSet = [...new Set(horas.map(h => h.hora))].sort((a,b) => a-b);
  if (!horaSet.length) { ctx.parentElement.innerHTML = '<div class="empty">Sin datos de tendencia</div>'; return; }

  // Agrupar por forma de pago
  const datasets = fpIds.map((fp, i) => {
    const col = colorFP(fp);
    const nombreFP = horas.find(h => h.idformadepago === fp)?.descripcion || fp;
    return {
      label: nombreFP,
      data: horaSet.map(h => {
        const row = horas.find(r => r.hora === h && r.idformadepago === fp);
        return row ? row.importe : 0;
      }),
      borderColor:     col,
      backgroundColor: col+'22',
      borderWidth:     2.8,
      pointRadius:     3,
      pointHoverRadius:6,
      pointBackgroundColor:'#fff',
      pointBorderColor:col,
      pointBorderWidth:2,
      tension:         0.35,
      fill:            false,
    };
  });

  _charts.linea = new Chart(ctx, {
    type: 'line',
    data: {
      labels: horaSet.map(h => `${String(h).padStart(2,'0')}:00`),
      datasets
    },
    options: {
      responsive: true, maintainAspectRatio: false,
      interaction: { mode:'index', intersect:false },
      animation:{duration:700,easing:'easeOutQuart'},
      plugins: {
        legend: { labels:{ usePointStyle:true, pointStyle:'circle', font:{size:10,family:'Plus Jakarta Sans',weight:'700'}, boxWidth:8, padding:12, color:'#475569' } },
        tooltip: { backgroundColor:'rgba(15,23,42,.94)', padding:10, cornerRadius:8, callbacks: { label: ctx => ` ${ctx.dataset.label}: $${Number(ctx.raw).toLocaleString('es-MX',{minimumFractionDigits:2})}` } }
      },
      scales: {
        x: { border:{display:false}, grid:{color:'rgba(148,163,184,.14)',drawTicks:false}, ticks:{font:{size:10,weight:'700'},color:'#64748b'} },
        y: { border:{display:false}, beginAtZero:true, grid:{color:'rgba(148,163,184,.14)',drawTicks:false}, ticks:{callback: v=>'$'+Number(v).toLocaleString('es-MX'), font:{size:10,weight:'700'},color:'#94a3b8'} }
      }
    }
  });
}

// Tabla paginada
function renderTabla(detalle, pag) {
  _pag = pag;
  const ini  = (pag-1)*PAGE_SIZE;
  const page = detalle.slice(ini, ini+PAGE_SIZE);
  const total = detalle.length;
  const totalPags = Math.ceil(total/PAGE_SIZE);

  const tbl = document.getElementById('tbl-detalle');
  const pagRow = document.getElementById('pag-row');
  if (!tbl) return;

  if (!page.length) { tbl.innerHTML = '<div class="empty">Sin registros</div>'; return; }

  tbl.innerHTML = `<table>
    <thead><tr>
      <th>Folio</th><th>Fecha</th><th>Mesa</th><th>Mesero</th>
      <th>Forma de pago</th><th>Marca</th>
      <th style="text-align:right">Importe</th>
      <th style="text-align:right">Propina</th>
      <th style="text-align:right">Total cuenta</th>
      <th>Estado</th>
    </tr></thead>
    <tbody>
      ${page.map(r => `<tr>
        <td class="folio">#${r.folio}</td>
        <td style="white-space:nowrap;font-size:11px;color:var(--text-3)">${fdt(r.fecha)}</td>
        <td>${r.mesa}</td>
        <td style="font-size:11px">${r.mesero}</td>
        <td><span class="fp-badge ${classFP(r.idformadepago)}">${r.forma_pago}</span></td>
        <td style="font-size:11px;color:var(--text-3)">${r.marca_tarjeta||'—'}</td>
        <td class="money">${fmt(r.importe)}</td>
        <td class="num" style="color:var(--text-3)">${r.propina>0?fmt(r.propina):'—'}</td>
        <td class="money">${fmt(r.total_cuenta)}</td>
        <td><span class="${r.estado==='Abierta'?'badge-abierta':'badge-pagada'}">${r.estado}</span></td>
      </tr>`).join('')}
    </tbody>
  </table>`;

  // Paginación
  if (pagRow) {
    let btns = '';
    for (let p=1; p<=totalPags; p++) {
      if (totalPags <= 7 || p===1 || p===totalPags || Math.abs(p-pag)<=1) {
        btns += `<button class="pag-btn${p===pag?' active':''}" onclick="renderTabla(window._dt,${p})">${p}</button>`;
      } else if (Math.abs(p-pag)===2) {
        btns += `<span style="padding:0 2px;color:var(--text-3)">…</span>`;
      }
    }
    pagRow.innerHTML = `<span>Mostrando ${ini+1}–${Math.min(ini+PAGE_SIZE,total)} de ${total}</span><div class="pag-btns">${btns}</div>`;
  }
  window._dt = detalle;
}

// ─── Exportar CSV ────────────────────────────────────────────────────────────
function exportarCSV() {
  if (!_datos?.detalle?.length) return;
  const cols = ['folio','fecha','mesa','mesero','forma_pago','marca_tarjeta','importe','propina','total_cuenta','estado'];
  const header = cols.join(',');
  const rows = _datos.detalle.map(r =>
    cols.map(c => {
      const v = r[c] ?? '';
      return typeof v === 'string' && v.includes(',') ? `"${v}"` : v;
    }).join(',')
  );
  const blob = new Blob([header+'\n'+rows.join('\n')], {type:'text/csv;charset=utf-8;'});
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = `formas_pago_${document.getElementById('f-ini').value||'turno'}.csv`;
  a.click();
}

// ─── Init ────────────────────────────────────────────────────────────────────
(async () => {
  try {
    await _getToken();
    // Ocultar topbar si está dentro de un iframe
    if (window.self !== window.top) {
      const tb = document.querySelector('.topbar');
      if (tb) tb.style.display = 'none';
    }
    const hoyStr = hoy();
    document.getElementById('f-ini').value = hoyStr;
    document.getElementById('f-fin').value = hoyStr;
    await cargarTurnos();
    await consultar();
  } catch(e) {
    document.getElementById('error-box').textContent = 'Error de inicio: ' + e.message;
    document.getElementById('error-box').style.display = 'block';
    document.getElementById('spinner').style.display = 'none';
  }
})();
</script>
</body>
</html>
