<?php
// views/pages/painel.php

// 1) Boot e middlewares
require_once __DIR__ . '/../../app/config.php';
require_once __DIR__ . '/../../app/db.php';
require_once __DIR__ . '/../../app/auth_middleware.php';
require_once __DIR__ . '/../../app/license_middleware.php';
require_once __DIR__ . '/components/tutorial.php';

require_once __DIR__ . '/../../app/license_guard.php';
license_guard_or_die();


require_auth_or_redirect();
ensure_active_license_or_redirect();

$userName = isset($_SESSION['user']['name']) ? trim((string)$_SESSION['user']['name']) : 'Usuário';
$safeUserName = htmlspecialchars($userName, ENT_QUOTES, 'UTF-8');

// =====================================================
// (OPCIONAL) URL do vídeo de tutorial
// Troque apenas o VIDEO_ID abaixo, ex: dQw4w9WgXcQ
// Você também pode montar dinamicamente com base no DB.
// =====================================================
$tutorialEmbedUrl = 'https://www.youtube-nocookie.com/embed/VIDEO_ID';

// 2) (Opcional) recuperar dados da licença
$licenca = null;
$diasRestantes = null;
try {
  $pdo = db();
  $q = $pdo->prepare("
    SELECT contratado_em, expira_em
    FROM public.auth_users
    WHERE id = :id
    LIMIT 1
  ");
  $q->execute([':id' => $_SESSION['user']['id']]);
  $licenca = $q->fetch();

  if ($licenca && !empty($licenca['expira_em'])) {
    $now  = new DateTimeImmutable('now');
    $fim  = new DateTimeImmutable($licenca['expira_em']);
    $diasRestantes = max(0, (int)ceil(($fim->getTimestamp() - $now->getTimestamp()) / 86400));
  }
} catch (Throwable $e) {
  // silencioso
}

// 3) Flash
$flashError = $_SESSION['flash_error'] ?? null;
unset($_SESSION['flash_error']);
?>
<style>
  /* ========= Spotlight (primeiro acesso) ========= */
  #spotlightOverlay{
    position:fixed; inset:0; z-index:60;
    background: radial-gradient(
      circle at var(--x,50%) var(--y,50%),
      transparent 0 var(--r,120px),
      rgba(0,0,0,.6) calc(var(--r,120px) + 1px)
    );
  }
  #spotlightOverlay.hidden{ display:none; }

  .spotlight-pulse{ position:relative; }
  .spotlight-pulse::after{
    content:""; position:absolute; inset:-6px; border-radius:12px;
    box-shadow:0 0 0 0 rgba(99,102,241,.85);
    animation:pulse 1.6s ease-out infinite;
    pointer-events:none;
  }
  @keyframes pulse{
    0%{   box-shadow:0 0 0 0   rgba(99,102,241,.85); }
    70%{  box-shadow:0 0 0 16px rgba(99,102,241,0); }
    100%{ box-shadow:0 0 0 0   rgba(99,102,241,0); }
  }

  .spotlight-tip{
    position:fixed; z-index:70;
    background:#4f46e5; color:#fff;
    padding:8px 12px; border-radius:10px; font-size:12px;
    box-shadow:0 10px 18px rgba(0,0,0,.15);
    white-space:nowrap;
  }

  /* ========= FIX: Saudação responsiva ========= */
  .painel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }
  @media (max-width: 640px) {
    .painel-header {
      flex-direction: column;
      align-items: flex-start;
    }
    .painel-header h2 {
      font-size: 1rem;
    }
  }
</style>

<div class="space-y-4">

  <!-- Saudação + Botão Tutorial -->
  <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
    <div class="painel-header">
      <h2 class="text-lg font-semibold">Olá, <?= $safeUserName ?> 👋 bem-vindo ao seu painel</h2>
     <?= tutorial_component(['page' => 'painel']); ?>

    </div>
  </div>


<?php
// ================== BANNER LANÇAMENTO CURSO ==================
$mostrarBannerCurso = false;

$bannerImg = '/app/views/pages/formacao.png';
$bannerLink = 'https://iaevolua.com/formacao-n8n-ao-saas';
?>

