<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Almacén — 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;
  --text:#111827;--text-2:#4b5563;--text-3:#9ca3af;
  --orange:#f97316;--orange-lt:rgba(249,115,22,.10);
  --red:#ef4444;--red-lt:rgba(239,68,68,.10);
  --green:#10b981;--green-lt:rgba(16,185,129,.10);
  --blue:#2563eb;--blue-lt:rgba(37,99,235,.10);
  --yellow:#f59e0b;--yellow-lt:rgba(245,158,11,.10);
  
  --shadow-sm:0 1px 3px rgba(17,24,39,.06);--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,textarea{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(6px);}to{opacity:1;transform:translateY(0);}}
@keyframes pulse{0%,100%{opacity:1;}50%{opacity:.4;}}

/* TOPBAR */
.topbar{background:var(--surface);border-bottom:1px solid var(--border);height:52px;padding:0 18px;display:flex;align-items:center;gap:10px;position:sticky;top:0;z-index:20;box-shadow:var(--shadow-sm);}
.topbar-icon{width:32px;height:32px;border-radius:9px;background:var(--orange);display:flex;align-items:center;justify-content:center;}
.topbar-icon svg{width:15px;height:15px;stroke:#fff;stroke-width:2.2;fill:none;}
.topbar h1{font-size:14px;font-weight:800;letter-spacing:-.3px;flex:1;}
.live-pill{display:flex;align-items:center;gap:5px;padding:4px 10px;background:var(--green-lt);border-radius:20px;}
.live-dot{width:7px;height:7px;border-radius:50%;background:var(--green);animation:pulse 2s infinite;}
.live-pill span{font-size:10px;font-weight:700;color:var(--green);}
.topbar-btn{display:flex;align-items:center;gap:5px;padding:6px 12px;border:1px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text-2);font-size:11px;font-weight:700;cursor:pointer;transition:.15s;}
.topbar-btn:hover{background:var(--bg);border-color:#d1d5db;}
.topbar-btn svg{width:12px;height:12px;stroke:currentColor;stroke-width:2.2;fill:none;}

/* TABS */
.tabs-bar{background:var(--surface);border-bottom:1px solid var(--border);padding:0 18px;display:flex;gap:0;}
.tab-btn{padding:10px 16px;border:none;border-bottom:2px solid transparent;background:transparent;font-size:12px;font-weight:700;color:var(--text-3);cursor:pointer;transition:.15s;display:flex;align-items:center;gap:6px;white-space:nowrap;}
.tab-btn.active{color:var(--orange);border-bottom-color:var(--orange);}
.tab-btn:hover:not(.active){color:var(--text);}
.tab-btn svg{width:13px;height:13px;stroke:currentColor;stroke-width:2.2;fill:none;}
.tab-badge{background:var(--red-lt);color:var(--red);font-size:9px;font-weight:800;padding:1px 5px;border-radius:8px;}

/* LAYOUT */
.container{max-width:1300px;margin:0 auto;padding:16px 18px 40px;}
.section{display:none;animation:fadeUp .2s ease;}
.section.active{display:block;}

/* KPI ROW */
.kpi-row{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:14px;}
@media(min-width:600px){.kpi-row{grid-template-columns:repeat(4,1fr);}}
.kpi{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:14px 16px;box-shadow:var(--shadow-sm);animation:fadeUp .2s ease;}
.kpi-label{font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin-bottom:4px;}
.kpi-val{font-size:22px;font-weight:800;letter-spacing:-.5px;}
.kpi-sub{font-size:10px;color:var(--text-3);font-weight:600;margin-top:2px;}
.kpi-val.green{color:var(--green);}
.kpi-val.red{color:var(--red);}
.kpi-val.yellow{color:var(--yellow);}
.kpi-val.blue{color:var(--blue);}
.kpi-val.orange{color:var(--orange);}

/* FOOD COST HERO */
.fc-hero{background:linear-gradient(135deg,#f97316,#0e7490);border-radius:var(--r);padding:20px 24px;color:#fff;display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;box-shadow:0 4px 18px rgba(249,115,22,.3);}
.fc-hero-left h2{font-size:13px;font-weight:700;opacity:.8;margin-bottom:4px;}
.fc-hero-left .fc-pct{font-size:52px;font-weight:800;letter-spacing:-2px;line-height:1;}
.fc-hero-left small{font-size:10px;opacity:.7;}
.fc-hero-right{text-align:right;}
.fc-stat{margin-bottom:6px;}
.fc-stat-label{font-size:9px;font-weight:700;opacity:.7;text-transform:uppercase;letter-spacing:.06em;}
.fc-stat-val{font-size:16px;font-weight:800;}
.fc-gauge{width:100%;height:8px;background:rgba(255,255,255,.2);border-radius:4px;margin-top:12px;overflow:hidden;}
.fc-gauge-fill{height:100%;border-radius:4px;transition:width .6s ease;background:#fff;}

/* ALERTAS */
.alertas-wrap{margin-bottom:14px;}
.alerta-row{display:flex;align-items:center;gap:10px;padding:10px 14px;border-radius:9px;margin-bottom:6px;animation:fadeUp .15s ease;}
.alerta-row.critico{background:var(--red-lt);border-left:3px solid var(--red);}
.alerta-row.bajo{background:var(--yellow-lt);border-left:3px solid var(--yellow);}
.alerta-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0;}
.alerta-dot.critico{background:var(--red);}
.alerta-dot.bajo{background:var(--yellow);}
.alerta-name{font-weight:700;font-size:12px;flex:1;}
.alerta-vals{font-size:11px;color:var(--text-3);}

/* TABLE GENÉRICA */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow-sm);overflow:hidden;margin-bottom:12px;}
.card-head{padding:12px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px;}
.card-title{font-size:13px;font-weight:800;flex:1;}
.tbl-wrap{overflow-x:auto;}
table.data-tbl{width:100%;border-collapse:collapse;}
table.data-tbl thead th{padding:9px 12px;text-align:left;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);background:var(--bg);border-bottom:1px solid var(--border);}
table.data-tbl thead th.r{text-align:right;}
table.data-tbl tbody tr{border-bottom:1px solid var(--border);transition:.1s;}
table.data-tbl tbody tr:last-child{border-bottom:none;}
table.data-tbl tbody tr:hover{background:var(--bg);}
table.data-tbl tbody td{padding:9px 12px;font-size:12px;color:var(--text-2);}
table.data-tbl tbody td.r{text-align:right;font-weight:700;color:var(--text);}
table.data-tbl tbody td.bold{font-weight:700;color:var(--text);}
.badge{display:inline-flex;align-items:center;padding:2px 8px;border-radius:20px;font-size:9.5px;font-weight:700;}
.badge.ok{background:var(--green-lt);color:var(--green);}
.badge.bajo{background:var(--yellow-lt);color:var(--yellow);}
.badge.critico{background:var(--red-lt);color:var(--red);}

