<?php /* Vendas > CRM: UI completa com Kanban, filtros e timeline */ ?>
<?php 
  // Injetar API Key temporária na UI para validação dos botões
  // Lida via localStorage ou cookie para que apiRequest adicione o cabeçalho X-API-Key
  use Gestoreasy\Core\Config\Config; 
  $tmpApiKey = (string)Config::get('SPED_API_KEY', '');
?>
<script>
  (function(){
    var k = '<?= htmlspecialchars($tmpApiKey, ENT_QUOTES) ?>';
    if (!k) return;
    try {
      if (!localStorage.getItem('api_key')) { localStorage.setItem('api_key', k); }
    } catch(_) {
      document.cookie = 'api_key=' + encodeURIComponent(k) + '; path=/';
    }
  })();
</script>
<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;gap:1rem;">
  <div>
    <h1>CRM de Vendas</h1>
    <p class="muted">Pipeline de oportunidades, atividades e interações</p>
  </div>
  <div>
    <a href="/dashboard" class="btn btn-secondary">Voltar</a>
  </div>
  </div>

<div class="card" style="padding:1rem;">
  <form id="crm-filters" style="display:flex;flex-wrap:wrap;gap:0.5rem;align-items:end;">
    <div>
      <label for="f-q">Buscar</label>
      <input id="f-q" type="text" placeholder="Empresa, contato ou e-mail" />
    </div>
    <div>
      <label for="f-seller">Vendedor</label>
      <select id="f-seller"><option value="">Todos</option></select>
    </div>
    <div>
      <label for="f-start">Início</label>
      <input id="f-start" type="date" />
    </div>
    <div>
      <label for="f-end">Fim</label>
      <input id="f-end" type="date" />
    </div>
    <button type="button" class="btn" id="btn-aplicar">Aplicar</button>
    <button type="button" class="btn btn-secondary" id="btn-limpar">Limpar</button>
    <div style="margin-left:auto;display:flex;gap:0.5rem;">
      <button type="button" class="btn" id="btn-novo">Novo Lead</button>
      <a id="btn-export" class="btn btn-secondary" href="#" target="_blank">Exportar CSV</a>
      <button type="button" class="btn btn-secondary" id="btn-export-pdf">Exportar PDF (Pipeline)</button>
      <button type="button" class="btn" id="btn-import-quotes" title="Importar orçamentos para o CRM">Importar Orçamentos</button>
      <button type="button" class="btn" id="btn-import-orders" title="Importar pedidos para o CRM">Importar Pedidos</button>
    </div>
  </form>
</div>

<div class="grid" style="display:grid;grid-template-columns: 2fr 1fr;gap:1rem;align-items:start;">
  <section>
    <div class="card" style="padding:0.5rem;margin-bottom:1rem;">
      <div style="display:flex;align-items:center;justify-content:space-between;">
        <h2 style="margin:0;">Funil do Pipeline</h2>
        <small id="pipeline-summary" class="muted"></small>
      </div>
      <canvas id="pipeline-chart" width="800" height="220" style="max-width:100%;"></canvas>
    </div>
    <div class="card" style="padding:0.5rem;">
      <div style="display:flex;align-items:center;gap:0.5rem;">
        <h2 style="margin:0;">Kanban</h2>
        <small id="kpi-summary" class="muted"></small>
      </div>
      <div id="kanban" style="margin-top:0.5rem;display:flex;gap:0.75rem;overflow-x:auto;">
        <!-- colunas -->
      </div>
    </div>

    <div class="card" style="margin-top:1rem;padding:0.5rem;">
      <div style="display:flex;align-items:center;justify-content:space-between;">
        <h2 style="margin:0;">Leads</h2>
      </div>
      <table id="leads-table" class="table" style="width:100%;">
        <thead>
          <tr>
            <th>Empresa</th><th>Contato</th><th>Vendedor</th><th>Estágio</th><th>Valor</th><th>Próx. ação</th><th></th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
      <div id="leads-pagination" style="display:flex;align-items:center;gap:0.5rem;justify-content:flex-end;margin-top:0.5rem;">
        <button class="btn btn-secondary" id="leads-prev">Anterior</button>
        <span id="leads-page-indicator" class="muted">Página 1</span>
        <button class="btn btn-secondary" id="leads-next">Próxima</button>
      </div>
    </div>
  </section>
  <aside>
    <div class="card" style="padding:0.5rem;">
      <h2 style="margin:0;">Detalhes</h2>
      <div id="lead-details" class="muted">Selecione um lead para ver detalhes.</div>
    </div>
    <div class="card" style="padding:0.5rem;margin-top:1rem;">
      <div style="display:flex;align-items:center;justify-content:space-between;">
        <h3 style="margin:0;">Atividades</h3>
        <button class="btn btn-secondary" id="btn-add-activity">Nova atividade</button>
      </div>
      <ul id="activities-list" style="list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:0.5rem;"></ul>
    </div>
  </aside>
</div>

