<!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>Facturación CFDI — 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/invoicing.css"></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 class="theme-bar__sep"></div>
      <span class="theme-bar__label" id="live-clock">--:--:--</span>
    </div>
    <div class="theme-bar__right">
      <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/dashboard">
          <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" href="/pos/inventory">
          <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/workshop">
          <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.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
          </svg>
          <span>Taller</span>
        </a>

        <a class="nav-item is-active" href="/pos/invoicing" 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="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>

        <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">Gestión</span>
          <h1 class="page-header__title">Facturación CFDI</h1>
        </div>
        <div class="page-header__actions">
          <button class="btn btn--ghost" onclick="openInvoiceFilters(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>
          <button class="btn btn--ghost" onclick="exportVisibleTableCSV('facturacion')">
            <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>
          <script>
          function openInvoiceFilters(btn) {
              var table = document.querySelector('table');
              if (!table) { showToast('Carga las facturas primero', 'warn'); return; }
              var ths = table.querySelectorAll('thead th');
              var colMap = {};
              ths.forEach(function(th, i) {
                  var t = th.textContent.trim().toLowerCase();
                  if (t.indexOf('status') !== -1 || t.indexOf('estado') !== -1) colMap.status = i;
                  if (t.indexOf('cliente') !== -1 || t.indexOf('receptor') !== -1) colMap.cliente = i;
                  if (t.indexOf('tipo') !== -1) colMap.tipo = i;
              });
              var filters = [];
              if (colMap.status !== undefined) filters.push({label:'Estado', column: colMap.status, values: getUniqueColumnValues(table, colMap.status)});
              if (colMap.tipo !== undefined) filters.push({label:'Tipo', column: colMap.tipo, values: getUniqueColumnValues(table, colMap.tipo)});
              if (colMap.cliente !== undefined) filters.push({label:'Cliente', column: colMap.cliente, values: getUniqueColumnValues(table, colMap.cliente, 15)});
              if (filters.length === 0) {
                  for (var i = 1; i < Math.min(3, ths.length); i++) {
                      filters.push({label: ths[i].textContent.trim(), column: i, values: getUniqueColumnValues(table, i)});
                  }
              }
              toggleFilterPanel(btn, filters);
          }
          </script>
          <button class="btn btn--secondary" onclick="showToast('Nota de Crédito requiere integración SAT — disponible en siguiente actualización', 'info')">
            <svg viewBox="0 0 24 24">
              <path d="M9 14l-4-4 4-4"/>
              <path d="M5 10h11a4 4 0 0 1 0 8h-1"/>
            </svg>
            Nota de Crédito
          </button>
          <button class="btn btn--primary" onclick="window.showNewInvoiceModal()">
            <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 Factura
          </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="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"/>
            </svg>
          </div>
          <div class="summary-card__body">
            <div class="summary-card__label">Facturas del Mes</div>
            <div class="summary-card__value" id="inv-total-count">0</div>
            <div class="summary-card__delta summary-card__delta--up">+18 vs mes anterior</div>
          </div>
        </div>

        <div class="summary-card">
          <div class="summary-card__icon summary-card__icon--money">
            <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">Monto Facturado</div>
            <div class="summary-card__value" id="inv-total-billed">$0</div>
            <div class="summary-card__sub">MXN · Mes en curso</div>
          </div>
        </div>

        <div class="summary-card">
          <div class="summary-card__icon summary-card__icon--pending">
            <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">Pendientes de Pago</div>
            <div class="summary-card__value" id="inv-pending">0</div>
            <div class="summary-card__sub">Facturas por cobrar</div>
          </div>
        </div>

        <div class="summary-card">
          <div class="summary-card__icon summary-card__icon--cancelled">
            <svg viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10"/>
              <line x1="15" y1="9" x2="9" y2="15"/>
              <line x1="9" y1="9" x2="15" y2="15"/>
            </svg>
          </div>
          <div class="summary-card__body">
            <div class="summary-card__label">Canceladas</div>
            <div class="summary-card__value" id="inv-cancelled">0</div>
            <div class="summary-card__sub">Este mes</div>
          </div>
        </div>

      </div>

      <!-- Tabs Row -->
      <div class="tabs-row" role="tablist" aria-label="Módulos de Facturación">
        <button class="tab-btn is-active" role="tab" aria-selected="true"  aria-controls="panel-facturas"     id="tab-facturas"     onclick="switchTab('facturas')">
          Facturas <span class="tab-btn__badge" id="badge-facturas">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-notas"        id="tab-notas"        onclick="switchTab('notas')">
          Notas de Crédito <span class="tab-btn__badge" id="badge-notas-credito">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-complementos" id="tab-complementos" onclick="switchTab('complementos')">
          Complementos de Pago <span class="tab-btn__badge" id="badge-complementos">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-cancelaciones" id="tab-cancelaciones" onclick="switchTab('cancelaciones')">
          Cancelaciones <span class="tab-btn__badge tab-btn__badge--warn" id="badge-cancelaciones">0</span>
        </button>
        <button class="tab-btn" role="tab" aria-selected="false" aria-controls="panel-config"       id="tab-config"       onclick="switchTab('config')">
          Configuración CFDI
        </button>
      </div>

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

        <!-- =================================================================
             TAB 1 — FACTURAS
             ================================================================= -->
        <div class="tab-panel is-active" id="panel-facturas" role="tabpanel" aria-labelledby="tab-facturas">

          <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 id="facturas-search" type="text" placeholder="Buscar folio, RFC, cliente…" oninput="Invoicing.filterFacturas()" aria-label="Buscar facturas" />
            </div>

            <select id="facturas-status-filter" class="select-filter" aria-label="Filtrar por estatus" onchange="Invoicing.loadFacturas()">
              <option value="">Todas</option>
              <option value="stamped">Timbradas</option>
              <option value="pending">Pendientes</option>
              <option value="cancelled">Canceladas</option>
            </select>

            <div class="toolbar__spacer"></div>

            <button class="btn btn--primary" onclick="Invoicing.openGlobalInvoiceModal()">
              <svg viewBox="0 0 24 24" style="width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2;">
                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                <line x1="16" y1="2" x2="16" y2="6"/>
                <line x1="8" y1="2" x2="8" y2="6"/>
                <line x1="3" y1="10" x2="21" y2="10"/>
              </svg>
              Factura Global
            </button>

            <button id="facturas-export-csv" class="btn btn--ghost" onclick="Invoicing.exportFacturasCSV()">
              <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>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio</th>
                  <th>Serie</th>
                  <th>Cliente</th>
                  <th>RFC</th>
                  <th style="text-align:right;">Subtotal</th>
                  <th style="text-align:right;">IVA</th>
                  <th style="text-align:right;">Total</th>
                  <th>Uso CFDI</th>
                  <th>Estatus</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><!-- /panel-facturas -->

        <!-- =================================================================
             TAB 2 — NOTAS DE CRÉDITO
             ================================================================= -->
        <div class="tab-panel" id="panel-notas" role="tabpanel" aria-labelledby="tab-notas">

          <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 nota de crédito…" aria-label="Buscar notas de credito" />
            </div>
            <div class="toolbar__spacer"></div>
            <button id="notas-export-csv" class="btn btn--ghost" onclick="Invoicing.exportNotasCSV()">
              <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
            </button>
            <button id="notas-new" class="btn btn--primary" onclick="Invoicing.newCreditNote()">
              <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 Nota de Crédito
            </button>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio NC</th>
                  <th>Factura Relacionada</th>
                  <th>Cliente</th>
                  <th>Motivo</th>
                  <th style="text-align:right;">Monto</th>
                  <th>Estatus</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><!-- /panel-notas -->

        <!-- =================================================================
             TAB 3 — COMPLEMENTOS DE PAGO
             ================================================================= -->
        <div class="tab-panel" id="panel-complementos" role="tabpanel" aria-labelledby="tab-complementos">

          <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 complemento de pago…" aria-label="Buscar complementos de pago" />
            </div>
            <select id="complementos-method-filter" class="select-filter" aria-label="Método de pago" onchange="Invoicing.loadComplementos()">
              <option value="">Todos los métodos</option>
              <option value="03">03 Transferencia electrónica</option>
              <option value="04">04 Tarjeta de crédito</option>
              <option value="28">28 Tarjeta de débito</option>
              <option value="01">01 Efectivo</option>
              <option value="99">99 Por definir</option>
            </select>
            <div class="toolbar__spacer"></div>
            <button id="complementos-new" class="btn btn--primary" onclick="Invoicing.newPaymentComplement()">
              <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 Complemento
            </button>
          </div>

          <div class="table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>Folio CP</th>
                  <th>Facturas</th>
                  <th>Cliente</th>
                  <th style="text-align:right;">Monto Pagado</th>
                  <th>Método Pago</th>
                  <th>Fecha</th>
                  <th>Estatus</th>
                  <th>Acciones</th>
                </tr>
              </thead>
              <tbody>
                <!-- Populated by JS -->
              </tbody>
            </table>

            <div class="table-footer">
              <span></span>
              <div class="pagination" id="complementos-pagination"></div>
            </div>
          </div>
        </div><!-- /panel-complementos -->

        <!-- =================================================================
             TAB 4 — CANCELACIONES
             ================================================================= -->
        <div class="tab-panel" id="panel-cancelaciones" role="tabpanel" aria-labelledby="tab-cancelaciones">

          <div class="section-heading">
            <span class="section-heading__title">Solicitudes de Cancelación SAT — Marzo 2026</span>
            <span class="section-heading__line"></span>
            <button class="btn btn--ghost btn--sm">
              <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>
              Actualizar estatus
            </button>
          </div>

          <div class="cancel-grid">

            <div class="cancel-card cancel-card--proceso">
              <div class="cancel-card__header">
                <span class="cancel-card__folio">NAP-001290</span>
                <span class="badge badge--proceso">En proceso</span>
              </div>
              <div class="cancel-card__body">
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Cliente</span>
                  <span class="cancel-card__row-value">Flotillas Logísticas Monterrey</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">RFC</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-size:0.8rem;">FLM8710234KL9</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Motivo</span>
                  <span class="cancel-card__row-value">02 — Comprobante emitido con errores sin relación</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Monto</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-weight:600;color:var(--color-text-primary);">$9,152.40 MXN</span>
                </div>
              </div>
              <div class="cancel-card__footer">
                <span style="font-size:var(--text-caption);color:var(--color-text-muted);">Solicitada: 31/03/2026 08:20</span>
                <button class="btn btn--ghost btn--sm">Ver detalle</button>
              </div>
            </div>

            <div class="cancel-card cancel-card--proceso">
              <div class="cancel-card__header">
                <span class="cancel-card__folio">NAP-001285</span>
                <span class="badge badge--proceso">En proceso</span>
              </div>
              <div class="cancel-card__body">
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Cliente</span>
                  <span class="cancel-card__row-value">Refaccionaria El Piston SC</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">RFC</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-size:0.8rem;">REP9305077HG5</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Motivo</span>
                  <span class="cancel-card__row-value">01 — Comprobante emitido con errores con relación</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Monto</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-weight:600;color:var(--color-text-primary);">$6,148.00 MXN</span>
                </div>
              </div>
              <div class="cancel-card__footer">
                <span style="font-size:var(--text-caption);color:var(--color-text-muted);">Solicitada: 30/03/2026 11:42</span>
                <button class="btn btn--ghost btn--sm">Ver detalle</button>
              </div>
            </div>

            <div class="cancel-card cancel-card--aceptada">
              <div class="cancel-card__header">
                <span class="cancel-card__folio">NAP-001260</span>
                <span class="badge badge--aceptada">Aceptada SAT</span>
              </div>
              <div class="cancel-card__body">
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Cliente</span>
                  <span class="cancel-card__row-value">Servicio Exprés Autopartes</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">RFC</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-size:0.8rem;">SEA020819PP3</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Motivo</span>
                  <span class="cancel-card__row-value">02 — Comprobante emitido con errores sin relación</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Monto</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-weight:600;color:var(--color-text-primary);">$2,320.00 MXN</span>
                </div>
              </div>
              <div class="cancel-card__footer">
                <span style="font-size:var(--text-caption);color:var(--color-text-muted);">Aceptada: 28/03/2026 09:15</span>
                <button class="btn btn--ghost btn--sm">Ver detalle</button>
              </div>
            </div>

            <div class="cancel-card cancel-card--aceptada">
              <div class="cancel-card__header">
                <span class="cancel-card__folio">NAP-001210</span>
                <span class="badge badge--aceptada">Aceptada SAT</span>
              </div>
              <div class="cancel-card__body">
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Cliente</span>
                  <span class="cancel-card__row-value">Grupo Automotriz Torres e Hijos</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">RFC</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-size:0.8rem;">GAT7612098DF2</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Motivo</span>
                  <span class="cancel-card__row-value">04 — Operación nominativa relacionada en factura global</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Monto</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-weight:600;color:var(--color-text-primary);">$14,900.00 MXN</span>
                </div>
              </div>
              <div class="cancel-card__footer">
                <span style="font-size:var(--text-caption);color:var(--color-text-muted);">Aceptada: 21/03/2026 10:05</span>
                <button class="btn btn--ghost btn--sm">Ver detalle</button>
              </div>
            </div>

            <div class="cancel-card cancel-card--rechazada">
              <div class="cancel-card__header">
                <span class="cancel-card__folio">NAP-001243</span>
                <span class="badge badge--rechazada">Rechazada SAT</span>
              </div>
              <div class="cancel-card__body">
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Cliente</span>
                  <span class="cancel-card__row-value">Taller Mecánico Ramírez</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">RFC</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-size:0.8rem;">TMR8402156HJ</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Motivo</span>
                  <span class="cancel-card__row-value">03 — No se llevó a cabo la operación</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Monto</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-weight:600;color:var(--color-text-primary);">$4,560.00 MXN</span>
                </div>
              </div>
              <div class="cancel-card__footer">
                <span style="font-size:var(--text-caption);color:var(--color-text-muted);">Rechazada: 25/03/2026 16:30</span>
                <button class="btn btn--ghost btn--sm">Ver detalle</button>
              </div>
            </div>

            <div class="cancel-card cancel-card--rechazada">
              <div class="cancel-card__header">
                <span class="cancel-card__folio">NAP-001198</span>
                <span class="badge badge--rechazada">Rechazada SAT</span>
              </div>
              <div class="cancel-card__body">
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Cliente</span>
                  <span class="cancel-card__row-value">Distribuidora Automotriz del Norte SA de CV</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">RFC</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-size:0.8rem;">DAN950312AB7</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Motivo</span>
                  <span class="cancel-card__row-value">01 — Comprobante emitido con errores con relación</span>
                </div>
                <div class="cancel-card__row">
                  <span class="cancel-card__row-label">Monto</span>
                  <span class="cancel-card__row-value" style="font-family:var(--font-mono);font-weight:600;color:var(--color-text-primary);">$31,248.00 MXN</span>
                </div>
              </div>
              <div class="cancel-card__footer">
                <span style="font-size:var(--text-caption);color:var(--color-text-muted);">Rechazada: 18/03/2026 14:45</span>
                <button class="btn btn--ghost btn--sm">Ver detalle</button>
              </div>
            </div>

          </div>
        </div><!-- /panel-cancelaciones -->

        <!-- =================================================================
             TAB 5 — CONFIGURACIÓN CFDI
             ================================================================= -->
        <div class="tab-panel" id="panel-config" role="tabpanel" aria-labelledby="tab-config">

          <div class="config-grid">

            <!-- DATOS FISCALES DEL EMISOR -->
            <div class="config-section">
              <div class="config-section__header">
                <svg viewBox="0 0 24 24">
                  <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
                  <polyline points="9 22 9 12 15 12 15 22"/>
                </svg>
                <span class="config-section__title">Datos Fiscales del Emisor</span>
              </div>
              <div class="config-section__body">
                <div class="form-grid">

                  <div class="form-field">
                    <label class="form-label" for="rfc-emisor">RFC Emisor</label>
                    <input class="form-input" id="rfc-emisor" type="text" value="NAP960714JK3" style="font-family:var(--font-mono);" />
                    <span class="form-hint">RFC registrado ante el SAT</span>
                  </div>

                  <div class="form-field">
                    <label class="form-label" for="cp-fiscal">C.P. Fiscal</label>
                    <input class="form-input" id="cp-fiscal" type="text" value="64000" />
                    <span class="form-hint">Código postal del domicilio fiscal</span>
                  </div>

                  <div class="form-field form-field--span2">
                    <label class="form-label" for="razon-social">Razón Social</label>
                    <input class="form-input" id="razon-social" type="text" value="NEXUS AUTOPARTES SA DE CV" />
                  </div>

                  <div class="form-field form-field--span2">
                    <label class="form-label" for="regimen-fiscal">Régimen Fiscal</label>
                    <select class="form-select" id="regimen-fiscal">
                      <option selected>601 — General de Ley Personas Morales</option>
                      <option>603 — Personas Morales con Fines no Lucrativos</option>
                      <option>605 — Sueldos y Salarios e Ingresos Asimilados a Salarios</option>
                      <option>612 — Personas Físicas con Actividades Empresariales</option>
                      <option>621 — Incorporación Fiscal</option>
                      <option>626 — Régimen Simplificado de Confianza</option>
                    </select>
                    <span class="form-hint">Régimen del emisor según el SAT</span>
                  </div>

                </div>

                <div style="margin-top:var(--space-4);display:flex;justify-content:flex-end;gap:var(--space-3);">
                  <button class="btn btn--ghost">Cancelar</button>
                  <button class="btn btn--primary">
                    <svg viewBox="0 0 24 24">
                      <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/>
                      <polyline points="17 21 17 13 7 13 7 21"/>
                      <polyline points="7 3 7 8 15 8"/>
                    </svg>
                    Guardar Datos
                  </button>
                </div>
              </div>
            </div>

            <!-- CERTIFICADO DE SELLO DIGITAL -->
            <div class="config-section">
              <div class="config-section__header">
                <svg viewBox="0 0 24 24">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                </svg>
                <span class="config-section__title">Certificado de Sello Digital (CSD)</span>
              </div>
              <div class="config-section__body">

                <div class="cert-status" id="csd-status">
                  <div class="cert-status__icon">
                    <svg viewBox="0 0 24 24">
                      <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                      <polyline points="22 4 12 14.01 9 11.01"/>
                    </svg>
                  </div>
                  <div class="cert-status__info">
                    <div class="cert-status__name" id="csd-status-name">
                      CSD — Consultar estado en Facturapi
                    </div>
                    <div class="cert-status__detail" id="csd-status-detail">
                      El estado del certificado se muestra en la sección Facturapi (PAC).
                    </div>
                  </div>
                </div>

                <form id="csd-form" enctype="multipart/form-data">
                  <div class="form-grid">
                    <div class="form-field">
                      <label class="form-label">Archivo .cer</label>
                      <input type="file" id="csd-cer" name="certificate" accept=".cer" style="display:none;" />
                      <button type="button" class="btn btn--secondary" id="csd-cer-btn" style="width:100%;justify-content:center;" onclick="document.getElementById('csd-cer').click()">
                        <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>
                        <span id="csd-cer-label">Subir certificado .cer</span>
                      </button>
                      <span class="form-hint">Certificado público del SAT</span>
                    </div>

                    <div class="form-field">
                      <label class="form-label">Archivo .key</label>
                      <input type="file" id="csd-key" name="private_key" accept=".key" style="display:none;" />
                      <button type="button" class="btn btn--secondary" id="csd-key-btn" style="width:100%;justify-content:center;" onclick="document.getElementById('csd-key').click()">
                        <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>
                        <span id="csd-key-label">Subir llave privada .key</span>
                      </button>
                      <span class="form-hint">Llave privada del CSD</span>
                    </div>

                    <div class="form-field form-field--span2">
                      <label class="form-label" for="contrasena-csd">Contraseña del CSD</label>
                      <input class="form-input" id="contrasena-csd" name="password" type="password" placeholder="Contraseña de la llave privada" />
                      <span class="form-hint">Contraseña asignada al generar el CSD en el SAT</span>
                    </div>
                  </div>

                  <div style="margin-top:var(--space-4);display:flex;justify-content:flex-end;gap:var(--space-3);">
                    <button type="button" class="btn btn--ghost" onclick="Invoicing.resetCsdForm()">Cancelar</button>
                    <button type="button" class="btn btn--primary" id="csd-submit-btn" onclick="Invoicing.uploadCsd(this)">
                      <svg viewBox="0 0 24 24">
                        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                        <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                      </svg>
                      Actualizar CSD
                    </button>
                  </div>
                </form>
              </div>
            </div>

            <!-- FACTURAPI STATUS -->
            <div class="config-section" style="grid-column: span 2;">
              <div class="config-section__header">
                <svg viewBox="0 0 24 24">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                  <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                </svg>
                <span class="config-section__title">Facturapi (PAC)</span>
              </div>
              <div class="config-section__body" id="facturapi-status">
                <p style="color:var(--color-text-muted);">Cargando estado de Facturapi...</p>
              </div>
            </div>

            <!-- CONFIGURACIÓN DE SERIES — full width -->
            <div class="config-section" style="grid-column: span 2;">
              <div class="config-section__header">
                <svg viewBox="0 0 24 24">
                  <line x1="8" y1="6" x2="21" y2="6"/>
                  <line x1="8" y1="12" x2="21" y2="12"/>
                  <line x1="8" y1="18" x2="21" y2="18"/>
                  <line x1="3" y1="6" x2="3.01" y2="6"/>
                  <line x1="3" y1="12" x2="3.01" y2="12"/>
                  <line x1="3" y1="18" x2="3.01" y2="18"/>
                </svg>
                <span class="config-section__title">Configuración de Series de Folios</span>
                <button class="btn btn--ghost btn--sm">
                  <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 Serie
                </button>
              </div>
              <div class="config-section__body" style="padding:0;">
                <table class="data-table">
                  <thead>
                    <tr>
                      <th>Serie</th>
                      <th>Descripción</th>
                      <th>Folio Actual</th>
                      <th>Folio Inicial</th>
                      <th>Tipo CFDI</th>
                      <th style="text-align:center;">Predeterminada</th>
                      <th>Estatus</th>
                      <th>Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    <!-- Populated by JS -->
                  </tbody>
                </table>
              </div>
            </div>

          </div>
        </div><!-- /panel-config -->

      </div><!-- /tab-panels -->

    </main>

  </div><!-- /app-shell -->

  <!-- =========================================================================
       MODAL: DETALLE CFDI + XML PREVIEW
       ========================================================================= -->
  <div class="modal-overlay" id="modalDetalleOverlay" style="display:none; position:fixed; inset:0; z-index:var(--z-modal); background:var(--overlay-backdrop); display:none; align-items:center; justify-content:center;">
    <div class="modal-card" style="background:var(--color-bg-elevated); border:1px solid var(--color-border); border-radius:var(--radius-lg); width:720px; max-width:95vw; max-height:90vh; overflow:auto; box-shadow:var(--shadow-xl);">
      <div style="display:flex; align-items:center; justify-content:space-between; padding:var(--space-5) var(--space-6); border-bottom:1px solid var(--color-border);">
        <div>
          <div style="font-family:var(--font-heading); font-size:var(--text-h5); font-weight:var(--heading-weight-primary); color:var(--color-text-primary);">Detalle de Factura</div>
          <div style="font-size:var(--text-caption); color:var(--color-text-muted); margin-top:2px;">NAP-001289 — Timbrada</div>
        </div>
        <button onclick="document.getElementById('modalDetalleOverlay').style.display='none'" style="background:none; border:none; color:var(--color-text-muted); font-size:1.4rem; cursor:pointer; padding:var(--space-2);">✕</button>
      </div>
      <div style="padding:var(--space-5) var(--space-6);">
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:var(--space-4); margin-bottom:var(--space-6);">
          <div>
            <div style="font-size:var(--text-caption); color:var(--color-text-muted); text-transform:uppercase; letter-spacing:var(--tracking-widest); margin-bottom:var(--space-1);">Emisor</div>
            <div style="font-weight:var(--font-weight-semibold);">Nexus Autoparts SA de CV</div>
            <div style="font-family:var(--font-mono); font-size:var(--text-body-sm); color:var(--color-text-secondary);">NAP960714JK3</div>
          </div>
          <div>
            <div style="font-size:var(--text-caption); color:var(--color-text-muted); text-transform:uppercase; letter-spacing:var(--tracking-widest); margin-bottom:var(--space-1);">Receptor</div>
            <div style="font-weight:var(--font-weight-semibold);">Taller Mecánico Rodríguez</div>
            <div style="font-family:var(--font-mono); font-size:var(--text-body-sm); color:var(--color-text-secondary);">TMR8402156HJ</div>
          </div>
          <div>
            <div style="font-size:var(--text-caption); color:var(--color-text-muted); text-transform:uppercase; letter-spacing:var(--tracking-widest); margin-bottom:var(--space-1);">UUID</div>
            <div style="font-family:var(--font-mono); font-size:var(--text-caption); color:var(--color-text-accent); word-break:break-all;">6ba7b810-9dad-11d1-80b4-00c04fd430c8</div>
          </div>
          <div>
            <div style="font-size:var(--text-caption); color:var(--color-text-muted); text-transform:uppercase; letter-spacing:var(--tracking-widest); margin-bottom:var(--space-1);">Total</div>
            <div style="font-family:var(--font-mono); font-size:var(--text-h4); font-weight:var(--font-weight-bold); color:var(--color-text-primary);">$4,002.00</div>
          </div>
        </div>
        <!-- XML Preview -->
        <div style="font-size:var(--text-caption); color:var(--color-text-muted); text-transform:uppercase; letter-spacing:var(--tracking-widest); margin-bottom:var(--space-2);">Vista previa XML</div>
        <pre style="background:var(--color-surface-3); border:1px solid var(--color-border); border-radius:var(--radius-md); padding:var(--space-4); font-family:var(--font-mono); font-size:11px; color:var(--color-text-secondary); overflow-x:auto; max-height:200px; line-height:1.6;">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/4"
  Version="4.0" Serie="A" Folio="001289"
  Fecha="2026-03-31T14:22:00" FormaPago="01"
  SubTotal="3450.00" Moneda="MXN"
  Total="4002.00" TipoDeComprobante="I"
  MetodoPago="PUE" LugarExpedicion="64000"&gt;
  &lt;cfdi:Emisor Rfc="NAP960714JK3"
    Nombre="Nexus Autoparts SA de CV"
    RegimenFiscal="601"/&gt;
  &lt;cfdi:Receptor Rfc="TMR8402156HJ"
    Nombre="Taller Mecánico Rodríguez"
    UsoCFDI="G03" DomicilioFiscalReceptor="64000"
    RegimenFiscalReceptor="612"/&gt;
  &lt;cfdi:Conceptos&gt;
    &lt;cfdi:Concepto ClaveProdServ="25174800"
      Cantidad="4" ClaveUnidad="H87"
      Descripcion="Balatas delanteras TRW"
      ValorUnitario="485.00" Importe="1940.00"/&gt;
  &lt;/cfdi:Conceptos&gt;