/* FILTROS */
.filters{display:flex;gap:8px;flex-wrap:wrap;align-items:flex-end;margin-bottom:12px;}
.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=text],input[type=number],input[type=date],select{padding:7px 10px;border:1px solid var(--border);border-radius:8px;font-size:12px;font-weight:600;color:var(--text);outline:none;background:var(--surface);}
input:focus,select:focus{border-color:var(--orange);}
.btn{display:inline-flex;align-items:center;gap:5px;padding:7px 14px;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;transition:.15s;}
.btn svg{width:12px;height:12px;stroke:currentColor;stroke-width:2.2;fill:none;}
.btn-orange{background:var(--orange);color:#fff;box-shadow:0 2px 8px rgba(249,115,22,.28);}
.btn-orange:hover{transform:translateY(-1px);}
.btn-green{background:var(--green);color:#fff;box-shadow:0 2px 8px rgba(16,185,129,.28);}
.btn-green:hover{transform:translateY(-1px);}
.btn-ghost{background:transparent;color:var(--text-2);border:1px solid var(--border);}
.btn-ghost:hover{background:var(--bg);}
.btn-red{background:var(--red);color:#fff;}

/* SPIN */
.spin{display:inline-block;width:16px;height:16px;border:2px solid var(--border);border-top-color:var(--orange);border-radius:50%;animation:spin .7s linear infinite;}
.empty{padding:28px;text-align:center;color:var(--text-3);font-size:12px;font-weight:600;}

/* RECETAS LAYOUT */
.recetas-layout{display:grid;grid-template-columns:280px 1fr;gap:12px;}
@media(max-width:700px){.recetas-layout{grid-template-columns:1fr;}}
.prod-list{max-height:calc(100vh - 200px);overflow-y:auto;}
.prod-item{padding:10px 14px;cursor:pointer;border-bottom:1px solid var(--border);transition:.1s;display:flex;align-items:center;justify-content:space-between;}
.prod-item:hover{background:var(--bg);}
.prod-item.active{background:var(--orange-lt);border-left:3px solid var(--orange);}
.prod-item-name{font-size:12px;font-weight:700;color:var(--text);}
.prod-item-grupo{font-size:10px;color:var(--text-3);}
.prod-item-badge{width:7px;height:7px;border-radius:50%;flex-shrink:0;}
.prod-item-badge.has{background:var(--green);}
.prod-item-badge.no{background:var(--border);}
.receta-editor{}
.receta-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;}
.receta-line{display:grid;grid-template-columns:1fr 100px 90px 80px 28px;gap:6px;align-items:center;padding:8px 0;border-bottom:1px solid var(--border);}
.receta-line:last-child{border-bottom:none;}
.receta-costo-total{font-size:14px;font-weight:800;color:var(--orange);margin-top:12px;text-align:right;}

/* PDF IMPORT */
.pdf-steps{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;}
.pdf-step{display:flex;align-items:center;gap:6px;padding:6px 12px;background:var(--surface);border:1px solid var(--border);border-radius:20px;font-size:11px;font-weight:700;color:var(--text-3);}
.pdf-step.active{background:var(--orange-lt);border-color:var(--orange);color:var(--orange);}
.pdf-step.done{background:var(--green-lt);border-color:var(--green);color:var(--green);}
.pdf-step-num{width:18px;height:18px;border-radius:50%;background:currentColor;color:#fff;display:flex;align-items:center;justify-content:center;font-size:9px;font-weight:800;}
.drop-zone{border:2px dashed var(--border);border-radius:var(--r);padding:40px;text-align:center;cursor:pointer;transition:.2s;background:var(--surface);}
.drop-zone:hover,.drop-zone.drag-over{border-color:var(--orange);background:var(--orange-lt);}
.drop-zone svg{width:36px;height:36px;stroke:var(--text-3);stroke-width:1.5;fill:none;margin-bottom:10px;}
.drop-zone p{font-size:13px;font-weight:700;color:var(--text-2);margin-bottom:4px;}
.drop-zone small{font-size:11px;color:var(--text-3);}
.preview-row{display:grid;grid-template-columns:100px 1fr 80px 80px 90px 28px;gap:6px;align-items:center;padding:8px 0;border-bottom:1px solid var(--border);}
.preview-row:last-child{border-bottom:none;}
.estado-badge{font-size:9px;font-weight:700;padding:2px 7px;border-radius:8px;}
.estado-badge.ok{background:var(--green-lt);color:var(--green);}
.estado-badge.revisar{background:var(--yellow-lt);color:var(--yellow);}
.estado-badge.incompleto{background:var(--red-lt);color:var(--red);}

/* MODAL */
.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.4);display:none;align-items:center;justify-content:center;z-index:100;}
.modal-overlay.open{display:flex;}
.modal-box{background:var(--surface);border-radius:14px;padding:22px;width:90%;max-width:480px;box-shadow:0 20px 60px rgba(0,0,0,.2);animation:fadeUp .2s ease;}
.modal-title{font-size:15px;font-weight:800;margin-bottom:14px;color:var(--text);}
.form-row{margin-bottom:10px;}
.form-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);display:block;margin-bottom:4px;}
.form-row input,.form-row select{width:100%;}
.modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:16px;}

/* ═══════════════════════════════════════════════════════
   RESPONSIVE INVENTARIO — móvil primero
═══════════════════════════════════════════════════════ */

/* Topbar en móvil */
@media(max-width:600px){
  .topbar{padding:0 10px;gap:6px;}
  .topbar h1{font-size:12px;}
  .topbar-btn span{display:none;}
  .topbar-btn{padding:6px 9px;min-width:32px;justify-content:center;}
  .live-pill span{display:none;}
  .live-pill{padding:4px 6px;}

  /* Tabs — scroll horizontal sin wrap */
  .tabs-bar{padding:0 10px;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none;flex-wrap:nowrap;}
  .tabs-bar::-webkit-scrollbar{display:none;}
  .tab-btn{padding:8px 12px;font-size:11px;flex-shrink:0;}

  /* Container */
  .container{padding:10px 10px 60px;}

  /* KPIs — 2 columnas */
  .kpi-row{grid-template-columns:repeat(2,1fr);gap:6px;margin-bottom:10px;}
  .kpi{padding:10px 12px;}
  .kpi-val{font-size:18px;}

  /* Cards */
  .card-head{padding:10px 12px;flex-wrap:wrap;gap:6px;}
  .card-head .btn{font-size:11px;padding:6px 10px;}

  /* Filters — columna */
  .filters{flex-direction:column;gap:6px;}
  .filter-input{width:100%;}

  /* Tabla con scroll */
  .tbl-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;}
  .insumos-tbl{min-width:580px;}
  .insumos-tbl th,.insumos-tbl td{padding:6px 8px;font-size:11px;}

  /* Layout recetas — 1 columna */
  .recetas-layout{grid-template-columns:1fr !important;}
  .prod-list{max-height:220px;}

  /* Form rows — 1 columna */
  .form-row[style*="grid-template-columns:1fr 1fr"]{grid-template-columns:1fr !important;}

  /* Modal insumo */
  .modal-box{width:calc(100vw - 20px);max-height:88vh;overflow-y:auto;}

  /* Food cost tabla */
  .fc-tbl{min-width:500px;}
  .fc-wrap{overflow-x:auto;}
}