<!-- Modal: Novo Lead -->
<dialog id="modal-novo-lead" style="max-width:640px;width:90%;">
  <form id="form-novo-lead" method="dialog" style="display:flex;flex-direction:column;gap:0.5rem;">
    <h3>Novo Lead</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.5rem;">
      <div>
        <label>Empresa</label>
        <input name="company" type="text" required />
      </div>
      <div>
        <label>Contato</label>
        <input name="contact_name" type="text" />
      </div>
      <div>
        <label>E-mail</label>
        <input name="email" type="email" />
      </div>
      <div>
        <label>Telefone</label>
        <input name="phone" type="text" />
      </div>
      <div>
        <label>Vendedor</label>
        <select name="seller_email" id="novo-seller"></select>
      </div>
      <div>
        <label>Estágio</label>
        <select name="stage_id" id="novo-stage"></select>
      </div>
      <div>
        <label>Valor (R$)</label>
        <input name="value_cents" type="number" step="0.01" min="0" />
      </div>
      <div>
        <label>Fonte</label>
        <input name="source" type="text" />
      </div>
    </div>
    <div>
      <label>Notas</label>
      <textarea name="notes" rows="3"></textarea>
    </div>
    <div style="display:flex;gap:0.5rem;justify-content:flex-end;">
      <button type="button" id="cancel-novo">Cancelar</button>
      <button type="submit" class="btn">Salvar</button>
    </div>
  </form>
  <div id="novo-lead-msg" class="muted" style="margin-top:0.5rem;"></div>
</dialog>

<!-- Modal: Nova Atividade -->
<dialog id="modal-atividade" style="max-width:520px;width:90%;">
  <form id="form-atividade" method="dialog" style="display:flex;flex-direction:column;gap:0.5rem;">
    <h3>Nova Atividade</h3>
    <div>
      <label>Tipo</label>
      <select name="type">
        <option value="call">Ligação</option>
        <option value="email">E-mail</option>
        <option value="meeting">Reunião</option>
        <option value="task">Tarefa</option>
        <option value="note">Nota</option>
      </select>
    </div>
    <div>
      <label>Assunto</label>
      <input name="subject" type="text" />
    </div>
    <div>
      <label>Para quando?</label>
      <input name="due_at" type="datetime-local" />
    </div>
    <div>
      <label>Observações</label>
      <textarea name="notes" rows="3"></textarea>
    </div>
    <div style="display:flex;gap:0.5rem;justify-content:flex-end;">
      <button type="button" id="cancel-atividade">Cancelar</button>
      <button type="submit" class="btn">Salvar</button>
    </div>
  </form>
  <div id="atividade-msg" class="muted" style="margin-top:0.5rem;"></div>
</dialog>

<!-- Biblioteca para Exportar PDF -->
<script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>

<!-- Modais: Editar Valor, Próxima Ação e Mover Estágio -->
<dialog id="modal-edit-valor" style="max-width:420px;width:90%;">
  <form id="form-edit-valor" method="dialog" style="display:flex;flex-direction:column;gap:0.5rem;">
    <h3>Editar Valor</h3>
    <div>
      <label>Novo valor (R$)</label>
      <input name="valor" id="input-edit-valor" type="number" step="0.01" min="0" />
    </div>
    <div style="display:flex;gap:0.5rem;justify-content:flex-end;">
      <button type="button" id="cancel-edit-valor">Cancelar</button>
      <button type="submit" class="btn">Salvar</button>
    </div>
  </form>
  <div id="edit-valor-msg" class="muted" style="margin-top:0.5rem;"></div>
  </dialog>

<dialog id="modal-edit-next" style="max-width:420px;width:90%;">
  <form id="form-edit-next" method="dialog" style="display:flex;flex-direction:column;gap:0.5rem;">
    <h3>Editar Próxima Ação</h3>
    <div>
      <label>Data e hora</label>
      <input name="next" id="input-edit-next" type="datetime-local" />
    </div>
    <small class="muted">Deixe em branco para limpar.</small>
    <div style="display:flex;gap:0.5rem;justify-content:flex-end;">
      <button type="button" id="cancel-edit-next">Cancelar</button>
      <button type="submit" class="btn">Salvar</button>
    </div>
  </form>
  <div id="edit-next-msg" class="muted" style="margin-top:0.5rem;"></div>
  </dialog>

<dialog id="modal-move-stage" style="max-width:420px;width:90%;">
  <form id="form-move-stage" method="dialog" style="display:flex;flex-direction:column;gap:0.5rem;">
    <h3>Mover Lead de Estágio</h3>
    <div>
      <label>Estágio</label>
      <select id="select-move-stage"></select>
    </div>
    <div style="display:flex;gap:0.5rem;justify-content:flex-end;">
      <button type="button" id="cancel-move-stage">Cancelar</button>
      <button type="submit" class="btn">Mover</button>
    </div>
  </form>
  <div id="move-stage-msg" class="muted" style="margin-top:0.5rem;"></div>
  </dialog>

