<div class="card" style="padding: 16px;">
  <h1>Relatórios de Clientes</h1>
  <p>Extração e análise por período, status e busca. Exporte em CSV.</p>

  <div style="display:flex; gap:12px; flex-wrap:wrap; margin: 12px 0;">
    <div class="form-group">
      <label for="cliDataInicio">Início</label>
      <input id="cliDataInicio" type="date" />
    </div>
    <div class="form-group">
      <label for="cliDataFim">Fim</label>
      <input id="cliDataFim" type="date" />
    </div>
    <div class="form-group" style="min-width:220px;">
      <label for="cliStatus">Status</label>
      <select id="cliStatus">
        <option value="todos">Todos</option>
        <option value="ativos">Ativos</option>
        <option value="inativos">Inativos</option>
        <option value="bloqueados">Bloqueados</option>
      </select>
    </div>
    <div class="form-group" style="flex:1; min-width:240px; position: relative;">
      <label for="cliBusca">Busca</label>
      <input id="cliBusca" type="text" placeholder="Nome, fantasia, CPF/CNPJ" autocomplete="off" />
      <input id="cliClienteId" type="hidden" />
      <div id="cliBuscaAutocomplete" style="position:absolute; left:0; right:0; top:100%; background:#fff; border:1px solid #ddd; border-top:none; z-index:1000; display:none; max-height:240px; overflow:auto; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
        <div id="cliAutoList"></div>
        <div id="cliAutoPagination" style="display:flex; justify-content:space-between; border-top:1px solid #eee; padding:6px; background:#fafafa; position:sticky; bottom:0;">
          <button id="cliAutoPrev" class="btn" style="padding:4px 8px;">Anterior</button>
          <span id="cliAutoPageInfo" style="align-self:center; font-size:12px; color:#666;">Página 1</span>
          <button id="cliAutoNext" class="btn" style="padding:4px 8px;">Próxima</button>
        </div>
      </div>
    </div>
    <div class="form-group">
      <label for="cliCsvSep">Separador CSV</label>
      <select id="cliCsvSep">
        <option value=";">Ponto e vírgula (;)</option>
        <option value=",">Vírgula (,)</option>
        <option value="\t">Tabulação (\t)</option>
      </select>
    </div>
    <div class="form-group" style="min-width:160px;">
      <label for="cliDiasSemCompra">Dias sem compra</label>
      <input id="cliDiasSemCompra" type="number" min="1" step="1" value="90" />
    </div>
  </div>

  <div style="display:flex; gap:8px; margin-bottom: 12px;">
    <button id="cliBtnGerar" class="btn">Gerar</button>
    <button id="cliBtnExport" class="btn">Exportar CSV</button>
  </div>

  <div id="cliResumo" style="display:flex; gap:12px; flex-wrap:wrap; margin-bottom: 12px;">
    <div class="card" style="padding:8px;">
      <div>Total Ativos</div>
      <strong id="cliTotAtivos">-</strong>
    </div>
    <div class="card" style="padding:8px;">
      <div>Inativos</div>
      <strong id="cliTotInativos">-</strong>
    </div>
    <div class="card" style="padding:8px;">
      <div>Bloqueados</div>
      <strong id="cliTotBloqueados">-</strong>
    </div>
    <div class="card" style="padding:8px;">
      <div>Com movimentação</div>
      <strong id="cliTotMov">-</strong>
    </div>
    <div class="card" style="padding:8px;">
      <div>Valor total (período)</div>
      <strong id="cliTotValor">R$ -</strong>
    </div>
  </div>

  <div style="margin-bottom:8px; display:flex; gap:6px;">
    <button id="tabLista" class="btn btn-secondary" data-tab="lista">Lista</button>
    <button id="tabRanking" class="btn btn-secondary" data-tab="ranking">Ranking</button>
    <button id="tabInativos" class="btn btn-secondary" data-tab="inativos">Inativos</button>
  </div>

  <div id="secLista" class="table" style="overflow:auto;">
    <table style="width:100%; border-collapse: collapse;">
      <thead>
        <tr style="text-align:left; border-bottom: 1px solid #ddd;">
          <th>ID</th>
          <th>Cliente</th>
          <th>Pedidos</th>
          <th>Total Vendas</th>
          <th>Última Compra</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody id="cliTabelaBody"></tbody>
    </table>
  </div>

  <div id="secRanking" class="table" style="overflow:auto; display:none;">
    <table style="width:100%; border-collapse: collapse;">
      <thead>
        <tr style="text-align:left; border-bottom: 1px solid #ddd;">
          <th>#</th>
          <th>ID</th>
          <th>Cliente</th>
          <th>Pedidos</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody id="cliRankingBody"></tbody>
    </table>
  </div>

  <div id="secInativos" class="table" style="overflow:auto; display:none;">
    <table style="width:100%; border-collapse: collapse;">
      <thead>
        <tr style="text-align:left; border-bottom: 1px solid #ddd;">
          <th>ID</th>
          <th>Cliente</th>
          <th>Última Compra</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody id="cliInativosBody"></tbody>
    </table>
  </div>

  <div style="margin-top:10px;">
    <small>Dica: clique em Gerar após ajustar filtros para atualizar os dados.</small>
  </div>