@media(max-width:380px){
  .tab-btn{padding:7px 9px;font-size:10px;}
  .kpi-val{font-size:16px;}
}
</style>
<link rel="stylesheet" href="/css/responsive.css?v=406r"/>
</head>
<body>

<!-- TOPBAR -->
<div class="topbar">
  <div class="topbar-icon">
    <svg viewBox="0 0 24 24"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8m-4-4v4"/><path d="M6 7h4m-4 4h8"/></svg>
  </div>
  <h1>Almacén e Insumos</h1>
  <div class="live-pill"><div class="live-dot"></div><span id="live-label">En vivo</span></div>
  <button class="topbar-btn" onclick="refrescar()">
    <svg viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>
    Actualizar
  </button>
</div>

<!-- TABS -->
<div class="tabs-bar">
  <button class="tab-btn active" id="tab-btn-monitor"   onclick="showTab('monitor',this)">
    <svg viewBox="0 0 24 24"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>Monitor en vivo
  </button>
  <button class="tab-btn" id="tab-btn-insumos" onclick="showTab('insumos',this)">
    <svg viewBox="0 0 24 24"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/></svg>Catálogo
  </button>
  <button class="tab-btn" id="tab-btn-recetas" onclick="showTab('recetas',this)">
    <svg viewBox="0 0 24 24"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>Recetas
  </button>
</div>

<div class="container">

<!-- ═══════════════════════ TAB: MONITOR ═══════════════════════ -->
<div class="section active" id="sec-monitor">

  <!-- Food cost hero -->
  <div class="fc-hero" id="fc-hero">
    <div class="fc-hero-left">
      <h2>Food Cost — Turno actual</h2>
      <div class="fc-pct" id="fc-pct">—</div>
      <small id="fc-turno-label">Cargando...</small>
      <div class="fc-gauge"><div class="fc-gauge-fill" id="fc-gauge" style="width:0%"></div></div>
    </div>
    <div class="fc-hero-right">
      <div class="fc-stat"><div class="fc-stat-label">Costo estimado</div><div class="fc-stat-val" id="fc-costo">—</div></div>
      <div class="fc-stat"><div class="fc-stat-label">Venta del turno</div><div class="fc-stat-val" id="fc-venta">—</div></div>
    </div>
  </div>

  <!-- KPIs -->
  <div class="kpi-row">
    <div class="kpi"><div class="kpi-label">Insumos activos</div><div class="kpi-val orange" id="k-total">—</div><div class="kpi-sub">en catálogo</div></div>
    <div class="kpi"><div class="kpi-label">Alertas críticas</div><div class="kpi-val red" id="k-critico">—</div><div class="kpi-sub">stock bajo mínimo</div></div>
    <div class="kpi"><div class="kpi-label">Alertas bajas</div><div class="kpi-val yellow" id="k-bajo">—</div><div class="kpi-sub">por debajo del ideal</div></div>
    <div class="kpi"><div class="kpi-label">Valor inventario</div><div class="kpi-val green" id="k-valor">—</div><div class="kpi-sub">costo promedio</div></div>
  </div>

  <!-- Alertas -->
  <div id="alertas-container"></div>

  <!-- Tabla stock -->
  <div class="card">
    <div class="card-head">
      <div class="card-title">Stock actual por insumo</div>
      <div class="filters" style="margin:0">
        <input type="text" id="filter-stock" placeholder="Buscar insumo..." oninput="filtrarStock()" style="width:180px"/>
        <select id="filter-estado" onchange="filtrarStock()">
          <option value="">Todos</option>
          <option value="critico">Solo críticos</option>
          <option value="bajo">Solo bajos</option>
          <option value="ok">Solo ok</option>
        </select>
      </div>
    </div>
    <div class="tbl-wrap">
      <table class="data-tbl">
        <thead><tr>
          <th>Insumo</th><th>Presentación</th><th>Almacén</th>
          <th class="r">Existencia</th><th class="r">Costo prom.</th><th class="r">Valor total</th><th>Estado</th>
        </tr></thead>
        <tbody id="tbl-stock"><tr><td colspan="7" class="empty"><div class="spin"></div></td></tr></tbody>
      </table>
    </div>
  </div>
</div>

<!-- ═══════════════════════ TAB: CATÁLOGO ═══════════════════════ -->
<div class="section" id="sec-insumos">
  <div class="card">
    <div class="card-head">
      <div class="card-title">Catálogo de Insumos</div>
      <div style="display:flex;gap:8px;align-items:center;">
        <input type="text" id="filter-insumos" placeholder="Buscar..." oninput="filtrarInsumos()" style="width:180px"/>
        <button class="btn btn-orange" onclick="abrirModalNuevoInsumo()">
          <svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          Nuevo insumo
        </button>
      </div>
    </div>
    <div class="tbl-wrap">
      <table class="data-tbl">
        <thead><tr>
          <th>Clave</th><th>Descripción</th><th>Unidad</th>
          <th class="r">Último costo</th><th class="r">Costo prom.</th><th class="r">Merma %</th><th></th>
        </tr></thead>
        <tbody id="tbl-insumos"><tr><td colspan="7" class="empty"><div class="spin"></div></td></tr></tbody>
      </table>
    </div>
  </div>
</div>