<!-- Modal: Editar Atividade -->
<dialog id="modal-edit-activity" style="max-width:520px;width:90%;">
  <form id="form-edit-activity" method="dialog" style="display:flex;flex-direction:column;gap:0.5rem;">
    <h3>Editar Atividade</h3>
    <div>
      <label>Tipo</label>
      <select id="input-activity-type" name="type">
        <option value="call">Ligação</option>
        <option value="email">E-mail</option>
        <option value="meeting">Reunião</option>
        <option value="task">Tarefa</option>
        <option value="note">Nota</option>
      </select>
    </div>
    <div>
      <label>Assunto</label>
      <input id="input-activity-subject" name="subject" type="text" />
    </div>
    <div>
      <label>Para quando?</label>
      <input id="input-activity-due" name="due_at" type="datetime-local" />
    </div>
    <div>
      <label>Observações</label>
      <textarea id="input-activity-notes" name="notes" rows="3"></textarea>
    </div>
    <div style="display:flex;gap:0.5rem;justify-content:flex-end;">
      <button type="button" id="cancel-edit-activity">Cancelar</button>
      <button type="submit" class="btn">Salvar</button>
    </div>
  </form>
  <div id="edit-activity-msg" class="muted" style="margin-top:0.5rem;"></div>
</dialog>

<!-- Modal: Confirmar Exclusão de Atividade -->
<dialog id="modal-delete-activity" style="max-width:420px;width:90%;">
  <form method="dialog" style="display:flex;flex-direction:column;gap:0.5rem;">
    <h3>Excluir Atividade</h3>
    <div class="muted">Você está prestes a excluir: <strong id="delete-activity-label"></strong></div>
    <small class="muted">Esta ação não pode ser desfeita.</small>
    <div style="display:flex;gap:0.5rem;justify-content:flex-end;">
      <button type="button" id="cancel-delete-activity">Cancelar</button>
      <button type="button" class="btn" id="confirm-delete-activity">Excluir</button>
    </div>
  </form>
