<?php /* views/partials/sidebar.php — controle por plano dinâmico + white label + menus customizados */ ?>
<?php
  require_once __DIR__ . '/_wl_bootstrap.php';
  require_once __DIR__ . '/../../app/db.php';
  require_once __DIR__ . '/../../app/plans.php';
  require_once __DIR__ . '/../../app/custom_menus.php';

  // White label
  $WL_SYS = wl_system();

  // === Config ===
  $UPGRADE_URL = 'https://pay.kiwify.com.br/E0l5xMZ';

  $isActive = fn($k) => isset($page) && $page === $k;

  $agentsPages = ['agente-disparo', 'agente-atendimento'];
  $isAgentsOpen = isset($page) && in_array($page, $agentsPages, true);

  $apiOficialPages = ['apioficial', 'disparos_oficial'];
  $isApiOficialOpen = isset($page) && in_array($page, $apiOficialPages, true);

  // === Lê features do usuário logado (da sessão, carregada no login) ===
  $userFeatures = plans_user_features();
  $userPlan = $_SESSION['user_plan_data']['id'] ?? '';

  function canView(string $key, string $plan = ''): bool {
    return plans_user_can_view($key);
  }

  function linkAttrs(string $key, string $href, string $plan, bool $external = false): string {
    if (canView($key, $plan)) {
      return $external
        ? 'href="'.htmlspecialchars($href).'" target="_blank" rel="noopener noreferrer"'
        : 'href="'.htmlspecialchars($href).'"';
    }
    return 'href="#" data-locked="1" data-key="'.htmlspecialchars($key).'"';
  }

  function linkClass(string $key, string $plan, string $base): string {
    return canView($key, $plan) ? $base : $base.' is-locked';
  }

  function shouldRender(string $key): bool {
    return plans_user_can_view($key);
  }