<!-- ═══════════════════════ TAB: RECETAS ═══════════════════════ -->
<div class="section" id="sec-recetas">
  <div class="recetas-layout">
    <!-- Lista de productos -->
    <div class="card" style="overflow:hidden">
      <div class="card-head">
        <div class="card-title">Productos</div>
      </div>
      <div style="padding:8px 12px;border-bottom:1px solid var(--border);">
        <input type="text" id="filter-productos" placeholder="Buscar producto..." oninput="filtrarProductos()" style="width:100%"/>
      </div>
      <div class="prod-list" id="prod-list">
        <div class="empty"><div class="spin"></div></div>
      </div>
    </div>

    <!-- Editor de receta -->
    <div>
      <div class="card" id="receta-card">
        <div class="card-head">
          <div class="card-title" id="receta-prod-nombre">Selecciona un producto</div>
          <button class="btn btn-green" id="btn-guardar-receta" onclick="guardarReceta()" style="display:none">
            <svg viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
            Guardar receta en SR
          </button>
        </div>
        <div style="padding:16px;" id="receta-content">
          <div class="empty" style="padding:40px">
            <svg viewBox="0 0 24 24" style="width:32px;height:32px;stroke:var(--text-3);stroke-width:1.5;fill:none;margin:0 auto 8px;display:block;"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>
            Selecciona un producto de la lista para ver o editar su receta
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ═══════════════════════ TAB: PDF ═══════════════════════ -->
<div class="section" id="sec-pdf">

  <!-- Pasos -->
  <div class="pdf-steps">
    <div class="pdf-step active" id="pdf-step-1">
      <div class="pdf-step-num" style="background:var(--orange)">1</div>
      Subir PDF
    </div>
    <div class="pdf-step" id="pdf-step-2">
      <div class="pdf-step-num">2</div>
      Revisar
    </div>
    <div class="pdf-step" id="pdf-step-3">
      <div class="pdf-step-num">3</div>
      Confirmar
    </div>
  </div>

  <!-- Paso 1: Drop zone -->
  <div id="pdf-step1-content">
    <div class="drop-zone" id="drop-zone" onclick="$('file-input').click()" ondragover="dragOver(event)" ondragleave="dragLeave(event)" ondrop="dropFile(event)">
      <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"/><line x1="12" y1="18" x2="12" y2="12"/><line x1="9" y1="15" x2="15" y2="15"/></svg>
      <p>Arrastra tu PDF de insumos aquí</p>
      <small>O haz clic para seleccionar · PDF de costos, insumos o análisis (Burger Adict, SR, etc.)</small>
    </div>
    <input type="file" id="file-input" accept=".pdf,.txt,.xlsx,.png,.jpg,.jpeg,.webp" style="display:none" onchange="archivoSeleccionado(this)"/>
    <div style="margin-top:10px;display:flex;gap:8px;align-items:flex-start;">
      <div style="flex:1">
        <div style="display:grid;grid-template-columns:190px 1fr;gap:8px;margin-bottom:8px;">
          <div>
            <div class="fl" style="margin-bottom:4px">Tipo de importacion</div>
            <select id="smart-import-tipo">
              <option value="inventario">Inventario / insumos</option>
              <option value="menu">Menu / productos</option>
            </select>
          </div>
          <div>
            <div class="fl" style="margin-bottom:4px">Prefijo opcional</div>
            <input id="smart-import-prefijo" placeholder="Ej: BAR, COC, MEN" maxlength="6"/>
          </div>
        </div>
        <div class="fl" style="margin-bottom:4px">O pega el texto del PDF directamente:</div>
        <textarea id="texto-manual" placeholder="Pega aquí el contenido del PDF..." rows="6" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:8px;font-size:12px;resize:vertical;"></textarea>
      </div>
    </div>
    <div style="margin-top:10px;">
      <button class="btn btn-orange" onclick="parsearPDF()">
        <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>
        Analizar y previsualizar
      </button>
    </div>
  </div>

  <!-- Paso 2: Preview -->
  <div id="pdf-step2-content" style="display:none">
    <div class="card">
      <div class="card-head">
        <div class="card-title" id="pdf-preview-title">Previsualización</div>
        <div style="display:flex;gap:8px">
          <button class="btn btn-ghost" onclick="resetPDF()">
            <svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"/></svg>
            Volver
          </button>
          <button class="btn btn-green" onclick="confirmarImport()">
            <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
            Importar a SR
          </button>
        </div>
      </div>
      <div style="padding:12px 16px;background:var(--bg);border-bottom:1px solid var(--border);font-size:11px;color:var(--text-2);">
        <b>Revisa y edita</b> cada fila antes de importar. Las de color amarillo requieren revisión de la clave.
      </div>
      <!-- encabezado -->
      <div style="padding:8px 16px;display:grid;grid-template-columns:100px 1fr 80px 80px 90px 28px;gap:6px;border-bottom:1px solid var(--border);">
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Clave</div>
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Descripción</div>
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Unidad</div>
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Costo</div>
        <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Estado</div>
        <div></div>
      </div>
      <div id="pdf-preview-rows" style="padding:0 16px;max-height:500px;overflow-y:auto;"></div>
    </div>
  </div>

  <!-- Paso 3: Resultado -->
  <div id="pdf-step3-content" style="display:none">
    <div class="card">
      <div class="card-head"><div class="card-title">Resultado de importación</div></div>
      <div id="pdf-resultado" style="padding:20px;"></div>
      <div style="padding:0 20px 20px;display:flex;gap:8px;">
        <button class="btn btn-orange" onclick="resetPDF()">Nueva importación</button>
        <button class="btn btn-ghost" onclick="showTab('insumos', document.getElementById('tab-btn-insumos'))">Ver catálogo</button>
      </div>
    </div>
  </div>
</div>

</div><!-- /container -->

<!-- MODAL: Nuevo / Editar insumo -->
<div class="modal-overlay" id="modal-insumo">
  <div class="modal-box">
    <div class="modal-title" id="modal-insumo-title">Nuevo Insumo</div>
    <input type="hidden" id="mi-modo"/>
    <div class="form-row">
      <label class="form-label">Clave (máx. 10 chars)</label>
      <input type="text" id="mi-clave" placeholder="Ej: 001003" maxlength="10"/>
    </div>
    <div class="form-row">
      <label class="form-label">Descripción</label>
      <input type="text" id="mi-desc" placeholder="Ej: ACEITE DE OLIVA" maxlength="60"/>
    </div>
    <div class="form-row" style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
      <div>
        <label class="form-label">Unidad</label>
        <select id="mi-unidad">
          <option>KGS</option><option>PZA</option><option>LT</option><option>ML</option>
          <option>GALON</option><option>CAJA</option><option>OZ</option><option>GR</option>
          <option>TON</option><option>BOLSA</option><option>PAQ</option><option>BOT</option><option>LATA</option>
        </select>
      </div>
      <div>
        <label class="form-label">Costo unitario</label>
        <input type="number" id="mi-costo" min="0" step="0.01" value="0"/>
      </div>
    </div>
    <div class="form-row" style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
      <div>
        <label class="form-label">% Merma</label>
        <input type="number" id="mi-merma" min="0" max="100" step="0.1" value="0"/>
      </div>
      <div>
        <label class="form-label">Inventariable</label>
        <select id="mi-inv"><option value="1">Sí</option><option value="0">No</option></select>
      </div>
    </div>
    <div id="modal-error" style="color:var(--red);font-size:11px;font-weight:700;display:none;margin-bottom:8px;"></div>
    <div class="modal-actions">
      <button class="btn btn-ghost" onclick="cerrarModal()">Cancelar</button>
      <button class="btn btn-orange" onclick="guardarInsumo()">
        <svg viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
        Guardar en SR
      </button>
    </div>
  </div>
</div>

<script src="/js/arkhon-utils.js"></script>
<script>
// ─── Globals ──────────────────────────────────────────────────────────────────
const $ = id => document.getElementById(id);
let currentTab = 'monitor';
let stockData   = [];
let insumosData = [];
let productosData = [];
let recetaActual  = [];
let prodActual    = null;
let pdfFilas      = [];
let pdfSmartMode  = false;
let selectedImportFile = null;
let refreshTimer  = null;
let recetaGrupoSel = '';

var LOCAL_API_KEY = '';


// ─── Tabs ──────────────────────────────────────────────────────────────────
function showTab(name, btn) {
  currentTab = name;
  document.querySelectorAll('.section').forEach(s=>s.classList.remove('active'));
  document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
  const sec = $('sec-'+name);
  if(sec) sec.classList.add('active');
  if(btn) btn.classList.add('active');
  if(name==='insumos' && !insumosData.length) cargarInsumos();
  if(name==='recetas' && !productosData.length) cargarProductos();
  if(name==='monitor') cargarMonitor();
}