</dialog>
<script>
  const filters = { q:'', seller:'', start:'', end:'' };
  let stages = [];
  let selectedLeadId = null;
  let editingLead = null;
  let leadsPage = 1;
  let leadsLimit = 20;
  let lastLeadsCount = 0;

  function fmtMoney(cents){ return (cents/100).toLocaleString('pt-BR', {style:'currency', currency:'BRL'}); }
  function el(tag, attrs={}, children=[]) { const e = document.createElement(tag); Object.entries(attrs).forEach(([k,v])=>{ if(k==='class') e.className=v; else if(k==='text') e.textContent=v; else e.setAttribute(k,v); }); children.forEach(c=>{ if(typeof c==='string') e.appendChild(document.createTextNode(c)); else if(c) e.appendChild(c); }); return e; }

  async function loadConfig(){
    const r = await apiRequest('/api/vendas/crm/config'); const data = await r.json(); stages = data.stages || [];
    const sellerSel = document.querySelector('#f-seller'); sellerSel.innerHTML = '<option value="">Todos</option>' + (data.sellers||[]).map(s=>`<option>${s.email}</option>`).join('');
    const novoSeller = document.querySelector('#novo-seller'); novoSeller.innerHTML = (data.sellers||[]).map(s=>`<option>${s.email}</option>`).join('');
    const novoStage = document.querySelector('#novo-stage'); novoStage.innerHTML = stages.map(s=>`<option value="${s.id}">${s.name}</option>`).join('');
  }

  function stageById(id){ return stages.find(s=>s.id==id); }

  async function loadKanban(){
    const qs = new URLSearchParams(filters).toString();
    const r = await apiRequest('/api/vendas/crm/kanban?'+qs);
    const data = await r.json(); const columns = data.columns||[];
    const kb = document.querySelector('#kanban'); kb.innerHTML = '';
    let total = 0, count = 0;
    columns.forEach(col => {
      total += col.kpis?.value_cents||0; count += col.kpis?.count||0;
      const h = el('div', {class:'muted'}, [document.createTextNode(`${col.kpis?.count||0} • ${fmtMoney(col.kpis?.value_cents||0)}`)]);
      const list = el('div', {class:'kanban-list', style:'display:flex;flex-direction:column;gap:0.5rem;min-width:260px;background:#fafafa;border:1px solid #ddd;border-radius:6px;padding:0.5rem;'}, []);
      list.dataset.stageId = col.stage.id;
      list.addEventListener('dragover', ev=>{ ev.preventDefault(); list.style.background='#f0f7ff'; });
      list.addEventListener('dragleave', ev=>{ list.style.background='#fafafa'; });
      list.addEventListener('drop', async ev=>{ ev.preventDefault(); list.style.background='#fafafa'; const leadId = ev.dataTransfer.getData('text/plain'); if(!leadId) return; await moveLead(leadId, col.stage.id); await refreshAll(); });
      const title = el('div', {style:'display:flex;align-items:center;justify-content:space-between;margin-bottom:0.25rem;'}, [ el('strong',{text:col.stage.name}), h ]);
      kb.appendChild(el('div', {style:'min-width:280px;'}, [ title, list ]));
      // cards
      col.leads.forEach(l => {
        const card = el('div', {class:'card', style:'padding:0.5rem;cursor:grab;'});
        card.draggable = true;
        card.addEventListener('dragstart', ev=>{ ev.dataTransfer.setData('text/plain', l.id); });
        card.addEventListener('click', ()=>selectLead(l.id));
        const topRow = el('div', {style:'display:flex;align-items:center;justify-content:space-between;'});
        topRow.appendChild(el('strong',{text:l.company||'-'}));
        const valSpan = el('span',{class:'muted',text:fmtMoney(l.value_cents||0)});
        valSpan.style.cursor='pointer'; valSpan.title='Clique para editar valor';
        valSpan.addEventListener('click', async (ev)=>{ ev.stopPropagation(); openEditLeadValue(l); });
        topRow.appendChild(valSpan);
        card.appendChild(topRow);

        const contactRow = el('div', {class:'muted', text:(l.contact_name||'') + (l.email? ' • '+l.email : '')});
        card.appendChild(contactRow);
        const sellerRow = el('div', {class:'muted'});
        sellerRow.textContent = (l.seller_email||'');
        card.appendChild(sellerRow);

        const nextRow = el('div', {style:'display:flex;align-items:center;justify-content:space-between;'});
        const nextSpan = el('span',{class:'muted', text:(l.next_action_at||'') || 'Sem próxima ação'});
        nextSpan.style.cursor='pointer'; nextSpan.title='Clique para editar próxima ação';
        nextSpan.addEventListener('click', async (ev)=>{ ev.stopPropagation(); openEditLeadNextAction(l); });
        nextRow.appendChild(nextSpan);
        const moveBtn = el('button',{class:'btn btn-secondary'}, ['Mover']);
        moveBtn.addEventListener('click', async (ev)=>{ ev.stopPropagation(); openMoveLead(l, col.stage.id); });
        nextRow.appendChild(moveBtn);
        card.appendChild(nextRow);
        list.appendChild(card);
      });
    });
    document.querySelector('#kpi-summary').textContent = `${count} leads • ${fmtMoney(total)}`;
  }

  async function loadLeads(){
    const params = { ...filters, page: String(leadsPage), limit: String(leadsLimit) };
    const qs = new URLSearchParams(params).toString();
    const r = await apiRequest('/api/vendas/crm/leads?'+qs); const data = await r.json(); const items = data.items||[];
    lastLeadsCount = items.length;
    const tbody = document.querySelector('#leads-table tbody'); tbody.innerHTML = '';
    items.forEach(l => {
      const tr = el('tr');
      tr.dataset.leadId = String(l.id);
      tr.appendChild(el('td',{text:l.company||'-'}));
      tr.appendChild(el('td',{text:(l.contact_name||'') + (l.email? ' • '+l.email : '')}));
      tr.appendChild(el('td',{text:l.seller_email||''}));
      tr.appendChild(el('td',{text:stageById(l.stage_id)?.name || ''}));
      tr.appendChild(el('td',{text:fmtMoney(l.value_cents||0)}));
      tr.appendChild(el('td',{text:(l.next_action_at||'')}));
      const tdAct = el('td');
      const btnVer = el('button',{class:'btn btn-secondary'}, [ 'Ver' ]); btnVer.addEventListener('click', ()=>selectLead(l.id)); tdAct.appendChild(btnVer);
      tr.appendChild(tdAct);
      tbody.appendChild(tr);
    });
    updatePaginationControls();
  }

  function updatePaginationControls(){
    const prev = document.querySelector('#leads-prev');
    const next = document.querySelector('#leads-next');
    const ind = document.querySelector('#leads-page-indicator');
    if (ind) ind.textContent = `Página ${leadsPage}`;
    if (prev) prev.disabled = (leadsPage <= 1);
    if (next) next.disabled = (lastLeadsCount < leadsLimit);
  }

  async function selectLead(id){ selectedLeadId = id; await loadLeadDetails(); await loadActivities(); }

  async function loadLeadDetails(){
    const details = document.querySelector('#lead-details');
    const row = document.querySelector(`#leads-table tbody tr[data-lead-id="${selectedLeadId}"]`);
    const nameCell = row?.children?.[0];
    if (!nameCell) { details.textContent = 'Lead não encontrado.'; return; }
    details.innerHTML = '';
    details.appendChild(el('div', {style:'display:flex;align-items:center;justify-content:space-between;'}, [ el('strong',{text:nameCell.textContent}), el('div',{class:'muted',text:`ID ${selectedLeadId}`}) ]));
    // Ações rápidas
    const actions = el('div', {style:'display:flex;gap:0.5rem;margin-top:0.25rem;flex-wrap:wrap;'});
    stages.forEach(s=>{
      const b = el('button',{class:'btn btn-secondary',text:s.name});
      b.addEventListener('click', async ()=>{ await moveLead(selectedLeadId, s.id); await refreshAll(); });
      actions.appendChild(b);
    });
    // Conversões
    const btnConvQuote = el('button',{class:'btn'}, ['Converter em Orçamento']);
    btnConvQuote.addEventListener('click', async ()=>{ if(!selectedLeadId){ alert('Selecione um lead'); return; } const r = await apiRequest(`/api/vendas/crm/leads/${selectedLeadId}/convert/quote`, { method:'POST' }); const res = await r.json(); if(res.ok){ const info = el('div',{class:'muted'}); info.innerHTML = `Orçamento criado: <strong>${res.quote_numero}</strong> • <a href="/vendas/orcamentos" target="_blank">Abrir lista</a> • <a href="/vendas/orcamentos/${res.quote_id}/imprimir" target="_blank">Imprimir</a>`; details.appendChild(info); } else { alert('Falha: '+(res.error||'erro desconhecido')); } });
    const btnConvOrder = el('button',{class:'btn'}, ['Converter em Pedido']);
    btnConvOrder.addEventListener('click', async ()=>{ if(!selectedLeadId){ alert('Selecione um lead'); return; } const r = await apiRequest(`/api/vendas/crm/leads/${selectedLeadId}/convert/order`, { method:'POST' }); const res = await r.json(); if(res.ok){ const info = el('div',{class:'muted'}); info.innerHTML = `Pedido criado: <strong>${res.order_numero}</strong> • <a href="/vendas/pedidos" target="_blank">Abrir lista</a> • <a href="/vendas/pedidos/${res.order_id}/imprimir" target="_blank">Imprimir</a>`; details.appendChild(info); } else { alert('Falha: '+(res.error||'erro desconhecido')); } });
    const convWrap = el('div',{style:'display:flex;gap:0.5rem;'}); convWrap.appendChild(btnConvQuote); convWrap.appendChild(btnConvOrder);
    actions.appendChild(convWrap);
    details.appendChild(actions);
  }

  async function loadActivities(){
    const list = document.querySelector('#activities-list'); list.innerHTML = '';
    if (!selectedLeadId) { list.appendChild(el('li',{class:'muted',text:'Nenhum lead selecionado.'})); return; }
    const r = await apiRequest(`/api/vendas/crm/leads/${selectedLeadId}/atividades`);
    const data = await r.json(); const items = data.items||[];
    items.forEach(a => {
      const li = el('li', {class:'card', style:'padding:0.5rem;'});
      li.appendChild(el('div',{style:'display:flex;align-items:center;justify-content:space-between;'}, [ el('strong',{text:(a.type||'')+ (a.subject? ': '+a.subject : '')}), el('span',{class:'muted',text:a.due_at||a.done_at||a.created_at||''}) ]));
      li.appendChild(el('div',{class:'muted',text:a.notes||''}));
      const actions = el('div', {style:'display:flex;gap:0.5rem;margin-top:0.25rem;'});
      const doneBtn = el('button',{class:'btn btn-secondary'}, ['Concluir']);
      doneBtn.disabled = !!a.done_at;
      doneBtn.title = a.done_at ? 'Já concluída' : 'Marcar como concluída';
      doneBtn.addEventListener('click', async ()=>{ await updateActivity(a.id, { done_at: new Date().toISOString().slice(0,19).replace('T',' ') }); await loadActivities(); });
      const editBtn = el('button',{class:'btn btn-secondary'}, ['Editar']);
      editBtn.addEventListener('click', ()=>{ openEditActivity(a); });
      const delBtn = el('button',{class:'btn btn-secondary'}, ['Excluir']);
      delBtn.addEventListener('click', ()=>{ openDeleteActivity(a); });
      actions.appendChild(doneBtn);
      actions.appendChild(editBtn);
      actions.appendChild(delBtn);
      li.appendChild(actions);
      list.appendChild(li);
    });
    if (items.length===0) list.appendChild(el('li',{class:'muted',text:'Sem atividades.'}));
  }

  async function moveLead(id, stageId){
    await apiRequest(`/api/vendas/crm/leads/${id}/move`, { method:'POST', body: JSON.stringify({stage_id:stageId}) });
  }

  async function updateLead(id, data){
    await apiRequest(`/api/vendas/crm/leads/${id}`, { method:'PUT', body: JSON.stringify(data) });
  }
  function openEditLeadValue(lead){
    editingLead = lead;
    const m = document.querySelector('#modal-edit-valor');
    const input = document.querySelector('#input-edit-valor');
    if (input) { input.value = ((lead.value_cents||0)/100).toString(); }
    m.showModal();
  }
  function openEditLeadNextAction(lead){
    editingLead = lead;
    const m = document.querySelector('#modal-edit-next');
    const input = document.querySelector('#input-edit-next');
    const v = (lead.next_action_at||'');
    const val = v ? (v.replace(' ', 'T').slice(0,16)) : '';
    if (input) { input.value = val; }
    m.showModal();
  }
  function openMoveLead(lead, currentStageId){
    editingLead = lead;
    const m = document.querySelector('#modal-move-stage');
    const sel = document.querySelector('#select-move-stage');
    if (sel) {
      sel.innerHTML = stages.map(s=>`<option value="${s.id}">${s.name}</option>`).join('');
      sel.value = String(currentStageId||lead.stage_id||'');
    }
    m.showModal();
  }

  async function updateActivity(id, data){
    await apiRequest(`/api/vendas/crm/atividades/${id}`, { method:'PUT', body: JSON.stringify(data) });
  }

  async function deleteActivity(id){
    await apiRequest(`/api/vendas/crm/atividades/${id}`, { method:'DELETE' });
  }

  function updateExportLink(){
    const qs = new URLSearchParams(filters).toString();
    const href = qs ? '/api/vendas/crm/export?' + qs : '/api/vendas/crm/export';
    const a = document.querySelector('#btn-export'); if (a) a.href = href;
  }

  async function refreshAll(){ await loadKanban(); await loadLeads(); await loadLeadDetails(); await loadActivities(); }

  // Novo lead
  document.addEventListener('DOMContentLoaded', ()=>{
    loadConfig().then(refreshAll);
    const btnAplicar = document.querySelector('#btn-aplicar');
    const btnLimpar = document.querySelector('#btn-limpar');
    const btnNovo = document.querySelector('#btn-novo');
    const modalNovo = document.querySelector('#modal-novo-lead');
    const formNovo = document.querySelector('#form-novo-lead');
    const msgNovo = document.querySelector('#novo-lead-msg');
    const btnAddAct = document.querySelector('#btn-add-activity');
    const modalAct = document.querySelector('#modal-atividade');
    const formAct = document.querySelector('#form-atividade');
    const btnExportPdf = document.querySelector('#btn-export-pdf');
    const btnImportQuotes = document.querySelector('#btn-import-quotes');
    const btnImportOrders = document.querySelector('#btn-import-orders');

    // Modais: Editar Atividade
    const modalEditAct = document.querySelector('#modal-edit-activity');
    const formEditAct = document.querySelector('#form-edit-activity');
    document.querySelector('#cancel-edit-activity')?.addEventListener('click', ()=> modalEditAct.close());
    formEditAct.addEventListener('submit', async (ev)=>{
      ev.preventDefault();
      const data = Object.fromEntries(new FormData(formEditAct).entries());
      const payload = {
        type: data.type||null,
        subject: data.subject||null,
        due_at: (data.due_at? String(data.due_at).replace('T',' ') + (String(data.due_at).length===16? ':00' : '') : null),
        notes: data.notes||null
      };
      try { await updateActivity(editingActivity.id, payload); showAlert('Atividade atualizada', 'success'); }
      catch(e){ showAlert('Erro ao atualizar atividade: '+(e.message||e), 'error'); }
      modalEditAct.close(); await loadActivities();
    });

    // Modais: Excluir Atividade
    const modalDelAct = document.querySelector('#modal-delete-activity');
    document.querySelector('#cancel-delete-activity')?.addEventListener('click', ()=> modalDelAct.close());
    document.querySelector('#confirm-delete-activity')?.addEventListener('click', async ()=>{
      try { await deleteActivity(deletingActivityId); showAlert('Atividade excluída', 'success'); }
      catch(e){ showAlert('Erro ao excluir atividade: '+(e.message||e), 'error'); }
      modalDelAct.close(); deletingActivityId = null; await loadActivities();
    });

    // Modais: Editar Valor
    const modalEditValor = document.querySelector('#modal-edit-valor');
    const formEditValor = document.querySelector('#form-edit-valor');
    document.querySelector('#cancel-edit-valor')?.addEventListener('click', ()=> modalEditValor.close());
    formEditValor.addEventListener('submit', async (ev)=>{
      ev.preventDefault();
      const raw = (document.querySelector('#input-edit-valor')?.value || '').trim();
      const num = Number(String(raw).replace(',','.'));
      if (isNaN(num)) { showAlert('Valor inválido', 'error'); return; }
      try { await updateLead(editingLead.id, { value_cents: Math.round(num*100) }); showAlert('Valor atualizado', 'success'); }
      catch(e){ showAlert('Erro ao atualizar valor: '+(e.message||e), 'error'); }
      modalEditValor.close(); await refreshAll();
    });

    // Modais: Editar Próxima Ação
    const modalEditNext = document.querySelector('#modal-edit-next');
    const formEditNext = document.querySelector('#form-edit-next');
    document.querySelector('#cancel-edit-next')?.addEventListener('click', ()=> modalEditNext.close());
    formEditNext.addEventListener('submit', async (ev)=>{
      ev.preventDefault();
      const raw = (document.querySelector('#input-edit-next')?.value || '').trim();
      const payload = { next_action_at: (raw? raw.replace('T',' ') + (raw.length===16? ':00' : '') : null) };
      try { await updateLead(editingLead.id, payload); showAlert('Próxima ação atualizada', 'success'); }
      catch(e){ showAlert('Erro ao atualizar próxima ação: '+(e.message||e), 'error'); }
      modalEditNext.close(); await refreshAll();
    });

    // Modais: Mover Estágio
    const modalMoveStage = document.querySelector('#modal-move-stage');
    const formMoveStage = document.querySelector('#form-move-stage');
    document.querySelector('#cancel-move-stage')?.addEventListener('click', ()=> modalMoveStage.close());
    formMoveStage.addEventListener('submit', async (ev)=>{
      ev.preventDefault();
      const target = parseInt(String(document.querySelector('#select-move-stage')?.value||''), 10);
      if (!target || isNaN(target)) { showAlert('Estágio inválido', 'error'); return; }
      try { await moveLead(editingLead.id, target); showAlert('Lead movido de estágio', 'success'); }
      catch(e){ showAlert('Erro ao mover lead: '+(e.message||e), 'error'); }
      modalMoveStage.close(); await refreshAll();
    });

    btnAplicar.addEventListener('click', ()=>{
      filters.q = document.querySelector('#f-q').value.trim();
      filters.seller = document.querySelector('#f-seller').value;
      filters.start = document.querySelector('#f-start').value;
      filters.end = document.querySelector('#f-end').value;
      leadsPage = 1;
      updateExportLink();
      refreshAll();
    });
    btnLimpar.addEventListener('click', ()=>{
      document.querySelector('#f-q').value=''; document.querySelector('#f-seller').value=''; document.querySelector('#f-start').value=''; document.querySelector('#f-end').value='';
      filters.q=''; filters.seller=''; filters.start=''; filters.end='';
      leadsPage = 1;
      updateExportLink();
      refreshAll();
    });
    updateExportLink();
    btnNovo.addEventListener('click', ()=>{ modalNovo.showModal(); });
    document.querySelector('#cancel-novo').addEventListener('click', ()=> modalNovo.close());
    formNovo.addEventListener('submit', async (ev)=>{
      ev.preventDefault(); msgNovo.textContent = '';
      const data = Object.fromEntries(new FormData(formNovo).entries());
      if (data.value_cents) { data.value_cents = Math.round(parseFloat(data.value_cents.replace(',','.'))*100); }
      const r = await apiRequest('/api/vendas/crm/leads', { method:'POST', body: JSON.stringify(data) });
      const res = await r.json(); if (res.id){ msgNovo.textContent = 'Lead criado com sucesso'; modalNovo.close(); refreshAll(); } else { msgNovo.textContent = 'Erro: '+(res.error||'Falha ao criar'); }
    });
    btnAddAct.addEventListener('click', ()=>{ if(!selectedLeadId){ alert('Selecione um lead primeiro'); return; } modalAct.showModal(); });
    document.querySelector('#cancel-atividade').addEventListener('click', ()=> modalAct.close());
    formAct.addEventListener('submit', async (ev)=>{
      ev.preventDefault(); document.querySelector('#atividade-msg').textContent='';
      if(!selectedLeadId){ document.querySelector('#atividade-msg').textContent='Selecione um lead primeiro'; return; }
      const data = Object.fromEntries(new FormData(formAct).entries());
      const r = await apiRequest(`/api/vendas/crm/leads/${selectedLeadId}/atividades`, { method:'POST', body: JSON.stringify(data) });
      const res = await r.json(); if(res.id){ document.querySelector('#atividade-msg').textContent='Atividade adicionada'; modalAct.close(); refreshAll(); } else { document.querySelector('#atividade-msg').textContent='Erro: '+(res.error||'Falha ao salvar'); }
    });

    btnExportPdf.addEventListener('click', async ()=>{
      const data = await loadPipeline(true);
      exportPipelinePdf(data?.stages||[]);
    });

    async function runImport(endpoint){
      const qs = new URLSearchParams(filters).toString();
      const url = endpoint + '?' + qs;
      try {
        const r = await apiRequest(url, { method:'POST', skipAuth: true, useApiKey: true });
        const res = await r.json();
        if (res.ok) { alert(`Importação concluída: criados ${res.created}, atualizados ${res.updated}, ignorados ${res.skipped}`); refreshAll(); }
        else { alert('Falha na importação: ' + (res.error||'erro desconhecido')); }
      } catch (e) { alert('Erro na importação: '+ e.message); }
    }
    btnImportQuotes.addEventListener('click', async ()=>{ await runImport('/api/vendas/crm/import/quotes'); });
    btnImportOrders.addEventListener('click', async ()=>{ await runImport('/api/vendas/crm/import/orders'); });

    // Paginação: eventos
    document.querySelector('#leads-prev')?.addEventListener('click', async ()=>{ if (leadsPage>1) { leadsPage--; await loadLeads(); } });
    document.querySelector('#leads-next')?.addEventListener('click', async ()=>{ if (lastLeadsCount >= leadsLimit) { leadsPage++; await loadLeads(); } });
  });

  let editingActivity = null;
  let deletingActivityId = null;
  function openEditActivity(a){
    editingActivity = a;
    const m = document.querySelector('#modal-edit-activity');
    const type = document.querySelector('#input-activity-type');
    const subj = document.querySelector('#input-activity-subject');
    const due = document.querySelector('#input-activity-due');
    const notes = document.querySelector('#input-activity-notes');
    if (type) type.value = a.type||'';
    if (subj) subj.value = a.subject||'';
    if (due) due.value = a.due_at ? a.due_at.replace(' ','T').slice(0,16) : '';
    if (notes) notes.value = a.notes||'';
    m.showModal();
  }
  function openDeleteActivity(a){
    deletingActivityId = a.id;
    const m = document.querySelector('#modal-delete-activity');
    const lbl = document.querySelector('#delete-activity-label');
    if (lbl) lbl.textContent = `${a.type||'Atividade'}${a.subject? ': '+a.subject : ''}`;
    m.showModal();
  }

  async function loadPipeline(returnData=false){
    const qs = new URLSearchParams(filters).toString();
    const r = await apiRequest('/api/vendas/crm/pipeline?'+qs);
    const data = await r.json();
    drawPipelineChart(data?.stages||[]);
    if (returnData) return data;
  }

  function drawPipelineChart(stages){
    const c = document.getElementById('pipeline-chart'); if(!c) return;
    const ctx = c.getContext('2d'); if(!ctx) return;
    ctx.clearRect(0,0,c.width,c.height);
    const labels = stages.map(s=>s.stage_name);
    const totals = stages.map(s=> Number(s.total_cents||0)/100);
    const max = Math.max(1, ...totals);
    const w = c.width, h = c.height, pad = 40;
    const barW = Math.max(20, Math.floor((w - pad*2) / (labels.length||1) - 10));
    // Axes
    ctx.strokeStyle = '#999'; ctx.beginPath(); ctx.moveTo(pad, pad); ctx.lineTo(pad, h-pad); ctx.lineTo(w-pad, h-pad); ctx.stroke();
    // Bars
    totals.forEach((val, i) => {
      const x = pad + i*(barW+10) + 10;
      const bh = Math.round((val / max) * (h - pad*2));
      ctx.fillStyle = '#4a90e2'; ctx.fillRect(x, h-pad-bh, barW, bh);
      ctx.fillStyle = '#333'; ctx.font = '12px sans-serif';
      ctx.save(); ctx.translate(x + barW/2, h-pad+14); ctx.rotate(-Math.PI/6);
      ctx.textAlign='center'; ctx.fillText(String(labels[i]||''), 0, 0); ctx.restore();
      ctx.fillStyle = '#000'; ctx.textAlign='center';
      ctx.fillText((val).toLocaleString('pt-BR',{style:'currency', currency:'BRL'}), x+barW/2, h-pad-bh-6);
    });
    const sum = totals.reduce((a,b)=>a+b,0);
    const summaryEl = document.querySelector('#pipeline-summary');
    const baseText = `${labels.length} estágios • Total ${sum.toLocaleString('pt-BR',{style:'currency', currency:'BRL'})}`;
    if (sum === 0) {
      summaryEl.textContent = baseText + ' • Sem dados para os filtros';
    } else {
      summaryEl.textContent = baseText;
    }
  }

  function exportPipelinePdf(stages){
    if (!window.jspdf?.jsPDF) { alert('Biblioteca jsPDF não encontrada'); return; }
    const doc = new window.jspdf.jsPDF({unit:'pt',format:'a4'});
    const title = 'Relatório do Pipeline CRM';
    doc.setFont('helvetica','bold'); doc.setFontSize(14); doc.text(title, 40, 40);
    doc.setFont('helvetica','normal'); doc.setFontSize(10);
    const filtersText = `Filtros: q="${filters.q}", vendedor="${filters.seller||'Todos'}", período=${filters.start||'-'} a ${filters.end||'-'}`;
    doc.text(filtersText, 40, 60);
    let y = 90;
    doc.setFont('helvetica','bold'); doc.text('Estágio', 40, y); doc.text('Qtde', 260, y); doc.text('Total (R$)', 320, y);
    doc.setFont('helvetica','normal'); y += 14;
    let grand = 0;
    stages.forEach(s => { const tot = Number(s.total_cents||0)/100; grand += tot; doc.text(String(s.stage_name||''), 40, y); doc.text(String(s.qty||0), 260, y); doc.text(tot.toLocaleString('pt-BR',{style:'currency', currency:'BRL'}), 320, y); y += 16; });
    doc.setFont('helvetica','bold'); doc.text(`Total geral: ${grand.toLocaleString('pt-BR',{style:'currency', currency:'BRL'})}`, 40, y+8);
    doc.save('pipeline_crm.pdf');
  }
</script>