?>
<style>
  :root {
    --sb1: <?= htmlspecialchars($WL_SYS['sidebar_bg1'], ENT_QUOTES, 'UTF-8') ?>;
    --sb2: <?= htmlspecialchars($WL_SYS['sidebar_bg2'], ENT_QUOTES, 'UTF-8') ?>;
    --sb-brand:  <?= htmlspecialchars($WL_SYS['brand'],  ENT_QUOTES, 'UTF-8') ?>;
    --sb-brand2: <?= htmlspecialchars($WL_SYS['brand2'], ENT_QUOTES, 'UTF-8') ?>;
    --sbText: #e5e7eb;
    --sbMuted: #9aa4b2;
    --sbBorder: rgba(148,163,184,.16);
  }

  .sb {
    width: 16rem;
    color: var(--sbText);
    background: linear-gradient(180deg, var(--sb1), var(--sb2));
    border-right: 1px solid var(--sbBorder);
  }
  .sb-head{ height:64px; display:flex; align-items:center; gap:.6rem; padding:0 1.25rem; }
  .sb-head svg{ color:#8b5cf6 }
  .sb-nav{ padding:.9rem 0; }

  .sb-link{
    position:relative; display:flex; align-items:center; gap:.75rem;
    margin:.25rem .75rem; padding:.55rem .75rem; border-radius:12px;
    text-decoration:none; color:var(--sbText); font-weight:500;
    border:1px solid transparent; transition:background .18s, box-shadow .18s, border-color .18s;
  }
  .sb-link:hover{ background:rgba(255,255,255,.05); border-color:var(--sbBorder); }
  .sb-link svg{ flex-shrink:0; opacity:.9 }
  .sb-link.is-active{ background:rgba(255,255,255,.08); border-color:rgba(255,255,255,.12); box-shadow:0 8px 24px rgba(34,24,69,.35); }

  .sb-link.is-active::before{
    content:""; position:absolute; left:8px; top:8px; bottom:8px; width:4px; border-radius:999px;
    background: linear-gradient(180deg, var(--sb-brand), var(--sb-brand2));
  }

  .sb-link.is-locked{ opacity:.85; }
  .sb-link.is-locked .sb-lock{ margin-left:auto; opacity:.9; }
  .sb-link.is-locked:hover{ background:rgba(255,255,255,.04); border-color:rgba(255,255,255,.12); }

  .sb-group{ margin-top:.6rem; }
  .sb-group-header{
    display:flex; align-items:center; gap:.6rem;
    margin:.25rem .75rem; padding:.6rem .75rem; color:var(--sbText);
    border-radius:12px; border:1px solid transparent; background:rgba(255,255,255,.03);
    cursor:pointer; user-select:none; transition:background .18s, border-color .18s;
    min-width:0;
  }
  .sb-group-header:hover{ background:rgba(255,255,255,.05); border-color:var(--sbBorder); }
  .sb-group-title{
    font-weight:700; font-size:.95rem;
    display:flex; align-items:center; gap:.45rem;
    min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
  }
  .sb-caret{ margin-left:auto; display:inline-flex; transition:transform .18s ease; opacity:.9; }
  .sb-group.is-open .sb-caret{ transform:rotate(90deg); }
  .sb-sub{ overflow:hidden; max-height:0; opacity:0; transition:max-height .25s ease, opacity .2s ease; padding-left:0; }
  .sb-group.is-open .sb-sub{ opacity:1; max-height:500px; padding-left:0; }
  .sb-sub .sb-link{ margin-left:1.5rem; }

  .sb-divider{ height:1px; background:var(--sbBorder); margin:.8rem .75rem; }
  .sb-footer{ padding:1rem; border-top:1px solid var(--sbBorder); }

  .sb-exit{
    width:100%; display:inline-flex; align-items:center; justify-content:center; gap:.5rem;
    border-radius:12px; padding:.6rem .75rem; text-decoration:none; font-weight:700;
    background: linear-gradient(90deg, var(--sb-brand), var(--sb-brand2));
    color:#0b1020;
    box-shadow: 0 10px 30px color-mix(in srgb, var(--sb-brand2) 35%, transparent);
    transition:transform .15s, filter .2s;
  }
  .sb-exit:hover{ transform:translateY(-1px); filter:brightness(1.05); }

  .modal-backdrop{
    position:fixed; inset:0; background:rgba(0,0,0,.55);
    display:none; align-items:center; justify-content:center; z-index:60;
  }
  .modal-backdrop.is-open{ display:flex; }
  .modal-card{
    width:92%; max-width:520px; background:#0f172a; color:#e5e7eb; border:1px solid rgba(148,163,184,.18);
    border-radius:16px; box-shadow:0 20px 60px rgba(2,6,23,.6); padding:20px;
  }
  .modal-card h3{ margin:0 0 8px; font-size:1.1rem; font-weight:800; }
  .modal-card p{ margin:0 0 12px; color:#cbd5e1; }
  .modal-actions{ display:flex; gap:10px; justify-content:flex-end; margin-top:14px; }
  .btn{ border:none; border-radius:10px; padding:10px 14px; font-weight:700; cursor:pointer; }
  .btn-up{
    background: linear-gradient(90deg, var(--sb-brand), var(--sb-brand2));
    color:#0b1020;
  }
  .btn-close{ background:#0b1020; color:#e5e7eb; border:1px solid rgba(148,163,184,.18); }

  .sb-badge{
    flex-shrink:0; white-space:nowrap;
    font-size:9px; padding:2px 6px; border-radius:6px;
  }
  .sb-badge.api{
    background: linear-gradient(135deg, #22c55e, #16a34a);
    color: #052e16;
    font-weight: 800; line-height: 1; letter-spacing: .4px;
    box-shadow: 0 0 0 1px rgba(34,197,94,.25) inset;
  }

  .sb-link{ min-width: 0; }
  .sb-link-text{ flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

  .sb-group-compact .sb-link { font-size: 12px; padding-top: 6px; padding-bottom: 6px; }
  .sb-group-compact .sb-link svg { width: 16px; height: 16px; }
  .sb-group[data-group="externos"] .sb-link > svg:last-child { display: none; }
</style>

<div class="sb fixed inset-y-0 left-0 flex flex-col">
  <div class="sb-head">
    <a href="?page=painel" aria-label="Painel" style="display:flex;align-items:center;gap:.6rem;text-decoration:none;">
      <img src="<?= htmlspecialchars($WL_SYS['logo_url'], ENT_QUOTES, 'UTF-8') ?>" alt="Logo"
           style="display:block;height:50px;width:auto;max-width:180px;object-fit:contain;padding:6px 10px;">
    </a>
  </div>

  <nav class="sb-nav flex-1 overflow-y-auto">

    <!-- ====== MENUS CUSTOMIZADOS: posição "top" ====== -->
    <?= custom_menus_render_position('top') ?>

    <!-- Básico -->
<?php if (shouldRender('painel')): ?>
    <a class="<?= linkClass('painel', $userPlan, 'sb-link '.($isActive('painel')?'is-active':'')) ?>"
       <?= linkAttrs('painel','?page=painel',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
        <path d="M3 12l9-9 9 9v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
        <path d="M9 21V9h6v12" />
      </svg>
      Painel
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "after_painel" ====== -->
    <?= custom_menus_render_position('after_painel') ?>

<?php if (shouldRender('conexoes')): ?>
    <a class="<?= linkClass('conexoes', $userPlan, 'sb-link '.($isActive('conexoes')?'is-active':'')) ?>"
       <?= linkAttrs('conexoes','?page=conexoes',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
        <circle cx="6" cy="12" r="2" /><circle cx="18" cy="12" r="2" /><line x1="8" y1="12" x2="16" y2="12" />
      </svg>
      Conexões
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "after_conexoes" ====== -->
    <?= custom_menus_render_position('after_conexoes') ?>

<?php if (shouldRender('leads')): ?>
    <a class="<?= linkClass('leads', $userPlan, 'sb-link '.($isActive('leads')?'is-active':'')) ?>"
       <?= linkAttrs('leads','?page=leads',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
        <circle cx="12" cy="7" r="4" /><path d="M6 21v-2a6 6 0 0 1 12 0v2" />
      </svg>
      Leads
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "after_leads" ====== -->
    <?= custom_menus_render_position('after_leads') ?>

    <div class="sb-divider"></div>

    <!-- ===== Grupo: Agentes ===== -->
    <?php if (shouldRender('agente-disparo') || shouldRender('agente-atendimento')): ?>
    <div class="sb-group sb-group-compact <?= $isAgentsOpen ? 'is-open' : '' ?>" data-group="agentes">
      <div class="sb-group-header js-toggle-group" role="button" tabindex="0" aria-expanded="<?= $isAgentsOpen ? 'true' : 'false' ?>">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
          <path d="M12 2l3 7h7l-5.5 4 2 7L12 17l-6.5 4 2-7L2 9h7z" />
        </svg>
        <span class="sb-group-title">Agentes</span>
        <span class="sb-caret" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 6l6 6-6 6" />
          </svg>
        </span>
      </div>
      <div class="sb-sub">
        <?php if (shouldRender('agente-disparo')): ?>
        <a class="<?= linkClass('agente-disparo', $userPlan, 'sb-link '.($isActive('agente-disparo')?'is-active':'')) ?>"
           <?= linkAttrs('agente-disparo','?page=agente-disparo',$userPlan) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
            <path d="M2 12h20M2 12l6-6M2 12l6 6" />
          </svg>
          Agente de Disparo
        </a>
        <?php endif; ?>

        <?php if (shouldRender('agente-atendimento')): ?>
        <a class="<?= linkClass('agente-atendimento', $userPlan, 'sb-link '.($isActive('agente-atendimento')?'is-active':'')) ?>"
           <?= linkAttrs('agente-atendimento','?page=agente-atendimento',$userPlan) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
            <path d="M12 12c2.21 0 4-1.79 4-4S14.21 4 12 4 8 5.79 8 8s1.79 4 4 4z" />
            <path d="M6 20v-2c0-2.21 1.79-4 4-4h4c2.21 0 4 1.79 4 4v2" />
          </svg>
          Agente de Atendimento
        </a>
        <?php endif; ?>

        <!-- ====== MENUS CUSTOMIZADOS: posição "in_agentes" ====== -->
        <?= custom_menus_render_position('in_agentes') ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- ===== Grupo: Ferramentas externas ===== -->
    <?php if (shouldRender('extrator-maps') || shouldRender('instagram') || shouldRender('radarcnpj') || shouldRender('gruposwpp')): ?>
    <div class="sb-group sb-group-compact" data-group="externos">
      <div class="sb-group-header js-toggle-group" role="button" tabindex="0" aria-expanded="false">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
          <path d="M12 21s7-6.11 7-11a7 7 0 1 0-14 0c0 4.89 7 11 7 11z" />
        </svg>
        <span class="sb-group-title">Ferramentas</span>
        <span class="sb-caret" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 6l6 6-6 6" />
          </svg>
        </span>
      </div>
      <div class="sb-sub">
        <?php if (shouldRender('extrator-maps')): ?>
        <a class="<?= linkClass('extrator-maps', $userPlan, 'sb-link') ?>"
           <?= linkAttrs('extrator-maps','?page=google',$userPlan,false) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
            <path d="M12 21s7-6.11 7-11a7 7 0 1 0-14 0c0 4.89 7 11 7 11z" />
            <circle cx="12" cy="10" r="2.5" />
          </svg>
          Extrator Maps
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" style="margin-left:auto;opacity:.8">
            <path d="M18 3h3v3M21 3l-7 7" /><rect x="3" y="3" width="14" height="14" rx="2"></rect>
          </svg>
        </a>
        <?php endif; ?>

        <?php if (shouldRender('instagram')): ?>
        <a class="<?= linkClass('instagram', $userPlan, 'sb-link') ?>"
           <?= linkAttrs('instagram','?page=instagram',$userPlan,false) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
            <rect x="3" y="3" width="18" height="18" rx="5" />
            <circle cx="12" cy="12" r="4" />
            <circle cx="17.5" cy="6.5" r="1.2" />
          </svg>
          Extrator Instagram
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" style="margin-left:auto;opacity:.8">
            <path d="M18 3h3v3M21 3l-7 7" /><rect x="3" y="3" width="14" height="14" rx="2"></rect>
          </svg>
        </a>
        <?php endif; ?>

        <?php if (shouldRender('radarcnpj')): ?>
        <a class="<?= linkClass('radarcnpj', $userPlan, 'sb-link') ?>"
           <?= linkAttrs('radarcnpj','?page=radarcnpj',$userPlan,false) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
            <rect x="3" y="3" width="18" height="18" rx="2" />
            <path d="M8 9h8M8 13h5" />
          </svg>
          Extrator CNPJ
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" style="margin-left:auto;opacity:.8">
            <path d="M18 3h3v3M21 3l-7 7" /><rect x="3" y="3" width="14" height="14" rx="2"></rect>
          </svg>
        </a>
        <?php endif; ?>

        <?php if (shouldRender('gruposwpp')): ?>
        <a class="<?= linkClass('gruposwpp', $userPlan, 'sb-link') ?>"
           <?= linkAttrs('gruposwpp','?page=gruposwpp',$userPlan,false) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
            <path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"/>
            <circle cx="9" cy="10" r="1"/><circle cx="12" cy="10" r="1"/><circle cx="15" cy="10" r="1"/>
          </svg>
          Extrator Grupos WhatsApp
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" style="margin-left:auto;opacity:.8">
            <path d="M18 3h3v3M21 3l-7 7" /><rect x="3" y="3" width="14" height="14" rx="2"></rect>
          </svg>
        </a>
        <?php endif; ?>

        <!-- ====== MENUS CUSTOMIZADOS: posição "in_ferramentas" ====== -->
        <?= custom_menus_render_position('in_ferramentas') ?>
      </div>
    </div>
    <?php endif; ?>

    <div class="sb-divider"></div>

<?php if (shouldRender('disparos')): ?>
    <a class="<?= linkClass('disparos', $userPlan, 'sb-link '.($isActive('disparos')?'is-active':'')) ?>"
       <?= linkAttrs('disparos','?page=disparos',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
        <path d="M4 16c0-5 4-11 8-13 4 2 8 8 8 13v3a1 1 0 0 1-1 1h-5l-2 3-2-3H5a1 1 0 0 1-1-1v-3z"/>
        <circle cx="12" cy="9" r="1.5"/>
      </svg>
      Disparos
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "after_disparos" ====== -->
    <?= custom_menus_render_position('after_disparos') ?>

<?php if (shouldRender('crm')): ?>
    <a class="<?= linkClass('crm', $userPlan, 'sb-link '.($isActive('crm')?'is-active':'')) ?>"
       <?= linkAttrs('crm','?page=crm',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
        <rect x="3" y="4" width="6" height="16" rx="2"></rect>
        <rect x="13" y="4" width="8" height="8" rx="2"></rect>
        <rect x="13" y="14" width="8" height="6" rx="2"></rect>
      </svg>
      <span style="display: flex; align-items: center; gap: 6px;">
        CRM/Follow-Up
        <span style="background: linear-gradient(135deg, #6366f1, #8b5cf6); color: white; font-size: 9px; font-weight: 700; padding: 2px 6px; border-radius: 4px; letter-spacing: 0.5px; text-transform: uppercase;">Beta</span>
      </span>
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "after_crm" ====== -->
    <?= custom_menus_render_position('after_crm') ?>

<?php
/*
if (shouldRender('evolua_chat')): ?>
    <a class="<?= linkClass('evolua_chat', $userPlan, 'sb-link '.($isActive('evolua_chat')?'is-active':'')) ?>"
       <?= linkAttrs('evolua_chat','https://evoluaprospect.com/evolua-chat.html',$userPlan,true) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
        <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7A8.38 8.38 0 0 1 8 19l-5 2 2-5a8.38 8.38 0 0 1-.9-3.8A8.5 8.5 0 0 1 12 3a8.5 8.5 0 0 1 9 8.5z"/>
      </svg>
      <span style="display:flex; align-items:center; gap:6px;">
        Evolua Chat
        <span style="background: linear-gradient(135deg, #10b981, #22c55e); color: white; font-size: 9px; font-weight: 700; padding: 2px 6px; border-radius: 4px; letter-spacing: .4px; text-transform: uppercase;">Bônus</span>
      </span>
    </a>
<?php endif;
*/
?>

<?php if (shouldRender('dicas')): ?>
    <a class="<?= linkClass('dicas', $userPlan, 'sb-link '.($isActive('dicas')?'is-active':'')) ?>"
       <?= linkAttrs('dicas','?page=dicas',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
        <path d="M9 18h6M10 22h4" />
        <path d="M12 2a7 7 0 0 0-7 7c0 2.38 1.19 4.47 3 5.74V18h8v-3.26A7 7 0 0 0 12 2z" />
      </svg>
      <span style="display:flex;align-items:center;gap:6px;">
        Dicas
        <span style="background: linear-gradient(135deg, #8b5cf6, #6366f1); color: #fff; font-size: 9px; font-weight: 700; padding: 2px 6px; border-radius: 4px; letter-spacing: .4px; text-transform: uppercase;">Estratégias</span>
      </span>
    </a>
<?php endif; ?>

<?php if (shouldRender('funis')): ?>
    <a class="<?= linkClass('funis', $userPlan, 'sb-link '.($isActive('funis')?'is-active':'')) ?>"
       <?= linkAttrs('funis','?page=funis',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
        <path d="M3 4h18l-7 8v6l-4 2v-8L3 4z"></path>
      </svg>
      Funil de Prospecção
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "after_funis" ====== -->
    <?= custom_menus_render_position('after_funis') ?>

<?php if (shouldRender('webhook')): ?>
    <a class="<?= linkClass('webhook', $userPlan, 'sb-link '.($isActive('webhook')?'is-active':'')) ?>"
       <?= linkAttrs('webhook','?page=webhook',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
        <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7a2.5 2.5 0 0 0 0-1.39l7.13-4.11a2.5 2.5 0 1 0-.95-1.68L8 9.64a2.5 2.5 0 1 0 0 4.72l7.09 4.09c.05.72.65 1.29 1.41 1.29a1.5 1.5 0 0 0 0-3z" />
      </svg>
      Webhook
    </a>
<?php endif; ?>

<?php if (shouldRender('suporte')): ?>
    <a class="<?= linkClass('suporte', $userPlan, 'sb-link '.($isActive('suporte')?'is-active':'')) ?>"
       <?= linkAttrs('suporte','?page=suporte',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
        <circle cx="12" cy="12" r="10" />
        <path d="M9 9h.01M15 9h.01M8 13a4 4 0 0 0 8 0" />
      </svg>
      Suporte
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "after_suporte" ====== -->
    <?= custom_menus_render_position('after_suporte') ?>

    <!-- API Oficial -->
    <?php if (shouldRender('apioficial') || shouldRender('disparos_oficial')): ?>
    <div class="sb-group sb-group-compact is-highlight <?= $isApiOficialOpen ? 'is-open' : '' ?>" data-group="apioficial">
      <div class="sb-group-header js-toggle-group" role="button" tabindex="0" aria-expanded="<?= $isApiOficialOpen ? 'true' : 'false' ?>">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 12a9 9 0 1 0-16.2 5.3L4 21l3.8-1A9 9 0 0 0 21 12z"/>
          <path d="M9.5 12.5l1.5 1.5 3-3"/>
        </svg>
        <span class="sb-group-title">API Oficial <span class="sb-badge api">WhatsApp</span></span>
        <span class="sb-caret" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 6l6 6-6 6"/>
          </svg>
        </span>
      </div>
      <div class="sb-sub">
        <?php if (shouldRender('apioficial')): ?>
        <a class="<?= linkClass('apioficial', $userPlan, 'sb-link '.($isActive('apioficial')?'is-active':'')) ?>"
           <?= linkAttrs('apioficial','?page=apioficial',$userPlan) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
            <path d="M10 13a5 5 0 0 1 0-7l2-2a5 5 0 0 1 7 7l-1.5 1.5"/>
            <path d="M14 11a5 5 0 0 1 0 7l-2 2a5 5 0 0 1-7-7L6.5 11.5"/>
          </svg>
          <span class="sb-link-text" style="display:flex;align-items:center;gap:6px;">
            Conexão <span class="sb-badge api">API Oficial</span>
          </span>
        </a>
        <?php endif; ?>

        <?php if (shouldRender('disparos_oficial')): ?>
        <a class="<?= linkClass('disparos_oficial', $userPlan, 'sb-link '.($isActive('disparos_oficial')?'is-active':'')) ?>"
           <?= linkAttrs('disparos_oficial','?page=disparos_oficial',$userPlan) ?>>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
            <path d="M22 2L11 13"/>
            <path d="M22 2l-7 20-4-9-9-4 20-7z"/>
          </svg>
          <span class="sb-link-text" style="display:flex;align-items:center;gap:6px;">
            Disparos <span class="sb-badge api">API Oficial</span>
          </span>
        </a>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "before_minha_conta" ====== -->
    <?= custom_menus_render_position('before_minha_conta') ?>

<?php if (shouldRender('minha_conta')): ?>
    <a class="<?= linkClass('minha_conta', $userPlan, 'sb-link '.($isActive('minha_conta')?'is-active':'')) ?>"
       <?= linkAttrs('minha_conta', '?page=minha_conta', $userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true">
        <path stroke-linecap="round" d="M16 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
        <circle cx="12" cy="7" r="4"/>
      </svg>
      Minha conta
      <?php if (!canView('minha_conta', $userPlan)): ?>
        <span class="sb-lock" aria-hidden="true">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="10" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
        </span>
      <?php endif; ?>
    </a>
<?php endif; ?>

<?php if (shouldRender('atualizacoes')): ?>
    <a class="<?= linkClass('atualizacoes', $userPlan, 'sb-link '.($isActive('atualizacoes')?'is-active':'')) ?>"
       <?= linkAttrs('atualizacoes','?page=atualizacoes',$userPlan) ?>>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
        <path d="M3 11v2a4 4 0 0 0 4 4h1"/>
        <path d="M7 15V9"/>
        <path d="M21 8v8l-9-3H8a3 3 0 0 1-3-3 3 3 0 0 1 3-3h4l9-3z"/>
      </svg>
      Atualizações
    </a>
<?php endif; ?>

    <!-- ====== MENUS CUSTOMIZADOS: posição "end" ====== -->
    <?= custom_menus_render_position('end') ?>

  </nav>

  <div class="sb-footer">
    <a href="<?= BASE_URL ?>logout.php" class="sb-exit">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.6">
        <path d="M15 3h4a2 2 0 0 1 2 2v4" />
        <path d="M10 14 21 3" />
        <path d="M21 3v6h-6" />
        <path d="M15 10v10H5a2 2 0 0 1-2-2V8h10" />
      </svg>
      Sair
    </a>
  </div>
</div>

<!-- Modal de Upgrade -->
<div id="upgradeModal" class="modal-backdrop" aria-hidden="true">
  <div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="upg-title">
    <h3 id="upg-title">Desbloqueie tudo com o Plano Pró 🚀</h3><br>
    <p style="margin-bottom:10px">Faça o upgrade agora por <strong>R$ 97,00</strong> e receba <strong>+30 dias de bônus</strong>.</p>
    <p style="margin-bottom:10px">Na prática: você terá <strong>2 meses de acesso pelo preço de 1</strong>.</p>
    <p>
      <a id="upgradeLink" href="<?= htmlspecialchars($UPGRADE_URL) ?>" target="_blank" rel="noopener noreferrer" style="color:#93c5fd; text-decoration:underline; font-weight:600">
        Fazer upgrade por R$ 97,00 e ganhar +30 dias
      </a>
    </p>
    <div class="modal-actions">
      <button type="button" class="btn btn-close" id="btnCloseModal">Fechar</button>
      <a class="btn btn-up" id="btnGoUpgrade" href="<?= htmlspecialchars($UPGRADE_URL) ?>" target="_blank" rel="noopener noreferrer">Fazer Upgrade</a>
    </div>
  </div>
</div>

<script>
  (function () {
    const KEY_PREFIX = 'sb-open-';
    const groups = document.querySelectorAll('.sb-group');

    groups.forEach(g => {
      const id = g.getAttribute('data-group');
      const saved = localStorage.getItem(KEY_PREFIX + id);
      if (saved === '1') g.classList.add('is-open');
      if (saved === '0') g.classList.remove('is-open');

      const header = g.querySelector('.sb-group-header');
      if (header) header.setAttribute('aria-expanded', g.classList.contains('is-open') ? 'true' : 'false');
    });

    function toggleGroup(g) {
      const header = g.querySelector('.sb-group-header');
      const id = g.getAttribute('data-group') || Math.random().toString(36).slice(2);
      const isOpen = g.classList.toggle('is-open');
      if (header) header.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
      try { localStorage.setItem(KEY_PREFIX + id, isOpen ? '1' : '0'); } catch (e) {}
    }

    document.querySelectorAll('.js-toggle-group').forEach(btn => {
      btn.addEventListener('click', () => toggleGroup(btn.closest('.sb-group')));
      btn.addEventListener('keydown', (ev) => {
        if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); toggleGroup(btn.closest('.sb-group')); }
      });
    });

    const activeInside = document.querySelector('.sb-group[data-group="agentes"] .sb-link.is-active');
    const agentsGroup = document.querySelector('.sb-group[data-group="agentes"]');
    if (activeInside && agentsGroup && !agentsGroup.classList.contains('is-open')) {
      toggleGroup(agentsGroup);
    }

    const modal = document.getElementById('upgradeModal');
    const btnClose = document.getElementById('btnCloseModal');
    function openModal(){ modal.classList.add('is-open'); modal.setAttribute('aria-hidden','false'); }
    function closeModal(){ modal.classList.remove('is-open'); modal.setAttribute('aria-hidden','true'); }
    btnClose?.addEventListener('click', closeModal);
    modal?.addEventListener('click', (e)=>{ if (e.target === modal) closeModal(); });
    document.addEventListener('keydown', (e)=>{ if (e.key === 'Escape') closeModal(); });

    document.querySelectorAll('a[data-locked="1"]').forEach(a => {
      a.addEventListener('click', function(ev){ ev.preventDefault(); openModal(); });
    });
  })();
</script>

<?php if (!empty($_SESSION['user'])): ?>
<script>
  setInterval(() => {
    fetch('<?= BASE_URL ?>ping.php', { credentials: 'include' }).catch(() => {});
  }, 5 * 60 * 1000);
</script>
<?php endif; ?>