// ─── Monitor en vivo ──────────────────────────────────────────────────────
async function cargarMonitor() {
  try {
    const [snap, fc] = await Promise.all([
      apiFetch('/api/inventario/resumen').catch(() => null),
      apiFetch('/api/inventario/food-cost').catch(() => null),
    ]);
    if(snap) renderMonitor(snap);
    renderFoodCost(fc);  // renderFoodCost ya maneja null/sin_turno

    const stock = await apiFetch('/api/inventario/existencias').catch(() => []);
    stockData = stock || [];
    renderStock(stockData);
  } catch(e) {
    console.error('cargarMonitor:', e);
    $('fc-turno-label').textContent = 'Error al cargar datos';
  }
}

function renderFoodCost(fc) {
  if(!fc || fc.sin_turno) {
    $('fc-pct').textContent = '—';
    $('fc-turno-label').textContent = 'Sin turno activo';
    return;
  }
  const pct = fc.food_cost_pct || 0;
  $('fc-pct').textContent = pct.toFixed(1) + '%';
  $('fc-costo').textContent = fmt(fc.costo_total || 0);
  $('fc-venta').textContent = fmt(fc.venta_total || 0);
  $('fc-turno-label').textContent = `Turno #${fc.idturno}`;
  const w = Math.min(pct, 100);
  $('fc-gauge').style.width = w + '%';
  // Color del gauge según food cost
  $('fc-gauge').style.background = pct > 35 ? '#ef4444' : pct > 28 ? '#f59e0b' : '#fff';
}

function renderMonitor(data) {
  if(!data) return;
  const r = data.resumen || {};
  $('k-total').textContent = r.total_insumos || 0;
  $('k-critico').textContent = r.alertas_criticas || 0;
  $('k-bajo').textContent = r.alertas_bajas || 0;
  $('k-valor').textContent = r.valor_total ? fmt(r.valor_total) : '$0';

  const alertas = data.alertas || [];
  if(alertas.length) {
    $('alertas-container').innerHTML = `
      <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-3);margin-bottom:8px;">
        ! ${alertas.length} alerta${alertas.length!==1?'s':''} de stock
      </div>
      <div class="alertas-wrap">
        ${alertas.slice(0,10).map(a=>`
          <div class="alerta-row ${a.estado}">
            <div class="alerta-dot ${a.estado}"></div>
            <div class="alerta-name">${a.insumo} <span style="font-weight:500;color:var(--text-3)">${a.presentacion||''}</span></div>
            <div class="alerta-vals">Exist: ${a.existencia} ${a.unidad} · Mín: ${a.stock_minimo}</div>
            <span class="badge ${a.estado}">${a.estado==='critico'?'Crítico':'Bajo'}</span>
          </div>
        `).join('')}
      </div>`;
  } else {
    $('alertas-container').innerHTML = '';
  }
}

function renderStock(data) {
  if(!data || !data.length) {
    $('tbl-stock').innerHTML = '<tr><td colspan="7" class="empty">Sin datos de stock</td></tr>';
    return;
  }
  $('tbl-stock').innerHTML = data.map(r=>`
    <tr>
      <td class="bold">${r.insumo}</td>
      <td>${r.presentacion||'—'}</td>
      <td>${r.almacen||'—'}</td>
      <td class="r">${Number(r.existencia).toFixed(2)} ${r.unidad}</td>
      <td class="r">${fmt(r.costo_promedio)}</td>
      <td class="r">${fmt(r.valor_total)}</td>
      <td><span class="badge ${r.estado}">${r.estado==='critico'?'Crítico':r.estado==='bajo'?'Bajo':'OK'}</span></td>
    </tr>`).join('');
}

function filtrarStock() {
  const q = $('filter-stock').value.toLowerCase();
  const e = $('filter-estado').value;
  const filtered = stockData.filter(r => {
    const matchQ = !q || r.insumo.toLowerCase().includes(q);
    const matchE = !e || r.estado === e;
    return matchQ && matchE;
  });
  renderStock(filtered);
}

// ─── Catálogo de insumos ──────────────────────────────────────────────────
async function cargarInsumos() {
  $('tbl-insumos').innerHTML = '<tr><td colspan="7" class="empty"><div class="spin"></div></td></tr>';
  try {
    insumosData = await apiFetch('/api/inventario/insumos') || [];
    renderInsumos(insumosData);
  } catch(e) {
    $('tbl-insumos').innerHTML = '<tr><td colspan="7" class="empty">Error cargando insumos</td></tr>';
  }
}

function renderInsumos(data) {
  if(!data.length) {
    $('tbl-insumos').innerHTML = '<tr><td colspan="7" class="empty">Sin insumos en catálogo</td></tr>';
    return;
  }
  $('tbl-insumos').innerHTML = data.map(i=>`
    <tr>
      <td class="bold" style="font-family:monospace;font-size:11px">${i.idinsumo}</td>
      <td class="bold">${i.descripcion}</td>
      <td>${i.unidad}</td>
      <td class="r">${fmt(i.ultimo_costo)}</td>
      <td class="r">${fmt(i.costo_promedio)}</td>
      <td class="r">${i.merma_pct > 0 ? i.merma_pct + '%' : '—'}</td>
      <td>
        <button class="btn btn-ghost" style="padding:4px 8px;font-size:10px" onclick='abrirModalEditarInsumo(${JSON.stringify(i)})'>
          <svg viewBox="0 0 24 24" style="width:11px;height:11px;stroke:currentColor;stroke-width:2.2;fill:none;"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
        </button>
      </td>
    </tr>`).join('');
}

function filtrarInsumos() {
  const q = $('filter-insumos').value.toLowerCase();
  renderInsumos(insumosData.filter(i => i.descripcion.toLowerCase().includes(q) || i.idinsumo.toLowerCase().includes(q)));
}

// ─── Modal insumo ─────────────────────────────────────────────────────────
function abrirModalNuevoInsumo() {
  $('modal-insumo-title').textContent = 'Nuevo Insumo';
  $('mi-modo').value = 'nuevo';
  $('mi-clave').value = '';
  $('mi-desc').value = '';
  $('mi-unidad').value = 'KGS';
  $('mi-costo').value = '0';
  $('mi-merma').value = '0';
  $('mi-inv').value = '1';
  $('mi-clave').disabled = false;
  $('modal-error').style.display = 'none';
  $('modal-insumo').classList.add('open');
}

function abrirModalEditarInsumo(insumo) {
  $('modal-insumo-title').textContent = 'Editar Insumo';
  $('mi-modo').value = 'editar';
  $('mi-clave').value = insumo.idinsumo;
  $('mi-desc').value = insumo.descripcion;
  $('mi-unidad').value = insumo.unidad || 'KGS';
  $('mi-costo').value = insumo.ultimo_costo || 0;
  $('mi-merma').value = insumo.merma_pct || 0;
  $('mi-inv').value = insumo.inventariable ? '1' : '0';
  $('mi-clave').disabled = true;
  $('modal-error').style.display = 'none';
  $('modal-insumo').classList.add('open');
}

function cerrarModal() {
  $('modal-insumo').classList.remove('open');
}

