<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Gastos — 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"/>
<style>
:root{
  --bg:#f7f8fc;--surface:#fff;--border:#eaecf4;--border-2:#d8dce8;
  --text:#111827;--text-2:#4b5563;--text-3:#9ca3af;--text-4:#c4c9d4;
  --orange:#f97316;--orange-d:#ea6a0a;--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);
  --red:#ef4444;--red-lt:rgba(239,68,68,.10);
  --yellow:#f59e0b;--yellow-lt:rgba(245,158,11,.10);
  --amber:#b45309;
  --shadow-sm:0 1px 3px rgba(17,24,39,.06);--shadow:0 2px 8px rgba(17,24,39,.08);
  --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);}}
@keyframes pulse{0%,100%{opacity:1;}50%{opacity:.5;}}

.topbar{
  background:var(--surface);border-bottom:1px solid var(--border);
  height:58px;padding:0 24px;
  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(--orange);
  display:flex;align-items:center;justify-content:center;
  box-shadow:0 3px 10px rgba(249,115,22,.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-right{display:flex;align-items:center;gap:8px;}
.rt-badge{
  display:flex;align-items:center;gap:6px;
  background:var(--green-lt);border:1px solid rgba(16,185,129,.2);
  color:var(--green);font-size:11px;font-weight:700;
  padding:5px 10px;border-radius:20px;
}
.rt-dot{width:7px;height:7px;border-radius:50%;background:var(--green);animation:pulse 1.8s ease-in-out infinite;}
.rt-badge.loading{background:var(--yellow-lt);border-color:rgba(245,158,11,.2);color:var(--yellow);}
.rt-badge.loading .rt-dot{background:var(--yellow);}
.back{
  color:var(--text-2);font-size:12px;font-weight:700;
  border:1px solid var(--border);padding:7px 14px;border-radius:8px;
  transition:.15s;display:flex;align-items:center;gap:6px;
  text-decoration:none;background:var(--surface);cursor:pointer;
}
.back:hover{background:var(--orange);border-color:var(--orange);color:#fff;}
.back svg{width:13px;height:13px;stroke:currentColor;stroke-width:2.2;fill:none;}

.container{max-width:1060px;margin:0 auto;padding:20px 20px 40px;}

/* ── MODO TABS ── */
.mode-tabs{display:flex;gap:6px;margin-bottom:14px;}
.mode-tab{
  padding:8px 18px;border-radius:8px;border:1.5px solid var(--border);
  font-size:12px;font-weight:700;cursor:pointer;background:var(--surface);color:var(--text-2);
  transition:.15s;
}
.mode-tab.active{background:var(--orange);border-color:var(--orange);color:#fff;box-shadow:0 2px 8px rgba(249,115,22,.25);}

/* ── FILTROS ── */
.filters-card{
  background:var(--surface);border:1px solid var(--border);border-radius:var(--r);
  box-shadow:var(--shadow-sm);padding:14px 18px;margin-bottom:14px;
  display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap;
}
.filter-group{display:flex;flex-direction:column;gap:4px;}
.filter-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-3);}
.filter-input{
  padding:7px 11px;border:1.5px solid var(--border);border-radius:8px;
  font-size:12.5px;font-weight:600;color:var(--text);background:var(--bg);
  outline:none;transition:.15s;min-width:130px;
}
.filter-input:focus{border-color:var(--orange);background:var(--surface);box-shadow:0 0 0 3px rgba(249,115,22,.07);}
.filter-sep{font-size:11px;color:var(--text-4);font-weight:600;padding-bottom:8px;}
.btn-buscar{
  display:flex;align-items:center;gap:7px;
  padding:8px 20px;background:var(--orange);color:#fff;
  border:none;border-radius:8px;font-size:12.5px;font-weight:700;
  cursor:pointer;transition:.15s;box-shadow:0 2px 8px rgba(249,115,22,.22);
}
.btn-buscar:hover{background:var(--orange-d);transform:translateY(-1px);box-shadow:0 4px 14px rgba(249,115,22,.32);}
.btn-buscar svg{width:13px;height:13px;stroke:#fff;stroke-width:2.2;fill:none;}
.btn-print{
  display:flex;align-items:center;gap:6px;
  padding:8px 16px;background:var(--surface);color:var(--text-2);
  border:1px solid var(--border);border-radius:8px;font-size:12.5px;font-weight:700;
  cursor:pointer;transition:.15s;
}
.btn-print:hover{border-color:var(--text-3);color:var(--text);}
.btn-print svg{width:13px;height:13px;stroke:currentColor;stroke-width:2;fill:none;}

/* ── STAT GRID ── */
.stat-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:14px;}
@media(max-width:700px){.stat-grid{grid-template-columns:repeat(2,1fr);}}
.stat-card{
  background:var(--surface);border:1px solid var(--border);border-radius:var(--r);
  box-shadow:var(--shadow-sm);padding:16px 18px;
  display:flex;flex-direction:column;gap:4px;animation:fadeUp .25s ease;
}
.stat-card.accent-orange{background:linear-gradient(135deg,#ffedd5 0%,#fff7ed 100%);border-color:rgba(249,115,22,.2);}
.stat-card.accent-green{background:linear-gradient(135deg,#d1fae5 0%,#f0fdf4 100%);border-color:rgba(16,185,129,.2);}
.stat-icon{width:30px;height:30px;border-radius:8px;display:flex;align-items:center;justify-content:center;margin-bottom:4px;}
.stat-icon svg{width:15px;height:15px;stroke-width:2;fill:none;}
.stat-icon.orange{background:var(--orange-lt);} .stat-icon.orange svg{stroke:var(--orange);}
.stat-icon.green{background:var(--green-lt);}   .stat-icon.green svg{stroke:var(--green);}
.stat-icon.blue{background:var(--blue-lt);}     .stat-icon.blue svg{stroke:var(--blue);}
.stat-icon.red{background:var(--red-lt);}       .stat-icon.red svg{stroke:var(--red);}
.stat-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);}
.stat-value{font-size:24px;font-weight:800;color:var(--text);letter-spacing:-.5px;line-height:1;}
.stat-value.orange{color:var(--orange);}
.stat-sub{font-size:10.5px;color:var(--text-3);font-weight:500;}

/* ── CARD ── */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);overflow:hidden;margin-bottom:12px;animation:fadeUp .2s ease;}
.card-head{padding:12px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:10px;}
.card-head-left{display:flex;align-items:center;gap:8px;}
.card-head-icon{width:26px;height:26px;border-radius:7px;display:flex;align-items:center;justify-content:center;flex-shrink:0;}
.card-head-icon svg{width:13px;height:13px;stroke-width:2.2;fill:none;}
.card-head-icon.orange{background:var(--orange-lt);}  .card-head-icon.orange svg{stroke:var(--orange);}
.card-head-icon.blue{background:var(--blue-lt);}      .card-head-icon.blue svg{stroke:var(--blue);}
.card-head-icon.gray{background:#f3f4f6;}              .card-head-icon.gray svg{stroke:var(--text-3);}
.card-title{font-size:12px;font-weight:800;color:var(--text);letter-spacing:-.1px;}
.card-count{font-size:10px;font-weight:700;padding:3px 9px;border-radius:20px;background:#f3f4f6;color:var(--text-3);}
.card-body{padding:0;}

.two-cols{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;}
@media(max-width:700px){.two-cols{grid-template-columns:1fr;}}

/* ── TABLES ── */
.data-table{width:100%;border-collapse:collapse;}
.data-table thead tr{border-bottom:1px solid var(--border);}
.data-table th{padding:9px 14px;text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);white-space:nowrap;background:var(--bg);}
.data-table th.right,.data-table td.right{text-align:right;}
.data-table th.center,.data-table td.center{text-align:center;}
.data-table tbody tr{border-bottom:1px solid var(--border);}
.data-table tbody tr:last-child{border-bottom:none;}
.data-table tbody tr:hover{background:var(--bg);}
.data-table td{padding:9px 14px;font-size:12px;font-weight:500;color:var(--text-2);vertical-align:middle;}
.data-table td strong{color:var(--text);font-weight:700;}

.mini-table{width:100%;border-collapse:collapse;}
.mini-table th{padding:8px 14px;text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);background:var(--bg);border-bottom:1px solid var(--border);}
.mini-table th.right,.mini-table td.right{text-align:right;}
.mini-table tbody tr{border-bottom:1px solid var(--border);}
.mini-table tbody tr:last-child{border-bottom:none;}
.mini-table tbody tr:hover{background:var(--bg);}
.mini-table td{padding:9px 14px;font-size:12px;font-weight:500;color:var(--text-2);}

/* ── BADGES ── */
.badge{display:inline-flex;align-items:center;padding:3px 8px;border-radius:6px;font-size:10.5px;font-weight:700;}
.badge-orange{background:var(--orange-lt);color:var(--orange);border:1px solid rgba(249,115,22,.15);}
.badge-blue{background:var(--blue-lt);color:var(--blue);border:1px solid rgba(37,99,235,.15);}
.badge-gray{background:#f3f4f6;color:var(--text-2);border:1px solid var(--border);}
.badge-green{background:var(--green-lt);color:var(--green);border:1px solid rgba(16,185,129,.15);}

/* ── BARRA ── */
.bar-wrap{display:flex;align-items:center;gap:8px;}
.bar-track{flex:1;background:var(--border);height:5px;border-radius:4px;overflow:hidden;min-width:50px;}
.bar-fill{height:100%;border-radius:4px;transition:width .5s ease;}
.bar-fill.orange{background:var(--orange);}
.bar-fill.blue{background:var(--blue);}

/* ── FOLIO ── */
.folio{font-size:11.5px;font-weight:800;color:var(--text);background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:3px 8px;letter-spacing:.02em;}
.importe-ret{color:var(--orange);font-weight:700;}

/* ── PROPINA BADGE ── */
.propina-chip{display:inline-flex;align-items:center;gap:4px;padding:2px 7px;border-radius:5px;background:var(--green-lt);color:var(--green);border:1px solid rgba(16,185,129,.2);font-size:10px;font-weight:700;}

/* ── EN VIVO TABLE HIGHLIGHT ── */
.new-row{animation:fadeUp .4s ease;}

/* ── PAGINACION ── */
.pag-bar{display:flex;justify-content:space-between;align-items:center;padding:10px 18px;border-top:1px solid var(--border);font-size:11px;color:var(--text-3);font-weight:600;}
.pag-btns{display:flex;gap:4px;}
.pag-btn{padding:5px 10px;border:1px solid var(--border);background:var(--surface);font-size:11.5px;font-weight:700;cursor:pointer;border-radius:7px;color:var(--text-2);transition:.15s;font-family:'Plus Jakarta Sans',sans-serif;}
.pag-btn:hover{border-color:var(--orange);color:var(--orange);}
.pag-btn.active{background:var(--orange);color:#fff;border-color:var(--orange);}
.pag-btn:disabled{opacity:.35;cursor:default;}

/* ── ESTADOS ── */
.empty-state{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:52px 24px;gap:10px;}
.empty-icon{width:48px;height:48px;border-radius:14px;background:var(--orange-lt);display:flex;align-items:center;justify-content:center;margin-bottom:4px;}
.empty-icon svg{width:22px;height:22px;stroke:var(--orange);stroke-width:2;fill:none;}
.empty-title{font-size:14px;font-weight:800;color:var(--text);}
.empty-sub{font-size:12px;color:var(--text-3);font-weight:500;}
.loading-state{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:52px 24px;gap:12px;}
.loader{width:28px;height:28px;border:3px solid var(--border);border-top-color:var(--orange);border-radius:50%;animation:spin .8s linear infinite;}
.loading-txt{font-size:12px;color:var(--text-3);font-weight:600;}

/* ── HEADER INFO ── */
.report-header{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);padding:16px 20px;margin-bottom:14px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;}
.report-header-left{display:flex;flex-direction:column;gap:3px;}
.report-empresa{font-size:16px;font-weight:800;color:var(--text);letter-spacing:-.3px;}
.report-sub{font-size:11.5px;color:var(--text-3);font-weight:500;}
.report-header-right{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
.periodo-tag{font-size:11px;font-weight:700;padding:4px 10px;border-radius:20px;background:var(--orange-lt);color:var(--orange);border:1px solid rgba(249,115,22,.15);}
.gen-time{font-size:11px;color:var(--text-3);font-weight:500;}

/* ── EN VIVO PANEL ── */
.envivo-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;}
.envivo-title{font-size:15px;font-weight:800;color:var(--text);letter-spacing:-.3px;}
.envivo-count{font-size:11px;font-weight:700;padding:4px 12px;border-radius:20px;background:var(--orange-lt);color:var(--orange);border:1px solid rgba(249,115,22,.15);}
.envivo-total{font-size:13px;font-weight:700;color:var(--text);}

@media print {
  * { margin: 0; padding: 0; }
  html, body { height: auto; min-height: auto; background: #fff; margin: 0; padding: 0; }
  .topbar, .back, .filtros-card, .no-print { display: none !important; }
  .container { max-width: 100%; margin: 0; padding: 20px; }
  .card { page-break-inside: avoid; margin-bottom: 20px; }
  table { width: 100%; border-collapse: collapse; }
  tr { page-break-inside: avoid; }
  h1, h2, h3 { page-break-after: avoid; }
}
</style>
<link rel="stylesheet" href="/css/responsive.css?v=406r"/>
</head>
<body>

<header class="topbar">
  <div class="topbar-icon">
    <svg viewBox="0 0 24 24"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>
  </div>
  <h1>Gastos</h1>
  <div class="topbar-right">
    <div class="rt-badge" id="rtBadge">
      <div class="rt-dot"></div>
      <span id="rtLabel">En vivo</span>
    </div>
    <button class="back" onclick="window.history.back()">
      <svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"/></svg>
      Volver
    </button>
  </div>
</header>

<div class="container">

  
  <div class="mode-tabs">
    <button class="mode-tab active" id="tabVivo"   onclick="setModo('vivo')">En vivo (hoy)</button>
    <button class="mode-tab"        id="tabBuscar" onclick="setModo('buscar')">Buscar por período</button>
  </div>

  
  <div class="filters-card" id="filtrosCard" style="display:none">
    <div class="filter-group">
      <span class="filter-label">Fecha inicio</span>
      <input type="date" class="filter-input" id="f-inicio"/>
    </div>
    <div class="filter-sep">—</div>
    <div class="filter-group">
      <span class="filter-label">Fecha fin</span>
      <input type="date" class="filter-input" id="f-fin"/>
    </div>
    <div class="filter-group">
      <span class="filter-label">ID Turno</span>
      <input type="text" class="filter-input" id="f-turno" placeholder="Ej: 76" style="min-width:90px"/>
    </div>
    <button class="btn-buscar" onclick="buscar()">
      <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>
      Buscar
    </button>
    <button class="btn-print" onclick="window.print()">
      <svg viewBox="0 0 24 24"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
      Imprimir
    </button>
  </div>

  
  <div class="report-header" id="reportHeader" style="display:none">
    <div class="report-header-left">
      <div class="report-empresa" id="hEmpresa"></div>
      <div class="report-sub">Movimientos de Caja — Gastos</div>
    </div>
    <div class="report-header-right">
      <span class="periodo-tag" id="hPeriodo">—</span>
      <span class="gen-time"    id="hGenerado">—</span>
    </div>
  </div>

  <div id="mainArea"></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 EMPRESA       = (window._EMPRESA || 'MI EMPRESA');

let modo          = 'vivo';
let estadoActual  = { inicio: null, fin: null, idturno: null, page: 1 };
let autoTimer     = null;
const VIVO_INTERVAL   = 10000; 
const BUSCAR_INTERVAL = 60000; 

const $   = id => document.getElementById(id);

function fmtFecha(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('es-MX',{ day:'2-digit', month:'2-digit', year:'numeric' })
       + ' ' + d.toLocaleTimeString('es-MX',{ hour:'2-digit', minute:'2-digit' });
}

function setModo(m) {
  modo = m;
  stopAuto();
  $('tabVivo').classList.toggle('active',   m === 'vivo');
  $('tabBuscar').classList.toggle('active', m === 'buscar');
  $('filtrosCard').style.display   = m === 'buscar' ? 'flex' : 'none';
  $('reportHeader').style.display  = 'none';
  $('mainArea').innerHTML = '';
  if (m === 'vivo') cargarVivo();
}

async function cargarVivo(silent = false) {
  if (!silent) setRtLoading(true);
  try {
    const data = await api('/gastos/en-vivo');
    setRtLoading(false);
    renderVivo(data);
  } catch (e) {
    setRtLoading(false);
    renderError(e.message);
  }
  startAuto();
}

function renderVivo(d) {
  const { movimientos, resumen_hoy, generadoEn } = d;
  const total = movimientos.length;

  let statsHtml = `
    <div class="stat-grid">
      <div class="stat-card accent-orange">
        <div class="stat-icon orange"><svg viewBox="0 0 24 24"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg></div>
        <div class="stat-label">Total Retirado Hoy</div>
        <div class="stat-value orange" style="font-size:18px">${fmt(resumen_hoy.total_importe_hoy)}</div>
        <div class="stat-sub">del día</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon blue"><svg viewBox="0 0 24 24"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/></svg></div>
        <div class="stat-label">Movimientos Hoy</div>
        <div class="stat-value">${resumen_hoy.total_hoy}</div>
        <div class="stat-sub">gastos registrados</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon green"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg></div>
        <div class="stat-label">Último Actualizado</div>
        <div class="stat-value" style="font-size:14px;padding-top:4px">${new Date(generadoEn).toLocaleTimeString('es-MX',{hour:'2-digit',minute:'2-digit',second:'2-digit'})}</div>
        <div class="stat-sub">actualización automática 10s</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon orange"><svg viewBox="0 0 24 24"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg></div>
        <div class="stat-label">Promedio por Gasto</div>
        <div class="stat-value" style="font-size:16px">${resumen_hoy.total_hoy > 0 ? fmt(resumen_hoy.total_importe_hoy / resumen_hoy.total_hoy) : fmt(0)}</div>
        <div class="stat-sub">por movimiento</div>
      </div>
    </div>`;

  let tablaHtml;
  if (total === 0) {
    tablaHtml = `
      <div class="card">
        <div class="empty-state">
          <div class="empty-icon"><svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg></div>
          <div class="empty-title">Sin gastos hoy</div>
          <div class="empty-sub">No se han registrado gastos de caja en el día.</div>
        </div>
      </div>`;
  } else {
    const filas = movimientos.map(m => `
      <tr class="new-row">
        <td class="center"><span class="folio">${String(m.folio).padStart(9,'0')}</span></td>
        <td>${fmtFecha(m.fecha)}</td>
        <td><strong style="color:var(--text)">${m.concepto}</strong>${m.referencia ? `<br><span style="font-size:10.5px;color:var(--text-3)">${m.referencia}</span>` : ''}</td>
        <td class="right"><span class="importe-ret">${fmt(m.importe)}</span></td>
        <td class="center">${m.idturno || '—'}</td>
        <td class="center">${m.es_propina ? '<span class="propina-chip"><svg viewBox="0 0 24 24" style="width:10px;height:10px;stroke:currentColor;fill:none;stroke-width:2"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>Propina</span>' : '<span class="badge badge-orange">Gasto</span>'}</td>
        <td class="center"><span class="badge badge-blue">${m.usuario}</span></td>
      </tr>`).join('');

    tablaHtml = `
      <div class="card">
        <div class="card-head">
          <div class="card-head-left">
            <div class="card-head-icon orange"><svg viewBox="0 0 24 24"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg></div>
            <span class="card-title">Gastos del día — en tiempo real</span>
          </div>
          <span class="card-count">${total} movimiento(s)</span>
        </div>
        <div class="card-body" style="overflow-x:auto">
          <table class="data-table">
            <thead><tr>
              <th class="center">Folio</th>
              <th>Fecha y Hora</th>
              <th>Concepto</th>
              <th class="right">Importe</th>
              <th class="center">Turno</th>
              <th class="center">Tipo</th>
              <th class="center">Autorizó</th>
            </tr></thead>
            <tbody>${filas}</tbody>
          </table>
        </div>
      </div>`;
  }

  $('mainArea').innerHTML = statsHtml + tablaHtml;
}

function buscar(page = 1, silent = false) {
  const idturno = $('f-turno').value.trim();
  const inicio  = $('f-inicio').value;
  const fin     = $('f-fin').value;
  estadoActual  = { inicio, fin, idturno: idturno || null, page };

  let url;
  if (idturno) {
    url = `/api/gastos?idturno=${idturno}&page=${page}&pageSize=50`;
  } else {
    if (!inicio || !fin) { alert('Ingresa un rango de fechas o un ID de turno.'); return; }
    url = `/api/gastos?inicio=${inicio}&fin=${fin}&page=${page}&pageSize=50`;
  }

  if (!silent) {
    setRtLoading(true);
    $('mainArea').innerHTML = `<div class="card"><div class="loading-state"><div class="loader"></div><span class="loading-txt">Cargando gastos…</span></div></div>`;
    $('reportHeader').style.display = 'none';
  }

  // url already starts with /api/gastos - strip /api prefix for api() helper
  const ep = url.replace(/^\/api/, '');
  api(ep)
    .then(data => {
      setRtLoading(false);
      renderBuscar(data);
      startAuto();
    })
    .catch(e => {
      setRtLoading(false);
      renderError(e.message);
    });
}

function renderBuscar(d) {
  const { resumen, porConcepto, porUsuario, movimientos, paginacion, periodo, generadoEn } = d;

  $('hEmpresa').textContent  = EMPRESA;
  $('hGenerado').textContent = 'Actualizado: ' + fmtFecha(generadoEn);
  $('hPeriodo').textContent  = periodo.tipo === 'turno'
    ? `Turno #${periodo.idturno}`
    : `${periodo.inicio} al ${periodo.fin}`;
  $('reportHeader').style.display = 'flex';

  if (resumen.total_movimientos === 0) {
    $('mainArea').innerHTML = `
      <div class="card">
        <div class="empty-state">
          <div class="empty-icon"><svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg></div>
          <div class="empty-title">Sin gastos</div>
          <div class="empty-sub">No se encontraron gastos en el período indicado.</div>
        </div>
      </div>`;
    return;
  }

  
  const statsHtml = `
    <div class="stat-grid">
      <div class="stat-card accent-orange">
        <div class="stat-icon orange"><svg viewBox="0 0 24 24"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg></div>
        <div class="stat-label">Total Gastos</div>
        <div class="stat-value orange" style="font-size:18px">${fmt(resumen.total_gastos)}</div>
        <div class="stat-sub">${resumen.total_movimientos} movimiento(s)</div>
      </div>
      <div class="stat-card accent-green">
        <div class="stat-icon green"><svg viewBox="0 0 24 24"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg></div>
        <div class="stat-label">Total Propinas</div>
        <div class="stat-value" style="font-size:18px">${fmt(resumen.total_propinas)}</div>
        <div class="stat-sub">pagadas a meseros</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon blue"><svg viewBox="0 0 24 24"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v16"/></svg></div>
        <div class="stat-label">Turnos</div>
        <div class="stat-value">${resumen.turnos_involucrados}</div>
        <div class="stat-sub">${resumen.dias} día(s) en período</div>
      </div>
      <div class="stat-card">
        <div class="stat-icon orange"><svg viewBox="0 0 24 24"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg></div>
        <div class="stat-label">Promedio</div>
        <div class="stat-value" style="font-size:16px">${resumen.total_movimientos > 0 ? fmt(resumen.total_gastos / resumen.total_movimientos) : fmt(0)}</div>
        <div class="stat-sub">por gasto</div>
      </div>
    </div>`;

  
  const maxConc = Math.max(...porConcepto.map(c => c.importe_total), 1);
  const maxUsr  = Math.max(...porUsuario.map(u => u.importe_total), 1);

  const concHtml = porConcepto.length === 0
    ? '<div style="padding:20px 18px;color:var(--text-3);font-size:12px;font-weight:600">Sin datos</div>'
    : `<table class="mini-table">
        <thead><tr><th>Concepto</th><th class="right">Cant.</th><th class="right">Importe</th><th></th></tr></thead>
        <tbody>${porConcepto.map(c => `
          <tr>
            <td style="color:var(--text);font-weight:600">${c.concepto}</td>
            <td class="right"><strong>${c.cantidad}</strong></td>
            <td class="right">${fmt(c.importe_total)}</td>
            <td style="width:90px">
              <div class="bar-wrap"><div class="bar-track"><div class="bar-fill orange" style="width:${(c.importe_total/maxConc*100).toFixed(0)}%"></div></div></div>
            </td>
          </tr>`).join('')}
        </tbody></table>`;

  const usrHtml = porUsuario.length === 0
    ? '<div style="padding:20px 18px;color:var(--text-3);font-size:12px;font-weight:600">Sin datos</div>'
    : `<table class="mini-table">
        <thead><tr><th>Autorizó</th><th class="right">Cant.</th><th class="right">Importe</th><th></th></tr></thead>
        <tbody>${porUsuario.map(u => `
          <tr>
            <td><span class="badge badge-blue">${u.usuario}</span></td>
            <td class="right"><strong>${u.cantidad}</strong></td>
            <td class="right">${fmt(u.importe_total)}</td>
            <td style="width:90px">
              <div class="bar-wrap"><div class="bar-track"><div class="bar-fill blue" style="width:${(u.importe_total/maxUsr*100).toFixed(0)}%"></div></div></div>
            </td>
          </tr>`).join('')}
        </tbody></table>`;

  const colsHtml = `
    <div class="two-cols">
      <div class="card">
        <div class="card-head">
          <div class="card-head-left">
            <div class="card-head-icon orange"><svg viewBox="0 0 24 24"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg></div>
            <span class="card-title">Top conceptos</span>
          </div>
          <span class="card-count">${porConcepto.length}</span>
        </div>
        <div class="card-body">${concHtml}</div>
      </div>
      <div class="card">
        <div class="card-head">
          <div class="card-head-left">
            <div class="card-head-icon blue"><svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg></div>
            <span class="card-title">Por usuario que autorizó</span>
          </div>
          <span class="card-count">${porUsuario.length}</span>
        </div>
        <div class="card-body">${usrHtml}</div>
      </div>
    </div>`;

  
  const { page, pageSize, total, paginas } = paginacion;
  const desde = (page - 1) * pageSize + 1;
  const hasta = Math.min(page * pageSize, total);

  function pagHtml() {
    if (paginas <= 1) return `<div class="pag-bar"><span><strong style="color:var(--text)">${total}</strong> gasto(s)</span><div></div></div>`;
    let btns = '';
    for (let i = 1; i <= paginas; i++) {
      if (i === 1 || i === paginas || (i >= page-2 && i <= page+2))
        btns += `<button class="pag-btn ${i===page?'active':''}" onclick="buscar(${i})">${i}</button>`;
      else if (i === page-3 || i === page+3)
        btns += `<span style="padding:5px 4px;color:var(--text-4);font-size:11px">…</span>`;
    }
    return `<div class="pag-bar">
      <span>Mostrando <strong style="color:var(--text)">${desde}–${hasta}</strong> de <strong style="color:var(--text)">${total}</strong></span>
      <div class="pag-btns">
        <button class="pag-btn" onclick="buscar(${page-1})" ${page<=1?'disabled':''}>← Ant</button>
        ${btns}
        <button class="pag-btn" onclick="buscar(${page+1})" ${page>=paginas?'disabled':''}>Sig →</button>
      </div>
    </div>`;
  }

  const filas = movimientos.map(m => `
    <tr>
      <td class="center"><span class="folio">${String(m.folio).padStart(9,'0')}</span></td>
      <td>${fmtFecha(m.fecha)}</td>
      <td><strong style="color:var(--text)">${m.concepto}</strong>${m.referencia ? `<br><span style="font-size:10.5px;color:var(--text-3)">${m.referencia}</span>` : ''}</td>
      <td class="right"><span class="importe-ret">${fmt(m.importe)}</span></td>
      <td class="center">${m.idturno || '—'}</td>
      <td class="center">${m.es_propina ? '<span class="propina-chip">Propina</span>' : '<span class="badge badge-orange">Gasto</span>'}</td>
      <td class="center"><span class="badge badge-blue">${m.usuario}</span></td>
    </tr>`).join('');

  const tablaHtml = `
    <div class="card">
      <div class="card-head">
        <div class="card-head-left">
          <div class="card-head-icon orange"><svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg></div>
          <span class="card-title">Detalle de gastos</span>
        </div>
        <span class="card-count">${total} total</span>
      </div>
      ${pagHtml()}
      <div class="card-body" style="overflow-x:auto">
        <table class="data-table">
          <thead><tr>
            <th class="center">Folio</th>
            <th>Fecha y Hora</th>
            <th>Concepto / Referencia</th>
            <th class="right">Importe</th>
            <th class="center">Turno</th>
            <th class="center">Tipo</th>
            <th class="center">Autorizó</th>
          </tr></thead>
          <tbody>${filas}</tbody>
        </table>
      </div>
      ${pagHtml()}
    </div>`;

  $('mainArea').innerHTML = statsHtml + colsHtml + tablaHtml;
}

function renderError(msg) {
  $('mainArea').innerHTML = `
    <div class="card"><div class="empty-state">
      <span style="font-size:24px">!️</span>
      <div class="empty-title">Error al cargar datos</div>
      <div class="empty-sub">${msg || 'Sin detalles'}</div>
    </div></div>`;
}

function setRtLoading(v) {
  const badge = $('rtBadge'), label = $('rtLabel');
  if (v) { badge.className='rt-badge loading'; label.textContent='Actualizando…'; }
  else   { badge.className='rt-badge';         label.textContent='En vivo'; }
}

function startAuto() {
  stopAuto();
  const interval = modo === 'vivo' ? VIVO_INTERVAL : BUSCAR_INTERVAL;
  autoTimer = setInterval(() => {
    if (modo === 'vivo') cargarVivo(true);
    else                 buscar(estadoActual.page, true);
  }, interval);
}
function stopAuto() {
  if (autoTimer) { clearInterval(autoTimer); autoTimer = null; }
}

(function initWS() {
  const s = document.createElement('script');
  s.src = '/socket.io/socket.io.js';
  s.onload = () => {
    const socket = io(window.location.origin);
    socket.on('actualizacion', () => {
      if (modo === 'vivo') cargarVivo(true);
    });
  };
  document.head.appendChild(s);
})();

function initFiltros() {
  $('f-inicio').value = hoy();
  $('f-fin').value    = hoy();
}

initFiltros();
(async()=>{ try { await _initAuth(); cargarVivo(); } catch(e) { console.error('Init error:', e.message); } })();
</script>
</body>
</html>