<?php if ($mostrarBannerCurso): ?>
<div class="rounded-2xl overflow-hidden border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 mb-4">
  <a href="<?= htmlspecialchars($bannerLink, ENT_QUOTES, 'UTF-8') ?>"
     target="_blank"
     rel="noopener"
     class="block">
    <img
      src="<?= htmlspecialchars($bannerImg, ENT_QUOTES, 'UTF-8') ?>"
      alt="Formação n8n do Zero ao SaaS"
      class="w-full h-auto block"
      style="max-height: 220px; object-fit: contain;"
      loading="lazy"
    />
  </a>
</div>
<?php endif; ?>


  <?php if ($flashError): ?>
    <div class="rounded-xl border border-red-400/40 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 p-4 text-sm">
      <?= strip_tags($flashError, '<a><strong><b><br>') ?>
    </div>
  <?php endif; ?>

<?php if ($licenca && false): ?>
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
        <div class="text-sm text-gray-500 dark:text-gray-400">
          Licença ativa • expira em
          <strong><?= (new DateTimeImmutable($licenca['expira_em']))->format('d/m/Y H:i') ?></strong>
        </div>
        <?php if ($diasRestantes !== null): ?>
          <div class="text-xs text-gray-600 dark:text-gray-300">
            Restam <strong><?= $diasRestantes ?></strong> dia<?= $diasRestantes == 1 ? '' : 's' ?>.
          </div>
        <?php endif; ?>
      </div>
    </div>
  <?php endif; ?>

  <!-- KPIs -->
  <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4">
    <!-- Status da Conexão -->
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
      <div class="text-sm text-gray-500 dark:text-gray-400">Status da Conexão</div>
      <div id="connBox" class="mt-2">
        <span id="connBadge" class="inline-flex items-center px-2 py-1 rounded text-xs bg-gray-100 text-gray-700">Carregando…</span>
      </div>
    </div>

    <!-- Taxa de entrega -->
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
      <div class="text-sm text-gray-500 dark:text-gray-400">Taxa de entrega</div>
      <div class="mt-2 text-2xl md:text-3xl font-semibold"><span id="txEntrega">0</span>%</div>
      <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">Enviadas ÷ Total</div>
    </div>

    <!-- Taxa de erro -->
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
      <div class="text-sm text-gray-500 dark:text-gray-400">Taxa de erro</div>
      <div class="mt-2 text-2xl md:text-3xl font-semibold"><span id="txErro">0</span>%</div>
      <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">Erros ÷ Total</div>
    </div>

    <!-- Leads cadastrados -->
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
      <div class="text-sm text-gray-500 dark:text-gray-400">Leads cadastrados</div>
      <div class="mt-2 text-2xl md:text-3xl font-semibold"><span id="leadsCount">0</span></div>
      <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">Total na base</div>
    </div>
  </div>

  <!-- Linha 2 -->
  <div class="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
    <!-- NOVO: Distribuição do CRM por etapa (barras horizontais) -->
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
      <div class="flex items-center justify-between mb-3">
        <div>
          <div class="text-sm text-gray-500 dark:text-gray-400">Leads por etapa (CRM)</div>
          <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">Quantidade de leads em cada coluna do Kanban</div>
        </div>
        <button id="btnReloadCRM" class="rounded border px-3 py-1.5 text-sm">Atualizar</button>
      </div>

      <div id="crmChartWrap" class="relative overflow-hidden" style="height:260px">
        <canvas id="chartCRM" style="display:block; width:100% !important; height:100% !important;"></canvas>
      </div>
    </div>

    <!-- Gráfico: Entregues vs Erros (doughnut) -->
    <div class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4">
      <div class="flex items-center justify-between mb-2">
        <div class="text-sm text-gray-500 dark:text-gray-400">Desempenho das campanhas</div>
        <button id="btnReload" class="rounded border px-3 py-1.5 text-sm">Atualizar</button>
      </div>

      <div class="relative h-56 overflow-hidden">
        <canvas id="chartPerf" style="display:block; width:100% !important; height:100% !important;"></canvas>
      </div>

      <div class="text-xs text-gray-500 dark:text-gray-400 mt-2">
        Mostrando agregado de todas as campanhas (Enviadas x Erros).
      </div>
    </div>
  </div>

  <!-- Frase motivacional -->
  <div class="text-center mt-6">
    <p id="motivacional" class="text-xs italic text-gray-500 dark:text-gray-400"></p>
  </div>

</div>