async function guardarInsumo() {
  const modo  = $('mi-modo').value;
  const clave = $('mi-clave').value.trim().toUpperCase();
  const desc  = $('mi-desc').value.trim().toUpperCase();
  if(!clave || !desc) {
    $('modal-error').textContent = 'Clave y descripción son requeridos';
    $('modal-error').style.display = 'block';
    return;
  }
  const body = { idinsumo: clave, descripcion: desc, unidad: $('mi-unidad').value,
    ultimocosto: parseFloat($('mi-costo').value)||0, porcentajemerma: parseFloat($('mi-merma').value)||0,
    inventariable: $('mi-inv').value==='1' };

  try {
    let r;
    if(modo === 'nuevo') {
      r = await apiFetch('/api/inventario/insumos', { method:'POST', body: JSON.stringify(body) });
    } else {
      r = await apiFetch('/api/inventario/insumos/'+clave, { method:'PUT', body: JSON.stringify(body) });
    }
    // Si apiFetch no lanzó excepción = éxito
    cerrarModal();
    await cargarInsumos();
  } catch(e) {
    $('modal-error').textContent = e.message;
    $('modal-error').style.display = 'block';
  }
}

// ─── Recetas ──────────────────────────────────────────────────────────────
async function cargarProductos() {
  $('prod-list').innerHTML = '<div class="empty"><div class="spin"></div></div>';
  try {
    productosData = await apiFetch('/api/inventario/productos') || [];
    if (!productosData.length) {
      $('prod-list').innerHTML = '<div class="empty">Sin productos registrados en el sistema</div>';
      return;
    }
    renderProductosList(productosData);
  } catch(e) {
    $('prod-list').innerHTML = `<div class="empty" style="color:#ef4444">
      Error cargando productos<br>
      <span style="font-size:11px;color:var(--text-3)">${e.message || 'Error de conexión'}</span><br>
      <button onclick="cargarProductos()" style="margin-top:8px;padding:5px 12px;font-size:11px;
        border:1px solid var(--border);border-radius:6px;background:transparent;
        color:var(--text-2);cursor:pointer;">Reintentar</button>
    </div>`;
  }
}

function renderProductosList(data) {
  if(!data.length) { $('prod-list').innerHTML = '<div class="empty">Sin productos</div>'; return; }
  $('prod-list').innerHTML = data.map(p=>`
    <div class="prod-item" id="pi-${p.idproducto}" onclick="seleccionarProducto('${p.idproducto}','${escHtml(p.descripcion)}')">
      <div>
        <div class="prod-item-name">${p.descripcion}</div>
        <div class="prod-item-grupo">${p.grupo||'Sin grupo'}</div>
      </div>
      <div class="prod-item-badge ${p.tiene_receta>0?'has':'no'}" title="${p.tiene_receta>0?'Tiene receta':'Sin receta'}"></div>
    </div>`).join('');
}

function filtrarProductos() {
  const q = $('filter-productos').value.toLowerCase();
  renderProductosList(productosData.filter(p => p.descripcion.toLowerCase().includes(q)));
}

async function seleccionarProducto(idprod, nombre) {
  prodActual = idprod;
  await asegurarInsumosCatalogo();
  document.querySelectorAll('.prod-item').forEach(el => el.classList.remove('active'));
  const pi = $('pi-'+idprod);
  if(pi) pi.classList.add('active');
  $('receta-prod-nombre').textContent = nombre;
  $('btn-guardar-receta').style.display = '';
  $('receta-content').innerHTML = '<div class="empty"><div class="spin"></div></div>';

  try {
    recetaActual = await apiFetch('/api/inventario/recetas/'+idprod) || [];
    renderRecetaEditor(recetaActual);
  } catch(e) {
    $('receta-content').innerHTML = '<div class="empty">Error cargando receta</div>';
  }
}

function renderRecetaEditor(lines) {
  const costoTotal = lines.reduce((a,l) => a + (l.costo_linea||0), 0);
  const selector = renderSelectorInsumoReceta();
  const html = `
    <div style="margin-bottom:8px;display:grid;grid-template-columns:1fr 100px 90px 80px 28px;gap:6px;padding:0 0 6px;border-bottom:1px solid var(--border);">
      <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Insumo</div>
      <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Unidad</div>
      <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Cantidad</div>
      <div style="font-size:9.5px;font-weight:700;text-transform:uppercase;color:var(--text-3);">Costo línea</div>
      <div></div>
    </div>
    <div id="receta-lines">
      ${lines.map((l,i) => renderRecetaLine(l,i)).join('')}
    </div>
    <div style="margin-top:12px;display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:8px;align-items:center">
      ${selector}
      <button class="btn btn-ghost" onclick="agregarLineaReceta()">
        <svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        Agregar insumo
      </button>
    </div>
    <div style="margin-top:10px;display:flex;justify-content:flex-end">
      <div class="receta-costo-total">Costo total estimado: ${fmt(costoTotal)}</div>
    </div>`;
  $('receta-content').innerHTML = html;
}

async function asegurarInsumosCatalogo() {
  if(insumosData.length) return;
  insumosData = await apiFetch('/api/inventario/insumos') || [];
}

function gruposReceta() {
  const map = new Map();
  insumosData.forEach(i => {
    const id = i.idgrupo || i.idgruposi || '';
    const nombre = i.grupo || (id ? id : 'Sin grupo');
    if(!map.has(id)) map.set(id, nombre);
  });
  return [...map.entries()].sort((a,b) => String(a[1]).localeCompare(String(b[1])));
}

function insumosFiltradosReceta() {
  if(!recetaGrupoSel && gruposReceta().length) recetaGrupoSel = gruposReceta()[0][0];
  return insumosData.filter(i => String(i.idgrupo || i.idgruposi || '') === String(recetaGrupoSel));
}

function renderSelectorInsumoReceta() {
  const grupos = gruposReceta();
  if(!grupos.length) return '<select id="receta-grupo" disabled><option>Sin grupos</option></select><select id="receta-insumo" disabled><option>Sin insumos</option></select>';
  if(!recetaGrupoSel || !grupos.some(([id]) => String(id) === String(recetaGrupoSel))) recetaGrupoSel = grupos[0][0];
  const insumos = insumosFiltradosReceta();
  return `
    <select id="receta-grupo" onchange="recetaGrupoSel=this.value;renderRecetaEditor(recetaActual)">
      ${grupos.map(([id,nombre]) => `<option value="${id}" ${String(id)===String(recetaGrupoSel)?'selected':''}>${nombre}</option>`).join('')}
    </select>
    <select id="receta-insumo">
      ${insumos.map(i => `<option value="${i.idinsumo}">${i.descripcion} (${i.unidad||''})</option>`).join('')}
    </select>`;
}

function renderRecetaLine(l, i) {
  return `<div class="receta-line" id="rl-${i}">
    <div style="font-size:12px;font-weight:700">${l.insumo||l.idinsumo}</div>
    <div style="font-size:11px;color:var(--text-3)">${l.unidad||''}</div>
    <input type="number" value="${l.cantidad}" min="0" step="0.0001" onchange="recetaActual[${i}].cantidad=+this.value;recalcReceta()"
      style="width:80px;padding:5px 8px;border:1px solid var(--border);border-radius:7px;font-size:12px;font-weight:700"/>
    <div style="font-size:12px;font-weight:700;color:var(--orange)">${fmt(l.costo_linea||0)}</div>
    <button onclick="eliminarLineaReceta(${i})" style="width:24px;height:24px;border:none;border-radius:6px;background:var(--red-lt);color:var(--red);cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0">
      <svg viewBox="0 0 24 24" style="width:11px;height:11px;stroke:currentColor;stroke-width:2.2;fill:none;"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
    </button>
  </div>`;
}