&lt;/cfdi:Comprobante&gt;</pre>
      </div>
      <div style="display:flex; gap:var(--space-3); justify-content:flex-end; padding:var(--space-4) var(--space-6); border-top:1px solid var(--color-border);">
        <button style="padding:var(--space-2) var(--space-5); border:1px solid var(--color-border); border-radius:var(--radius-md); background:transparent; color:var(--color-text-primary); cursor:pointer; font-family:var(--font-body); font-size:var(--text-body-sm);">Descargar XML</button>
        <button style="padding:var(--space-2) var(--space-5); border:1px solid var(--color-border); border-radius:var(--radius-md); background:transparent; color:var(--color-text-primary); cursor:pointer; font-family:var(--font-body); font-size:var(--text-body-sm);">Descargar PDF</button>
        <button style="padding:var(--space-2) var(--space-5); border:1px solid var(--btn-danger-bg); border-radius:var(--radius-md); background:var(--btn-danger-bg); color:var(--btn-danger-text); cursor:pointer; font-family:var(--font-body); font-size:var(--text-body-sm); font-weight:var(--font-weight-semibold);" onclick="document.getElementById('modalDetalleOverlay').style.display='none'; document.getElementById('modalCancelOverlay').style.display='flex';">Cancelar CFDI</button>
      </div>
    </div>
  </div>

  <!-- =========================================================================
       MODAL: CANCELACIÓN CFDI — Selector Motivo SAT
       ========================================================================= -->
  <div class="modal-overlay" id="modalCancelOverlay" style="display:none; position:fixed; inset:0; z-index:var(--z-modal); background:var(--overlay-backdrop); display:none; align-items:center; justify-content:center;">
    <div class="modal-card" style="background:var(--color-bg-elevated); border:1px solid var(--color-border); border-radius:var(--radius-lg); width:520px; max-width:95vw; box-shadow:var(--shadow-xl);">
      <div style="display:flex; align-items:center; gap:var(--space-3); padding:var(--space-5) var(--space-6); border-bottom:1px solid var(--color-border);">
        <div style="width:40px; height:40px; border-radius:var(--radius-full); background:rgba(239,68,68,0.12); display:flex; align-items:center; justify-content:center; flex-shrink:0;">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--color-error)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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>
          <div style="font-family:var(--font-heading); font-size:var(--text-h5); font-weight:var(--heading-weight-primary); color:var(--color-text-primary);">Cancelar CFDI</div>
          <div style="font-size:var(--text-caption); color:var(--color-text-muted);">NAP-001289 — $4,002.00 MXN</div>
        </div>
        <button onclick="document.getElementById('modalCancelOverlay').style.display='none'" style="background:none; border:none; color:var(--color-text-muted); font-size:1.4rem; cursor:pointer; padding:var(--space-2); margin-left:auto;">✕</button>
      </div>
      <div style="padding:var(--space-5) var(--space-6);">
        <div style="font-size:var(--text-body-sm); font-weight:var(--font-weight-semibold); color:var(--color-text-primary); margin-bottom:var(--space-3);">Motivo de cancelación (SAT)</div>
        <div style="display:flex; flex-direction:column; gap:var(--space-2);">
          <label style="display:flex; align-items:flex-start; gap:var(--space-3); padding:var(--space-3) var(--space-4); border:1px solid var(--color-border); border-radius:var(--radius-md); cursor:pointer; transition:var(--transition-fast);" onmouseover="this.style.borderColor='var(--color-primary)'" onmouseout="this.style.borderColor='var(--color-border)'">
            <input type="radio" name="motivo-sat" value="01" style="margin-top:3px; accent-color:var(--color-primary);" checked>
            <div>
              <div style="font-weight:var(--font-weight-semibold); font-size:var(--text-body-sm);">01 — Comprobante emitido con errores con relación</div>
              <div style="font-size:var(--text-caption); color:var(--color-text-muted);">Se sustituirá por otro CFDI. Requiere UUID de reemplazo.</div>
            </div>
          </label>
          <label style="display:flex; align-items:flex-start; gap:var(--space-3); padding:var(--space-3) var(--space-4); border:1px solid var(--color-border); border-radius:var(--radius-md); cursor:pointer; transition:var(--transition-fast);" onmouseover="this.style.borderColor='var(--color-primary)'" onmouseout="this.style.borderColor='var(--color-border)'">
            <input type="radio" name="motivo-sat" value="02" style="margin-top:3px; accent-color:var(--color-primary);">
            <div>
              <div style="font-weight:var(--font-weight-semibold); font-size:var(--text-body-sm);">02 — Comprobante emitido con errores sin relación</div>
              <div style="font-size:var(--text-caption); color:var(--color-text-muted);">No se sustituirá por otro CFDI.</div>
            </div>
          </label>
          <label style="display:flex; align-items:flex-start; gap:var(--space-3); padding:var(--space-3) var(--space-4); border:1px solid var(--color-border); border-radius:var(--radius-md); cursor:pointer; transition:var(--transition-fast);" onmouseover="this.style.borderColor='var(--color-primary)'" onmouseout="this.style.borderColor='var(--color-border)'">
            <input type="radio" name="motivo-sat" value="03" style="margin-top:3px; accent-color:var(--color-primary);">
            <div>
              <div style="font-weight:var(--font-weight-semibold); font-size:var(--text-body-sm);">03 — No se llevó a cabo la operación</div>
              <div style="font-size:var(--text-caption); color:var(--color-text-muted);">La operación que amparó el CFDI no se realizó.</div>
            </div>
          </label>
          <label style="display:flex; align-items:flex-start; gap:var(--space-3); padding:var(--space-3) var(--space-4); border:1px solid var(--color-border); border-radius:var(--radius-md); cursor:pointer; transition:var(--transition-fast);" onmouseover="this.style.borderColor='var(--color-primary)'" onmouseout="this.style.borderColor='var(--color-border)'">
            <input type="radio" name="motivo-sat" value="04" style="margin-top:3px; accent-color:var(--color-primary);">
            <div>
              <div style="font-weight:var(--font-weight-semibold); font-size:var(--text-body-sm);">04 — Operación nominativa relacionada en una factura global</div>
              <div style="font-size:var(--text-caption); color:var(--color-text-muted);">Cancelar cuando la operación se desglosó en una factura global.</div>
            </div>
          </label>
        </div>
        <!-- UUID de reemplazo (solo para motivo 01) -->
        <div style="margin-top:var(--space-4);">
          <label style="font-size:var(--text-caption); color:var(--color-text-muted); text-transform:uppercase; letter-spacing:var(--tracking-widest); display:block; margin-bottom:var(--space-1);">UUID de CFDI sustituto (motivo 01)</label>
          <input type="text" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" style="width:100%; padding:var(--space-2) var(--space-3); border:1px solid var(--color-border); border-radius:var(--radius-md); background:var(--color-surface-2); color:var(--color-text-primary); font-family:var(--font-mono); font-size:var(--text-body-sm);">
        </div>
      </div>
      <div style="display:flex; gap:var(--space-3); justify-content:flex-end; padding:var(--space-4) var(--space-6); border-top:1px solid var(--color-border);">
        <button onclick="document.getElementById('modalCancelOverlay').style.display='none'" style="padding:var(--space-2) var(--space-5); border:1px solid var(--color-border); border-radius:var(--radius-md); background:transparent; color:var(--color-text-primary); cursor:pointer; font-family:var(--font-body); font-size:var(--text-body-sm);">Cancelar</button>
        <button onclick="document.getElementById('modalCancelOverlay').style.display='none'" style="padding:var(--space-2) var(--space-5); border:1px solid var(--btn-danger-bg); border-radius:var(--radius-md); background:var(--btn-danger-bg); color:var(--btn-danger-text); cursor:pointer; font-family:var(--font-body); font-size:var(--text-body-sm); font-weight:var(--font-weight-semibold);">Solicitar Cancelación SAT</button>
      </div>
    </div>
  </div>

  <!-- Nueva Factura Modal -->
  <div id="newInvoiceModalOverlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;align-items:center;justify-content:center;">
    <div style="background:var(--color-surface-1);border-radius:var(--radius-lg);width:min(480px,90vw);box-shadow:var(--shadow-lg);">
      <div style="padding:var(--space-5) var(--space-6);border-bottom:1px solid var(--color-border);display:flex;justify-content:space-between;align-items:center;">
        <div style="font-family:var(--font-heading);font-size:var(--text-h4);font-weight:var(--heading-weight-primary);">Nueva Factura</div>
        <button class="btn btn--ghost btn--sm" onclick="window.closeNewInvoiceModal()">&times;</button>
      </div>
      <div style="padding:var(--space-6);">
        <p style="font-size:var(--text-body-sm);color:var(--color-text-muted);margin-bottom:var(--space-4);">Ingrese el ID de la venta para generar el CFDI (Ingreso).</p>
        <div style="margin-bottom:var(--space-4);">
          <label style="display:block;font-size:var(--text-caption);color:var(--color-text-muted);margin-bottom:var(--space-1);text-transform:uppercase;letter-spacing:var(--tracking-widest);">ID de Venta</label>
          <input type="number" id="invoiceSaleId" placeholder="Ej: 1042" style="width:100%;padding:var(--space-2) var(--space-3);border:1px solid var(--color-border);border-radius:var(--radius-md);background:var(--color-surface-2);color:var(--color-text-primary);font-size:var(--text-body-sm);" />
        </div>
        <div id="invoiceResult" style="margin-bottom:var(--space-3);"></div>
      </div>
      <div style="padding:var(--space-4) var(--space-6);border-top:1px solid var(--color-border);display:flex;justify-content:flex-end;gap:var(--space-3);">
        <button class="btn btn--ghost" onclick="window.closeNewInvoiceModal()">Cancelar</button>
        <button class="btn btn--primary" onclick="window.submitNewInvoice()">Generar Factura</button>
      </div>
    </div>
  </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/invoicing.js?v=33" 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 invoicing stats for tab badges
    async function loadInvoicingStats() {
      const token = localStorage.getItem('pos_token') || '';
      try {
        const res = await fetch('/pos/api/invoicing/stats', {
          headers: token ? { 'Authorization': 'Bearer ' + token } : {}
        });
        if (!res.ok) return;
        const data = await res.json();
        const map = {
          'badge-facturas': data.facturas,
          'badge-notas-credito': data.notas_credito,
          'badge-complementos': data.complementos,
          'badge-cancelaciones': data.cancelaciones
        };
        Object.entries(map).forEach(function([id, val]) {
          const el = document.getElementById(id);
          if (el) el.textContent = val || 0;
        });
      } catch (e) {
        console.error('Failed to load invoicing stats:', e);
      }
    }
    window.loadInvoicingStats = loadInvoicingStats;
    loadInvoicingStats();
  </script>

  <!-- =====================================================================
       MODAL: FACTURA GLOBAL
       ===================================================================== -->
  <div class="modal-overlay" id="modalGlobalInvoice" style="display:none; position:fixed; inset:0; z-index:var(--z-modal); background:var(--overlay-backdrop); align-items:center; justify-content:center;">
    <div class="modal-card" style="background:var(--color-bg-elevated); border:1px solid var(--color-border); border-radius:var(--radius-lg); width:480px; max-width:95vw; box-shadow:var(--shadow-xl);">
      <div style="display:flex; align-items:center; justify-content:space-between; padding:var(--space-5) var(--space-6); border-bottom:1px solid var(--color-border);">
        <div>
          <div style="font-weight:var(--font-weight-semibold); font-size:var(--text-body-lg);">Generar Factura Global</div>
          <div style="font-size:var(--text-caption); color:var(--color-text-muted); margin-top:2px;">Agrupa ventas de contado no facturadas</div>
        </div>
        <button onclick="document.getElementById('modalGlobalInvoice').style.display='none'" style="background:none; border:none; color:var(--color-text-muted); font-size:1.4rem; cursor:pointer; padding:var(--space-2);">✕</button>
      </div>
      <div style="padding:var(--space-5) var(--space-6);">
        <div style="display:flex; gap:var(--space-3); margin-bottom:var(--space-4);">
          <div style="flex:1;">
            <label style="font-size:var(--text-caption); color:var(--color-text-muted); display:block; margin-bottom:var(--space-1);">Año</label>
            <input type="number" id="global-year" class="form-input" style="width:100%;" />
          </div>
          <div style="flex:1;">
            <label style="font-size:var(--text-caption); color:var(--color-text-muted); display:block; margin-bottom:var(--space-1);">Mes</label>
            <input type="number" id="global-month" class="form-input" style="width:100%;" min="1" max="12" />
          </div>
        </div>
        <div id="global-preview" style="background:var(--color-surface); border-radius:var(--radius-md); padding:var(--space-3); font-size:var(--text-caption); color:var(--color-text-muted);">
          Presiona "Vista previa" para ver ventas elegibles.
        </div>
      </div>
      <div style="display:flex; gap:var(--space-3); justify-content:flex-end; padding:var(--space-4) var(--space-6); border-top:1px solid var(--color-border);">
        <button onclick="document.getElementById('modalGlobalInvoice').style.display='none'" class="btn btn--ghost">Cancelar</button>
        <button onclick="Invoicing.previewGlobalInvoice()" class="btn btn--ghost">Vista previa</button>
        <button onclick="Invoicing.generateGlobalInvoice()" class="btn btn--primary">Generar</button>
      </div>
    </div>
  </div>
</body>
</html>