</div>

<script>
function apiRequest(url, options){
  // Reaproveita a função global de _layout.php, que gerencia tokens e 401 sem redirecionar
  if (typeof window.apiRequest === 'function') {
    return window.apiRequest(url, options || {});
  }
  const opts = options || {}; const headers = opts.headers || {};
  return fetch(url, { ...opts, headers, credentials: 'include' });
}

function fmtMoney(v){ try { return 'R$ ' + Number(v||0).toLocaleString('pt-BR', {minimumFractionDigits: 2, maximumFractionDigits: 2}); } catch(e){ return 'R$ ' + (v||0); } }

function readFilters(){
  return {
    start: document.getElementById('cliDataInicio').value,
    end: document.getElementById('cliDataFim').value,
    status: document.getElementById('cliStatus').value,
    q: document.getElementById('cliBusca').value,
    cliente_id: document.getElementById('cliClienteId').value,
    dias: document.getElementById('cliDiasSemCompra').value,
    sep: document.getElementById('cliCsvSep').value
  };
}

function saveFilters(){
  const f = readFilters();
  try { localStorage.setItem('rel_cli_filters', JSON.stringify(f)); } catch(e){}
}
function restoreFilters(){
  try {
    const raw = localStorage.getItem('rel_cli_filters');
    if(!raw) return;
    const f = JSON.parse(raw);
    if(f.start) document.getElementById('cliDataInicio').value = f.start;
    if(f.end) document.getElementById('cliDataFim').value = f.end;
    if(f.status) document.getElementById('cliStatus').value = f.status;
    if(f.q) document.getElementById('cliBusca').value = f.q;
    if(f.cliente_id) document.getElementById('cliClienteId').value = f.cliente_id;
    if(f.dias) document.getElementById('cliDiasSemCompra').value = f.dias;
    if(f.sep) document.getElementById('cliCsvSep').value = f.sep;
  } catch(e){}
}

function attachFilterListeners(){
  ['cliDataInicio','cliDataFim','cliStatus','cliBusca','cliCsvSep'].forEach(id => {
    const el = document.getElementById(id); if(!el) return;
    el.addEventListener('change', saveFilters);
    el.addEventListener('input', saveFilters);
  });
}

async function carregarResumo(){
  const { start, end } = readFilters();
  const url = new URL('/api/relatorios/clientes/resumo', window.location.origin);
  if(start) url.searchParams.set('start', start);
  if(end) url.searchParams.set('end', end);
  const resp = await apiRequest(url.toString());
  if(!resp.ok) return;
  const data = await resp.json();
  const t = data.totais || {};
  document.getElementById('cliTotAtivos').textContent = t.ativos ?? '-';
  document.getElementById('cliTotInativos').textContent = t.inativos ?? '-';
  document.getElementById('cliTotBloqueados').textContent = t.bloqueados ?? '-';
  document.getElementById('cliTotMov').textContent = t.clientes_com_movimentacao ?? '-';
  document.getElementById('cliTotValor').textContent = fmtMoney(t.valor_total ?? 0);
}

