<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Corte de Caja</title>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }

  body {
    font-family: Arial, sans-serif;
    font-size: 11px;
    background: #d0d0d0;
    padding: 20px;
    color: #111;
  }

  .cut-report-shell {
    width: 100%;
    overflow-x: auto;
    overflow-y: visible;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 8px;
  }
  .page {
    background: white;
    width: 900px;
    min-width: 900px;
    margin: 0 auto;
    padding: 16px 20px 24px;
    box-shadow: 0 4px 24px rgba(0,0,0,0.25);
  }

  /* HEADER */
  .report-title {
    text-align: center;
    font-size: 15px;
    font-weight: bold;
    margin-bottom: 6px;
  }

  .header-meta {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 6px;
    gap: 10px;
  }

  .logo-box {
    background: #e67e22;
    color: white;
    font-size: 13px;
    font-weight: bold;
    padding: 6px 14px;
    border-radius: 3px;
    letter-spacing: 1px;
  }

  .meta-right { text-align: right; font-size: 10.5px; line-height: 1.8; }
  .meta-right strong { margin-right: 4px; }
  .sucursal-line { font-size: 9.5px; color: #666; max-width: 340px; margin-top: 2px; }

  .empresa-title {
    text-align: center;
    font-size: 14px;
    font-weight: bold;
    margin: 8px 0 4px;
  }

  /* RESUMEN DEL TURNO */
  .section-header {
    background: #3a5a8a;
    color: white;
    text-align: center;
    font-weight: bold;
    font-size: 11.5px;
    padding: 4px;
  }

  .resumen-table {
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #3a5a8a;
    margin-bottom: 8px;
  }

  .resumen-table td {
    border: 1px solid #b0bcd0;
    padding: 5px 8px;
    vertical-align: middle;
  }

  .td-venta-total {
    background: #e67e22;
    color: white;
    text-align: center;
    width: 130px;
  }

  .td-venta-total .vtl { font-size: 10px; display: block; }
  .td-venta-total .vta { font-size: 20px; font-weight: bold; display: block; line-height: 1.2; }

  .td-prom {
    background: #3a5a8a;
    color: white;
    text-align: center;
    width: 115px;
    font-size: 10px;
    line-height: 1.7;
  }

  .td-prom .pl { font-size: 9px; opacity: 0.8; display: block; }
  .td-prom .pv { font-size: 13px; font-weight: bold; display: block; }

  .td-data { text-align: center; font-size: 10.5px; }
  .td-data .da { font-weight: bold; font-size: 12px; display: block; }
  .td-data .dl { font-size: 9.5px; color: #555; display: block; }

  /* TRES COLUMNAS */
  .three-cols {
    display: grid;
    grid-template-columns: 195px 1fr 210px;
    border: 1px solid #aaa;
    margin-bottom: 6px;
  }

  .col-box { border-right: 1px solid #aaa; }
  .col-box:last-child { border-right: none; }

  .col-hdr {
    background: #3a5a8a;
    color: white;
    text-align: center;
    font-weight: bold;
    font-size: 10.5px;
    padding: 3px 6px;
  }

  .col-hdr.green { background: #229954; }

  .col-body { padding: 5px 8px; }

  .row2 {
    display: flex;
    justify-content: space-between;
    padding: 1.5px 0;
    font-size: 10.5px;
  }

  .row2.bold { font-weight: bold; }
  .row2.border-t { border-top: 1px dashed #bbb; margin-top: 3px; padding-top: 3px; }
  .row2.solid-t  { border-top: 1px solid #bbb; margin-top: 4px; padding-top: 4px; }

  .inner-hdr {
    background: #3a5a8a;
    color: white;
    text-align: center;
    font-size: 9.5px;
    font-weight: bold;
    padding: 2px 6px;
    margin: 5px -8px;
  }

  .inner-hdr.green { background: #229954; }

  .cat-row {
    display: flex;
    justify-content: space-between;
    padding: 2px 0;
    font-size: 10.5px;
    border-bottom: 1px dotted #ddd;
  }
  .cat-row:last-child { border-bottom: none; }
  .cat-right { text-align: right; }
  .pct-tag { color: #888; font-size: 9.5px; margin-left: 4px; }

  .mes-row {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 3px 0;
    border-bottom: 1px dotted #ddd;
    font-size: 10.5px;
  }
  .mes-row:last-child { border-bottom: none; }

  .mes-badge {
    width: 18px; height: 18px;
    border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 9px; font-weight: bold;
    color: white; flex-shrink: 0;
  }
  .gold   { background: #c8a415; }
  .silver { background: #8a8a8a; }
  .bronze { background: #a05a2c; }

  .prod-row {
    display: flex;
    justify-content: space-between;
    gap: 4px;
    padding: 2px 0;
    font-size: 9.5px;
    border-bottom: 1px dotted #eee;
  }
  .prod-row:last-child { border-bottom: none; }
  .prod-qty  { color: #555; min-width: 20px; }
  .prod-name { flex: 1; }
  .prod-amt  { font-weight: bold; }

  /* DECLARACION */
  .decl-grid {
    display: grid;
    grid-template-columns: 195px 1fr 210px;
    border: 1px solid #aaa;
    border-top: none;
    margin-bottom: 8px;
  }

  /* EVENTOS */
  .eventos-bar {
    background: #f5f5f5;
    border: 1px solid #bbb;
    padding: 4px 10px;
    display: flex;
    gap: 28px;
    font-size: 10.5px;
    margin-bottom: 5px;
    flex-wrap: wrap;
  }

  /* STATS TABLE */
  .stats-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 7px;
    font-size: 10.5px;
  }
  .stats-table td {
    border: 1px solid #bbb;
    padding: 3px 7px;
  }
  .stats-table .sl { font-weight: bold; background: #f5f5f5; width: 155px; }
  .stats-table .sq { width: 40px; text-align: center; }
  .stats-table .sa { width: 95px; text-align: right; }
  .stats-table .se { color: #444; }

  /* 4 COLS */
  .four-cols {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    border: 1px solid #aaa;
    margin-bottom: 6px;
  }

  .fc { border-right: 1px solid #aaa; }
  .fc:last-child { border-right: none; }
  .fc-hdr { background: #229954; color: white; text-align: center; font-weight: bold; font-size: 9.5px; padding: 3px; }
  .fc-body { padding: 4px 6px; font-size: 10px; }
  .fc-row { display: flex; justify-content: space-between; padding: 1px 0; }
  .fc-row .fv { font-weight: bold; }

  .report-footer {
    text-align: right;
    font-size: 9px;
    color: #888;
    margin-top: 8px;
    border-top: 1px solid #ddd;
    padding-top: 4px;
  }

  @media print {
    body { background: white; padding: 0; }
    .cut-report-shell { overflow: visible; padding-bottom: 0; }
    .page { box-shadow: none; width: 900px; min-width: 900px; }
    #turno-nav { display: none !important; }
  }

  @media (max-width: 820px) {
    body { padding: 10px; background: #e0e0e0; }
    .cut-report-shell { margin: 0 -2px; padding: 0 2px 8px; }
    .page { width: 900px !important; min-width: 900px !important; padding: 14px 16px 20px; border-radius: 8px; }
    .report-title { font-size: 14px; margin-bottom: 8px; }
    .header-meta { flex-direction: row; align-items: flex-start; gap: 10px; }
    .meta-right { text-align: right; }
    .empresa-title { font-size: 12px; }
    .section-header { font-size: 10px; padding: 3px 6px; }
    .resumen-table,
    .hora-table,
    .stats-table { min-width: 100%; }
    .stats-table td { white-space: nowrap; font-size: 10px; padding: 3px 5px; }
  }

  @media (max-width: 430px) {
    body { padding: 4px; }
    .cut-report-shell { margin: 0; padding-bottom: 6px; }
    .page { width: 900px !important; min-width: 900px !important; padding: 12px 14px 18px; }
    .report-title { font-size: 12px; }
    .filtro-bar { padding: 4px 6px; }
    .btn-consultar, .btn-imprimir { padding: 5px 8px; font-size: 10px; }
  }
</style>
</head>
<body class="cut-report-view">
<div class="cut-report-shell">
<div class="page cut-report-document">

  <div class="report-title">CORTE X &mdash; ARQUEO POR TURNO Y ESTACIÓN</div>

  <!-- NAVEGADOR DE TURNOS -->
  <div id="turno-nav" class="no-print" style="display:flex;align-items:center;justify-content:center;gap:10px;margin-bottom:10px;padding:8px;background:#f5f5f5;border:1px solid #ddd;border-radius:4px;flex-wrap:wrap;">
    <button onclick="cambiarTurno(-1)" id="btn-prev" style="padding:4px 12px;border:1px solid #ccc;border-radius:3px;cursor:pointer;background:#fff;font-size:11px;font-weight:bold;">&#8592; Anterior</button>
    <span style="font-size:11px;font-weight:bold;color:#555;" id="nav-label">Cargando…</span>
    <button onclick="cambiarTurno(1)" id="btn-next" style="padding:4px 12px;border:1px solid #ccc;border-radius:3px;cursor:pointer;background:#fff;font-size:11px;font-weight:bold;">Siguiente &#8594;</button>
    <button onclick="cargarTurno(null)" style="padding:4px 12px;border:1px solid #e67e22;border-radius:3px;cursor:pointer;background:#e67e22;color:#fff;font-size:11px;font-weight:bold;margin-left:8px;">&#8635; Turno actual</button>
    <button onclick="window.location.href='/corte-z?tipo=X'" style="padding:4px 12px;border:1px solid #3a5a8a;border-radius:3px;cursor:pointer;background:#fff;color:#3a5a8a;font-size:11px;font-weight:bold;">Volver</button>
    <button onclick="iniciar()" style="padding:4px 12px;border:1px solid #3a5a8a;border-radius:3px;cursor:pointer;background:#3a5a8a;color:#fff;font-size:11px;font-weight:bold;">Actualizar</button>
    <button onclick="window.print()" style="padding:4px 12px;border:1px solid #229954;border-radius:3px;cursor:pointer;background:#229954;color:#fff;font-size:11px;font-weight:bold;">Imprimir</button>
  </div>

  <div class="header-meta">
    <div>
      <div class="logo-box" id="h-empresa">—</div>
    </div>
    <div class="meta-right">
      <div><strong>Fecha:</strong> <span id="h-fecha">—</span></div>
      <div><strong>Turno:</strong> <span id="h-turno">—</span> &nbsp; <strong>Caja:</strong> <span id="h-caja">—</span> &nbsp; <strong>Cajero:</strong> <span id="h-cajero">—</span></div>
      <div class="sucursal-line" id="h-sucursal"></div>
    </div>
  </div>

  <div class="empresa-title" id="empresa-nombre">—</div>

  <!-- RESUMEN DEL TURNO -->
  <div class="section-header">RESUMEN DEL TURNO</div>
  <table class="resumen-table">
    <tr>
      <td rowspan="3" class="td-venta-total">
        <span class="vtl">VENTA TOTAL</span>
        <span class="vta" id="rt-vt">—</span>
      </td>
      <td class="td-prom" rowspan="3">
        <span class="pl">CUENTA PROMEDIO</span>
        <span class="pv" id="rt-cprom">—</span>
        <span class="pl">TICKET PROMEDIO</span>
        <span class="pv" id="rt-tprom">—</span>
      </td>
      <td class="td-data"><span class="da" id="rt-ef">—</span><span class="dl">EFECTIVO</span></td>
      <td class="td-data"><span class="da" id="rt-al">—</span><span class="dl">ALIMENTOS</span></td>
      <td class="td-data"><span class="da" id="rt-com">—</span><span class="dl">COMEDOR</span></td>
    </tr>
    <tr>
      <td class="td-data"><span class="da" id="rt-tar">—</span><span class="dl">TARJETAS</span></td>
      <td class="td-data"><span class="da" id="rt-be">—</span><span class="dl">BEBIDAS</span></td>
      <td class="td-data"><span class="da" id="rt-dom">—</span><span class="dl">DOMICILIO</span></td>
    </tr>
    <tr>
      <td class="td-data"><span class="da" id="rt-otp">—</span><span class="dl">OTROS</span></td>
      <td class="td-data"><span class="da" id="rt-otc">—</span><span class="dl">OTROS</span></td>
      <td class="td-data"><span class="da" id="rt-rap">—</span><span class="dl">RÁPIDO</span></td>
    </tr>
  </table>

  <!-- TRES COLUMNAS -->
  <div class="three-cols">
    <!-- CAJA -->
    <div class="col-box">
      <div class="col-hdr">CAJA</div>
      <div class="col-body" id="caja-body"></div>
    </div>
    <!-- VENTA SIN IMPUESTO -->
    <div class="col-box">
      <div class="col-hdr">VENTA (SIN IMPUESTO)</div>
      <div class="col-body" id="venta-body"></div>
    </div>
    <!-- MESEROS / PRODUCTOS -->
    <div class="col-box">
      <div class="col-hdr">TOP 3 MESEROS</div>
      <div class="col-body" id="meseros-body"></div>
      <div class="col-hdr">PRODUCTOS MÁS VENDIDOS</div>
      <div class="col-body" id="prods-body"></div>
      <div class="col-hdr">PRODUCTOS A MONITOREAR</div>
      <div class="col-body" id="monitor-body"></div>
    </div>
  </div>

  <!-- DECLARACION (abajo solo columna izquierda) -->
  <div class="decl-grid">
    <div class="col-box">
      <div class="col-hdr green">DECLARACIÓN DE CAJERO</div>
      <div class="col-body" id="decl-body"></div>
    </div>
    <div class="col-box" style="border-right:none;grid-column:2/4"></div>
  </div>

  <!-- EVENTOS DE SEGURIDAD -->
  <div class="eventos-bar">
    <span>Eventos de seguridad</span>
    <span><strong>FOLIO INICIAL:</strong> <span id="ev-ini">—</span></span>
    <span><strong>FOLIO FINAL:</strong> <span id="ev-fin">—</span></span>
  </div>

  <!-- STATS -->
  <table class="stats-table">
    <tr>
      <td class="sl">Total de cuentas</td>
      <td class="sq" id="ss-tq">—</td>
      <td class="sa" id="ss-ta">—</td>
      <td class="se">Propinas</td>
      <td class="sa" id="ss-prop">—</td>
    </tr>
    <tr>
      <td class="sl">Cuentas canceladas</td>
      <td class="sq" id="ss-cq">—</td>
      <td class="sa" id="ss-ca">—</td>
      <td class="se"># De comensales</td>
      <td class="sa" id="ss-com">—</td>
    </tr>
    <tr>
      <td class="sl">Cortesías</td>
      <td class="sq" id="ss-coq">—</td>
      <td class="sa" id="ss-coa">—</td>
      <td class="se">Cargos</td>
      <td class="sa" id="ss-carg">—</td>
    </tr>
    <tr>
      <td class="sl">Descuento a cuenta</td>
      <td class="sq" id="ss-dq">—</td>
      <td class="sa" id="ss-da">—</td>
      <td class="se">Re impresión de cuentas</td>
      <td class="sa">0</td>
    </tr>
    <tr>
      <td class="sl">Descuento monedero</td>
      <td class="sq">—</td>
      <td class="sa" id="ss-mon">—</td>
      <td class="se">Re apertura de cuentas</td>
      <td class="sa">0</td>
    </tr>
  </table>

  <!-- 4 COLUMNAS -->
  <div class="four-cols">
    <div class="fc">
      <div class="fc-hdr">FORMAS DE PAGO VENTAS</div>
      <div class="fc-body" id="fc-pagos"></div>
    </div>
    <div class="fc">
      <div class="fc-hdr">FORMAS DE PAGO PROPINAS</div>
      <div class="fc-body" id="fc-propinas"><span style="color:#888">—</span></div>
    </div>
    <div class="fc">
      <div class="fc-hdr">VENTAS POR ÁREA</div>
      <div class="fc-body" id="fc-areas"></div>
    </div>
    <div class="fc">
      <div class="fc-hdr">VENTA RÁPIDA POR TIPO</div>
      <div class="fc-body" id="fc-tipo"><span style="color:#888">—</span></div>
    </div>
  </div>

  <div class="report-footer">REPORTE GENERADO — <span id="gen-time">—</span></div>
</div>

<script src="/js/arkhon-utils.js"></script>
<script>
// LOCAL_API_KEY es manejado por arkhon-utils.js via window.LOCAL_API_KEY
// token loaded via _initAuth() from arkhon-utils.js
const API_URL  = '/api/reportes/corte-x';
const EMPRESA  = 'MI EMPRESA'; // ← cambia este valor


const $ = id => document.getElementById(id);
const pct = (a,b) => b>0 ? ((a/b)*100).toFixed(2)+'%' : '0.00%';

function dtRange(a,b) {
  const o = { day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit', second:'2-digit' };
  return `DEL: ${new Date(a).toLocaleString('es-MX',o)} AL: ${b ? new Date(b).toLocaleString('es-MX',o) : 'ACTIVO'}`;
}

function dtFull(iso) {
  return iso ? new Date(iso).toLocaleString('es-MX',{ day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit', second:'2-digit' }) : '—';
}

function render(d) {
  const { turno, ventas, cancelados, formasPago, ventasServicio, meseros, generadoEn, billing, source, operationalCut } = d;
  const sections = d.sections || {};
  const cashDrawer = operationalCut?.cashDrawer || {};
  const security = operationalCut?.securityEvents || {};
  const averages = operationalCut?.averages || {};
  const courtesies = operationalCut?.courtesies || {};
  const discounts = operationalCut?.discounts || {};
  const products = operationalCut?.products || {};
  const isOpen = turno.estado === 'abierto' || operationalCut?.isOpen;
  const statusLabel = sections.header?.status || (isOpen ? 'En vivo / Turno abierto' : 'Definitivo / Turno cerrado');
  const liveNote = ' - ' + statusLabel + (isOpen ? ' - Cifras sujetas a cambio hasta cierre' : '');

  // Header
  $('h-empresa').textContent      = sections.header?.businessName || EMPRESA;
  $('empresa-nombre').textContent = sections.header?.businessName || EMPRESA;
  $('h-fecha').textContent        = dtRange(turno.apertura, turno.cierre) + liveNote;
  $('h-turno').textContent        = turno.idturno || turno.idturnointerno;
  $('h-caja').textContent         = turno.idestacion || '—';
  $('h-cajero').textContent       = turno.cajero || '—';
  $('h-sucursal').textContent     = sections.header?.branchAddress || sections.header?.branchName || turno.sucursal || '';

  const vtConImp = ventas.venta_total || 0;
  const vtSinImp = ventas.subtotal   || (vtConImp - (ventas.impuestos||0));

  // Resumen
  $('rt-vt').textContent   = fmt(vtConImp);
  $('rt-cprom').textContent = fmt(ventas.ticket_promedio);
  $('rt-tprom').textContent = fmt(ventas.ticket_promedio);

  const paymentKind = p => {
    const id = String(p.idformadepago || '').trim().toLowerCase();
    const name = String(p.forma_pago || '').trim().toLowerCase();
    const brand = String(p.cardBrand || '').trim().toLowerCase();
    const tipo = Number(p.tipo || 0);
    if (id === 'ef' || id === 'dll' || name.includes('efectivo') || name.includes('dolares')) return 'cash';
    if (tipo === 2 || ['visa','mc','amex','tc','td'].includes(id) || /visa|mastercard|american|tarjeta|debito|débito|credito|crédito/.test(name + ' ' + brand)) return 'card';
    if (tipo === 3 || id === 'val' || name.includes('vale')) return 'voucher';
    return 'other';
  };
  let sumEf=0, sumTar=0, sumVal=0, sumOt=0;
  formasPago.forEach(p => {
    const amount = Number(p.total || 0);
    const kind = paymentKind(p);
    if (kind === 'cash') sumEf += amount;
    else if (kind === 'card') sumTar += amount;
    else if (kind === 'voucher') sumVal += amount;
    else sumOt += amount;
  });

  $('rt-ef').textContent  = fmt(sumEf);
  $('rt-tar').textContent = fmt(sumTar);
  $('rt-otp').textContent = fmt(sumOt);
  $('rt-al').textContent  = fmt(ventas.alimentos);
  $('rt-be').textContent  = fmt(ventas.bebidas);
  $('rt-otc').textContent = fmt(ventas.otros);

  const svcMap = {};
  (ventasServicio||[]).forEach(s => svcMap[String(s.servicio || s.area || '').toLowerCase()] = s);
  const getSvc = k => svcMap[k] || { total:0 };

  const com = getSvc('comedor');
  const dom = getSvc('domicilio');
  const rap = getSvc('rapido') || getSvc('rápido') || { total:0 };

  $('rt-com').textContent = `${fmt(com.total)} (${pct(com.total,vtConImp)})`;
  $('rt-dom').textContent = `${fmt(dom.total)} (${pct(dom.total,vtConImp)})`;
  $('rt-rap').textContent = `${fmt(rap.total)} (${pct(rap.total,vtConImp)})`;

  // CAJA
  const fondo   = cashDrawer.initialCash ?? turno.fondo ?? 0;
  const ef      = sumEf;
  const tar     = sumTar;
  const vales   = sumVal;
  const otros   = sumOt;
  const depositos = cashDrawer.deposits || 0;
  const retiros = cashDrawer.withdrawals || 0;
  const propPagadas = cashDrawer.paidTips || 0;
  const saldo   = cashDrawer.finalExpected ?? (fondo + ef + tar + vales + otros + depositos - retiros - propPagadas);
  const efFinal = cashDrawer.expectedCash ?? (fondo + ef + depositos - retiros - propPagadas);

  $('caja-body').innerHTML = `
    <div class="row2"><span>+FONDO INICIAL:</span><span>${fmt(fondo)}</span></div>
    <div class="row2"><span>+EFECTIVO:</span><span>${fmt(ef)}</span></div>
    <div class="row2"><span>+TARJETA:</span><span>${fmt(tar)}</span></div>
    <div class="row2"><span>+VALES:</span><span>${fmt(vales)}</span></div>
    <div class="row2"><span>+OTROS:</span><span>${fmt(otros)}</span></div>
    <div class="row2"><span>+DEPÓSITOS EFECTIVO:</span><span>${fmt(depositos)}</span></div>
    <div class="row2"><span>-RETIROS EFECTIVO:</span><span>${fmt(retiros)}</span></div>
    <div class="row2"><span>-PROPINAS PAGADAS:</span><span>${fmt(propPagadas)}</span></div>
    <div style="border-top:1px dashed #aaa;margin:4px 0"></div>
    <div class="row2 bold"><span>EFECTIVO ESPERADO:</span><span>${fmt(efFinal)}</span></div>
  `;

  // DECLARACIÓN
  const totalDecl = (cashDrawer.declaredCash || 0) + (cashDrawer.declaredCard || 0) + (cashDrawer.declaredVouchers || 0) + (cashDrawer.declaredOther || 0);
  const diff      = cashDrawer.overShort ?? (totalDecl - vtConImp);
  const declarationConfirmed = Array.isArray(cashDrawer.declarationLines) && cashDrawer.declarationLines.length > 0;
  $('decl-body').innerHTML = declarationConfirmed ? `
    <div class="row2"><span>EFECTIVO:</span><span>${declarationConfirmed ? fmt(cashDrawer.declaredCash||0) : 'Sin datos'}</span></div>
    <div class="row2"><span>TARJETA:</span><span>${declarationConfirmed ? fmt(cashDrawer.declaredCard||0) : 'Sin datos'}</span></div>
    <div class="row2"><span>VALES:</span><span>${declarationConfirmed ? fmt(cashDrawer.declaredVouchers||0) : 'Sin datos'}</span></div>
    <div class="row2"><span>OTROS:</span><span>${declarationConfirmed ? fmt(cashDrawer.declaredOther||0) : 'Sin datos'}</span></div>
    <div style="border-top:1px dashed #aaa;margin:4px 0"></div>
    <div class="row2 bold"><span>TOTAL:</span><span>${declarationConfirmed ? fmt(totalDecl) : 'Sin datos'}</span></div>
    <div class="row2"><span>SOBRANTE: (+)</span><span style="color:#27ae60">${declarationConfirmed && diff >= 0 ? fmt(diff) : ''}</span></div>
    <div class="row2"><span>FALTANTE: (-)</span><span style="color:#c0392b">${declarationConfirmed && diff < 0 ? fmt(Math.abs(diff)) : ''}</span></div>
  ` : '<div style="color:#888;font-size:9.5px;padding:3px 0">Declaracion no capturada</div>';

  // VENTA SIN IMPUESTO
  const salesWithoutTax = sections.salesWithoutTax?.lines || [
    { label:'ALIMENTOS', total:ventas.alimentos, percent: vtSinImp ? (ventas.alimentos / vtSinImp) * 100 : 0 },
    { label:'BEBIDAS', total:ventas.bebidas, percent: vtSinImp ? (ventas.bebidas / vtSinImp) * 100 : 0 },
    { label:'OTROS', total:ventas.otros, percent: vtSinImp ? (ventas.otros / vtSinImp) * 100 : 0 },
  ];
  const svcRows = (sections.serviceTypeBreakdown?.lines || ventasServicio || []).map(s =>
    `<div class="cat-row"><span>${s.area || s.servicio}:</span><span class="cat-right"><strong>${fmt(s.total)}</strong><span class="pct-tag">(${pct(s.total,vtSinImp)})</span></span></div>`
  ).join('');

  const ventaNeta = vtSinImp - (ventas.descuentos||0);
  const billingSynced = billing && billing.synced === true;
  const billingWarning = billing?.warning === 'billing_cloud_not_synced'
    ? 'Facturacion Arkhon no sincronizada'
    : 'No confirmado';
  $('venta-body').innerHTML = `
    ${salesWithoutTax.map(row => `<div class="cat-row"><span><strong>${row.label || row.key}:</strong></span><span class="cat-right"><strong>${fmt(row.total)}</strong><span class="pct-tag">(${Number(row.percent || 0).toFixed(2)}%)${row.quantity != null ? ' ' + Number(row.quantity).toFixed(2) : ''}</span></span></div>`).join('')}
    <div class="inner-hdr">POR TIPO DE SERVICIO</div>
    ${svcRows || '<div style="color:#888;font-size:9.5px;padding:3px 0">Sin datos</div>'}
    <div style="border-top:1px solid #aaa;margin:4px 0;padding-top:4px">
      <div class="row2"><span>SUBTOTAL:</span><span>${fmt(vtSinImp)}</span></div>
      <div class="row2"><span>- DESCUENTOS:</span><span>${fmt(ventas.descuentos||0)}</span></div>
      <div class="row2 bold border-t"><span>VENTA NETA:</span><span>${fmt(ventaNeta)}</span></div>
    </div>
    <div style="border-top:1px solid #aaa;border-bottom:1px solid #aaa;margin:4px 0;padding:4px 0">
      <div class="row2 bold"><span>IMPUESTO TOTAL:</span><span>${fmt(ventas.impuestos)}</span></div>
    </div>
    <div class="row2 bold" style="font-size:12px"><span>VENTA CON IMP.:</span><span>${fmt(vtConImp)}</span></div>
    <div class="inner-hdr">FACTURACIÓN</div>
    <div class="row2"><span>FUENTE:</span><span>Arkhon Cloud / Me-Facturo</span></div>
    <div class="row2"><span>VENTA FACTURADA:</span><span>${billingSynced ? fmt(billing.ventaFacturada||0) : billingWarning}</span></div>
    <div class="row2"><span>VENTA NO FACTURADA:</span><span>${billingSynced ? fmt(billing.ventaNoFacturada||0) : 'No confirmado'}</span></div>
    <div class="row2"><span>FACTURAS EMITIDAS:</span><span>${billingSynced ? (billing.facturasEmitidas||0) : 'No confirmado'}</span></div>
    <div class="row2"><span>UUID:</span><span>${billingSynced ? (billing.uuidCount||0) : 'No confirmado'}</span></div>
  `;

  // MESEROS
  const cols  = ['gold','silver','bronze'];
  const top3  = (sections.topWaiters?.lines || meseros || []).slice(0,3);
  $('meseros-body').innerHTML = top3.length ? top3.map((m,i) => `
    <div class="mes-row">
      <div class="mes-badge ${cols[i]}">${i+1}</div>
      <div style="flex:1">${m.waiter || m.idmesero || 'Sin mesero'}</div>
      <div><strong>${fmt(m.total ?? m.venta ?? 0)}</strong></div>
    </div>
  `).join('') : '<div style="color:#888;font-size:9.5px;padding:3px 0">Sin datos</div>';

  const topProducts = sections.topProducts?.lines || products.mostSold || d.top_productos || [];
  $('prods-body').innerHTML = topProducts.length
    ? topProducts.slice(0,5).map(p => `<div class="prod-row"><span class="prod-qty">${p.cantidad||0}</span><span class="prod-name">${p.producto||'Producto'}</span><span class="prod-amt">${fmt(p.total_venta||0)}</span></div>`).join('')
    : `<div style="color:#888;font-size:9.5px;padding:3px 0">Sin datos</div>`;
  const monitorProducts = sections.monitoredProducts?.lines || products.monitorProducts || [];
  $('monitor-body').innerHTML = monitorProducts.length
    ? monitorProducts.slice(0,5).map(p => `<div class="prod-row"><span class="prod-qty">${p.cantidad||0}</span><span class="prod-name">${p.producto||'Producto'}</span><span class="prod-amt">${fmt(p.total_venta||0)}</span></div>`).join('')
    : `<div style="color:#888;font-size:9.5px;padding:3px 0">${sections.monitoredProducts?.emptyMessage || 'Sin productos a monitorear configurados'}</div>`;

  // STATS
  $('ev-ini').textContent  = d.folios?.folio_inicial ?? operationalCut?.folioInicial ?? '—';
  $('ev-fin').textContent  = d.folios?.folio_final ?? operationalCut?.folioFinal ?? '—';
  $('ss-tq').textContent   = ventas.tickets;
  $('ss-ta').textContent   = fmt(vtConImp);
  $('ss-prop').textContent = fmt(ventas.propinas||0);
  $('ss-cq').textContent   = cancelados?.cantidad || 0;
  $('ss-ca').textContent   = fmt(cancelados?.importe||0) + ' ' + pct(cancelados?.importe||0, vtConImp);
  $('ss-com').textContent  = averages.guests ?? ventas.tickets;
  $('ss-coq').textContent  = security.courtesyAccounts ?? ventas.cortesias ?? 0;
  $('ss-coa').textContent  = fmt((courtesies.food||0) + (courtesies.drinks||0) + (courtesies.others||0));
  $('ss-carg').textContent = fmt(ventas.cargo || 0);
  $('ss-dq').textContent   = security.discountedAccounts ?? '—';
  $('ss-da').textContent   = fmt(ventas.descuentos||0);
  $('ss-mon').textContent  = fmt(discounts.wallet || ventas.descuentomonedero || 0);

  // FORMAS DE PAGO
  $('fc-pagos').innerHTML = formasPago.map(p =>
    `<div class="fc-row"><span>${p.forma_pago}</span><span class="fv">${fmt(p.total)}</span></div>`
  ).join('');

  $('fc-propinas').innerHTML = formasPago.filter(p => (p.propina||0) > 0).map(p =>
    `<div class="fc-row"><span>${p.forma_pago}</span><span class="fv">${fmt(p.propina)}</span></div>`
  ).join('') || '<span style="color:#888">$0.00 confirmado</span>';

  // VENTAS POR AREA
  const areaRows = sections.areaSales?.lines || ventasServicio || [];
  $('fc-areas').innerHTML = areaRows.length
    ? areaRows.map(s => `<div class="fc-row"><span>${s.area || s.servicio}</span><span class="fv">${fmt(s.total)}</span></div>`).join('')
    : '<span style="color:#888">Sin datos</span>';

  $('fc-tipo').innerHTML = `
    <div class="fc-row"><span>Alimentos</span><span class="fv">${fmt(operationalCut?.byProductType?.alimentos||ventas.alimentos||0)}</span></div>
    <div class="fc-row"><span>Bebidas</span><span class="fv">${fmt(operationalCut?.byProductType?.bebidas||ventas.bebidas||0)}</span></div>
    <div class="fc-row"><span>Otros</span><span class="fv">${fmt(operationalCut?.byProductType?.otros||ventas.otros||0)}</span></div>
  `;

  const warnings = source?.warnings?.length ? ' - ' + source.warnings.join(', ') : '';
  $('gen-time').textContent = dtFull(generadoEn || source?.generatedAt) + warnings;
}

// Estado de navegación
let turnoActualId = null;
let listaTurnos   = [];

// Carga lista de turnos para navegación y arranca con el más reciente
async function iniciar() {
  try {
    await _initAuth();
    const initialTurno = new URLSearchParams(window.location.search).get('idturno');
    if (initialTurno) {
      await cargarTurno(initialTurno);
      return;
    }
    // Primero trae el turno activo/más reciente
    const data = await api('/reportes/corte-x');
    if (data) {
      render(data);
      turnoActualId = data.turno.idturno;
      actualizarNav(data.turno);
    } else {
      mostrarError('No se encontró turno');
    }
  } catch(e) {
    mostrarError('Error de conexión: ' + e.message);
  }
}

async function cargarTurno(idturno) {
  const ep = idturno ? '/reportes/corte-x?idturno=' + idturno : '/reportes/corte-x';
  try {
    document.getElementById('turno-nav').style.opacity = '0.6';
    const data = await api(ep);
    if (data) {
      render(data);
      turnoActualId = data.turno.idturno;
      actualizarNav(data.turno);
    } else {
      mostrarError('Turno no encontrado');
    }
  } catch(e) {
    mostrarError('Error de conexión: ' + e.message);
  } finally {
    document.getElementById('turno-nav').style.opacity = '1';
  }
}

async function cambiarTurno(delta) {
  if (!turnoActualId) return;
  const nuevoId = parseInt(turnoActualId) + delta;
  if (nuevoId < 1) return;
  await cargarTurno(nuevoId);
}

function actualizarNav(turno) {
  const id = turno.idturno || turno.idturnointerno || '—';
  const estado = turno.estado === 'abierto' ? ' ● ABIERTO' : ' ○ CERRADO';
  document.getElementById('nav-label').textContent = 'Turno #' + id + estado;
  document.getElementById('btn-prev').disabled = parseInt(id) <= 1;
}

function mostrarError(msg) {
  document.querySelector('.page').innerHTML =
    '<div style="padding:40px;text-align:center;color:#c0392b;font-size:13px;font-weight:bold;">!️ ' + msg + '<br><br>' +
    '<button onclick="iniciar()" style="padding:8px 20px;background:#e67e22;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;font-weight:bold;">Reintentar</button></div>';
}

// Ocultar topbar si corre dentro de un iframe
if (window.self !== window.top) {
  const tb = document.querySelector('.topbar');
  if (tb) tb.style.display = 'none';
}

iniciar();
</script>
</body>
</html>
