<!DOCTYPE html>
<html lang="es" id="html-root">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{% block title %}ContaApp{% endblock %} — ContaApp</title>
  <!-- Aplicar tema antes de que carguen los estilos para evitar parpadeo -->
  <script>
    (function() {
      var t = localStorage.getItem('contaapp-theme');
      if (t === 'dark') document.documentElement.setAttribute('data-bs-theme', 'dark');
    })();
  </script>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    :root {
      --sb-w: 262px;
      --sb-bg: #0f1929;
      --sb-border: rgba(255,255,255,.09);
      --sb-hover: rgba(255,255,255,.08);
      --sb-active-bg: rgba(79,134,247,.2);
      --accent: #4f86f7;
      --page-bg: #f3f5fa;
    }

    *, *::before, *::after { box-sizing: border-box; }
    body {
      margin: 0;
      background: linear-gradient(150deg, #eef2ff 0%, #f3f5fa 45%, #f0fdf4 100%);
      background-attachment: fixed;
      font-family: 'Segoe UI', system-ui, sans-serif;
      color: #1e293b;
    }

    /* ─── SIDEBAR ─────────────────────────────── */
    #sidebar {
      position: fixed; inset: 0 auto 0 0;
      width: var(--sb-w); background: var(--sb-bg);
      display: flex; flex-direction: column;
      overflow-y: auto; overflow-x: hidden; z-index: 200;
      scrollbar-width: thin; scrollbar-color: rgba(255,255,255,.08) transparent;
      box-shadow: 4px 0 24px rgba(0,0,0,.18);
    }

    /* Brand */
    .sb-brand {
      padding: 20px 18px 16px; border-bottom: 1px solid var(--sb-border);
      display: flex; align-items: center; gap: 11px; text-decoration: none;
      flex-shrink: 0;
    }
    .sb-brand-icon {
      width: 38px; height: 38px; border-radius: 10px;
      background: linear-gradient(135deg,#4f86f7,#7c3aed);
      display: flex; align-items: center; justify-content: center; flex-shrink: 0;
      box-shadow: 0 4px 12px rgba(79,134,247,.5);
    }
    .sb-brand-icon i { color: #fff; font-size: 1.05rem; }
    .sb-brand .name { font-size: .95rem; font-weight: 700; color: #f1f5f9; letter-spacing: .3px; line-height: 1.2; }
    .sb-brand .sub  { font-size: .68rem; color: #7a9ab8; margin-top: 1px; }

    /* Section groups */
    .sb-group { padding: 6px 0; }
    .sb-group + .sb-group { border-top: 1px solid var(--sb-border); }

    /* Section toggle button */
    .sb-toggle {
      display: flex; align-items: center; justify-content: space-between;
      width: 100%; padding: 10px 18px 4px;
      border: none; background: none; cursor: pointer;
      font-size: .63rem; font-weight: 700; letter-spacing: 1.1px;
      text-transform: uppercase; color: #7a95b0;
    }
    .sb-toggle:hover { color: #a8bfd4; }
    .sb-toggle .sb-chevron { font-size: .7rem; transition: transform .22s ease; color: #7a95b0; }
    .sb-toggle[aria-expanded="false"] .sb-chevron { transform: rotate(-90deg); }

    /* Sidebar section label colors */
    [data-bs-target="#grp-fact"] span  { color: #60a5fa; }
    [data-bs-target="#grp-inv"]  span  { color: #34d399; }
    [data-bs-target="#grp-conta"] span { color: #fb923c; }
    [data-bs-target="#grp-cont"] span  { color: #c084fc; }
    [data-bs-target="#grp-anal"] span  { color: #38bdf8; }
    [data-bs-target="#grp-fisc"] span  { color: #f472b6; }
    [data-bs-target="#grp-vf"]   span  { color: #fb923c; }
    [data-bs-target="#grp-usr"]  span  { color: #a78bfa; }
    [data-bs-target="#grp-nom"]  span  { color: #34d399; }
    #grp-nom   .sb-link:not(.active) i { color: #34d399; }
    [data-bs-target="#grp-pgc"]  span  { color: #fbbf24; }
    #grp-pgc   .sb-link:not(.active) i { color: #fbbf24; }
    [data-bs-target="#grp-act"]  span  { color: #a3e635; }
    #grp-act   .sb-link:not(.active) i { color: #a3e635; }

    /* Nav links */
    .sb-link {
      display: flex; align-items: center; gap: 10px;
      padding: 8px 14px 8px 18px; margin: 1px 10px;
      border-radius: 8px; border-left: 3px solid transparent;
      color: #c2d4e8; font-size: .845rem; font-weight: 500;
      text-decoration: none; transition: background .14s, color .14s, border-color .14s;
    }
    .sb-link i { font-size: .9rem; width: 18px; text-align: center; flex-shrink: 0; transition: color .14s; }
    .sb-link:hover { background: var(--sb-hover); color: #f0f6ff; }
    .sb-link.active {
      background: var(--sb-active-bg); color: #fff; font-weight: 600;
      border-left-color: var(--accent);
      box-shadow: inset 0 0 0 1px rgba(79,134,247,.2);
    }
    .sb-link.active i { color: var(--accent); }

    /* Section-colored icons */
    #grp-fact  .sb-link:not(.active) i { color: #60a5fa; }
    #grp-inv   .sb-link:not(.active) i { color: #34d399; }
    #grp-conta .sb-link:not(.active) i { color: #fb923c; }
    #grp-cont  .sb-link:not(.active) i { color: #c084fc; }
    #grp-anal  .sb-link:not(.active) i { color: #38bdf8; }
    #grp-fisc  .sb-link:not(.active) i { color: #f472b6; }
    #grp-vf    .sb-link:not(.active) i { color: #fb923c; }
    #grp-usr   .sb-link:not(.active) i { color: #a78bfa; }

    /* Sub-links */
    .sb-subs { padding: 3px 0 6px 0; }
    .sb-sub {
      display: flex; align-items: center;
      padding: 6px 12px 6px 48px; margin: 2px 8px;
      border-radius: 8px;
      color: #8fafc8; font-size: .795rem; font-weight: 400;
      text-decoration: none; letter-spacing: .01em;
      transition: background .15s, color .15s;
      position: relative;
    }
    .sb-sub::before {
      content: '';
      position: absolute; left: 31px; top: 50%;
      width: 5px; height: 5px; border-radius: 50%;
      background: rgba(255,255,255,.25);
      transform: translateY(-50%);
      transition: background .15s, transform .15s;
    }
    .sb-sub:hover { background: rgba(255,255,255,.07); color: #c8dff0; }
    .sb-sub:hover::before { background: rgba(255,255,255,.5); transform: translateY(-50%) scale(1.3); }
    .sb-sub.active { background: rgba(79,134,247,.1); color: #7aabf5; font-weight: 500; }
    .sb-sub.active::before { background: #4f86f7; transform: translateY(-50%) scale(1.2); }

    /* Footer */
    .sb-footer { margin-top: auto; border-top: 1px solid var(--sb-border); padding: 6px 0 8px; }

    /* ─── MAIN ────────────────────────────────── */
    #main { margin-left: var(--sb-w); min-height: 100vh; display: flex; flex-direction: column; }

    .topbar {
      background: linear-gradient(135deg, #ffffff 0%, #f8faff 100%);
      border-bottom: 1px solid #dde6f5;
      padding: 0 28px; height: 58px;
      display: flex; align-items: center; justify-content: space-between;
      position: sticky; top: 0; z-index: 100;
      box-shadow: 0 2px 16px rgba(79,134,247,.09);
    }
    .topbar::after {
      content: '';
      position: absolute;
      bottom: 0; left: 0; right: 0; height: 3px;
      background: linear-gradient(90deg, #4f86f7 0%, #8b5cf6 35%, #14b8a6 68%, #f97316 100%);
    }
    .topbar-title {
      font-size: 1.05rem; font-weight: 800; margin: 0;
      background: linear-gradient(135deg, #0f172a 0%, #4f86f7 100%);
      -webkit-background-clip: text; -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    .topbar-actions { display: flex; align-items: center; gap: 8px; }

    .content { padding: 26px 28px; flex: 1; }

    /* ─── CARDS ──────────────────────────────── */
    .card {
      border: none; border-radius: 14px;
      box-shadow: 0 1px 4px rgba(0,0,0,.06), 0 2px 8px rgba(79,134,247,.04);
      transition: box-shadow .22s ease, transform .22s ease;
    }
    .card:hover {
      box-shadow: 0 4px 20px rgba(79,134,247,.12), 0 1px 4px rgba(0,0,0,.06);
    }
    .card-header {
      background: linear-gradient(135deg, #f6f9ff 0%, #eef3ff 100%) !important;
      border-bottom: 1px solid #dde6ff !important;
      font-weight: 700; color: #1e3a8a; font-size: .9rem;
      border-radius: 14px 14px 0 0 !important;
    }
    .stat-card {
      border-radius: 14px; padding: 22px; color: #fff;
      position: relative; overflow: hidden;
    }
    .stat-card::before {
      content: '';
      position: absolute; top: -20px; right: -20px;
      width: 90px; height: 90px; border-radius: 50%;
      background: rgba(255,255,255,.15); pointer-events: none;
    }
    .stat-card::after {
      content: '';
      position: absolute; bottom: -30px; right: 20px;
      width: 55px; height: 55px; border-radius: 50%;
      background: rgba(255,255,255,.08); pointer-events: none;
    }

    /* ─── BADGES ESTADO ──────────────────────── */
    .badge-estado-pendiente {
      background: linear-gradient(135deg, #fef9c3, #fde68a);
      color: #854d0e; padding: 3px 10px; border-radius: 20px;
      font-size: .74rem; font-weight: 600;
      border: 1px solid rgba(251,191,36,.4);
      box-shadow: 0 1px 3px rgba(245,158,11,.2);
    }
    .badge-estado-pagada {
      background: linear-gradient(135deg, #dcfce7, #bbf7d0);
      color: #14532d; padding: 3px 10px; border-radius: 20px;
      font-size: .74rem; font-weight: 600;
      border: 1px solid rgba(134,239,172,.5);
      box-shadow: 0 1px 3px rgba(16,185,129,.2);
    }
    .badge-estado-vencida {
      background: linear-gradient(135deg, #fee2e2, #fecaca);
      color: #7f1d1d; padding: 3px 10px; border-radius: 20px;
      font-size: .74rem; font-weight: 600;
      border: 1px solid rgba(252,165,165,.5);
      box-shadow: 0 1px 3px rgba(239,68,68,.2);
    }
    .badge-estado-cancelada {
      background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
      color: #475569; padding: 3px 10px; border-radius: 20px;
      font-size: .74rem; font-weight: 600;
      border: 1px solid rgba(203,213,225,.5);
    }
    .badge-estado-emitida {
      background: linear-gradient(135deg, #ede9fe, #ddd6fe);
      color: #4c1d95; padding: 3px 10px; border-radius: 20px;
      font-size: .74rem; font-weight: 600;
      border: 1px solid rgba(167,139,250,.4);
      box-shadow: 0 1px 3px rgba(139,92,246,.2);
    }

    /* ─── TABLE ──────────────────────────────── */
    .table thead th {
      font-size: .71rem; text-transform: uppercase; letter-spacing: .6px;
      font-weight: 700; padding: 12px 12px;
      background: linear-gradient(135deg, #f0f4ff 0%, #eaedff 100%);
      color: #3b5aca !important;
      border-bottom: 2px solid #c7d5f8 !important;
    }
    .table td { vertical-align: middle; }
    .table-hover tbody tr:hover {
      background: linear-gradient(90deg, rgba(79,134,247,.05) 0%, rgba(79,134,247,.02) 100%);
    }

    /* ─── ALERTS ─────────────────────────────── */
    .alert { border-radius: 12px; border: none; }
    .alert-success { background: #d1fae5; color: #065f46; box-shadow: inset 4px 0 0 #10b981; }
    .alert-danger  { background: #fee2e2; color: #991b1b; box-shadow: inset 4px 0 0 #ef4444; }
    .alert-warning { background: #fef3c7; color: #92400e; box-shadow: inset 4px 0 0 #f59e0b; }
    .alert-info    { background: #e0f2fe; color: #0c4a6e; box-shadow: inset 4px 0 0 #0ea5e9; }
    .alert-secondary { background: #f1f5f9; color: #334155; box-shadow: inset 4px 0 0 #94a3b8; }

    /* ─── FORMS ──────────────────────────────── */
    .form-label { font-weight: 600; font-size: .82rem; color: #374151; }
    .form-control, .form-select {
      border-radius: 8px; border-color: #dde6f0; font-size: .875rem;
      transition: border-color .15s, box-shadow .15s;
    }
    .form-control:focus, .form-select:focus {
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(79,134,247,.14);
    }

    /* ─── BUTTONS ────────────────────────────── */
    .btn { border-radius: 8px; font-weight: 500; font-size: .875rem; transition: all .18s ease; }
    .btn-primary {
      background: linear-gradient(135deg, #4f86f7, #3a6fd8);
      border: none;
      box-shadow: 0 2px 8px rgba(79,134,247,.35);
    }
    .btn-primary:hover {
      background: linear-gradient(135deg, #5c91f8, #4478e0);
      box-shadow: 0 4px 14px rgba(79,134,247,.45);
      transform: translateY(-1px);
    }
    .btn-primary:active { transform: translateY(0); box-shadow: 0 1px 4px rgba(79,134,247,.3); }
    .btn-success { box-shadow: 0 2px 8px rgba(16,185,129,.25); }
    .btn-danger  { box-shadow: 0 2px 8px rgba(239,68,68,.25); }
    .btn-action { padding: 4px 10px; font-size: .8rem; }
    .linea-factura td { vertical-align: middle; }

    @media print { #sidebar, .topbar, .no-print { display: none !important; } #main { margin-left: 0; } }

    /* ─── DARK MODE ───────────────────────────── */
    [data-bs-theme="dark"] body    { background: #0d1117; color: #e2e8f0; }
    [data-bs-theme="dark"] #main   { background: #0d1117; }
    [data-bs-theme="dark"] .topbar {
      background: linear-gradient(135deg, #161b22, #1a2030) !important;
      border-bottom-color: #30363d;
      box-shadow: 0 2px 16px rgba(0,0,0,.3);
    }
    [data-bs-theme="dark"] .topbar::after { opacity: .65; }
    [data-bs-theme="dark"] .topbar-title {
      background: linear-gradient(135deg, #f0f6fc, #79a8f7);
      -webkit-background-clip: text; -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    [data-bs-theme="dark"] .card {
      background: #161b22; border: 1px solid #30363d;
      box-shadow: 0 1px 3px rgba(0,0,0,.4);
    }
    [data-bs-theme="dark"] .card:hover {
      box-shadow: 0 4px 20px rgba(79,134,247,.18), 0 1px 4px rgba(0,0,0,.4);
    }
    [data-bs-theme="dark"] .card-header {
      background: linear-gradient(135deg, #1a2035, #1c2540) !important;
      border-bottom-color: #2a3550 !important; color: #93c5fd;
    }
    [data-bs-theme="dark"] .table  { color: #c9d1d9; }
    [data-bs-theme="dark"] .table thead th {
      background: linear-gradient(135deg, #1a2035, #1c2540) !important;
      border-bottom-color: #2a3550 !important;
      color: #7c98e0 !important;
    }
    [data-bs-theme="dark"] .table-hover tbody tr:hover { background: rgba(79,134,247,.08); }
    [data-bs-theme="dark"] .table-light { background: #1c2128 !important; color: #c9d1d9; }
    [data-bs-theme="dark"] .form-control,
    [data-bs-theme="dark"] .form-select {
      background: #0d1117; border-color: #30363d; color: #c9d1d9;
    }
    [data-bs-theme="dark"] .form-control:focus,
    [data-bs-theme="dark"] .form-select:focus {
      background: #0d1117; border-color: #4f86f7; color: #e2e8f0;
    }
    [data-bs-theme="dark"] .form-text  { color: #6e7681; }
    [data-bs-theme="dark"] .form-label { color: #c9d1d9; }
    [data-bs-theme="dark"] .text-muted { color: #6e7681 !important; }
    [data-bs-theme="dark"] hr          { border-color: #30363d; }
    [data-bs-theme="dark"] .alert-success { background:#0f3323; color:#3fb950; box-shadow: inset 4px 0 0 #238636; }
    [data-bs-theme="dark"] .alert-danger  { background:#3d1212; color:#f85149; box-shadow: inset 4px 0 0 #da3633; }
    [data-bs-theme="dark"] .alert-warning { background:#2d1f00; color:#e3b341; box-shadow: inset 4px 0 0 #9e6a03; }
    [data-bs-theme="dark"] .alert-info    { background:#0d2135; color:#58a6ff; box-shadow: inset 4px 0 0 #1f6feb; }
    [data-bs-theme="dark"] .alert-secondary { background:#1c2128; color:#8b949e; box-shadow: inset 4px 0 0 #484f58; }
    [data-bs-theme="dark"] .badge-estado-pendiente { background:linear-gradient(135deg,#2d1f00,#3b2800); color:#e3b341; border-color:#453600; }
    [data-bs-theme="dark"] .badge-estado-pagada    { background:linear-gradient(135deg,#0f3323,#0d2e1f); color:#3fb950; border-color:#1a4f30; }
    [data-bs-theme="dark"] .badge-estado-vencida   { background:linear-gradient(135deg,#3d1212,#330f0f); color:#f85149; border-color:#6e1313; }
    [data-bs-theme="dark"] .badge-estado-cancelada { background:linear-gradient(135deg,#1c2128,#181d24); color:#6e7681; border-color:#30363d; }
    [data-bs-theme="dark"] .badge-estado-emitida   { background:linear-gradient(135deg,#1f1535,#180f2d); color:#c084fc; border-color:#3a2060; }
    [data-bs-theme="dark"] .list-group-item        { background:#161b22; border-color:#30363d; color:#c9d1d9; }
    [data-bs-theme="dark"] #sidebar { background: var(--sb-bg); }
    /* Toggle button */
    #btn-toggle-theme {
      width:100%; text-align:left; background:none; border:none;
      padding:8px 14px 8px 18px; margin:1px 10px; border-radius:8px;
      color:#7c8db5; font-size:.845rem; font-weight:500; cursor:pointer;
      transition: background .14s, color .14s;
    }
    #btn-toggle-theme:hover { background: rgba(255,255,255,.055); color:#e2e8f0; }
  </style>
  {% block extra_head %}{% endblock %}
</head>
<body>

{% set ep = request.endpoint or '' %}
{% set in_facturacion  = 'factura' in ep or 'masivo' in ep or 'presupuesto' in ep or 'rectificativa' in ep or 'recurrente' in ep or 'cobro' in ep or 'abonos_prov' in ep %}
{% set in_contabilidad = 'transacciones' in ep or 'banco' in ep or 'ticket' in ep or 'ocr' in ep %}
{% set in_contactos    = 'clientes' in ep or 'proveedores' in ep %}
{% set in_analisis     = 'informes' in ep or 'autonomo' in ep or 'historial' in ep %}
{% set in_inventario   = 'inventario' in ep or 'catalogo' in ep or 'productos' in ep %}
{% set in_fiscal       = 'fiscal' in ep %}
{% set in_verifactu    = 'verifactu' in ep %}
{% set in_usuarios     = 'usuarios' in ep %}
{% set in_nominas      = 'nominas' in ep %}
{% set in_cuentas      = 'cuentas' in ep %}
{% set in_activos      = 'activos' in ep %}
{% set rol_sesion      = session.get('rol','admin') %}

<!-- ═══ SIDEBAR ═══════════════════════════════════════════════════════ -->
<nav id="sidebar">

  <a href="{{ url_for('dashboard.index') }}" class="sb-brand">
    <div class="sb-brand-icon"><i class="bi bi-building"></i></div>
    <div>
      <div class="name">ContaApp</div>
      <div class="sub">Gestión Contable</div>
    </div>
  </a>

  {% if _es_soporte %}
  <!-- Banner MODO SOPORTE -->
  <div style="margin:6px 10px 2px;padding:8px 12px;border-radius:8px;background:linear-gradient(135deg,#78350f,#b45309);border:1px solid #f59e0b">
    <div style="font-size:.7rem;font-weight:800;text-transform:uppercase;letter-spacing:1px;color:#fcd34d">
      <i class="bi bi-headset me-1"></i>Modo soporte activo
    </div>
    <div style="font-size:.75rem;color:#fbbf24;margin-top:2px">{{ session.get('empresa_nombre','') }}</div>
    <a href="{{ url_for('soporte.salir') }}" style="font-size:.7rem;color:#fed7aa;text-decoration:none;display:block;margin-top:4px">
      <i class="bi bi-arrow-left-circle me-1"></i>Volver al selector
    </a>
  </div>
  {% endif %}

  <!-- Inicio -->
  <div class="sb-group" style="padding: 10px 0 6px">
    <a href="{{ url_for('dashboard.index') }}"
       class="sb-link {% if ep == 'dashboard.index' %}active{% endif %}">
      <i class="bi bi-speedometer2"></i> Inicio
    </a>
  </div>

  <!-- Contactos -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-cont"
            aria-expanded="{{ 'true' if in_contactos else 'false' }}">
      <span>Contactos</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_contactos %}show{% endif %}" id="grp-cont">

      <a href="{{ url_for('clientes.lista') }}"
         class="sb-link {% if 'clientes' in ep %}active{% endif %}">
        <i class="bi bi-people"></i> Clientes
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('clientes.nuevo') }}"
           class="sb-sub {% if ep == 'clientes.nuevo' %}active{% endif %}">
          Nuevo cliente
        </a>
      </div>

      <a href="{{ url_for('proveedores.lista') }}"
         class="sb-link {% if 'proveedores' in ep %}active{% endif %}">
        <i class="bi bi-truck"></i> Proveedores
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('proveedores.nuevo') }}"
           class="sb-sub {% if ep == 'proveedores.nuevo' %}active{% endif %}">
          Nuevo proveedor
        </a>
      </div>

    </div>
  </div>

  <!-- Facturación -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-fact"
            aria-expanded="{{ 'true' if in_facturacion else 'false' }}">
      <span>Facturación</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_facturacion %}show{% endif %}" id="grp-fact">

      <a href="{{ url_for('facturas.emitidas') }}"
         class="sb-link {% if 'emitidas' in ep %}active{% endif %}">
        <i class="bi bi-file-earmark-arrow-up"></i> Facturas emitidas
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('facturas.nueva_emitida') }}"
           class="sb-sub {% if ep == 'facturas.nueva_emitida' %}active{% endif %}">
          Nueva factura emitida
        </a>
      </div>

      <a href="{{ url_for('facturas.recibidas') }}"
         class="sb-link {% if 'recibidas' in ep %}active{% endif %}">
        <i class="bi bi-file-earmark-arrow-down"></i> Facturas recibidas
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('facturas.nueva_recibida') }}"
           class="sb-sub {% if ep == 'facturas.nueva_recibida' %}active{% endif %}">
          Nueva factura recibida
        </a>
      </div>

      <a href="{{ url_for('presupuestos.lista') }}"
         class="sb-link {% if 'presupuesto' in ep %}active{% endif %}">
        <i class="bi bi-file-earmark-text"></i> Presupuestos
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('presupuestos.nuevo') }}"
           class="sb-sub {% if ep == 'presupuestos.nuevo' %}active{% endif %}">
          Nuevo presupuesto
        </a>
      </div>

      <a href="{{ url_for('cobros.index') }}"
         class="sb-link {% if 'cobro' in ep %}active{% endif %}">
        <i class="bi bi-clock-history"></i> Cobros pendientes
      </a>

      <a href="{{ url_for('rectificativas.lista') }}"
         class="sb-link {% if 'rectificativa' in ep %}active{% endif %}">
        <i class="bi bi-file-earmark-minus"></i> Rectificativas
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('rectificativas.nueva') }}"
           class="sb-sub {% if ep == 'rectificativas.nueva' %}active{% endif %}">
          Nueva rectificativa
        </a>
      </div>

      <a href="{{ url_for('recurrentes.lista') }}"
         class="sb-link {% if 'recurrente' in ep %}active{% endif %}">
        <i class="bi bi-arrow-repeat"></i> Recurrentes
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('recurrentes.nueva') }}"
           class="sb-sub {% if ep == 'recurrentes.nueva' %}active{% endif %}">
          Nueva plantilla
        </a>
      </div>

      <a href="{{ url_for('abonos_prov.index') }}"
         class="sb-link {% if 'abonos_prov' in ep %}active{% endif %}">
        <i class="bi bi-file-earmark-minus-fill"></i> Abonos a proveedores
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('abonos_prov.nuevo') }}"
           class="sb-sub {% if ep == 'abonos_prov.nuevo' %}active{% endif %}">
          Nuevo abono
        </a>
        <a href="{{ url_for('abonos_prov.plantillas') }}"
           class="sb-sub {% if ep in ('abonos_prov.plantillas','abonos_prov.plantilla_nueva','abonos_prov.plantilla_editar') %}active{% endif %}">
          Plantillas de correo
        </a>
      </div>

      <a href="{{ url_for('facturas.masivo_index') }}"
         class="sb-link {% if 'masivo' in ep %}active{% endif %}">
        <i class="bi bi-archive"></i> Archivo de facturas
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('facturas.masivo_subir') }}"
           class="sb-sub {% if ep == 'facturas.masivo_subir' %}active{% endif %}">
          Subir facturas en lote
        </a>
      </div>

    </div>
  </div>

  <!-- Almacén -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-inv"
            aria-expanded="{{ 'true' if in_inventario else 'false' }}">
      <span>Almacén</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_inventario %}show{% endif %}" id="grp-inv">
      <a href="{{ url_for('catalogo.lista') }}"
         class="sb-link {% if 'catalogo' in ep %}active{% endif %}">
        <i class="bi bi-tags"></i> Catálogo de productos
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('catalogo.nuevo') }}"
           class="sb-sub {% if ep == 'catalogo.nuevo' %}active{% endif %}">
          Nuevo producto
        </a>
      </div>
      <a href="{{ url_for('productos.lista') }}"
         class="sb-link {% if 'productos' in ep %}active{% endif %}">
        <i class="bi bi-box"></i> Fichas de producto
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('productos.nuevo') }}"
           class="sb-sub {% if ep == 'productos.nuevo' %}active{% endif %}">
          Nueva ficha
        </a>
      </div>
      <a href="{{ url_for('inventario.index') }}"
         class="sb-link {% if 'inventario' in ep %}active{% endif %}">
        <i class="bi bi-boxes"></i> Inventario
      </a>
    </div>
  </div>

  <!-- Contabilidad -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-conta"
            aria-expanded="{{ 'true' if in_contabilidad else 'false' }}">
      <span>Contabilidad</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_contabilidad %}show{% endif %}" id="grp-conta">

      <a href="{{ url_for('transacciones.lista') }}"
         class="sb-link {% if 'transacciones' in ep %}active{% endif %}">
        <i class="bi bi-arrow-left-right"></i> Transacciones
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('transacciones.nueva') }}?tipo=ingreso" class="sb-sub">Nuevo ingreso</a>
        <a href="{{ url_for('transacciones.nueva') }}?tipo=gasto"   class="sb-sub">Nuevo gasto</a>
      </div>

      <a href="{{ url_for('banco.index') }}"
         class="sb-link {% if 'banco' in ep %}active{% endif %}">
        <i class="bi bi-file-earmark-spreadsheet"></i> Importar movimientos
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('banco.conciliar') }}"
           class="sb-sub {% if ep == 'banco.conciliar' or ep == 'banco.conciliar_confirmar' or ep == 'banco.conciliar_descartar' %}active{% endif %}">
          Conciliación bancaria
        </a>
      </div>

      <a href="{{ url_for('tickets.lista') }}"
         class="sb-link {% if 'ticket' in ep %}active{% endif %}">
        <i class="bi bi-receipt"></i> Tickets de gasto
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('tickets.nuevo') }}"
           class="sb-sub {% if ep == 'tickets.nuevo' %}active{% endif %}">
          Nuevo ticket
        </a>
      </div>

      <a href="{{ url_for('ocr.index') }}"
         class="sb-link {% if 'ocr' in ep %}active{% endif %}">
        <i class="bi bi-upc-scan"></i> Escanear recibo
      </a>

    </div>
  </div>

  <!-- Plan de Cuentas -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-pgc"
            aria-expanded="{{ 'true' if in_cuentas else 'false' }}">
      <span>Plan de Cuentas</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_cuentas %}show{% endif %}" id="grp-pgc">

      <a href="{{ url_for('cuentas.index') }}"
         class="sb-link {% if ep == 'cuentas.index' %}active{% endif %}">
        <i class="bi bi-list-columns"></i> Plan de cuentas
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('cuentas.nueva') }}"
           class="sb-sub {% if ep == 'cuentas.nueva' %}active{% endif %}">
          Nueva cuenta
        </a>
      </div>

      <a href="{{ url_for('cuentas.asientos') }}"
         class="sb-link {% if 'asiento' in ep %}active{% endif %}">
        <i class="bi bi-journal-text"></i> Libro Diario
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('cuentas.asiento_nuevo') }}"
           class="sb-sub {% if ep == 'cuentas.asiento_nuevo' %}active{% endif %}">
          Nuevo asiento manual
        </a>
      </div>

      <a href="{{ url_for('cuentas.balance') }}"
         class="sb-link {% if ep == 'cuentas.balance' %}active{% endif %}">
        <i class="bi bi-bar-chart-steps"></i> Balance de sumas y saldos
      </a>

    </div>
  </div>

  <!-- Activos Fijos -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-act"
            aria-expanded="{{ 'true' if in_activos else 'false' }}">
      <span>Activos Fijos</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_activos %}show{% endif %}" id="grp-act">

      <a href="{{ url_for('activos.index') }}"
         class="sb-link {% if ep == 'activos.index' %}active{% endif %}">
        <i class="bi bi-buildings"></i> Registro de activos
      </a>
      <div class="sb-subs">
        <a href="{{ url_for('activos.nuevo') }}"
           class="sb-sub {% if ep == 'activos.nuevo' %}active{% endif %}">
          Nuevo activo
        </a>
      </div>

    </div>
  </div>

  <!-- Nóminas -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-nom"
            aria-expanded="{{ 'true' if in_nominas else 'false' }}">
      <span>Nóminas</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_nominas %}show{% endif %}" id="grp-nom">
      <a href="{{ url_for('nominas.empleados') }}"
         class="sb-link {% if 'empleado' in ep %}active{% endif %}">
        <i class="bi bi-people"></i> Empleados
      </a>
      <a href="{{ url_for('nominas.empleado_nuevo') }}"
         class="sb-link {% if ep == 'nominas.empleado_nuevo' %}active{% endif %}">
        <i class="bi bi-person-plus"></i> Nuevo empleado
      </a>
      <a href="{{ url_for('nominas.index') }}"
         class="sb-link {% if ep == 'nominas.index' %}active{% endif %}">
        <i class="bi bi-receipt"></i> Nóminas del mes
      </a>
    </div>
  </div>

  <!-- Análisis -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-anal"
            aria-expanded="{{ 'true' if in_analisis else 'false' }}">
      <span>Análisis</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_analisis %}show{% endif %}" id="grp-anal">

      <a href="{{ url_for('informes.index') }}"
         class="sb-link {% if ep == 'informes.index' or ep == 'informes.exportar' %}active{% endif %}">
        <i class="bi bi-bar-chart-line"></i> Informes P&amp;L
      </a>
      <a href="{{ url_for('informes.libro_iva') }}"
         class="sb-link {% if 'iva' in ep %}active{% endif %}">
        <i class="bi bi-receipt"></i> Libro de IVA
      </a>
      <a href="{{ url_for('informes.modelo130') }}"
         class="sb-link {% if ep == 'informes.modelo130' %}active{% endif %}">
        <i class="bi bi-calculator"></i> Modelo 130 (IRPF)
      </a>
      <a href="{{ url_for('autonomo.index') }}"
         class="sb-link {% if 'autonomo' in ep %}active{% endif %}">
        <i class="bi bi-person-badge"></i> Cuotas autónomo
      </a>
      <a href="{{ url_for('informes.categorias') }}"
         class="sb-link {% if ep == 'informes.categorias' %}active{% endif %}">
        <i class="bi bi-tags"></i> Categorías
      </a>
      <a href="{{ url_for('historial.index') }}"
         class="sb-link {% if 'historial' in ep %}active{% endif %}">
        <i class="bi bi-clock-history"></i> Historial de cambios
      </a>

    </div>
  </div>

  <!-- Fiscalidad -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-fisc"
            aria-expanded="{{ 'true' if in_fiscal else 'false' }}">
      <span>Fiscalidad</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_fiscal %}show{% endif %}" id="grp-fisc">

      <a href="{{ url_for('fiscal.index') }}"
         class="sb-link {% if ep == 'fiscal.index' %}active{% endif %}">
        <i class="bi bi-calendar3"></i> Calendario fiscal
      </a>
      <a href="{{ url_for('fiscal.modelo_303') }}"
         class="sb-link {% if ep == 'fiscal.modelo_303' or ep == 'fiscal.guardar_303' %}active{% endif %}">
        <i class="bi bi-receipt"></i> Modelo 303 (IVA)
      </a>
      <a href="{{ url_for('fiscal.modelo_130') }}"
         class="sb-link {% if ep == 'fiscal.modelo_130' or ep == 'fiscal.guardar_130' %}active{% endif %}">
        <i class="bi bi-person-badge"></i> Modelo 130 (IRPF)
      </a>
      <a href="{{ url_for('fiscal.modelo_390') }}"
         class="sb-link {% if ep == 'fiscal.modelo_390' or ep == 'fiscal.guardar_390' %}active{% endif %}">
        <i class="bi bi-file-earmark-bar-graph"></i> Modelo 390 (anual)
      </a>
      <a href="{{ url_for('fiscal.libros') }}"
         class="sb-link {% if ep == 'fiscal.libros' or ep == 'fiscal.libros_exportar' %}active{% endif %}">
        <i class="bi bi-journal-text"></i> Libros de registros
      </a>

    </div>
  </div>

  <!-- VeriFactu -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-vf"
            aria-expanded="{{ 'true' if in_verifactu else 'false' }}">
      <span>VeriFactu</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_verifactu %}show{% endif %}" id="grp-vf">

      <a href="{{ url_for('verifactu.index') }}"
         class="sb-link {% if ep == 'verifactu.index' %}active{% endif %}">
        <i class="bi bi-shield-lock"></i> Estado facturas
      </a>
      <a href="{{ url_for('verifactu.configuracion') }}"
         class="sb-link {% if ep == 'verifactu.configuracion' %}active{% endif %}">
        <i class="bi bi-gear"></i> Configuración
      </a>

    </div>
  </div>

  <!-- Equipo -->
  <div class="sb-group">
    <button class="sb-toggle" data-bs-toggle="collapse" data-bs-target="#grp-usr"
            aria-expanded="{{ 'true' if in_usuarios else 'false' }}">
      <span>Equipo</span><i class="bi bi-chevron-down sb-chevron"></i>
    </button>
    <div class="collapse {% if in_usuarios %}show{% endif %}" id="grp-usr">
      {% if rol_sesion == 'admin' %}
      <a href="{{ url_for('usuarios.index') }}"
         class="sb-link {% if ep == 'usuarios.index' %}active{% endif %}">
        <i class="bi bi-people"></i> Gestión de equipo
      </a>
      <a href="{{ url_for('usuarios.nuevo') }}"
         class="sb-link {% if ep == 'usuarios.nuevo' %}active{% endif %}">
        <i class="bi bi-person-plus"></i> Añadir usuario
      </a>
      {% endif %}
      <a href="{{ url_for('usuarios.perfil') }}"
         class="sb-link {% if ep == 'usuarios.perfil' %}active{% endif %}">
        <i class="bi bi-person-circle"></i> Mi perfil
      </a>
    </div>
  </div>

  <!-- Configuración (footer) -->
  <div class="sb-footer">
    <a href="{{ url_for('importar.index') }}"
       class="sb-link {% if 'importar' in ep %}active{% endif %}">
      <i class="bi bi-upload"></i> Importar datos
    </a>
    <a href="{{ url_for('ayuda.index') }}"
       class="sb-link {% if 'ayuda' in ep %}active{% endif %}">
      <i class="bi bi-question-circle"></i> Ayuda
    </a>
    <a href="{{ url_for('backup.index') }}"
       class="sb-link {% if 'backup' in ep %}active{% endif %}">
      <i class="bi bi-shield-check"></i> Copias de seguridad
    </a>
    <a href="{{ url_for('actualizaciones.index') }}"
       class="sb-link {% if 'actualizaciones' in ep %}active{% endif %}">
      <i class="bi bi-arrow-repeat"></i> Actualizaciones
      {% if _update_disponible %}<span style="background:#ef4444;color:#fff;font-size:.6rem;font-weight:700;padding:1px 5px;border-radius:9px;margin-left:4px;vertical-align:middle">●</span>{% endif %}
    </a>
    <a href="{{ url_for('rgpd.index') }}"
       class="sb-link {% if 'rgpd' in ep %}active{% endif %}">
      <i class="bi bi-shield-check"></i> RGPD / Datos
    </a>
    <a href="{{ url_for('configuracion.index') }}"
       class="sb-link {% if 'configuracion' in ep %}active{% endif %}">
      <i class="bi bi-gear"></i> Configuración
    </a>

    <!-- Indicador de licencia -->
    {% if _lic %}
    <a href="{{ url_for('licencia.index') }}"
       class="sb-link {% if 'licencia' in ep %}active{% endif %}"
       style="margin-top:2px">
      {% if _lic.status == 'active' %}
        <i class="bi bi-patch-check-fill" style="color:#4ade80"></i>
        <span style="color:#4ade80;font-size:.78rem">Licencia activa</span>
      {% elif _lic.status == 'trial' %}
        <i class="bi bi-hourglass-split" style="color:#fbbf24"></i>
        <span style="color:#fbbf24;font-size:.78rem">Prueba · {{ _lic.days_left }}d</span>
      {% else %}
        <i class="bi bi-shield-x" style="color:#f87171"></i>
        <span style="color:#f87171;font-size:.78rem">Sin licencia</span>
      {% endif %}
    </a>
    {% endif %}

    <!-- Info empresa + usuario -->
    <div style="margin:4px 10px 2px;padding:10px 12px;border-radius:10px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.09)">
      <div style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:#8fafc8;margin-bottom:5px">
        <i class="bi bi-building me-1"></i>{{ session.get('empresa_nombre','—') }}
      </div>
      <div style="font-size:.8rem;color:#7a95b0;display:flex;align-items:center;gap:6px">
        <i class="bi bi-person-circle" style="color:#475569"></i>
        {{ session.get('username','—') }}
        {% if rol_sesion == 'admin' %}
        <span style="font-size:.65rem;padding:1px 6px;border-radius:10px;background:#fef2f2;color:#dc2626;border:1px solid #fca5a5;font-weight:600">Admin</span>
        {% elif rol_sesion == 'contable' %}
        <span style="font-size:.65rem;padding:1px 6px;border-radius:10px;background:#eff6ff;color:#2563eb;border:1px solid #93c5fd;font-weight:600">Contable</span>
        {% else %}
        <span style="font-size:.65rem;padding:1px 6px;border-radius:10px;background:#f8fafc;color:#64748b;border:1px solid #cbd5e1;font-weight:600">Visor</span>
        {% endif %}
      </div>
    </div>

    <button id="btn-toggle-theme" onclick="toggleTheme()">
      <i class="bi bi-moon me-2"></i>Modo oscuro
    </button>

    <a href="{{ url_for('auth.logout') }}" class="sb-link" style="color:#ef4444;margin-top:2px">
      <i class="bi bi-box-arrow-left" style="color:#ef4444"></i> Cerrar sesión
    </a>

    <div style="margin:6px 12px 0;text-align:center;font-size:.65rem;color:#7a95b0;letter-spacing:.4px">
      ContaApp v{{ _version or '—' }}
    </div>
    <div style="margin:3px 12px 6px;text-align:center;font-size:.62rem">
      <a href="{{ url_for('legal.eula') }}" style="color:#607a92;text-decoration:none" class="me-2">EULA</a>
      <a href="{{ url_for('legal.privacidad') }}" style="color:#607a92;text-decoration:none">Privacidad</a>
    </div>
  </div>

</nav>

<!-- ═══ CONTENIDO PRINCIPAL ══════════════════════════════════════════ -->
<div id="main">

  {% if _demo %}
  <div style="background:linear-gradient(90deg,#1e3a5f,#1a3050);border-bottom:1px solid rgba(59,130,246,.3);padding:7px 20px;display:flex;align-items:center;justify-content:space-between;font-size:.8rem;gap:1rem;">
    <span style="color:#93c5fd;display:flex;align-items:center;gap:.5rem;">
      <i class="bi bi-clock" style="color:#60a5fa;"></i>
      <strong style="color:#fff;">Versión demo</strong> — {{ _demo_tiempo }}. Exportación, email y copias de seguridad desactivadas.
    </span>
    <a href="https://contaapp.es/#precios" target="_blank" style="background:#3b82f6;color:#fff;text-decoration:none;padding:4px 14px;border-radius:6px;font-weight:600;white-space:nowrap;font-size:.78rem;">Comprar ahora</a>
  </div>
  {% endif %}

  <div class="topbar">
    <h5 class="topbar-title">{% block page_title %}ContaApp{% endblock %}</h5>
    <form class="d-flex gap-1 mx-3" action="{{ url_for('buscar.resultados') }}" method="get">
      <input type="search" name="q" class="form-control form-control-sm" style="width:200px" placeholder="Buscar...">
      <button class="btn btn-sm btn-outline-secondary"><i class="bi bi-search"></i></button>
    </form>
    <div class="topbar-actions">{% block topbar_actions %}{% endblock %}</div>
  </div>

  <div class="content">
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% for cat, msg in messages %}
        <div class="alert alert-{{ cat }} alert-dismissible fade show" role="alert">
          {{ msg }}
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
      {% endfor %}
    {% endwith %}

    {% block content %}{% endblock %}
  </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>
{% block extra_scripts %}{% endblock %}
<script>
function _isDark() {
  return document.documentElement.getAttribute('data-bs-theme') === 'dark';
}
function _syncToggleBtn() {
  var btn = document.getElementById('btn-toggle-theme');
  if (!btn) return;
  btn.innerHTML = _isDark()
    ? '<i class="bi bi-sun me-2"></i>Modo claro'
    : '<i class="bi bi-moon me-2"></i>Modo oscuro';
}
function toggleTheme() {
  if (_isDark()) {
    document.documentElement.removeAttribute('data-bs-theme');
    localStorage.setItem('contaapp-theme', 'light');
  } else {
    document.documentElement.setAttribute('data-bs-theme', 'dark');
    localStorage.setItem('contaapp-theme', 'dark');
  }
  _syncToggleBtn();
}
_syncToggleBtn();
</script>

<!-- Visor de archivos en ventana modal (evita abrir pestaña del navegador) -->
<div class="modal fade" id="modalVerArchivo" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered" style="max-width:92vw; height:90vh; display:flex; flex-direction:column;">
    <div class="modal-content" style="flex:1; min-height:0; display:flex; flex-direction:column;">
      <div class="modal-header py-2 flex-shrink-0">
        <span class="fw-semibold small text-muted" id="modalArchivoNombre"></span>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-0" style="flex:1; min-height:0; overflow:hidden; display:flex; flex-direction:column;">
        <iframe id="modalArchivoFrame" src="" style="flex:1; width:100%; border:0; min-height:0;"></iframe>
      </div>
    </div>
  </div>
</div>
<script>
function verArchivo(url, nombre) {
  document.getElementById('modalArchivoFrame').src = url;
  document.getElementById('modalArchivoNombre').textContent = nombre || '';
  var modal = document.getElementById('modalVerArchivo');
  modal.addEventListener('hidden.bs.modal', function() {
    document.getElementById('modalArchivoFrame').src = '';
  }, { once: true });
  new bootstrap.Modal(modal).show();
}
</script>
</body>
</html>