async function carregarLista(){
  const f = readFilters();
  const url = new URL('/api/relatorios/clientes/list', window.location.origin);
  Object.entries({start:f.start,end:f.end,status:f.status,q:f.q,cliente_id:f.cliente_id}).forEach(([k,v]) => { if(v) url.searchParams.set(k,v); });
  // Paginação/ordenação server-side
  const cfg = window.__cliPagination || { page: 1, per_page: 25, sort: 'total_vendas', dir: 'desc' };
  url.searchParams.set('per_page', String(cfg.per_page || 25));
  url.searchParams.set('page', String(cfg.page || 1));
  url.searchParams.set('sort', cfg.sort || 'total_vendas');
  url.searchParams.set('dir', (cfg.dir || 'desc').toLowerCase()==='asc' ? 'asc' : 'desc');
  const resp = await apiRequest(url.toString());
  if(!resp.ok) return;
  const json = await resp.json();
  const rows = json.data || [];
  const tbody = document.getElementById('cliTabelaBody');
  tbody.innerHTML = '';
  rows.forEach(r => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.id}</td>
      <td>${r.nome || r.nome_fantasia || '-'}</td>
      <td>${r.pedidos ?? 0}</td>
      <td>${fmtMoney(r.total_vendas ?? 0)}</td>
      <td>${(r.ultima_compra||'').replace('T',' ').replace('.000Z','')}</td>
      <td>${r.bloqueado ? 'Bloqueado' : (r.inativo ? 'Inativo' : 'Ativo')}</td>
    `;
    tbody.appendChild(tr);
  });
  // Atualiza barra de paginação da Lista
  try {
    const total = (typeof json.total === 'number') ? json.total : 0;
    const totalPages = Math.max(1, Math.ceil(total / (cfg.per_page||25)));
    const pageInfo = document.getElementById('cliPageInfo'); if(pageInfo) pageInfo.textContent = `Página ${cfg.page||1} de ${totalPages}`;
    const prev = document.getElementById('cliPrevPage'); if(prev) prev.disabled = (cfg.page||1) <= 1;
    const next = document.getElementById('cliNextPage'); if(next) next.disabled = (cfg.page||1) >= totalPages || (Array.isArray(json.data) && json.data.length < (cfg.per_page||25));
  } catch(e){}
}

async function carregarRanking(){
  const f = readFilters();
  const url = new URL('/api/relatorios/clientes/ranking', window.location.origin);
  Object.entries({start:f.start,end:f.end}).forEach(([k,v]) => { if(v) url.searchParams.set(k,v); });
  url.searchParams.set('page', String(window.__rankPage || 1));
  url.searchParams.set('per_page', String(window.__rankPerPage || 25));
  // Ordenação server-side para Ranking
  url.searchParams.set('sort', String(window.__rankSort || 'total'));
  url.searchParams.set('dir', String((window.__rankDir || 'desc').toLowerCase()==='asc'?'asc':'desc'));
  const resp = await apiRequest(url.toString());
  if(!resp.ok) return;
  const json = await resp.json();
  window.__rankData = json.data || [];
  window.__rankTotalPages = json.total_pages || 1;
  window.__rankPage = Math.max(1, Math.min(window.__rankPage || 1, window.__rankTotalPages));
  window.__rankPerPage = window.__rankPerPage || 25;
  renderRankingPage();
}

async function carregarInativos(){
  const f = readFilters();
  const url = new URL('/api/relatorios/clientes/inativos', window.location.origin);
  url.searchParams.set('dias', String(f.dias||90));
  url.searchParams.set('page', String(window.__inativosPage || 1));
  url.searchParams.set('per_page', String(window.__inativosPerPage || 25));
  // Ordenação server-side para Inativos
  url.searchParams.set('sort', String(window.__inativosSort || 'ultima_compra'));
  url.searchParams.set('dir', String((window.__inativosDir || 'asc').toLowerCase()==='desc'?'desc':'asc'));
  const resp = await apiRequest(url.toString());
  if(!resp.ok) return;
  const json = await resp.json();
  window.__inativosData = json.data || [];
  window.__inativosTotalPages = json.total_pages || 1;
  window.__inativosPage = Math.max(1, Math.min(window.__inativosPage || 1, window.__inativosTotalPages));
  window.__inativosPerPage = window.__inativosPerPage || 25;
  renderInativosPage();
}

function exportarCsv(){
  const f = readFilters();
  const url = new URL('/api/relatorios/clientes/export.csv', window.location.origin);
  Object.entries({start:f.start,end:f.end,status:f.status,q:f.q,cliente_id:f.cliente_id,sep:f.sep}).forEach(([k,v]) => { if(v) url.searchParams.set(k,v); });
  window.open(url.toString(), '_blank');
}

document.addEventListener('DOMContentLoaded', () => {
  // Datas padrão: últimos 90 dias
  const today = new Date();
  const past = new Date(); past.setDate(today.getDate() - 90);
  const fmt = d => d.toISOString().slice(0,10);
  document.getElementById('cliDataInicio').value = fmt(past);
  document.getElementById('cliDataFim').value = fmt(today);
  restoreFilters();
  attachFilterListeners();
  initAutocompleteBusca();
  // Botão "Limpar Cliente" ao lado da busca
  const buscaInput = document.getElementById('cliBusca');
  if (buscaInput) {
    const grp = buscaInput.parentElement;
    if (!document.getElementById('cliBtnLimpar')) {
      const btnClear = document.createElement('button');
      btnClear.id = 'cliBtnLimpar';
      btnClear.type = 'button';
      btnClear.className = 'btn btn-secondary';
      btnClear.style.marginTop = '24px';
      btnClear.style.height = '32px';
      btnClear.textContent = 'Limpar';
      btnClear.title = 'Limpa a seleção do cliente';
      btnClear.addEventListener('click', () => {
        buscaInput.value = '';
        const hid = document.getElementById('cliClienteId'); if(hid) hid.value = '';
        saveFilters();
        carregarLista();
      });
      grp.appendChild(btnClear);
    }
  }
  // Criar controles de paginação/ordenação da lista
  window.__cliPagination = { page: 1, per_page: 25, sort: 'total_vendas', dir: 'desc' };
  const secLista = document.getElementById('secLista');
  if (secLista) {
    if (!document.getElementById('cliPerPage')) {
    const bar = document.createElement('div');
    bar.style.cssText = 'margin:6px 0; display:flex; gap:8px; align-items:center;';
    bar.innerHTML = `
      <label for="cliPerPage" class="muted">Itens por página</label>
      <select id="cliPerPage" style="max-width:90px;">
        <option value="10">10</option>
        <option value="25" selected>25</option>
        <option value="50">50</option>
        <option value="100">100</option>
      </select>
      <div style="margin-left:auto; display:flex; gap:6px; align-items:center;">
        <button id="cliPrevPage" class="btn">Anterior</button>
        <span id="cliPageInfo" class="muted">Página 1</span>
        <button id="cliNextPage" class="btn">Próxima</button>
      </div>
    `;
    secLista.parentNode.insertBefore(bar, secLista);
    const per = document.getElementById('cliPerPage'); per.addEventListener('change', (e) => { window.__cliPagination.per_page = parseInt(e.target.value||'25',10)||25; window.__cliPagination.page = 1; carregarLista(); });
    const prev = document.getElementById('cliPrevPage'); prev.addEventListener('click', () => { if(window.__cliPagination.page>1){ window.__cliPagination.page--; carregarLista(); } });
    const next = document.getElementById('cliNextPage'); next.addEventListener('click', () => { window.__cliPagination.page++; carregarLista(); });

    }
    
    const thead = secLista.querySelector('thead');
    if (thead) {
      const ths = thead.querySelectorAll('th');
      // Guarda rótulos iniciais para indicação visual de ordenação
      window.__cliSortLabels = window.__cliSortLabels || Array.from(ths).map(th => th.textContent.trim());
      const updateSortIndicators = () => {
        const map = ['id','nome','pedidos','total_vendas','ultima_compra'];
        const dirArrow = window.__cliPagination.dir==='asc' ? '▲' : '▼';
        Array.from(ths).forEach((th, i) => {
          const label = window.__cliSortLabels[i] || th.textContent.trim();
          const key = map[i];
          if (key && window.__cliPagination.sort===key) th.innerHTML = `${label} ${dirArrow}`; else th.textContent = label;
        });
      };
      const setSort = (s) => { if(window.__cliPagination.sort===s){ window.__cliPagination.dir = (window.__cliPagination.dir==='asc') ? 'desc' : 'asc'; } else { window.__cliPagination.sort = s; window.__cliPagination.dir = 'desc'; } window.__cliPagination.page = 1; updateSortIndicators(); carregarLista(); };
      if(ths[0]) { ths[0].style.cursor='pointer'; ths[0].title='Ordenar por ID'; ths[0].addEventListener('click', () => setSort('id')); }
      if(ths[1]) { ths[1].style.cursor='pointer'; ths[1].title='Ordenar por Nome'; ths[1].addEventListener('click', () => setSort('nome')); }
      if(ths[2]) { ths[2].style.cursor='pointer'; ths[2].title='Ordenar por Pedidos'; ths[2].addEventListener('click', () => setSort('pedidos')); }
      if(ths[3]) { ths[3].style.cursor='pointer'; ths[3].title='Ordenar por Total Vendas'; ths[3].addEventListener('click', () => setSort('total_vendas')); }
      if(ths[4]) { ths[4].style.cursor='pointer'; ths[4].title='Ordenar por Última Compra'; ths[4].addEventListener('click', () => setSort('ultima_compra')); }
      updateSortIndicators();
    }
  }
  // Paginação local para Ranking
  const secRanking = document.getElementById('secRanking');
  if (secRanking) {
    // Estado de ordenação padrão
    window.__rankSort = window.__rankSort || 'total';
    window.__rankDir = window.__rankDir || 'desc';
    window.__rankPage = window.__rankPage || 1; window.__rankPerPage = window.__rankPerPage || 25; window.__rankTotalPages = window.__rankTotalPages || 1;
    if (!document.getElementById('rankPerPage')) {
      const bar = document.createElement('div');
      bar.style.cssText = 'margin:6px 0; display:flex; gap:8px; align-items:center;';
      bar.innerHTML = `
        <label for="rankPerPage" class="muted">Itens por página</label>
        <select id="rankPerPage" style="max-width:90px;">
          <option value="10">10</option>
          <option value="25" selected>25</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
        <div style="margin-left:auto; display:flex; gap:6px; align-items:center;">
          <button id="rankPrevPage" class="btn">Anterior</button>
          <span id="rankPageInfo" class="muted">Página 1</span>
          <button id="rankNextPage" class="btn">Próxima</button>
        </div>
      `;
      secRanking.parentNode.insertBefore(bar, secRanking);
      document.getElementById('rankPerPage').addEventListener('change', (e) => { window.__rankPerPage = parseInt(e.target.value||'25',10)||25; window.__rankPage = 1; carregarRanking(); });
      document.getElementById('rankPrevPage').addEventListener('click', () => { if(window.__rankPage>1){ window.__rankPage--; carregarRanking(); } });
      document.getElementById('rankNextPage').addEventListener('click', () => { if(window.__rankPage < (window.__rankTotalPages||1)){ window.__rankPage++; carregarRanking(); } });
    }
    // Cabeçalhos ordenáveis: ignora a primeira coluna (#)
    const thead = secRanking.querySelector('thead');
    if (thead) {
      const ths = thead.querySelectorAll('th');
      window.__rankSortLabels = window.__rankSortLabels || Array.from(ths).map(th => th.textContent.trim());
      const updateRankSortIndicators = () => {
        const map = [null,'id','nome','pedidos','total'];
        const dirArrow = (String(window.__rankDir||'desc').toLowerCase()==='asc') ? '▲' : '▼';
        Array.from(ths).forEach((th, i) => {
          const label = window.__rankSortLabels[i] || th.textContent.trim();
          const key = map[i];
          if (key && window.__rankSort===key) th.innerHTML = `${label} ${dirArrow}`; else th.textContent = label;
        });
      };
      const setRankSort = (s) => {
        if(window.__rankSort===s){ window.__rankDir = (String(window.__rankDir||'desc').toLowerCase()==='asc') ? 'desc' : 'asc'; }
        else { window.__rankSort = s; window.__rankDir = 'desc'; }
        window.__rankPage = 1; updateRankSortIndicators(); carregarRanking();
      };
      if(ths[1]) { ths[1].style.cursor='pointer'; ths[1].title='Ordenar por ID'; ths[1].addEventListener('click', () => setRankSort('id')); }
      if(ths[2]) { ths[2].style.cursor='pointer'; ths[2].title='Ordenar por Nome'; ths[2].addEventListener('click', () => setRankSort('nome')); }
      if(ths[3]) { ths[3].style.cursor='pointer'; ths[3].title='Ordenar por Pedidos'; ths[3].addEventListener('click', () => setRankSort('pedidos')); }
      if(ths[4]) { ths[4].style.cursor='pointer'; ths[4].title='Ordenar por Total'; ths[4].addEventListener('click', () => setRankSort('total')); }
      updateRankSortIndicators();
    }
  }
  // Paginação local para Inativos
  const secInativos = document.getElementById('secInativos');
  if (secInativos) {
    // Estado de ordenação padrão
    window.__inativosSort = window.__inativosSort || 'ultima_compra';
    window.__inativosDir = window.__inativosDir || 'asc';
    window.__inativosPage = window.__inativosPage || 1; window.__inativosPerPage = window.__inativosPerPage || 25; window.__inativosTotalPages = window.__inativosTotalPages || 1;
    if (!document.getElementById('inativosPerPage')) {
      const bar = document.createElement('div');
      bar.style.cssText = 'margin:6px 0; display:flex; gap:8px; align-items:center;';
      bar.innerHTML = `
        <label for="inativosPerPage" class="muted">Itens por página</label>
        <select id="inativosPerPage" style="max-width:90px;">
          <option value="10">10</option>
          <option value="25" selected>25</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
        <div style="margin-left:auto; display:flex; gap:6px; align-items:center;">
          <button id="inativosPrevPage" class="btn">Anterior</button>
          <span id="inativosPageInfo" class="muted">Página 1</span>
          <button id="inativosNextPage" class="btn">Próxima</button>
        </div>
      `;
      secInativos.parentNode.insertBefore(bar, secInativos);
      document.getElementById('inativosPerPage').addEventListener('change', (e) => { window.__inativosPerPage = parseInt(e.target.value||'25',10)||25; window.__inativosPage = 1; carregarInativos(); });
      document.getElementById('inativosPrevPage').addEventListener('click', () => { if(window.__inativosPage>1){ window.__inativosPage--; carregarInativos(); } });
      document.getElementById('inativosNextPage').addEventListener('click', () => { if(window.__inativosPage < (window.__inativosTotalPages||1)){ window.__inativosPage++; carregarInativos(); } });
    }
    // Cabeçalhos ordenáveis: Status não é ordenável
    const theadI = secInativos.querySelector('thead');
    if (theadI) {
      const thsI = theadI.querySelectorAll('th');
      window.__inativosSortLabels = window.__inativosSortLabels || Array.from(thsI).map(th => th.textContent.trim());
      const updateInativosSortIndicators = () => {
        const mapI = ['id','nome','ultima_compra', null];
        const dirArrowI = (String(window.__inativosDir||'asc').toLowerCase()==='asc') ? '▲' : '▼';
        Array.from(thsI).forEach((th, i) => {
          const label = window.__inativosSortLabels[i] || th.textContent.trim();
          const key = mapI[i];
          if (key && window.__inativosSort===key) th.innerHTML = `${label} ${dirArrowI}`; else th.textContent = label;
        });
      };
      const setInativosSort = (s) => {
        if(window.__inativosSort===s){ window.__inativosDir = (String(window.__inativosDir||'asc').toLowerCase()==='asc') ? 'desc' : 'asc'; }
        else { window.__inativosSort = s; window.__inativosDir = 'asc'; }
        window.__inativosPage = 1; updateInativosSortIndicators(); carregarInativos();
      };
      if(thsI[0]) { thsI[0].style.cursor='pointer'; thsI[0].title='Ordenar por ID'; thsI[0].addEventListener('click', () => setInativosSort('id')); }
      if(thsI[1]) { thsI[1].style.cursor='pointer'; thsI[1].title='Ordenar por Nome'; thsI[1].addEventListener('click', () => setInativosSort('nome')); }
      if(thsI[2]) { thsI[2].style.cursor='pointer'; thsI[2].title='Ordenar por Última Compra'; thsI[2].addEventListener('click', () => setInativosSort('ultima_compra')); }
      updateInativosSortIndicators();
    }
  }
  // Abas
  let activeTab = 'lista';
  function setTab(tab){
    activeTab = tab;
    document.getElementById('secLista').style.display = (tab==='lista') ? '' : 'none';
    document.getElementById('secRanking').style.display = (tab==='ranking') ? '' : 'none';
    document.getElementById('secInativos').style.display = (tab==='inativos') ? '' : 'none';
  }
  document.getElementById('tabLista').addEventListener('click', ()=> setTab('lista'));
  document.getElementById('tabRanking').addEventListener('click', ()=> setTab('ranking'));
  document.getElementById('tabInativos').addEventListener('click', ()=> setTab('inativos'));

  document.getElementById('cliBtnGerar').addEventListener('click', async () => {
    await carregarResumo();
    if(activeTab==='lista') await carregarLista();
    else if(activeTab==='ranking') await carregarRanking();
    else if(activeTab==='inativos') await carregarInativos();
  });
  document.getElementById('cliBtnExport').addEventListener('click', exportarCsv);
  // Primeira carga
  carregarResumo();
  carregarLista();
});

// Renderizadores de páginas para Ranking e Inativos (paginação local)
function renderRankingPage(){
  const data = window.__rankData || [];
  const page = window.__rankPage || 1;
  const per = window.__rankPerPage || 25;
  const totalPages = window.__rankTotalPages || 1;
  const start = (page-1)*per;
  const tbody = document.getElementById('cliRankingBody');
  tbody.innerHTML = '';
  data.forEach((r, idx) => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${start + idx + 1}</td>
      <td>${r.id}</td>
      <td>${r.nome || '-'}</td>
      <td>${r.pedidos ?? 0}</td>
      <td>${fmtMoney(r.total ?? 0)}</td>
    `;
    tbody.appendChild(tr);
  });
  const info = document.getElementById('rankPageInfo'); if(info) info.textContent = `Página ${page} de ${totalPages}`;
  const prev = document.getElementById('rankPrevPage'); if(prev) prev.disabled = page<=1;
  const next = document.getElementById('rankNextPage'); if(next) next.disabled = page>=totalPages;
}