function recalcReceta() {
  // Recalcular costos línea
  recetaActual.forEach(l => { l.costo_linea = (l.cantidad||0) * (l.ultimo_costo||0); });
  const costoTotal = recetaActual.reduce((a,l) => a+(l.costo_linea||0), 0);
  document.querySelectorAll('.receta-costo-total').forEach(el => el.textContent = 'Costo total estimado: '+fmt(costoTotal));
}

async function agregarLineaReceta() {
  await asegurarInsumosCatalogo();
  const idinsumo = $('receta-insumo')?.value;
  if(!idinsumo) return;
  try {
    const r = insumosData.find(i => i.idinsumo === idinsumo);
    if(!r) { alert('Insumo no encontrado: '+idinsumo); return; }
    const ins = r;
    recetaActual.push({ idinsumo: ins.idinsumo, insumo: ins.descripcion, unidad: ins.unidad,
      cantidad: 1, ultimo_costo: ins.ultimo_costo, costo_linea: ins.ultimo_costo });
    renderRecetaEditor(recetaActual);
  } catch(e) { alert('Error: '+e.message); }
}

function eliminarLineaReceta(i) {
  recetaActual.splice(i, 1);
  renderRecetaEditor(recetaActual);
}

async function guardarReceta() {
  if(!prodActual) return;
  const lines = recetaActual.map(l => ({ idinsumo: l.idinsumo, cantidad: l.cantidad }));
  const r = await apiFetch('/api/inventario/recetas/'+prodActual, { method:'POST', body: JSON.stringify({ lines }) });
  // apiFetch lanza excepción si no es ok — si llegamos aquí es éxito
    const pi = $('pi-'+prodActual);
    if(pi) pi.querySelector('.prod-item-badge').className = 'prod-item-badge has';
    const pd = productosData.find(p=>p.idproducto===prodActual);
    if(pd) pd.tiene_receta = lines.length;
    alert(' Receta guardada en SoftRestaurant ('+lines.length+' insumos)');
}

// ─── PDF Import ───────────────────────────────────────────────────────────
function dragOver(e) { e.preventDefault(); $('drop-zone').classList.add('drag-over'); }
function dragLeave()  { $('drop-zone').classList.remove('drag-over'); }

function dropFile(e) {
  e.preventDefault();
  dragLeave();
  const file = e.dataTransfer.files[0];
  if(file) procesarArchivo(file);
}

function archivoSeleccionado(input) {
  if(input.files[0]) procesarArchivo(input.files[0]);
}

function procesarArchivo(file) {
  const reader = new FileReader();
  reader.onload = e => {
    $('texto-manual').value = e.target.result;
  };
  reader.readAsText(file);
}

async function parsearPDF() {
  const texto = $('texto-manual').value.trim();
  if(!texto) { alert('Primero sube un PDF o pega el texto'); return; }

  const r = await apiFetch('/api/inventario/importar-pdf', {
    method: 'POST',
    body: JSON.stringify({ texto })
  });
  pdfFilas = r.filas || r || [];
  $('pdf-preview-title').textContent = `${pdfFilas.length} insumos detectados · ${r.requieren_revision} requieren revisión`;

  // Render preview rows
  $('pdf-preview-rows').innerHTML = pdfFilas.map((f,i) => `
    <div class="preview-row" id="pr-${i}">
      <input type="text" value="${f.idinsumo}" onchange="pdfFilas[${i}].idinsumo=this.value.toUpperCase()" maxlength="10"
        style="font-size:11px;padding:4px 6px;font-family:monospace"/>
      <input type="text" value="${f.descripcion}" onchange="pdfFilas[${i}].descripcion=this.value.toUpperCase()" maxlength="60"
        style="font-size:11px;padding:4px 6px;"/>
      <select onchange="pdfFilas[${i}].unidad=this.value" style="font-size:11px;padding:4px 6px;">
        ${['KGS','PZA','LT','ML','GALON','CAJA','OZ','GR','BOLSA','PAQ','BOT'].map(u=>`<option ${f.unidad===u?'selected':''}>${u}</option>`).join('')}
      </select>
      <input type="number" value="${f.ultimo_costo}" onchange="pdfFilas[${i}].ultimo_costo=+this.value" min="0" step="0.01"
        style="font-size:11px;padding:4px 6px;"/>
      <span class="estado-badge ${f.estado}">${f.estado}</span>
      <button onclick="pdfFilas.splice(${i},1);parsearPDF()" style="width:22px;height:22px;border:none;border-radius:5px;background:var(--red-lt);color:var(--red);cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;padding:0">×</button>
    </div>`).join('');

  $('pdf-step1-content').style.display = 'none';
  $('pdf-step2-content').style.display = 'block';
  setPDFStep(2);
}

async function confirmarImport() {
  if(!pdfFilas.length) return;
  const r = await apiFetch('/api/inventario/importar-pdf', {
    method: 'POST',
    body: JSON.stringify({ filas_confirmadas: pdfFilas })
  });
  $('pdf-step2-content').style.display = 'none';
  $('pdf-step3-content').style.display = 'block';
  setPDFStep(3);

  // apiFetch lanza excepción si hay error — si llegamos aquí es éxito
  $('pdf-resultado').innerHTML = `
      <div style="text-align:center;padding:20px;">
        <div style="font-size:40px;margin-bottom:8px;"></div>
        <div style="font-size:18px;font-weight:800;color:var(--green);margin-bottom:4px;">${r.guardados} insumos importados</div>
        <div style="font-size:12px;color:var(--text-3);">de ${r.total} procesados</div>
      </div>
      ${r.resultados?.filter(x=>!x.ok).length ? `
        <div style="margin-top:12px;padding:10px;background:var(--red-lt);border-radius:8px;">
          <div style="font-size:11px;font-weight:700;color:var(--red);margin-bottom:6px;">Errores:</div>
          ${r.resultados.filter(x=>!x.ok).map(x=>`<div style="font-size:11px;color:var(--red)">${x.idinsumo}: ${x.error}</div>`).join('')}
        </div>` : ''}`;
  insumosData = [];
}

function resetPDF() {
  $('texto-manual').value = '';
  $('file-input').value = '';
  pdfFilas = [];
  $('pdf-step1-content').style.display = 'block';
  $('pdf-step2-content').style.display = 'none';
  $('pdf-step3-content').style.display = 'none';
  setPDFStep(1);
}