<!-- ===================== MODAL TUTORIAL ===================== -->
<div id="tutorialModal"
     class="fixed inset-0 z-50 hidden"
     role="dialog"
     aria-modal="true"
     aria-labelledby="tutorialTitle">
  <!-- backdrop -->
  <div id="tutorialBackdrop" class="absolute inset-0 bg-black/60"></div>

  <!-- dialog -->
  <div class="absolute inset-0 flex items-center justify-center p-4">
    <div class="w-full max-w-4xl rounded-2xl bg-white dark:bg-gray-900 shadow-xl overflow-hidden">
      <!-- header -->
      <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-800">
        <h3 id="tutorialTitle" class="text-base font-semibold">Tutorial rápido</h3>
        <button id="btnCloseTutorial"
                class="rounded p-2 hover:bg-gray-100 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                aria-label="Fechar">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="currentColor"><path d="M18.3 5.71 12 12l6.3 6.29-1.41 1.42L10.59 13.41 4.29 19.71 2.88 18.3 9.17 12 2.88 5.71 4.29 4.29l6.3 6.3 6.29-6.3z"/></svg>
        </button>
      </div>
      <!-- body -->
      <div class="aspect-video bg-black">
        <iframe id="tutorialFrame"
                class="w-full h-full"
                src=""
                title="Tutorial"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                allowfullscreen
                referrerpolicy="strict-origin-when-cross-origin"></iframe>
      </div>
      <!-- footer -->
      <div class="flex items-center justify-end gap-2 px-4 py-3 border-t border-gray-200 dark:border-gray-800">
        <a href="<?= htmlspecialchars($tutorialEmbedUrl, ENT_QUOTES, 'UTF-8') ?>"
           target="_blank"
           class="text-xs text-gray-500 hover:underline">Abrir no YouTube</a>
        <button id="btnCloseTutorial2"
                class="rounded-lg border px-3 py-1.5 text-sm hover:bg-gray-50 dark:hover:bg-gray-800">
          Fechar
        </button>
      </div>
    </div>
  </div>
</div>
<!-- =================== /MODAL TUTORIAL =================== -->

<!-- ===================== MODAL BOAS-VINDAS MOBILE ===================== -->
<div id="mobileWelcomeModal" class="mw-backdrop" aria-hidden="true" role="dialog" aria-modal="true">
  <div class="mw-card">
    <div class="mw-emoji">👋</div>
    <h3 class="mw-title">Bem-vindo ao Evolua Prospect!</h3>
    <p class="mw-text">
      Ficamos felizes em te ver por aqui! Para a <strong>melhor experiência</strong>,
      recomendamos acessar pelo <strong>computador</strong>, o painel foi pensado
      para telas maiores e você aproveita todos os recursos com mais conforto.
    </p>
    <p class="mw-text" style="margin-top:8px; font-size:0.85rem; color:#94a3b8;">
      Mas fique à vontade para usar no celular também!
    </p>

    <label class="mw-check">
      <input type="checkbox" id="mwDontShow">
      <span>Não exibir novamente</span>
    </label>

    <button type="button" id="mwClose" class="mw-btn">Entendi, vamos lá! 🚀</button>
  </div>
</div>