function renderInativosPage(){
  const data = window.__inativosData || [];
  const page = window.__inativosPage || 1;
  const per = window.__inativosPerPage || 25;
  const totalPages = window.__inativosTotalPages || 1;
  const tbody = document.getElementById('cliInativosBody');
  tbody.innerHTML = '';
  data.forEach(r => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.id}</td>
      <td>${r.nome || '-'}</td>
      <td>${(r.ultima_compra||'').replace('T',' ').replace('.000Z','')}</td>
      <td>${r.bloqueado ? 'Bloqueado' : (r.inativo ? 'Inativo' : 'Ativo')}</td>
    `;
    tbody.appendChild(tr);
  });
  const info = document.getElementById('inativosPageInfo'); if(info) info.textContent = `Página ${page} de ${totalPages}`;
  const prev = document.getElementById('inativosPrevPage'); if(prev) prev.disabled = page<=1;
  const next = document.getElementById('inativosNextPage'); if(next) next.disabled = page>=totalPages;
}

// ===== Autocomplete com 3 caracteres, rolagem e paginação =====
function initAutocompleteBusca(){
  const input = document.getElementById('cliBusca');
  const panel = document.getElementById('cliBuscaAutocomplete');
  const listEl = document.getElementById('cliAutoList');
  const prevBtn = document.getElementById('cliAutoPrev');
  const nextBtn = document.getElementById('cliAutoNext');
  const pageInfo = document.getElementById('cliAutoPageInfo');
  const perPage = 10;
  let page = 1;
  let currentQuery = '';
  let lastCount = 0;
  let lastTotalPages = 1;
  let lastTotal = 0;

  const debounced = debounce(async () => {
    const q = (input.value||'').trim();
    currentQuery = q;
    if(q.length < 3){ hidePanel(); return; }
    page = 1; await loadPage();
  }, 250);

  async function loadPage(){
    if(currentQuery.length < 3){ hidePanel(); return; }
    const url = new URL('/api/clientes', window.location.origin);
    url.searchParams.set('q', currentQuery);
    url.searchParams.set('per_page', String(perPage));
    url.searchParams.set('page', String(page));
    const resp = await apiRequest(url.toString());
    if(!resp.ok){ hidePanel(); return; }
    const data = await resp.json();
    const rows = Array.isArray(data.data) ? data.data : (Array.isArray(data) ? data : []);
    lastCount = rows.length;
    lastTotalPages = (data && typeof data.total_pages === 'number') ? data.total_pages : lastTotalPages;
    lastTotal = (data && typeof data.total === 'number') ? data.total : rows.length;
    renderList(rows);
    pageInfo.textContent = `Página ${page} de ${lastTotalPages}`;
    showPanel();
    updateButtons();
  }

  function renderList(rows){
    listEl.innerHTML = '';
    if(rows.length === 0){
      const empty = document.createElement('div');
      empty.textContent = 'Nenhum resultado';
      empty.style.padding = '8px';
      empty.style.color = '#666';
      listEl.appendChild(empty);
      return;
    }
    rows.forEach(r => {
      const item = document.createElement('div');
      item.style.padding = '8px';
      item.style.cursor = 'pointer';
      item.style.borderBottom = '1px solid #f0f0f0';
      item.addEventListener('mouseenter', () => { item.style.background='#f7f7f7'; });
      item.addEventListener('mouseleave', () => { item.style.background='transparent'; });
      const titulo = [r.nome_fantasia, r.nome, r.razao_social].find(Boolean) || '-';
      const doc = r.cnpj || r.cpf || '';
      item.innerHTML = `<strong>${escapeHtml(titulo)}</strong><br/><small>${escapeHtml(doc)} · ID ${escapeHtml(r.id)}</small>`;
      item.addEventListener('click', () => {
        input.value = titulo;
        document.getElementById('cliClienteId').value = r.id || '';
        saveFilters();
        hidePanel();
        carregarLista();
      });
      listEl.appendChild(item);
    });
  }

  function updateButtons(){
    prevBtn.disabled = page <= 1;
    // Com base no total de páginas retornado pela API
    nextBtn.disabled = page >= lastTotalPages;
  }

  function showPanel(){ panel.style.display = 'block'; }
  function hidePanel(){ panel.style.display = 'none'; }

  prevBtn.addEventListener('click', async () => { if(page > 1){ page--; await loadPage(); } });
  nextBtn.addEventListener('click', async () => { if(lastCount >= perPage){ page++; await loadPage(); } });

  input.addEventListener('input', debounced);
  input.addEventListener('focus', () => { if((input.value||'').trim().length >= 3) showPanel(); });
  document.addEventListener('click', (e) => { if(!panel.contains(e.target) && e.target !== input) hidePanel(); });
}

function debounce(fn, ms){
  let t; return function(){ clearTimeout(t); t = setTimeout(() => fn.apply(this, arguments), ms); };
}

function escapeHtml(s){
  return String(s||'').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
</script>