<?php /* views/pages/documentacao.php */ ?>
<style>
  :root{
    --bg:#ffffff; --text:#111827; --muted:#4b5563; --card:#f9fafb; --card-border:#e5e7eb; --card-hover:#f3f4f6;
    --primary:#2563eb; --green:#16a34a; --indigo:#4f46e5; --accent1:#6ee7ff; --accent2:#7c3aed;
  }
  .dark :root{
    --bg:#0b0f17; --text:#e5e7eb; --muted:#9ca3af; --card:#0f172a; --card-border:#1f2937; --card-hover:#111827;
    --primary:#60a5fa; --green:#22c55e;
  }

  .docs-container{max-width:1200px;margin:0 auto;padding:2rem 1rem;color:var(--text);}
  .docs-title{font-size:1.75rem;font-weight:800;margin-bottom:.25rem}
  .docs-sub{color:var(--muted);margin-bottom:1.75rem}

  .docs-grid{display:grid;gap:1.5rem;grid-template-columns:300px 1fr}
  @media (max-width:1024px){ .docs-grid{grid-template-columns:1fr} }

  .sidebar{position:sticky;top:1rem;height:calc(100dvh - 2rem);overflow:auto;background:var(--card);border:1px solid var(--card-border);border-radius:16px;padding:1rem}
  .search{position:relative;margin-bottom:1rem}
  .search input{width:100%;padding:.65rem .85rem;border:1px solid var(--card-border);border-radius:12px;background:#fff;color:#111827}
  .dark .search input{background:#0b1220;color:var(--text);border-color:#1f2937}

  .group{margin:.25rem 0 .5rem}
  .group summary{cursor:pointer;font-weight:700;color:var(--text);padding:.35rem .25rem;border-radius:8px}
  .topic{display:flex;gap:.5rem;align-items:center;padding:.45rem .5rem;margin:.15rem 0;border-radius:10px;color:var(--text);text-decoration:none}
  .topic small{color:var(--muted)}
  .topic.active, .topic:hover{background:var(--card-hover);}

  .content{min-height:60vh}
  .article{background:var(--card);border:1px solid var(--card-border);border-radius:16px;overflow:hidden}
  .video-wrap{aspect-ratio:16/9;background:#000;}
  .video-wrap iframe, .video-wrap video{width:100%;height:100%;display:block}

  .article-body{padding:1.25rem}
  .article-body h1{font-size:1.5rem;font-weight:800;margin-bottom:.5rem}
  .article-body p{color:var(--text);line-height:1.65;margin:.75rem 0}
  .article-body ul{padding-left:1.1rem}
  .article-body li{margin:.35rem 0}
  .badges{display:flex;gap:.5rem;flex-wrap:wrap;margin:.5rem 0 0}
  .badge{font-size:.75rem;padding:.25rem .5rem;border-radius:999px;background:rgba(99,102,241,.12);color:var(--indigo);border:1px solid rgba(99,102,241,.25)}

  .toolbar{display:flex;justify-content:space-between;align-items:center;margin:1rem 0 .75rem}
  .crumbs{color:var(--muted);font-size:.9rem}
  .actions{display:flex;gap:.5rem}
  .btn{border:none;border-radius:10px;padding:.55rem .8rem;cursor:pointer;background:linear-gradient(90deg,var(--accent1),var(--accent2));color:#fff;font-weight:700}
  .ghost{background:transparent;border:1px solid var(--card-border);color:var(--text)}
  .copylink{display:inline-flex;align-items:center;gap:.35rem}

  pre{background:#0b1220;color:#e5e7eb;border-radius:12px;padding:1rem;overflow:auto;border:1px solid #111827}
  code{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;}

  .nextprev{display:flex;justify-content:space-between;gap:1rem;margin-top:1rem}
  .nextprev a{flex:1;text-decoration:none;background:var(--card);border:1px solid var(--card-border);border-radius:12px;padding:.85rem}
  .nextprev a:hover{background:var(--card-hover)}
</style>

<div class="docs-container">
  <h1 class="docs-title">Documentação</h1>
  <p class="docs-sub">Tutoriais, vídeos e guias passo a passo do Evolua Prospect.</p>

  <div class="docs-grid">
    <!-- SIDEBAR -->
    <aside class="sidebar">
      <div class="search">
        <input id="searchInput" type="text" placeholder="Buscar tópicos...">
      </div>
      <nav id="sidebarNav"></nav>
    </aside>

    <!-- CONTENT -->
    <section class="content">
      <div class="toolbar">
        <div class="crumbs" id="breadcrumbs">Início ▸ Introdução</div>
        <div class="actions">
          <button class="btn ghost copylink" id="copyLinkBtn" title="Copiar link deste tópico">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
              <path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/>
              <path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/>
            </svg>
            Copiar link
          </button>
        </div>
      </div>

      <div class="article">
        <div class="video-wrap" id="videoMount"><!-- embed aqui --></div>
        <div class="article-body" id="articleBody"><!-- conteúdo aqui --></div>
      </div>

      <div class="nextprev" id="nextPrev"><!-- navegação próxima/anterior --></div>
    </section>
  </div>
</div>

<script>
/**
 * =============================
 * 1) Defina seus tópicos aqui
 * =============================
 * Estrutura:
 * - category: Agrupa no menu
 * - slug: usado na URL (?t=slug)
 * - title: título exibido
 * - yt: ID do YouTube (se usar YouTube). Ex.: "dQw4w9WgXcQ"
 * - video: {src:"/caminho/video.mp4"} se preferir MP4 local
 * - badges: etiquetas
 * - body: HTML do artigo
 */
const DOCS = [
  {
    category: "Introdução",
    slug: "boas-vindas",
    title: "Boas-vindas ao Evolua Prospect",
    yt: "l8mfP0LJw1E", // <— troque pelo seu ID do YouTube
    badges: ["overview", "primeiros passos"],
    body: `
      <h1>Boas-vindas 👋</h1>
      <p>Nesta página você encontra um panorama do sistema e os próximos passos para começar a usar.</p>
      <ul>
        <li>Conectar o WhatsApp</li>
        <li>Importar sua base de leads</li>
        <li>Criar um disparo com delays aleatórios</li>
      </ul>
      <p>Recomendamos seguir a playlist na ordem para uma melhor experiência.</p>
    `
  },
  {
    category: "Conexões",
    slug: "conectar-whatsapp",
    title: "Conectar seu WhatsApp",
    yt: "Q2J6G9u5WfE",
    badges: ["whatsapp", "conexao"],
    body: `
      <h1>Conectar WhatsApp</h1>
      <p>Acesse <strong>Conexões</strong> &rarr; <em>Gerar QR Code</em>, e escaneie com o app do WhatsApp.</p>
      <ul>
        <li>Mantenha o celular com internet e bateria.</li>
        <li>Se cair, gere um novo QR e reconecte.</li>
      </ul>
      <p><strong>Exemplo de fluxo de verificação</strong> (n8n, pseudo):</p>
      <pre><code>// Checa estado da instância
const res = await $http.get("${location.origin}/app/public/api/conexoes.php?action=status");
if (!res.ok) throw new Error("Sem conexão");
// segue o disparo...
</code></pre>
    `
  },
  {
    category: "Leads",
    slug: "importar-leads",
    title: "Importar Leads (CSV e Colagem)",
    yt: "s4XxYtQy3l8",
    badges: ["leads", "csv"],
    body: `
      <h1>Importar Leads</h1>
      <p>Em <strong>Leads</strong> &rarr; <em>Importar</em> você pode enviar um CSV ou colar dados. Telefones são normalizados automaticamente.</p>
      <ul>
        <li>Campos recomendados: <code>nome</code>, <code>telefone</code>, <code>tag</code></li>
        <li>Suporta formatos: <code>(11) 91234-5678</code> e <code>5511912345678</code></li>
      </ul>
    `
  },
  {
    category: "Disparos",
    slug: "criar-disparo",
    title: "Criar e Executar Disparos com Delays",
    yt: "Q0qVq3V2m8I",
    badges: ["disparos", "delays"],
    body: `
      <h1>Criar Disparos</h1>
      <p>Use janelas como <strong>20–50s</strong> (Delay Mín./Máx.). O sistema sorteia um valor aleatório a cada envio.</p>
      <pre><code>// Exemplo (n8n Code) — intervalo aleatório entre 20 e 50 segundos
const min=20, max=50;
const delay = Math.floor(Math.random()*(max-min+1))+min;
return [{ json: { delaySegundos: delay } }];
</code></pre>
      <p>Evite mensagens idênticas. Inclua variações e personalize com o nome do lead.</p>
    `
  },
  {
    category: "Agente de IA",
    slug: "agente-ia",
    title: "Usando o Agente de IA no Funil",
    yt: "Qy3l8s4XxYt",
    badges: ["ia", "funil"],
    body: `
      <h1>Agente de IA</h1>
      <p>O agente responde automaticamente, qualifica leads e pode transferir para humano quando necessário.</p>
      <ul>
        <li>Defina <em>tone</em> e objetivos no prompt</li>
        <li>Evite solicitar nome/e-mail se já vierem do front</li>
      </ul>
      <pre><code>// Exemplo de payload (resumo)
{
  "nome": "Maria",
  "whatsapp": "5599999999999",
  "contexto": "lead de tráfego pago"
}
</code></pre>
    `
  },
  {
    category: "Troubleshooting",
    slug: "erros-comuns",
    title: "Erros Comuns e Como Resolver",
    yt: "WfEQ2J6G9u5",
    badges: ["suporte", "erros"],
    body: `
      <h1>Erros Comuns</h1>
      <ul>
        <li><strong>401 Unauthorized</strong>: Sessão expirada – faça login novamente.</li>
        <li><strong>Instância offline</strong>: Reconecte o WhatsApp (QR Code).</li>
        <li><strong>CSV inválido</strong>: Cheque delimitadores e cabeçalhos.</li>
      </ul>
      <p>Se persistir, anexe prints e horário aproximado ao abrir chamado.</p>
    `
  }
];

/**
 * ===================================
 * 2) Renderização & Navegação (router)
 * ===================================
 */
const $q = (s, el=document) => el.querySelector(s);
const $qa = (s, el=document) => [...el.querySelectorAll(s)];

const state = { list: DOCS, filtered: DOCS, currentSlug: null };

function buildSidebar(list){
  const byCat = {};
  list.forEach(t => {
    byCat[t.category] = byCat[t.category] || [];
    byCat[t.category].push(t);
  });

  const nav = $q('#sidebarNav');
  nav.innerHTML = '';

  Object.entries(byCat).forEach(([cat, topics])=>{
    const det = document.createElement('details');
    det.className = 'group';
    det.open = true;
    const sum = document.createElement('summary');
    sum.textContent = cat;
    det.appendChild(sum);

    topics.forEach(t => {
      const a = document.createElement('a');
      a.href = `?t=${encodeURIComponent(t.slug)}`;
      a.className = 'topic';
      a.dataset.slug = t.slug;
      a.innerHTML = `
        <span>📄</span>
        <div>
          <div>${t.title}</div>
          <small>${t.badges?.join(' • ') || ''}</small>
        </div>
      `;
      det.appendChild(a);
    });

    nav.appendChild(det);
  });

  highlightActive();
}

function highlightActive(){
  $qa('.topic').forEach(el=>{
    el.classList.toggle('active', el.dataset.slug === state.currentSlug);
  });
}

function getTopic(slug){
  return state.list.find(t => t.slug === slug) || state.list[0];
}

function renderTopic(topic){
  state.currentSlug = topic.slug;
  // breadcrumbs
  $q('#breadcrumbs').textContent = `${topic.category} ▸ ${topic.title}`;

  // vídeo
  const mount = $q('#videoMount');
  mount.innerHTML = '';
  if (topic.yt){
    const iframe = document.createElement('iframe');
    iframe.setAttribute('src', `https://www.youtube.com/embed/${topic.yt}`);
    iframe.setAttribute('title', topic.title);
    iframe.setAttribute('frameborder', '0');
    iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');
    iframe.setAttribute('allowfullscreen', 'true');
    mount.appendChild(iframe);
  } else if (topic.video?.src){
    const vid = document.createElement('video');
    vid.controls = true;
    vid.src = topic.video.src;
    mount.appendChild(vid);
  } else {
    mount.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#fff;">Sem vídeo para este tópico</div>';
  }

  // corpo
  const body = $q('#articleBody');
  body.innerHTML = `
    ${topic.body || ''}
    <div class="badges">${(topic.badges||[]).map(b=>`<span class="badge">${b}</span>`).join('')}</div>
  `;

  // prev/next
  const idx = state.list.findIndex(x=>x.slug===topic.slug);
  const prev = idx>0 ? state.list[idx-1] : null;
  const next = idx<state.list.length-1 ? state.list[idx+1] : null;
  const np = $q('#nextPrev');
  np.innerHTML = `
    ${prev ? `<a href="?t=${encodeURIComponent(prev.slug)}">← ${prev.title}</a>` : '<span></span>'}
    ${next ? `<a style="text-align:right" href="?t=${encodeURIComponent(next.slug)}">${next.title} →</a>` : '<span></span>'}
  `;

  // salvar última leitura
  try { localStorage.setItem('evolua_docs_last', topic.slug); } catch {}
  highlightActive();
}

function initFromUrl(){
  const url = new URL(location.href);
  const slug = url.searchParams.get('t') || (localStorage.getItem('evolua_docs_last')||DOCS[0].slug);
  const topic = getTopic(slug);
  renderTopic(topic);
  buildSidebar(state.filtered);
}

function onNavClick(e){
  const a = e.target.closest('a.topic');
  if (!a) return;
  e.preventDefault();
  const url = new URL(a.href);
  history.pushState({}, '', url);
  renderTopic(getTopic(url.searchParams.get('t')));
}

function onSearch(e){
  const q = e.target.value.toLowerCase().trim();
  if (!q){
    state.filtered = state.list.slice();
  } else {
    state.filtered = state.list.filter(t =>
      t.title.toLowerCase().includes(q) ||
      (t.category.toLowerCase().includes(q)) ||
      (t.badges||[]).some(b=>b.toLowerCase().includes(q))
    );
  }
  buildSidebar(state.filtered);
}

function onCopyLink(){
  const url = new URL(location.href);
  url.searchParams.set('t', state.currentSlug || DOCS[0].slug);
  navigator.clipboard.writeText(url.toString())
    .then(()=> {
      const btn = $q('#copyLinkBtn');
      const prev = btn.textContent;
      btn.textContent = 'Link copiado!';
      setTimeout(()=>btn.textContent='Copiar link', 1200);
    })
    .catch(()=>alert('Não foi possível copiar o link'));
}

window.addEventListener('popstate', initFromUrl);

document.addEventListener('click', onNavClick);
$q('#searchInput').addEventListener('input', onSearch);
$q('#copyLinkBtn').addEventListener('click', onCopyLink);

initFromUrl();
</script>
