<!DOCTYPE html>
<html lang="es">
<head>
  <script>/*pos_theme_early*/(function(){var t=localStorage.getItem("pos_theme")||"industrial";document.documentElement.setAttribute("data-theme",t);})()</script>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Inventario — Nexus Autoparts POS</title>
  <link rel="stylesheet" href="/pos/static/css/chat.css" />
  <link rel="stylesheet" href="/pos/static/css/tokens.css" />
  <link rel="stylesheet" href="/pos/static/css/common.css" />
  <link rel="stylesheet" href="/pos/static/css/pos-ui.css?v=33" />
  <link rel="stylesheet" href="/pos/static/css/sidebar.css" />
  <link rel="stylesheet" href="/pos/static/css/pos-glass.css" />
  <link rel="manifest" href="/pos/static/pwa/manifest.json" />
  <meta name="theme-color" content="#F5A623" />
  <link rel="shortcut icon" type="image/png" href="/pos/static/pwa/icon-192.png" />

  <link rel="stylesheet" href="/pos/static/css/inventory.css?v=33"></head>

<body>

  <!-- =========================================================================
       THEME SWITCHER BAR
       ========================================================================= -->

  <header class="theme-bar" role="banner">
    <div class="theme-bar__left">
      <div class="theme-bar__store">
        <span class="theme-bar__dot"></span>
        Nexus Autoparts
      </div>
      <div class="theme-bar__sep"></div>
      <span class="theme-bar__label">Sucursal Centro &mdash; Usuario: H. García</span>
    </div>
    <div class="theme-bar__right">
      <button class="icon-btn" id="notifDropdownBtn" title="Notificaciones" onclick="NotificationsDropdown.toggle()" style="margin-right:8px;">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
        <span class="notif-dot" id="headerNotifDot"></span>
      </button>
      <button class="icon-btn" title="Modo táctil" onclick="TouchModeToggle.set(document.documentElement.getAttribute('data-touch') !== 'true')" style="margin-right:4px;">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="2" width="16" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg>
      </button>
      <button class="icon-btn" title="Densidad" onclick="DensityToggle.set(document.documentElement.getAttribute('data-density') === 'compact' ? 'normal' : 'compact')" style="margin-right:8px;">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/></svg>
      </button>
      <span class="theme-bar__label">Tema:</span>
      <button class="theme-btn theme-btn--industrial is-active" data-theme-target="industrial" onclick="setTheme('industrial')">
        <span class="theme-btn__swatch"></span>
        Industrial
      </button>
      <button class="theme-btn theme-btn--modern" data-theme-target="modern" onclick="setTheme('modern')">
        <span class="theme-btn__swatch"></span>
        Moderno
      </button>
    </div>
  </header>

  <!-- =========================================================================
       APP SHELL
       ========================================================================= -->

  <div class="app-shell">

    <!-- -----------------------------------------------------------------------
         SIDEBAR NAVIGATION
         ----------------------------------------------------------------------- -->

    <aside class="sidebar" role="navigation" aria-label="Navegación principal">

      <!-- Brand -->
      <div class="sidebar__brand">
        <div class="brand-logo">NA</div>
        <div class="brand-name">
          <span class="brand-name__primary">Nexus</span>
          <span class="brand-name__sub">Autoparts POS</span>
        </div>
      </div>

      <!-- Nav -->
      <nav class="sidebar__nav">
        <div class="nav-section-label">Principal</div>

        <a class="nav-item" href="/pos/sale">
          <!-- Dashboard icon -->
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/>
            <rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/>
          </svg>
          <span>Dashboard</span>
        </a>

        <a class="nav-item" href="/pos/sale">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/>
          </svg>
          <span>POS</span>
        </a>

        <a class="nav-item" href="/pos/catalog">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <path d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
          </svg>
          <span>Catálogo</span>
        </a>

        <a class="nav-item is-active" href="/pos/inventory" aria-current="page">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
            <polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/>
          </svg>
          <span>Inventario</span>
        </a>

        <div class="nav-section-label">Gestión</div>

        <a class="nav-item" href="/pos/customers">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
            <circle cx="9" cy="7" r="4"/>
            <path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>
          </svg>
          <span>Clientes</span>
        </a>

        <a class="nav-item" href="/pos/invoicing">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
            <polyline points="14 2 14 8 20 8"/>
            <line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>
            <polyline points="10 9 9 9 8 9"/>
          </svg>
          <span>Facturación</span>
        </a>

        <a class="nav-item" href="/pos/accounting">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <line x1="12" y1="1" x2="12" y2="23"/>
            <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
          </svg>
          <span>Contabilidad</span>
        </a>

        <a class="nav-item" href="/pos/reports">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/>
            <line x1="6"  y1="20" x2="6"  y2="14"/>
          </svg>
          <span>Reportes</span>
        </a>

        <a class="nav-item" href="/pos/historical-sales">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <rect x="4" y="5" width="16" height="16" rx="1"/>
            <line x1="4" y1="10" x2="20" y2="10"/>
            <line x1="8" y1="3" x2="8" y2="5"/>
            <line x1="16" y1="3" x2="16" y2="5"/>
          </svg>
          <span>Ventas Históricas</span>
        </a>

        <div class="nav-section-label">Sistema</div>

        <a class="nav-item" href="/pos/config">
          <svg class="nav-item__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="12" r="3"/>
            <path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"/>
          </svg>
          <span>Configuración</span>
        </a>
      </nav>

      <!-- Footer user -->
      <div class="sidebar__footer">
        <div class="sidebar__user-avatar">HG</div>
        <div class="sidebar__user-info">
          <div class="sidebar__user-name">Hugo García</div>
          <div class="sidebar__user-role">Administrador</div>
        </div>
      </div>
    </aside>

    <!-- -----------------------------------------------------------------------
         MAIN CONTENT
         ----------------------------------------------------------------------- -->

    <main class="main" role="main">

      <!-- Page Header -->
      <div class="page-header">
        <div class="page-header__title-group">
          <span class="page-header__eyebrow">Almacén &middot; Sucursal Centro</span>
          <h1 class="page-header__title">Inventario</h1>
        </div>
        <div class="page-header__actions">
          <button class="btn btn--ghost" onclick="document.getElementById('bulkImportModal').classList.add('is-open')">
            <svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
            Importar CSV
          </button>
          <button class="btn btn--ghost" onclick="exportVisibleTableCSV('inventario')">
            <svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Exportar CSV
          </button>
          <button class="btn btn--ghost" onclick="loadItems(1,'')">
            <svg viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-.38-4.93"/></svg>
            Sincronizar
          </button>
          <button class="btn btn--primary" onclick="showCreateModal()">
            <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 Producto
          </button>
        </div>
      </div>

      <!-- Summary Cards -->
      <div class="summary-strip">

        <div class="summary-card">
          <div class="summary-card__icon">
            <svg viewBox="0 0 24 24"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>
          </div>
          <div class="summary-card__body">
            <div class="summary-card__label">Total SKUs</div>
            <div class="summary-card__value" id="inv-total-skus">0</div>
            <div class="summary-card__sub">Productos activos</div>
          </div>
        </div>

        <div class="summary-card">
          <div class="summary-card__icon summary-card__icon--value">
            <svg viewBox="0 0 24 24"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
          </div>
          <div class="summary-card__body">
            <div class="summary-card__label">Valor Inventario</div>
            <div class="summary-card__value" id="inv-total-value">$0</div>
            <div class="summary-card__sub">MXN · Costo promedio</div>
          </div>
        </div>

        <div class="summary-card">
          <div class="summary-card__icon summary-card__icon--alert">
            <svg viewBox="0 0 24 24"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
          </div>
          <div class="summary-card__body">
            <div class="summary-card__label">Stock Bajo</div>
            <div class="summary-card__value" id="inv-low-stock">0</div>
            <div class="summary-card__sub">Productos por reabastecer</div>
          </div>
        </div>

        <div class="summary-card">
          <div class="summary-card__icon summary-card__icon--time">
            <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="summary-card__body">
            <div class="summary-card__label">Sin Movimiento</div>
            <div class="summary-card__value" id="inv-no-movement" style="font-size:1.1rem;">0</div>
            <div class="summary-card__sub">Productos sin venta reciente</div>
          </div>
        </div>

      </div>

      <!-- Tabs Row -->
      <div class="tabs-row" role="tablist" aria-label="Módulos de Inventario">
        <button class="tab-btn is-active" role="tab" aria-selected="true"  aria-controls="panel-stock"      onclick="switchTab('stock')">
          Stock Actual <span class="tab-btn__badge" id="badge-stock">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-entradas"   onclick="switchTab('entradas')">
          Entradas <span class="tab-btn__badge" id="badge-entradas">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-salidas"    onclick="switchTab('salidas')">
          Salidas <span class="tab-btn__badge" id="badge-salidas">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-traspasos"  onclick="switchTab('traspasos')">
          Traspasos <span class="tab-btn__badge" id="badge-traspasos">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-ajustes"    onclick="switchTab('ajustes')">
          Ajustes <span class="tab-btn__badge" id="badge-ajustes">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-conteos"    onclick="switchTab('conteos')">
          Conteos <span class="tab-btn__badge" id="badge-conteos">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-alertas"    onclick="switchTab('alertas')">
          Alertas <span class="tab-btn__badge tab-btn__badge--alert" id="badge-alertas">0</span>
        </button>
      </div>

      <!-- Tab Panels -->
      <div class="tab-panels" id="tab-panels">

        <!-- ===================================================================
             TAB 1 — STOCK ACTUAL
             =================================================================== -->
        <div class="tab-panel is-active" id="panel-stock" role="tabpanel">

          <div id="savedFiltersContainer" style="margin-bottom:var(--space-2);"></div>
          <div class="toolbar">
            <div class="search-box">
              <svg viewBox="0 0 24 24" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
              <input type="text" id="productSearch" placeholder="Buscar por SKU, nombre, marca…" />
            </div>
            <select class="select-filter">
              <option value="">Todas las marcas</option>
              <option>Gates</option><option>SKF</option><option>Bosch</option>
              <option>Monroe</option><option>NGK</option>
            </select>
            <select class="select-filter">
              <option value="">Todas las categorías</option>
              <option>Motor</option><option>Frenos</option><option>Suspensión</option>
              <option>Eléctrico</option><option>Filtros</option>
            </select>
            <select class="select-filter">
              <option value="">Estado stock</option>
              <option>OK</option><option>Bajo</option><option>Sobrestock</option>
            </select>
            <div class="toolbar__spacer"></div>
            <button class="btn btn--ghost btn--sm" onclick="openInventoryFilters(this)">
              <svg viewBox="0 0 24 24"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>
              Filtros
            </button>
            <script>
            function openInventoryFilters(btn) {
                var table = document.querySelector('table');
                if (!table) { showToast('Carga el inventario primero', 'warn'); return; }
                var brands = getUniqueColumnValues(table, 3);  // brand column
                var categories = getUniqueColumnValues(table, 4); // category column
                var statuses = getUniqueColumnValues(table, 5);   // stock status column
                toggleFilterPanel(btn, [
                    {label: 'Marca', column: 3, values: brands},
                    {label: 'Categoría', column: 4, values: categories},
                    {label: 'Estado Stock', column: 5, values: statuses},
                ]);
            }
            </script>
            <button class="btn btn--ghost btn--sm" onclick="showTierDiscountModal()">
              <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="6" x2="12" y2="12"/><line x1="16.24" y1="16.24" x2="12" y2="12"/></svg>
              <span id="tierDiscountBadge">Taller -15% · Mayoreo -25%</span>
            </button>
            <button class="btn btn--primary btn--sm" onclick="showCreateModal()">
              <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 Producto
            </button>
            <button class="btn btn--sm btn--meli" id="btnPublishML" style="display:none;" onclick="openMeliPublishModal()">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
              Publicar en ML <span id="meliSelectedCountBadge" style="background:#2D3277;color:#FFE600;border-radius:10px;padding:0 6px;font-size:11px;margin-left:4px;">0</span>
            </button>
          </div>

          <div class="table-wrapper">
            <div class="vs-container" style="max-height:60vh;overflow-y:auto;">
              <table class="data-table" id="stockTable">
                <thead>
                  <tr>
                    <th style="width:32px;"><input type="checkbox" id="selectAllItems" onclick="toggleSelectAllItems()" title="Seleccionar todos" /></th>
                    <th style="font-size:var(--text-caption);color:var(--color-text-muted);">ID</th>
                    <th>Barcode</th>
                    <th>No. Parte</th>
                    <th>Nombre</th>
                    <th>Marca</th>
                    <th style="text-align:right">Stock</th>
                    <th style="text-align:right">Costo</th>
                    <th style="text-align:right">Mostrador</th>
                    <th style="text-align:right">Taller</th>
                    <th style="text-align:right">Mayoreo</th>
                    <th>Ubicación</th>
                    <th>Acciones</th>
                  </tr>
                </thead>
                <tbody id="productTableBody">
                </tbody>
              </table>
            </div>
            <div class="table-footer">
              <div id="productPagination"></div>
            </div>
          </div>
        </div>

        <!-- ===================================================================
             TAB 2 — ENTRADAS
             =================================================================== -->
        <div class="tab-panel" id="panel-entradas" role="tabpanel">

          <div class="toolbar">
            <div class="search-box">
              <svg viewBox="0 0 24 24" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
              <input type="text" placeholder="Buscar por proveedor, folio…" />
            </div>
            <select class="select-filter">
              <option value="">Todos los estados</option>
              <option>Recibido</option><option>Pendiente</option><option>Parcial</option>
            </select>
            <input type="date" class="select-filter" value="2026-04-01" />
            <div class="toolbar__spacer"></div>
            <button class="btn btn--primary" onclick="showPurchaseModal()">
              <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>
              Nueva Entrada
            </button>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio</th>
                  <th>Fecha</th>
                  <th>Proveedor</th>
                  <th style="text-align:right"># Productos</th>
                  <th style="text-align:right">Total</th>
                  <th>Estado</th>
                  <th>Recibió</th>
                  <th>Acciones</th>
                </tr>
              </thead>
              <tbody id="entradasTableBody">
                <!-- Populated by JS -->
              </tbody>
            </table>
            <div class="table-footer">
              <span id="entradasFooter"></span>
              <div class="pagination" id="entradasPagination"></div>
            </div>
          </div>
        </div>

        <!-- ===================================================================
             TAB 3 — SALIDAS
             =================================================================== -->
        <div class="tab-panel" id="panel-salidas" role="tabpanel">

          <div class="toolbar">
            <div class="search-box">
              <svg viewBox="0 0 24 24" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
              <input type="text" placeholder="Buscar salidas…" />
            </div>
            <select class="select-filter">
              <option value="">Todos los tipos</option>
              <option>Venta</option><option>Garantía</option><option>Devolución</option><option>Traspaso</option>
            </select>
            <select class="select-filter">
              <option value="">Todos los estados</option>
              <option>Completado</option><option>En proceso</option><option>Cancelado</option>
            </select>
            <div class="toolbar__spacer"></div>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio</th>
                  <th>Fecha</th>
                  <th>Tipo</th>
                  <th style="text-align:right"># Productos</th>
                  <th>Destino / Referencia</th>
                  <th>Estado</th>
                  <th>Autorizó</th>
                </tr>
              </thead>
              <tbody id="salidasTableBody">
                <!-- Populated by JS -->
              </tbody>
            </table>
            <div class="table-footer">
              <span id="salidasFooter"></span>
              <div class="pagination" id="salidasPagination"></div>
            </div>
          </div>
        </div>

        <!-- ===================================================================
             TAB 4 — TRASPASOS
             =================================================================== -->
        <div class="tab-panel" id="panel-traspasos" role="tabpanel">

          <div class="toolbar">
            <div class="search-box">
              <svg viewBox="0 0 24 24" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
              <input type="text" placeholder="Buscar traspasos…" />
            </div>
            <select class="select-filter">
              <option value="">Todas las sucursales</option>
              <option>Sucursal Norte</option><option>Sucursal Sur</option><option>Sucursal Oriente</option>
            </select>
            <select class="select-filter">
              <option value="">Todos los estados</option>
              <option>En tránsito</option><option>Recibido</option><option>Pendiente</option>
            </select>
            <div class="toolbar__spacer"></div>
            <button class="btn btn--primary" onclick="showTransferModal()">
              <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 Traspaso
            </button>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio</th>
                  <th>Fecha</th>
                  <th>Origen</th>
                  <th>Destino</th>
                  <th style="text-align:right"># Productos</th>
                  <th>Estado</th>
                  <th>Solicitó</th>
                  <th>Acciones</th>
                </tr>
              </thead>
              <tbody id="traspasosTableBody">
                <!-- Populated by JS -->
              </tbody>
            </table>
            <div class="table-footer">
              <span id="traspasosFooter"></span>
              <div class="pagination" id="traspasosPagination"></div>
            </div>
          </div>
        </div>

        <!-- ===================================================================
             TAB 5 — AJUSTES
             =================================================================== -->
        <div class="tab-panel" id="panel-ajustes" role="tabpanel">

          <div class="toolbar">
            <div class="search-box">
              <svg viewBox="0 0 24 24" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
              <input type="text" placeholder="Buscar ajustes…" />
            </div>
            <select class="select-filter">
              <option value="">Todos los tipos</option>
              <option>Merma</option><option>Daño</option><option>Corrección</option>
            </select>
            <div class="toolbar__spacer"></div>
            <button class="btn btn--primary" onclick="showAdjustmentModal()">
              <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 Ajuste
            </button>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio</th>
                  <th>Fecha</th>
                  <th>Tipo</th>
                  <th>Producto</th>
                  <th style="text-align:right">Cantidad</th>
                  <th>Motivo</th>
                  <th>Autorizó</th>
                </tr>
              </thead>
              <tbody id="ajustesTableBody">
                <!-- Populated by JS -->
              </tbody>
            </table>
            <div class="table-footer">
              <span id="ajustesFooter"></span>
              <div class="pagination" id="ajustesPagination"></div>
            </div>
          </div>
        </div>

        <!-- ===================================================================
             TAB 6 — CONTEOS
             =================================================================== -->
        <div class="tab-panel" id="panel-conteos" role="tabpanel">

          <div class="toolbar">
            <div class="search-box">
              <svg viewBox="0 0 24 24" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
              <input type="text" placeholder="Buscar conteos…" />
            </div>
            <select class="select-filter">
              <option value="">Todas las zonas</option>
              <option>Zona A</option><option>Zona B</option><option>Zona C</option><option>Zona D</option><option>Zona E</option>
            </select>
            <select class="select-filter">
              <option value="">Todos los estados</option>
              <option>Completado</option><option>En proceso</option><option>Programado</option>
            </select>
            <div class="toolbar__spacer"></div>
            <button class="btn btn--primary" onclick="showCountModal()">
              <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>
              Programar Conteo
            </button>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio</th>
                  <th>Fecha</th>
                  <th>Zona</th>
                  <th style="text-align:right">Contados</th>
                  <th style="text-align:right">Diferencias</th>
                  <th>Estado</th>
                  <th>Realizó</th>
                  <th>Acciones</th>
                </tr>
              </thead>
              <tbody>
                <!-- Populated by JS -->
              </tbody>
            </table>
            <div class="table-footer">
              <span></span>
              <div class="pagination"></div>
            </div>
          </div>
        </div>

        <!-- ===================================================================
             TAB 7 — ALERTAS
             =================================================================== -->
        <div class="tab-panel" id="panel-alertas" role="tabpanel">
          <div id="alertsContent">
            <!-- Populated by JS -->
          </div><!-- /alertsContent -->
        </div>

      </div><!-- /tab-panels -->
    </main>
  </div><!-- /app-shell -->

  <!-- =========================================================================
       SCRIPTS
       ========================================================================= -->

  <script>
    /* ------------------------------------------------------------------
       Theme switcher
       ------------------------------------------------------------------ */

    function setTheme(theme) {
      document.documentElement.setAttribute('data-theme', theme);

      document.querySelectorAll('.theme-btn').forEach(function(btn) {
        btn.classList.toggle('is-active', btn.dataset.themeTarget === theme);
      });

      // Persist preference
      try { localStorage.setItem('pos_theme', theme); } catch(e) {}
    }

    // Restore on load
    (function() {
      var saved;
      try { saved = localStorage.getItem('pos_theme'); } catch(e) {}
      if (saved === 'industrial' || saved === 'modern') {
        setTheme(saved);
      }
    })();

    /* ------------------------------------------------------------------
       Tab switcher
       ------------------------------------------------------------------ */

    var TAB_MAP = {
      stock:     { btn: 0, panel: 'panel-stock'     },
      entradas:  { btn: 1, panel: 'panel-entradas'  },
      salidas:   { btn: 2, panel: 'panel-salidas'   },
      traspasos: { btn: 3, panel: 'panel-traspasos' },
      ajustes:   { btn: 4, panel: 'panel-ajustes'   },
      conteos:   { btn: 5, panel: 'panel-conteos'   },
      alertas:   { btn: 6, panel: 'panel-alertas'   },
    };

    var tabBtns   = document.querySelectorAll('.tab-btn');
    var tabPanels = document.querySelectorAll('.tab-panel');

    function switchTab(name) {
      var target = TAB_MAP[name];
      if (!target) return;

      // Deactivate all
      tabBtns.forEach(function(b)   { b.classList.remove('is-active'); b.setAttribute('aria-selected', 'false'); });
      tabPanels.forEach(function(p) { p.classList.remove('is-active'); });

      // Activate target
      tabBtns[target.btn].classList.add('is-active');
      tabBtns[target.btn].setAttribute('aria-selected', 'true');
      document.getElementById(target.panel).classList.add('is-active');

      // Scroll panels container back to top
      document.getElementById('tab-panels').scrollTop = 0;

      // Load operations data for non-stock tabs
      if (name !== 'stock' && name !== 'alertas' && name !== 'conteos' && window.loadOperations) {
        window.loadOperations(name, 1);
      }
    }

    /* ------------------------------------------------------------------
       Live clock (status bar)
       ------------------------------------------------------------------ */

    (function updateClock() {
      var now  = new Date();
      var hh   = String(now.getHours()).padStart(2, '0');
      var mm   = String(now.getMinutes()).padStart(2, '0');
      var el   = document.getElementById('live-clock');
      if (el) el.textContent = hh + ':' + mm;
      setTimeout(updateClock, 30000);
    })();
  </script>

  <!-- ===== MODALS ===== -->

  <!-- Create Item Modal -->
  <div class="inv-modal-overlay" id="createModal">
    <div class="inv-modal">
      <div class="inv-modal__header">
        <h3>Nuevo Producto</h3>
        <button class="inv-modal__close" onclick="closeCreateModal()">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div class="inv-form-grid">
          <div class="inv-field"><label>No. Parte *</label><input type="text" id="newPartNumber" placeholder="Ej: GAT-50104" /></div>
          <div class="inv-field"><label>Nombre *</label><input type="text" id="newName" placeholder="Nombre del producto" /></div>
          <div class="inv-field"><label>Marca</label><input type="text" id="newBrand" placeholder="Marca del fabricante" /></div>
          <div class="inv-field"><label>Categoría</label>
            <select class="select-filter" id="newCategory" onchange="onCategoryChange(this.value)" style="width:100%;">
              <option value="">Selecciona categoría</option>
            </select>
          </div>
          <div class="inv-field"><label>Subcategoría</label>
            <select class="select-filter" id="newSubcategory" style="width:100%;" disabled>
              <option value="">Selecciona categoría primero</option>
            </select>
          </div>
          <div class="inv-field"><label>Barcode</label><input type="text" id="newBarcode" placeholder="Auto-generado si vacío" /></div>
          <div class="inv-field"><label>SKU Alternativo 1</label><input type="text" id="newSku2" placeholder="Ej: SKU-Bodega-A" /></div>
          <div class="inv-field"><label>SKU Alternativo 2</label><input type="text" id="newSku3" placeholder="Ej: SKU-Bodega-B" /></div>
          <div class="inv-field"><label>Costo</label><input type="number" id="newCost" step="0.01" placeholder="0.00" /></div>
          <div class="inv-field"><label>Precio Mostrador</label><input type="number" id="newPrice1" step="0.01" placeholder="0.00" /></div>
          <div class="inv-field"><label>Stock Mínimo</label><input type="number" id="newMinStock" placeholder="0" /></div>
          <div class="inv-field"><label>Stock Inicial</label><input type="number" id="newInitialStock" placeholder="0" /></div>
          <div class="inv-field"><label>Ubicación</label><input type="text" id="newLocation" placeholder="Ej: A-12-3" /></div>
        </div>
        <div id="createResult" style="margin-top:var(--space-3);min-height:1.5em;"></div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closeCreateModal()">Cancelar</button>
        <button class="btn btn--primary" onclick="createItem()">Crear Producto</button>
      </div>
    </div>
  </div>

  <!-- Purchase Modal -->
  <div class="inv-modal-overlay" id="purchaseModal">
    <div class="inv-modal">
      <div class="inv-modal__header">
        <h3>Registrar Compra / Entrada</h3>
        <button class="inv-modal__close" onclick="closePurchaseModal()">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div class="inv-form-grid">
          <div class="inv-field inv-field--full" style="position:relative;">
            <label>Producto *</label>
            <input type="hidden" id="purchaseItemId" />
            <input type="text" id="purchaseItemSearch" placeholder="Escribe nombre, No. de parte o escanea código de barras..." autocomplete="off" />
            <div id="purchaseItemResults" style="position:absolute;left:0;right:0;top:100%;background:var(--color-bg-elevated);border:1px solid var(--color-border);border-radius:var(--radius-md);max-height:200px;overflow-y:auto;z-index:100;display:none;"></div>
            <div id="purchaseItemSelected" style="margin-top:var(--space-1);font-size:var(--text-caption);color:var(--color-text-secondary);"></div>
          </div>
          <div class="inv-field"><label>Cantidad *</label><input type="number" id="purchaseQty" placeholder="Cantidad" /></div>
          <div class="inv-field"><label>Costo Unitario *</label><input type="number" id="purchaseCost" step="0.01" placeholder="0.00" /></div>
          <div class="inv-field"><label>Factura Proveedor</label><input type="text" id="purchaseInvoice" placeholder="No. factura" /></div>
          <div class="inv-field inv-field--full"><label>Notas</label><input type="text" id="purchaseNotes" placeholder="Notas adicionales" /></div>
        </div>
        <div id="purchaseResult" style="margin-top:var(--space-3);min-height:1.5em;"></div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closePurchaseModal()">Cancelar</button>
        <button class="btn btn--primary" onclick="recordPurchase()">Registrar Compra</button>
      </div>
    </div>
  </div>

  <!-- Transfer Modal -->
  <div class="inv-modal-overlay" id="transferModal">
    <div class="inv-modal">
      <div class="inv-modal__header">
        <h3>Nuevo Traspaso</h3>
        <button class="inv-modal__close" onclick="closeTransferModal()">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div class="inv-form-grid">
          <div class="inv-field"><label>ID Producto *</label><input type="number" id="transferItemId" placeholder="ID inventario" /></div>
          <div class="inv-field"><label>Cantidad *</label><input type="number" id="transferQty" placeholder="Cantidad" /></div>
          <div class="inv-field"><label>Sucursal Origen *</label><input type="number" id="transferFrom" placeholder="ID sucursal origen" /></div>
          <div class="inv-field"><label>Sucursal Destino *</label><input type="number" id="transferTo" placeholder="ID sucursal destino" /></div>
          <div class="inv-field inv-field--full"><label>Notas</label><input type="text" id="transferNotes" placeholder="Notas adicionales" /></div>
        </div>
        <div id="transferResult" style="margin-top:var(--space-3);min-height:1.5em;"></div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closeTransferModal()">Cancelar</button>
        <button class="btn btn--primary" onclick="recordTransfer()">Registrar Traspaso</button>
      </div>
    </div>
  </div>

  <!-- Adjustment Modal -->
  <div class="inv-modal-overlay" id="adjustmentModal">
    <div class="inv-modal">
      <div class="inv-modal__header">
        <h3>Nuevo Ajuste</h3>
        <button class="inv-modal__close" onclick="closeAdjustmentModal()">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div class="inv-form-grid">
          <div class="inv-field"><label>ID Producto *</label><input type="number" id="adjustItemId" placeholder="ID inventario" /></div>
          <div class="inv-field"><label>Cantidad * (negativo=salida)</label><input type="number" id="adjustQty" placeholder="Ej: -3 o +5" /></div>
          <div class="inv-field inv-field--full"><label>Razón / Motivo *</label><input type="text" id="adjustReason" placeholder="Motivo del ajuste (obligatorio)" /></div>
        </div>
        <div id="adjustResult" style="margin-top:var(--space-3);min-height:1.5em;"></div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closeAdjustmentModal()">Cancelar</button>
        <button class="btn btn--primary" onclick="recordAdjustment()">Registrar Ajuste</button>
      </div>
    </div>
  </div>

  <!-- Physical Count Modal -->
  <div class="inv-modal-overlay" id="countModal">
    <div class="inv-modal inv-modal--wide">
      <div class="inv-modal__header">
        <h3>Conteo Físico</h3>
        <button class="inv-modal__close" onclick="closeCountModal()">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div id="countLines"></div>
        <button class="btn btn--ghost btn--sm" onclick="addCountLine()" style="margin-top:var(--space-2);">+ Agregar Línea</button>
        <div id="countResults" style="margin-top:var(--space-4);"></div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closeCountModal()">Cerrar</button>
        <button class="btn btn--primary" onclick="startPhysicalCount()">Iniciar Conteo</button>
      </div>
    </div>
  </div>

  <!-- History Modal -->
  <div class="inv-modal-overlay" id="historyModal">
    <div class="inv-modal inv-modal--wide">
      <div class="inv-modal__header">
        <h3>Historial de Movimientos</h3>
        <button class="inv-modal__close" onclick="closeHistoryModal()">&times;</button>
      </div>
      <div class="inv-modal__body" id="historyContent">
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closeHistoryModal()">Cerrar</button>
      </div>
    </div>
  </div>

  <!-- Tier Discounts Modal -->
  <div class="inv-modal-overlay" id="tierDiscountModal">
    <div class="inv-modal">
      <div class="inv-modal__header">
        <h3>Descuentos por Tipo de Cliente</h3>
        <button class="inv-modal__close" onclick="closeTierDiscountModal()">&times;</button>
      </div>
      <div class="inv-modal__body">
        <p style="font-size:var(--text-caption);color:var(--color-text-muted);margin-bottom:var(--space-4);">Estos descuentos se aplican automáticamente a todos los productos al calcular precios de Taller y Mayoreo.</p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
          <div class="inv-field"><label>Descuento Taller (%)</label><input type="number" id="tierDisc2" step="0.1" min="0" max="100" placeholder="15" /></div>
          <div class="inv-field"><label>Descuento Mayoreo (%)</label><input type="number" id="tierDisc3" step="0.1" min="0" max="100" placeholder="25" /></div>
        </div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closeTierDiscountModal()">Cancelar</button>
        <button class="btn btn--primary" onclick="saveTierDiscounts()">Guardar</button>
      </div>
    </div>
  </div>

  <!-- ══════════ Publicar en MercadoLibre Modal ══════════ -->
  <div class="inv-modal-overlay" id="meliPublishModal">
    <div class="inv-modal inv-modal--wide">
      <div class="inv-modal__header">
        <h3>Publicar en MercadoLibre</h3>
        <button class="inv-modal__close" onclick="closeMeliPublishModal()">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div id="meliPublishSelectedCount" style="font-size:var(--text-caption);color:var(--color-text-muted);margin-bottom:var(--space-3);">0 productos seleccionados</div>

        <!-- Pre-flight checks & editable preview -->
        <div id="meliPublishItemsPreview" style="max-height:320px;overflow-y:auto;margin-bottom:var(--space-4);">
          <p style="color:var(--color-text-muted);font-size:var(--text-caption);">Cargando preview...</p>
        </div>

        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:var(--space-4);">
          <div class="inv-field">
            <label>Categoría ML *</label>
            <div style="position:relative;">
              <input type="text" id="meliCategorySearch" placeholder="Buscar categoría..." oninput="searchMeliCategories()" onkeydown="handleMeliCatKeydown(event)" autocomplete="off" />
              <div id="meliCategoryResults"></div>
            </div>
            <input type="hidden" id="meliCategoryId" />
          </div>
          <div class="inv-field">
            <label>Tipo de Publicación</label>
            <select id="meliListingType">
              <option value="gold_special">Gold Special</option>
              <option value="gold_pro">Gold Pro</option>
              <option value="bronze">Bronce (gratis)</option>
            </select>
          </div>
          <div class="inv-field">
            <label>Modo de Envío</label>
            <select id="meliShippingMode" onchange="onMeliShippingChange()">
              <option value="me2" selected>MercadoEnvíos (me2)</option>
              <option value="custom">Propio (custom)</option>
              <option value="not_specified">No especificado</option>
            </select>
            <small style="color:var(--color-text-muted);font-size:var(--text-caption);">Si no puedes activar ME1/ME2 en ML, prueba 'Propio' o 'No especificado'.</small>
          </div>
          <div class="inv-field" id="meliShippingCostField" style="display:none;">
            <label>Costo de Envío (MXN)</label>
            <input type="number" id="meliShippingCost" value="150" min="0" step="1" />
          </div>
          <div class="inv-field" style="display:flex;align-items:center;gap:8px;margin-top:var(--space-2);">
            <input type="checkbox" id="meliSkipValidate" style="width:auto;height:auto;" />
            <label for="meliSkipValidate" style="margin:0;font-size:var(--text-caption);color:var(--color-text-muted);text-transform:none;">Saltear validación y publicar directamente (si la validación falla por config de cuenta)</label>
          </div>
        </div>

        <!-- Dynamic required attributes section -->
        <div id="meliAttrsSection" style="display:none;">
          <div class="meli-attrs-section">
            <strong style="font-size:var(--text-body-sm);">Atributos requeridos para esta categoría</strong>
            <div id="meliAttrsGrid" class="meli-attrs-grid"></div>
          </div>
        </div>

        <div id="meliPublishResult" style="min-height:1.5em;margin-top:var(--space-3);"></div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="closeMeliPublishModal()">Cancelar</button>
        <button class="btn btn--secondary" id="meliValidateBtn" onclick="validateMeliPublish()">Validar con ML</button>
        <button class="btn btn--meli" id="meliPublishBtn" onclick="executeMeliPublish()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg> Publicar</button>
      </div>
    </div>
  </div>

  <!-- ══════════ Product Timeline Modal ══════════ -->
  <div class="inv-modal-overlay" id="productTimelineModal">
    <div class="inv-modal inv-modal--wide">
      <div class="inv-modal__header">
        <h3>Timeline del Producto</h3>
        <button class="inv-modal__close" onclick="document.getElementById('productTimelineModal').classList.remove('is-open')">&times;</button>
      </div>
      <div class="inv-modal__body" id="productTimelineBody">
        <div class="timeline">
          <div class="timeline__item"><div class="timeline__dot"></div><div class="timeline__content"><div class="timeline__date">--</div><div class="timeline__title">Producto creado</div></div></div>
        </div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="document.getElementById('productTimelineModal').classList.remove('is-open')">Cerrar</button>
      </div>
    </div>
  </div>

  <!-- ══════════ Image Comparator Modal ══════════ -->
  <div class="inv-modal-overlay" id="imageCompareModal">
    <div class="inv-modal">
      <div class="inv-modal__header">
        <h3>Comparar Imágenes</h3>
        <button class="inv-modal__close" onclick="document.getElementById('imageCompareModal').classList.remove('is-open')">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div class="img-compare" id="imgCompareContainer" style="max-height:400px;">
          <img class="img-compare__img" src="" id="imgCompareNew" alt="Nueva" />
          <div class="img-compare__overlay">
            <img src="" id="imgCompareOld" alt="Anterior" />
          </div>
          <div class="img-compare__handle">↔</div>
        </div>
      </div>
    </div>
  </div>

  <!-- ══════════ Ticket Preview Modal ══════════ -->
  <div class="inv-modal-overlay" id="ticketPreviewModal">
    <div class="inv-modal" style="max-width:400px;">
      <div class="inv-modal__header">
        <h3>Vista previa del ticket</h3>
        <button class="inv-modal__close" onclick="document.getElementById('ticketPreviewModal').classList.remove('is-open')">&times;</button>
      </div>
      <div class="inv-modal__body" id="ticketPreviewBody">
        <!-- Populated by JS -->
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="document.getElementById('ticketPreviewModal').classList.remove('is-open')">Cerrar</button>
        <button class="btn btn--primary" onclick="window.print()">Imprimir</button>
      </div>
    </div>
  </div>

  <!-- ══════════ Bulk Import Modal ══════════ -->
  <div class="inv-modal-overlay" id="bulkImportModal">
    <div class="inv-modal" style="max-width:520px;">
      <div class="inv-modal__header">
        <h3>Importar Productos Masivamente</h3>
        <button class="inv-modal__close" onclick="document.getElementById('bulkImportModal').classList.remove('is-open')">&times;</button>
      </div>
      <div class="inv-modal__body">
        <div style="margin-bottom:12px;">
          <label style="display:block;margin-bottom:4px;font-size:var(--text-caption);color:var(--color-text-muted);">Archivo CSV o Excel</label>
          <input type="file" id="bulkImportFile" accept=".csv,.xlsx,.xls" style="width:100%;padding:8px;border:1px dashed var(--color-border);border-radius:6px;background:var(--color-surface);color:var(--color-text);" />
        </div>
        <div style="margin-bottom:12px;">
          <label style="display:block;margin-bottom:4px;font-size:var(--text-caption);color:var(--color-text-muted);">Modo de importación</label>
          <select id="bulkImportMode" class="select-filter" style="width:100%;">
            <option value="strict">Estricto — abortar al primer error</option>
            <option value="lenient" selected>Permisivo — saltar filas con error</option>
          </select>
        </div>
        <div style="margin-bottom:12px;">
          <label style="display:block;margin-bottom:4px;font-size:var(--text-caption);color:var(--color-text-muted);">Compatibilidad de vehículo faltante</label>
          <select id="bulkImportStrategy" class="select-filter" style="width:100%;">
            <option value="qwen" selected>Auto-generar con IA (QWEN)</option>
            <option value="skip">Omitir compatibilidad</option>
            <option value="reject">Rechazar filas sin compatibilidad</option>
          </select>
        </div>
        <div style="font-size:var(--text-caption);color:var(--color-text-muted);background:var(--color-surface);padding:10px;border-radius:6px;">
          <strong>Columnas esperadas:</strong>
          <code style="display:block;margin-top:4px;word-break:break-all;">sku, name, brand, price, stock, cost, location, description, category, make, model, year, engine, engine_code</code>
          <span style="display:block;margin-top:4px;">También se aceptan sinónimos en español: <em>numero_de_parte, nombre, marca, precio, cantidad, costo, ubicacion, categoria, fabricante, modelo, anio, motor, codigo_motor</em></span>
        </div>
        <div id="bulkImportResult" style="margin-top:12px;display:none;"></div>
      </div>
      <div class="inv-modal__footer">
        <button class="btn btn--ghost" onclick="document.getElementById('bulkImportModal').classList.remove('is-open')">Cancelar</button>
        <button class="btn btn--primary" onclick="submitBulkImport()">Importar</button>
      </div>
    </div>
  </div>

  <!-- Offline Banner -->
  <div id="offlineBanner" class="banner banner--warning" style="display:none;position:fixed;top:0;left:0;right:0;z-index:9999;border-radius:0;animation:none;">
    <span class="banner__icon"></span>
    <span class="banner__text" id="offlineBannerText"><strong>Modo offline</strong> — Funciones limitadas. Solo consultas en cache disponibles.</span>
    <button class="banner__dismiss" onclick="document.getElementById('offlineBanner').style.display='none'" aria-label="Cerrar">&times;</button>
  </div>

  <script src="/pos/static/js/i18n.js" defer></script>
  <script src="/pos/static/js/app-init.js" defer></script>
  <script src="/pos/static/js/splash-loader.js?v=33" defer></script>
  <script src="/pos/static/js/pos-utils.js?v=33" defer></script>
  <script src="/pos/static/js/sidebar.js" defer></script>
  <script src="/pos/static/js/virtual-scroll.js?v=33" defer></script>
  <script src="/pos/static/js/inventory.js?v=33" defer></script>
  <script src="/pos/static/js/offline-banner.js" defer></script>
  <script src="/pos/static/js/sync-engine.js" defer></script>
  <script>if('serviceWorker' in navigator){navigator.serviceWorker.register('/pos/sw.js',{scope:'/pos/'});}</script>
  <script src="/pos/static/js/pwa-install.js" defer></script>
  <script src="/pos/static/js/chat.js" defer></script>
  <script>
    // Load inventory stats for tab badges
    async function loadInventoryStats() {
      try {
        const token = localStorage.getItem('pos_token');
        if (!token) return;
        const res = await fetch('/pos/api/inventory/stats', {
          headers: { 'Authorization': 'Bearer ' + token }
        });
        if (!res.ok) return;
        const data = await res.json();
        const map = {
          'badge-stock': data.stock,
          'badge-entradas': data.entradas,
          'badge-salidas': data.salidas,
          'badge-traspasos': data.traspasos,
          'badge-ajustes': data.ajustes,
          'badge-conteos': data.conteos,
          'badge-alertas': data.alertas
        };
        for (const [id, value] of Object.entries(map)) {
          const el = document.getElementById(id);
          if (el) el.textContent = value || 0;
        }
      } catch (e) {
        console.error('Failed to load inventory stats:', e);
      }
    }
    window.loadInventoryStats = loadInventoryStats;
    loadInventoryStats();
  </script>
</body>
</html>