<style>
  /* ===== Modal Boas-Vindas Mobile ===== */
  .mw-backdrop {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.6);
    z-index: 200;
    align-items: center;
    justify-content: center;
    padding: 16px;
  }
  .mw-backdrop.is-open {
    display: flex;
  }
  .mw-card {
    width: 100%;
    max-width: 380px;
    background: linear-gradient(180deg, #1a1040, #0f172a);
    color: #e5e7eb;
    border: 1px solid rgba(148, 163, 184, 0.18);
    border-radius: 20px;
    padding: 28px 24px 24px;
    text-align: center;
    box-shadow: 0 20px 60px rgba(2, 6, 23, 0.7);
    animation: mwSlideUp 0.3s ease;
  }
  @keyframes mwSlideUp {
    from { opacity: 0; transform: translateY(30px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  .mw-emoji {
    font-size: 2.5rem;
    margin-bottom: 12px;
  }
  .mw-title {
    margin: 0 0 12px;
    font-size: 1.15rem;
    font-weight: 800;
    background: linear-gradient(90deg, #6ee7ff, #7c3aed);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
  .mw-text {
    margin: 0;
    font-size: 0.92rem;
    line-height: 1.5;
    color: #cbd5e1;
  }
  .mw-text strong {
    color: #fff;
  }
  .mw-check {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin: 18px 0 16px;
    font-size: 0.82rem;
    color: #94a3b8;
    cursor: pointer;
  }
  .mw-check input[type="checkbox"] {
    width: 16px;
    height: 16px;
    accent-color: #7c3aed;
    cursor: pointer;
  }
  .mw-btn {
    width: 100%;
    padding: 12px 20px;
    border: none;
    border-radius: 12px;
    font-size: 0.95rem;
    font-weight: 700;
    cursor: pointer;
    background: linear-gradient(90deg, #6ee7ff, #7c3aed) !important;
    color: #0b1020 !important;
    box-shadow: 0 8px 24px rgba(124, 58, 237, 0.35);
    transition: transform 0.15s, filter 0.2s;
  }
  .mw-btn:hover {
    transform: translateY(-1px);
    filter: brightness(1.05);
  }

  /* Só aparece no mobile */
  @media (min-width: 1025px) {
    .mw-backdrop { display: none !important; }
  }
</style>
<!-- =================== /MODAL BOAS-VINDAS MOBILE =================== -->

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- ========= Script principal do Painel ========= -->
<script>
(function(){
  const API_CONEXOES = 'api/conexoes.php';
  const API_DISPAROS = 'api/disparos.php';
  const API_LEADS    = 'api/leads.php';
  const API_CRM      = 'api/crm.php';

  const connBadge   = document.getElementById('connBadge');
  const txEntregaEl = document.getElementById('txEntrega');
  const txErroEl    = document.getElementById('txErro');
  const leadsCountEl= document.getElementById('leadsCount');

  const btnReload   = document.getElementById('btnReload');
  const btnReloadCRM= document.getElementById('btnReloadCRM');

  function setConn(status){
    const s = (status||'').toLowerCase();
    let text = 'Desconhecido', cls = 'bg-gray-100 text-gray-700';
    if (s === 'open' || s === 'connected') { text = 'Conectado';   cls = 'bg-emerald-100 text-emerald-800'; }
    else if (s === 'connecting')           { text = 'Conectando';  cls = 'bg-amber-100 text-amber-800'; }
    else if (s === 'closed')               { text = 'Desconectado';cls = 'bg-rose-100 text-rose-800'; }
    connBadge.className = 'inline-flex items-center px-2 py-1 rounded text-xs ' + cls;
    connBadge.textContent = text;
  }

  async function fetchJSON(url, opts={}){
    const r = await fetch(url, { credentials:'same-origin', cache:'no-store', ...opts });
    const t = await r.text();
    try {
      const j = JSON.parse(t);
      if (!r.ok) return { ok:false, error: j?.error || t };
      return j;
    } catch {
      return { ok:false, error: t || 'Falha' };
    }
  }

  async function loadConn(){
    const d = await fetchJSON(`${API_CONEXOES}?action=status`);
if (d.ok) setConn(d.connected ? 'connected' : 'closed'); else setConn(null);
  }

  async function loadLeads(){
    const d = await fetchJSON(`${API_LEADS}?action=list&page=1&limit=1`);
    if (d.ok) leadsCountEl.textContent = d.total ?? 0;
  }

  // ====== Doughnut (Enviadas x Erros) ======
  let chartPerf = null;
  function renderPerfChart(enviadas, erros){
    const ctx = document.getElementById('chartPerf').getContext('2d');
    if (chartPerf) { chartPerf.destroy(); chartPerf = null; }
    chartPerf = new Chart(ctx, {
      type: 'doughnut',
      data: { labels: ['Enviadas', 'Erros'], datasets: [{ data: [enviadas, erros] }] },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '60%',
        plugins: { legend: { position: 'bottom' } }
      }
    });
  }

  async function loadCamps(){
    const d = await fetchJSON(`${API_DISPAROS}?action=list&_=${Date.now()}`);
    if (!d.ok) {
      txEntregaEl.textContent = '0';
      txErroEl.textContent    = '0';
      renderPerfChart(0,0);
      return;
    }
    const arr = d.data || [];
    let total=0, enviados=0, erros=0;
    for (const c of arr) {
      total    += Number(c.total || 0);
      enviados += Number(c.enviados || 0);
      erros    += Number(c.erros || 0);
    }
    const txEntrega = total > 0 ? Math.round((enviados/total)*100) : 0;
    const txErro    = total > 0 ? Math.round((erros/total)*100)    : 0;

    txEntregaEl.textContent = txEntrega;
    txErroEl.textContent    = txErro;
    renderPerfChart(enviados, erros);
  }

  // ====== CRM: barras horizontais por etapa ======
  let chartCRM = null;
  function renderCRMChart(labels, values){
    const wrap = document.getElementById('crmChartWrap');
    const h = Math.max(160, Math.min(480, labels.length * 40));
    wrap.style.height = h + 'px';

    const ctx = document.getElementById('chartCRM').getContext('2d');
    if (chartCRM) { chartCRM.destroy(); chartCRM = null; }
    chartCRM = new Chart(ctx, {
      type: 'bar',
      data: { labels, datasets: [{ label: 'Leads', data: values, borderWidth: 1 }] },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: 'y',
        plugins: { legend: { display: false }, tooltip: { mode: 'nearest', intersect: false } },
        scales: {
          x: { beginAtZero: true, ticks: { precision: 0 } },
          y: { ticks: { autoSkip: false } }
        }
      }
    });
  }

  async function loadCRM(){
    const d = await fetchJSON(`api/crm.php?action=board&_=${Date.now()}`);
    if (!d.ok) { renderCRMChart(['Leads'], [0]); return; }
    const stages = d.stages || [];
    const cards  = d.cards  || {};
    const labels = stages.map(s => s.name);
    const values = stages.map(s => (cards[String(s.id)] || cards[Number(s.id)] || []).length);
    renderCRMChart(labels, values);
  }

  async function boot(){
    await Promise.all([loadConn(), loadLeads(), loadCamps(), loadCRM()]);
  }

  // botões de atualizar
  let reloading = false;
  btnReload?.addEventListener('click', async () => {
    if (reloading) return;
    reloading = true; btnReload.disabled = true;
    try { await Promise.all([loadCamps()]); } finally { reloading = false; btnReload.disabled = false; }
  });
  btnReloadCRM?.addEventListener('click', async () => {
    if (reloading) return;
    reloading = true; btnReloadCRM.disabled = true;
    try { await loadCRM(); } finally { reloading = false; btnReloadCRM.disabled = false; }
  });

  boot();
})();
</script>

<!-- ========= Frases motivacionais ========= -->
<script>
const frases = [
  "Cada não te aproxima de um sim.",
  "Venda é relacionamento, não insistência.",
  "Seu produto resolve problemas, não empurre — ajude.",
  "Confiança é a moeda mais valiosa em uma venda.",
  "Escute mais do que fale.",
  "Venda valor, não preço.",
  "Cada lead é uma oportunidade única.",
  "Seja consultor, não apenas vendedor.",
  "Perguntar abre portas, assumir fecha.",
  "Paciência fecha negócios duradouros.",
  "Persistência vence resistência.",
  "Soluções vendem mais que argumentos.",
  "Vender é ajudar alguém a decidir.",
  "Entusiasmo é contagiante.",
  "Empatia gera confiança.",
  "Preparação transforma objeções em vendas.",
  "Vendas começam com conexão humana.",
  "Seja curioso sobre a dor do cliente.",
  "Transparência gera fidelidade.",
  "Sorriso abre mais portas que descontos.",
  "Foco no cliente, não na comissão.",
  "Pequenas vitórias criam grandes resultados.",
  "O follow-up é onde mora o dinheiro.",
  "Histórias vendem mais que dados.",
  "Aprenda com cada não.",
  "Objeções são sinais de interesse.",
  "Nunca prometa o que não pode cumprir.",
  "Venda como gostaria de ser vendido.",
  "Credibilidade é seu maior ativo.",
  "Sucesso em vendas = disciplina diária."
];
function mostraFrase() {
  const alvo = document.getElementById('motivacional');
  if (!alvo) return;
  const idx = Math.floor(Math.random() * frases.length);
  alvo.textContent = frases[idx];
}
mostraFrase();
</script>

<!-- ========= Controle do Modal de Tutorial ========= -->
<script>
(function(){
  const openBtn = document.getElementById('btnOpenTutorial');
  const modal   = document.getElementById('tutorialModal');
  const backdrop= document.getElementById('tutorialBackdrop');
  const close1  = document.getElementById('btnCloseTutorial');
  const close2  = document.getElementById('btnCloseTutorial2');
  const frame   = document.getElementById('tutorialFrame');

  const EMBED = <?= json_encode($tutorialEmbedUrl, JSON_UNESCAPED_SLASHES) ?>;

  function openModal(){
    modal.classList.remove('hidden');
    frame.src = EMBED + (EMBED.includes('?') ? '&' : '?') + 'autoplay=1&rel=0';
    close1?.focus();
    document.addEventListener('keydown', onEsc);
  }
  function closeModal(){
    modal.classList.add('hidden');
    frame.src = '';
    document.removeEventListener('keydown', onEsc);
  }
  function onEsc(e){ if (e.key === 'Escape') closeModal(); }

  openBtn?.addEventListener('click', openModal);
  close1?.addEventListener('click', closeModal);
  close2?.addEventListener('click', closeModal);
  backdrop?.addEventListener('click', closeModal);

  try {
    const u = new URL(window.location.href);
    if (u.searchParams.get('tutorial') === '1') openModal();
  } catch {}
})();
</script>

<!-- ========= Spotlight (primeiro acesso) ========= -->
<script>
(function(){
  const BTN_ID = 'btnOpenTutorial';
  const STORAGE_KEY = 'tutorialSpotlightSeen';
  const btn = document.getElementById(BTN_ID);
  if (!btn) return;
  if (localStorage.getItem(STORAGE_KEY) === '1') return;

  const overlay = document.createElement('div');
  overlay.id = 'spotlightOverlay';
  document.body.appendChild(overlay);

  const tip = document.createElement('div');
  tip.className = 'spotlight-tip';
  tip.textContent = 'Novo: assista o tutorial';
  document.body.appendChild(tip);

  btn.classList.add('relative','z-[70]','spotlight-pulse');

  function positionSpotlight(){
    const r = btn.getBoundingClientRect();
    const x = r.left + r.width/2 + window.scrollX;
    const y = r.top  + r.height/2 + window.scrollY;
    const radius = Math.max(r.width, r.height) * 0.9 + 22;

    overlay.style.setProperty('--x', x + 'px');
    overlay.style.setProperty('--y', y + 'px');
    overlay.style.setProperty('--r', radius + 'px');

    const tipW = tip.offsetWidth;
    const left = r.left + (r.width/2) - (tipW/2) + window.scrollX;
    const top  = r.top - 40 + window.scrollY;
    tip.style.left = Math.max(12, left) + 'px';
    tip.style.top  = Math.max(12, top)  + 'px';
  }

  function endSpotlight(){
    overlay?.remove();
    tip?.remove();
    btn.classList.remove('spotlight-pulse','z-[70]','relative');
    localStorage.setItem(STORAGE_KEY, '1');
    window.removeEventListener('resize', positionSpotlight);
    window.removeEventListener('scroll', onScroll, true);
  }

  function onScroll(){ positionSpotlight(); }

  overlay.addEventListener('click', endSpotlight);
  btn.addEventListener('click', endSpotlight);
  window.addEventListener('resize', positionSpotlight);
  window.addEventListener('scroll', onScroll, { passive:true, capture:true });

  setTimeout(positionSpotlight, 80);
})();
</script>

<!-- ========= Script do Modal Boas-Vindas Mobile ========= -->
<script>
(function(){
  var STORAGE_KEY = 'evolua_mobile_welcome_seen';
  var modal = document.getElementById('mobileWelcomeModal');
  var btnClose = document.getElementById('mwClose');
  var checkbox = document.getElementById('mwDontShow');

  if (!modal || !btnClose || !checkbox) return;

  // Só mostra em telas mobile (≤1024px)
  if (window.innerWidth > 1024) return;

  // Já marcou "não exibir novamente"?
  if (localStorage.getItem(STORAGE_KEY) === '1') return;

  // Abre o modal
  modal.classList.add('is-open');
  modal.setAttribute('aria-hidden', 'false');

  function fechar() {
    if (checkbox.checked) {
      localStorage.setItem(STORAGE_KEY, '1');
    }
    modal.classList.remove('is-open');
    modal.setAttribute('aria-hidden', 'true');
  }

  btnClose.addEventListener('click', fechar);

  // Fecha ao clicar fora do card
  modal.addEventListener('click', function(e) {
    if (e.target === modal) fechar();
  });

  // Fecha com ESC
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && modal.classList.contains('is-open')) fechar();
  });
})();
</script>