function procesarArchivo(file) {
  selectedImportFile = file;
  if(/\.xls$/i.test(file.name) && !/\.xlsx$/i.test(file.name)) {
    selectedImportFile = null;
    $('texto-manual').value = '';
    alert('Formato .xls antiguo no soportado. Guarda el archivo como .xlsx y vuelve a importarlo.');
    return;
  }
  if(/\.(xlsx|pdf|png|jpe?g|webp)$/i.test(file.name)) {
    $('texto-manual').value = `Archivo seleccionado: ${file.name}`;
    return;
  }
  const reader = new FileReader();
  reader.onload = e => { $('texto-manual').value = e.target.result; };
  reader.readAsText(file);
}

async function parsearPDF() {
  const texto = $('texto-manual').value.trim();
  const tipo = $('smart-import-tipo')?.value || 'inventario';
  const prefijo = $('smart-import-prefijo')?.value || '';
  const usarInteligente = tipo === 'menu' || (selectedImportFile && /\.(xlsx|pdf|png|jpe?g|webp)$/i.test(selectedImportFile.name));
  if(!texto && !selectedImportFile) { alert('Primero sube un archivo o pega el texto'); return; }

  let r;
  if(usarInteligente) {
    const fd = new FormData();
    fd.append('tipo', tipo);
    fd.append('prefijo', prefijo);
    if(selectedImportFile) fd.append('file', selectedImportFile);
    else fd.append('texto', texto);
    const res = await fetch('/api/inventario/importar-inteligente/preview', {
      method: 'POST',
      headers: { 'X-Api-Token': LOCAL_API_KEY },
      body: fd,
    });
    const json = await res.json();
    if(!json.ok) throw new Error(json.error || 'Error al analizar archivo');
    r = json.data || json;
    pdfSmartMode = true;
  } else {
    r = await apiFetch('/api/inventario/importar-pdf', {
      method: 'POST',
      body: JSON.stringify({ texto })
    });
    pdfSmartMode = false;
  }

  pdfFilas = r.filas || r || [];
  $('pdf-preview-title').textContent = `${pdfFilas.length} ${tipo === 'menu' ? 'productos' : 'insumos'} detectados - ${r.requieren_revision || 0} requieren revision`;
  $('pdf-preview-rows').innerHTML = pdfFilas.map((f,i) => `
    <div class="preview-row" id="pr-${i}">
      <input type="text" value="${f.idinsumo || f.idproducto || ''}" onchange="${tipo === 'menu' ? `pdfFilas[${i}].idproducto=this.value.toUpperCase()` : `pdfFilas[${i}].idinsumo=this.value.toUpperCase()`}" maxlength="${tipo === 'menu' ? '20' : '10'}"
        style="font-size:11px;padding:4px 6px;font-family:monospace"/>
      <input type="text" value="${f.descripcion || ''}" onchange="pdfFilas[${i}].descripcion=this.value.toUpperCase()" maxlength="60"
        style="font-size:11px;padding:4px 6px;"/>
      <select onchange="pdfFilas[${i}].unidad=this.value" style="font-size:11px;padding:4px 6px;">
        ${['KGS','PZA','LT','ML','GALON','CAJA','OZ','GR','BOLSA','PAQ','BOT'].map(u=>`<option ${f.unidad===u?'selected':''}>${u}</option>`).join('')}
      </select>
      <input type="number" value="${f.ultimo_costo || f.precio || 0}" onchange="${tipo === 'menu' ? `pdfFilas[${i}].precio=+this.value` : `pdfFilas[${i}].ultimo_costo=+this.value`}" min="0" step="0.01"
        style="font-size:11px;padding:4px 6px;"/>
      <span class="estado-badge ${f.estado || 'revisar'}">${f.estado || 'revisar'}</span>
      <button onclick="pdfFilas.splice(${i},1);this.closest('.preview-row').remove()" style="width:22px;height:22px;border:none;border-radius:5px;background:var(--red-lt);color:var(--red);cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;padding:0">x</button>
    </div>`).join('');

  $('pdf-step1-content').style.display = 'none';
  $('pdf-step2-content').style.display = 'block';
  setPDFStep(2);
}

async function confirmarImport() {
  if(!pdfFilas.length) return;
  const tipo = $('smart-import-tipo')?.value || 'inventario';
  let r;
  if(pdfSmartMode || tipo === 'menu') {
    const smart = await apiFetch('/api/inventario/importar-inteligente/aplicar', {
      method: 'POST',
      body: JSON.stringify({ tipo, filas: pdfFilas })
    });
    r = smart.data || smart;
  } else {
    r = await apiFetch('/api/inventario/importar-pdf', {
      method: 'POST',
      body: JSON.stringify({ filas_confirmadas: pdfFilas })
    });
  }
  $('pdf-step2-content').style.display = 'none';
  $('pdf-step3-content').style.display = 'block';
  setPDFStep(3);

  $('pdf-resultado').innerHTML = `
      <div style="text-align:center;padding:20px;">
        <div style="font-size:18px;font-weight:800;color:var(--green);margin-bottom:4px;">${r.guardados} ${tipo === 'menu' ? 'productos' : 'insumos'} importados</div>
        <div style="font-size:12px;color:var(--text-3);">de ${r.total} procesados</div>
      </div>
      ${r.resultados?.filter(x=>!x.ok).length ? `
        <div style="margin-top:12px;padding:10px;background:var(--red-lt);border-radius:8px;">
          <div style="font-size:11px;font-weight:700;color:var(--red);margin-bottom:6px;">Errores:</div>
          ${r.resultados.filter(x=>!x.ok).map(x=>`<div style="font-size:11px;color:var(--red)">${x.idinsumo || x.idproducto || x.id}: ${x.error}</div>`).join('')}
        </div>` : ''}`;
  insumosData = [];
  productosData = [];
}

function resetPDF() {
  $('texto-manual').value = '';
  $('file-input').value = '';
  pdfFilas = [];
  pdfSmartMode = false;
  selectedImportFile = null;
  $('pdf-step1-content').style.display = 'block';
  $('pdf-step2-content').style.display = 'none';
  $('pdf-step3-content').style.display = 'none';
  setPDFStep(1);
}

function setPDFStep(n) {
  [1,2,3].forEach(i => {
    const el = $('pdf-step-'+i);
    if(!el) return;
    el.classList.remove('active','done');
    if(i < n) el.classList.add('done');
    else if(i === n) el.classList.add('active');
  });
}

// ─── Refresh ──────────────────────────────────────────────────────────────
async function refrescar() {
  if(currentTab==='monitor') await cargarMonitor();
  if(currentTab==='insumos') { insumosData=[]; await cargarInsumos(); }
  if(currentTab==='recetas') { productosData=[]; await cargarProductos(); }
}

function escHtml(s) { return String(s || '').replace(/'/g,"\\'"); }

// ─── Auto-refresh del monitor cada 30s ───────────────────────────────────
setInterval(() => { if(currentTab==='monitor') cargarMonitor(); }, 30000);

// ─── Init ─────────────────────────────────────────────────────────────────
(async () => {
  await _initAuth();
  // Ocultar topbar si está dentro de un iframe
  if (window.self !== window.top) {
    const tb = document.querySelector('.topbar');
    if (tb) tb.style.display = 'none';
  }
  cargarMonitor();
})();
</script>
</body>
</html>
