<section class="card">
  <h1>Relatórios de Vendas</h1>
  <p class="muted">Analise faturamento por período, compare tendências e veja desempenho por vendedor. Use os filtros para refinar.</p>
  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:1rem;align-items:end;">
    <div>
      <label for="vendasDataInicio">Data início</label>
      <input id="vendasDataInicio" type="date" />
    </div>
    <div>
      <label for="vendasDataFim">Data fim</label>
      <input id="vendasDataFim" type="date" />
    </div>
    <div>
      <label for="vendasProduto">Produto</label>
      <select id="vendasProduto"><option value="">Todos</option></select>
    </div>
    <div>
      <label for="vendasRegiao">Região</label>
      <select id="vendasRegiao"><option value="">Todas</option></select>
    </div>
    <div>
      <label for="vendasVendedor">Vendedor</label>
      <select id="vendasVendedor"><option value="">Todos</option></select>
    </div>
    <div style="display:flex;align-items:end;gap:.5rem;">
      <button id="btnGerarVendas" class="btn btn-primary">Gerar Relatório</button>
      <button id="btnExportarVendasCsv" class="btn">Exportar CSV (Vendedores)</button>
      <button id="btnExportarPdfPagina" class="btn btn-secondary">Exportar PDF (Página)</button>
    </div>
  </div>
</section>

<section class="card">
  <h3>Resumo</h3>
  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:1rem;">
    <div class="stat-card success"><h4>Faturamento (Atual)</h4><p id="fatAtual">R$ 0,00</p><small id="fatAtualPeriodo" class="muted"></small></div>
    <div class="stat-card info"><h4>Faturamento (Comparado)</h4><p id="fatPrev">R$ 0,00</p><small id="fatPrevPeriodo" class="muted"></small></div>
    <div class="stat-card warning"><h4>Variação</h4><p id="fatDelta">—</p><small class="muted">vs período comparado</small></div>
  </div>
</section>

<section class="card">
  <h3>Série diária</h3>
  <p class="muted">Faturamento consolidado por dia. Série atual vs período comparado automático.</p>
  <div id="chartVendasSerie" style="height:220px;display:flex;align-items:flex-end;gap:.25rem;border-bottom:1px solid #eee;padding-bottom:.5rem;overflow-x:auto;"></div>
  <div id="legendVendasSerie" class="muted" style="margin-top:.5rem;font-size:.9em;"></div>
  <div style="margin-top:.75rem;display:flex;gap:.5rem;flex-wrap:wrap;">
    <button id="btnVendasSeriePng" class="btn">Exportar PNG</button>
  </div>
</section>

<section class="card">
  <h3>Desempenho por vendedor</h3>
  <div style="overflow-x:auto;">
    <table class="table">
      <thead><tr><th>Vendedor</th><th style="text-align:right;">Pedidos</th><th style="text-align:right;">Faturamento</th><th style="text-align:right;">Ticket médio</th></tr></thead>
      <tbody id="tbodyBySeller">
        <tr><td colspan="4" style="text-align:center;padding:1.25rem;">Selecione período e clique em "Gerar Relatório"</td></tr>
      </tbody>
    </table>
  </div>
</section>

<section class="card">
  <h3>Top Produtos</h3>
  <div style="margin-bottom:.5rem;display:flex;gap:.5rem;flex-wrap:wrap;">
    <button id="btnExportTopProductsCsv" class="btn">Exportar CSV</button>
    <button id="btnTopProductsPng" class="btn">Exportar PNG (Gráfico)</button>
  </div>
  <div id="chartTopProducts" style="display:flex;flex-direction:column;gap:.4rem;margin:.25rem 0 .75rem 0;"></div>
  <div style="overflow-x:auto;">
    <table class="table">
      <thead><tr><th style="text-align:right;">#</th><th>Produto</th><th style="text-align:right;">Itens</th><th style="text-align:right;">Faturamento</th><th style="text-align:right;">Percentual</th></tr></thead>
      <tbody id="tbodyTopProducts">
        <tr><td colspan="5" style="text-align:center;padding:1.25rem;">Selecione período e clique em "Gerar Relatório"</td></tr>
      </tbody>
    </table>
  </div>
  <small class="muted">Aplica filtros de Região e Vendedor. Produto é ignorado para ranking.</small>
</section>

<section class="card">
  <h3>Top Regiões</h3>
  <div style="margin-bottom:.5rem;display:flex;gap:.5rem;flex-wrap:wrap;">
    <button id="btnExportTopRegionsCsv" class="btn">Exportar CSV</button>
    <button id="btnTopRegionsPng" class="btn">Exportar PNG (Gráfico)</button>
  </div>
  <div id="chartTopRegions" style="display:flex;flex-direction:column;gap:.4rem;margin:.25rem 0 .75rem 0;"></div>
  <div style="overflow-x:auto;">
    <table class="table">
      <thead><tr><th style="text-align:right;">#</th><th>Região</th><th style="text-align:right;">Pedidos</th><th style="text-align:right;">Faturamento</th><th style="text-align:right;">Percentual</th></tr></thead>
      <tbody id="tbodyTopRegions">
        <tr><td colspan="5" style="text-align:center;padding:1.25rem;">Selecione período e clique em "Gerar Relatório"</td></tr>
      </tbody>
    </table>
  </div>
  <small class="muted">Aplica filtro de Produto e Vendedor. Região é agregada pelo cadastro do cliente.</small>
</section>

<section class="card">
  <h3>Curva ABC de Vendas</h3>
  <div style="display:flex;gap:.75rem;align-items:center;flex-wrap:wrap;margin-bottom:.5rem;">
    <div>
      <label for="abcVendasMetric">Métrica</label>
      <select id="abcVendasMetric"><option value="valor" selected>Valor</option><option value="quantidade">Quantidade</option></select>
    </div>
    <div>
      <label for="abc-vendas-a-pct">Classe A (%)</label>
      <input id="abc-vendas-a-pct" type="number" min="0" max="100" step="1" value="80" style="width:90px;">
    </div>
    <div>
      <label for="abc-vendas-b-pct">Classe B (%)</label>
      <input id="abc-vendas-b-pct" type="number" min="0" max="100" step="1" value="15" style="width:90px;">
    </div>
    <div>
      <label for="abc-vendas-c-pct">Classe C (%)</label>
      <input id="abc-vendas-c-pct" type="number" min="0" max="100" step="1" value="5" style="width:90px;">
    </div>
    <div>
      <button id="btnExportVendasAbcCsv" class="btn">Exportar CSV</button>
    </div>
    <div>
      <button id="btnExportVendasAbcPdf" class="btn">Exportar ABC (PDF)</button>
    </div>
    <small id="abc-vendas-threshold-label" class="muted">Classificação: A=80%, B=15%, C=5%</small>
  </div>
  <div style="overflow-x:auto;">
    <table id="tbl-vendas-abc" class="table">
      <thead><tr><th>Produto</th><th>Código</th><th style="text-align:right;">Quantidade</th><th style="text-align:right;">Faturamento</th><th style="text-align:right;">Participação</th><th style="text-align:right;">Cumulativo</th><th>Categoria</th></tr></thead>
      <tbody id="tbodyVendasAbc">
        <tr><td colspan="7" style="text-align:center;padding:1.25rem;">Selecione período e clique em "Gerar Relatório"</td></tr>
      </tbody>
    </table>
  </div>
</section>

<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script>
function fmtBRL(v){ try { return (new Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'})).format(Number(v)/1); } catch(e){ return 'R$ '+Number(v).toFixed(2); } }
function fmtBRLCents(c){ return fmtBRL(Number(c||0)/100); }
// Helpers locais para fallback quando apiRequest global não estiver disponível
function readCookie(name){ const m = document.cookie.match(new RegExp('(?:^|; )'+name+'=([^;]+)')); return m ? decodeURIComponent(m[1]) : null; }
// Usa cliente global com Bearer token/x-tenant quando disponível; fallback injeta Authorization/x-tenant-id
function api(url, options){
  if (typeof apiRequest === 'function') return apiRequest(url, options||{});
  const opts = options || {};
  const hdrs = new Headers(opts.headers || {});
  try{
    const userToken = localStorage.getItem('auth_token') || readCookie('auth_token');
    if (userToken && !hdrs.has('Authorization')) hdrs.set('Authorization', 'Bearer ' + userToken);
    const apiKey = localStorage.getItem('api_key') || readCookie('api_key');
    if (apiKey && !hdrs.has('X-API-Key')) hdrs.set('X-API-Key', apiKey);
    const tenantId = readCookie('x-tenant-id') || 'default';
    if (tenantId && !hdrs.has('x-tenant-id')) hdrs.set('x-tenant-id', tenantId);
  } catch(_){}
  return fetch(url, { credentials: 'include', ...opts, headers: hdrs });
}

function notifyUnauthorized(){
  try { showAlert('Não autorizado: verifique login e permissões de acesso.', 'error'); } catch(_){ alert('Não autorizado: verifique login e permissões de acesso.'); }
}

function setDefaultDates(){
  const hoje = new Date();
  const inicio = new Date(hoje.getFullYear(), hoje.getMonth(), hoje.getDate()-30);
  document.getElementById('vendasDataInicio').value = inicio.toISOString().split('T')[0];
  document.getElementById('vendasDataFim').value = hoje.toISOString().split('T')[0];
}
function getParams(){
  const start = document.getElementById('vendasDataInicio').value||'';
  const end = document.getElementById('vendasDataFim').value||'';
  const product = document.getElementById('vendasProduto').value||'';
  const region = document.getElementById('vendasRegiao').value||'';
  const seller = document.getElementById('vendasVendedor').value||'';
  return {start,end,product,region,seller};
}

async function loadFilters(){
  try{
    const resp = await api('/api/sales/filters', { headers: { 'Accept':'application/json' } }); if(!resp.ok){ if (resp.status===401) notifyUnauthorized(); return; }
    const json = await resp.json();
    const selProd = document.getElementById('vendasProduto');
    const selReg = document.getElementById('vendasRegiao');
    const selSel = document.getElementById('vendasVendedor');
    (json.products||[]).forEach(p=>{ const opt=document.createElement('option'); opt.value=p.id; opt.textContent=p.name||('#'+p.id); selProd.appendChild(opt); });
    (json.regions||[]).forEach(r=>{ const opt=document.createElement('option'); opt.value=r.id||r.name; opt.textContent=r.name; selReg.appendChild(opt); });
    (json.sellers||[]).forEach(s=>{ const opt=document.createElement('option'); opt.value=s.id; opt.textContent=s.name||('Usuário #'+s.id); selSel.appendChild(opt); });
  } catch(e){}
}

function exportChartAsPng(containerId, filename){
  const el = document.getElementById(containerId); if(!el){ alert('Gráfico não encontrado'); return; }
  const hasBars = el.querySelector('div'); if(!hasBars){ alert('Sem dados para exportar'); return; }
  html2canvas(el).then(canvas=>{
    const a=document.createElement('a'); a.href=canvas.toDataURL('image/png'); a.download=filename||'grafico.png'; document.body.appendChild(a); a.click(); a.remove();
  }).catch(()=>alert('Falha ao exportar gráfico'));
}

async function renderAdvanced(){
  const {start,end,product,region,seller} = getParams();
  const url = `/api/sales/advanced?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&product=${encodeURIComponent(product)}&region=${encodeURIComponent(region)}&seller=${encodeURIComponent(seller)}`;
  const resp = await api(url, { headers: { 'Accept':'application/json' } }); if(!resp.ok){ if (resp.status===401) { notifyUnauthorized(); return; } const t=await resp.text(); try{ showAlert('Erro ao carregar série diária: '+t, 'error'); }catch(_){ alert('Erro ao carregar série diária: '+t); } return; }
  const json = await resp.json();
  const cur = (json.current?.items||[]); const prev = (json.previous?.items||[]);
  const sumCur = cur.reduce((acc,it)=>acc+Number(it.amount_cents||0),0);
  const sumPrev = prev.reduce((acc,it)=>acc+Number(it.amount_cents||0),0);
  document.getElementById('fatAtual').textContent = fmtBRLCents(sumCur);
  document.getElementById('fatPrev').textContent = fmtBRLCents(sumPrev);
  document.getElementById('fatDelta').textContent = (sumPrev>0?(((sumCur-sumPrev)/sumPrev)*100).toFixed(1)+'%': (sumCur>0?'+∞%':'—'));
  document.getElementById('fatAtualPeriodo').textContent = `${start} a ${end}`;
  // Período comparado é implícito; não expomos no filtro para simplicidade
  document.getElementById('fatPrevPeriodo').textContent = 'Período anterior equivalente';

  const chart = document.getElementById('chartVendasSerie'); chart.innerHTML='';
  const legend = document.getElementById('legendVendasSerie'); legend.innerHTML='';
  if(cur.length===0 && prev.length===0){ chart.innerHTML='<div class="muted" style="margin:auto;color:#666;">Sem dados para o período</div>'; return; }
  // Mapear dias para facilitar comparação
  const keys = Array.from(new Set([...cur.map(i=>i.date), ...prev.map(i=>i.date)])).sort();
  const mapCur = {}; const mapPrev={}; cur.forEach(i=>mapCur[i.date]=Number(i.amount_cents||0)); prev.forEach(i=>mapPrev[i.date]=Number(i.amount_cents||0));
  const max = Math.max(1, ...keys.map(d=>Math.max(Math.abs(mapCur[d]||0), Math.abs(mapPrev[d]||0))));
  keys.forEach(d=>{
    const wrap = document.createElement('div'); wrap.style.display='flex'; wrap.style.flexDirection='column'; wrap.style.alignItems='center'; wrap.style.gap='.25rem';
    const bars = document.createElement('div'); bars.style.display='flex'; bars.style.gap='2px'; bars.style.alignItems='flex-end';
    const hC = Math.max(4, Math.round(((Math.abs(mapCur[d]||0))/max)*180));
    const hP = Math.max(4, Math.round(((Math.abs(mapPrev[d]||0))/max)*180));
    const barC = document.createElement('div'); barC.style.width='14px'; barC.style.height=hC+'px'; barC.style.background='#2b8a3e'; barC.title=`Atual ${d}: ${fmtBRLCents(mapCur[d]||0)}`;
    const barP = document.createElement('div'); barP.style.width='14px'; barP.style.height=hP+'px'; barP.style.background='#364fc7'; barP.title=`Comparado ${d}: ${fmtBRLCents(mapPrev[d]||0)}`;
    bars.appendChild(barC); bars.appendChild(barP);
    const label = document.createElement('div'); label.style.fontSize='.8em'; label.textContent = d;
    wrap.appendChild(bars); wrap.appendChild(label); chart.appendChild(wrap);
  });
  legend.innerHTML = `<span class="chip" style="background:#2b8a3e;color:#fff;">Atual</span> <span class="chip" style="background:#364fc7;color:#fff;">Comparado</span>`;
}

async function renderBySeller(){
  const {start,end} = getParams();
  const resp = await api(`/api/sales/by-seller?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}`, { headers: { 'Accept':'application/json' } });
  const tbody = document.getElementById('tbodyBySeller');
  if(!resp.ok){ if (resp.status===401) { notifyUnauthorized(); tbody.innerHTML = `<tr><td colspan="4" style="text-align:center;padding:1.25rem;">Não autorizado</td></tr>`; return; } const t=await resp.text(); tbody.innerHTML = `<tr><td colspan="4" style="text-align:center;padding:1.25rem;">Erro: ${t}</td></tr>`; return; }
  const json = await resp.json();
  const rows = (json.data||[]);
  if(rows.length===0){ tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;padding:1.25rem;">Sem dados para o período</td></tr>'; return; }
  tbody.innerHTML = rows.map(r=>`<tr><td>${r.seller_name||'-'}</td><td style="text-align:right;">${Number(r.orders||0)}</td><td style="text-align:right;">${fmtBRLCents(r.revenue_cents||0)}</td><td style="text-align:right;">${fmtBRLCents(r.avg_ticket_cents||0)}</td></tr>`).join('');
  // Guardar dados para exportação CSV
  window.__vendasBySellerRows = rows;
}

async function renderTopProducts(){
  const {start,end,region,seller} = getParams();
  const url = `/api/sales/top-products?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&region=${encodeURIComponent(region)}&seller=${encodeURIComponent(seller)}`;
  const resp = await api(url, { headers: { 'Accept':'application/json' } });
  const tbody = document.getElementById('tbodyTopProducts');
  if(!resp.ok){ if (resp.status===401) { notifyUnauthorized(); tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;padding:1.25rem;">Não autorizado</td></tr>`; return; } const t=await resp.text(); tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;padding:1.25rem;">Erro: ${t}</td></tr>`; return; }
  const json = await resp.json();
  const rows = (json.data||[]);
  if(rows.length===0){ tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;padding:1.25rem;">Sem dados para o período</td></tr>'; return; }
  const totalRevenue = rows.reduce((acc,r)=>acc+Number(r.revenue_cents||0),0) || 1;
  tbody.innerHTML = rows.map((r,idx)=>{
    const pct = (Number(r.revenue_cents||0)/totalRevenue)*100;
    return `<tr><td style=\"text-align:right;\">${idx+1}</td><td>${r.product_name||('- #' + (r.product_id||''))}</td><td style=\"text-align:right;\">${Number(r.items_count||0)}</td><td style=\"text-align:right;\">${fmtBRLCents(r.revenue_cents||0)}</td><td style=\"text-align:right;\">${pct.toFixed(1)}%</td></tr>`;
  }).join('');
  window.__topProductsRows = rows;
  renderTopProductsChart(rows);
}

function exportTopProductsCsv(){
  const rows = window.__topProductsRows||[];
  const bom = '\uFEFF';
  const totalRevenue = rows.reduce((acc,r)=>acc+Number(r.revenue_cents||0),0) || 1;
  const header = ['#','Produto','Itens','Faturamento (BRL)','Percentual (%)'];
  const lines = [header.join(';')].concat(rows.map((r,idx)=>{
    const pct = (Number(r.revenue_cents||0)/totalRevenue)*100;
    return [
      String(idx+1),
      (r.product_name||('- #' + (r.product_id||''))),
      String(Number(r.items_count||0)),
      fmtBRLCents(r.revenue_cents||0),
      pct.toFixed(1)+'%'
    ].join(';');
  }));
  const csv = bom + lines.join('\n');
  const blob = new Blob([csv], {type:'text/csv;charset=utf-8'});
  const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='top_produtos.csv'; document.body.appendChild(a); a.click(); a.remove();
}

function renderTopProductsChart(rows){
  const cont = document.getElementById('chartTopProducts');
  if(!cont) return;
  cont.innerHTML = '';
  const data = (rows||[]).slice(0, 10);
  if(data.length===0){ cont.innerHTML = '<div class="muted">Sem dados para o período</div>'; return; }
  const sum = data.reduce((acc,r)=>acc+Number(r.revenue_cents||0),0) || 1;
  const max = Math.max(1, ...data.map(r=>Number(r.revenue_cents||0)));
  data.forEach(r=>{
    const line = document.createElement('div');
    line.style.display = 'flex'; line.style.alignItems = 'center'; line.style.gap = '.5rem';
    const label = document.createElement('div'); label.style.flex = '0 0 240px'; label.style.whiteSpace='nowrap'; label.style.overflow='hidden'; label.style.textOverflow='ellipsis';
    label.textContent = r.product_name||('- #' + (r.product_id||''));
    const barWrap = document.createElement('div'); barWrap.style.flex = '1'; barWrap.style.background = '#f3f4f6'; barWrap.style.borderRadius = '6px'; barWrap.style.height = '24px'; barWrap.style.position='relative';
    const bar = document.createElement('div'); bar.style.height = '100%'; bar.style.width = Math.max(4, Math.round((Number(r.revenue_cents||0)/max)*100))+'%'; bar.style.background = '#2b8a3e'; bar.style.borderRadius = '6px'; bar.title = 'Faturamento: '+fmtBRLCents(r.revenue_cents||0);
    const value = document.createElement('div'); value.style.position='absolute'; value.style.right='6px'; value.style.top='50%'; value.style.transform='translateY(-50%)'; value.style.color='#fff'; value.style.fontSize='.85em'; value.style.fontWeight='600';
    const pct = (Number(r.revenue_cents||0)/sum)*100; value.textContent = `${fmtBRLCents(r.revenue_cents||0)} (${pct.toFixed(1)}%)`;
    barWrap.appendChild(bar); barWrap.appendChild(value);
    line.appendChild(label); line.appendChild(barWrap); cont.appendChild(line);
  });
}

async function renderTopRegions(){
  const {start,end,product,seller} = getParams();
  const url = `/api/sales/top-regions?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&product=${encodeURIComponent(product)}&seller=${encodeURIComponent(seller)}`;
  const resp = await api(url, { headers: { 'Accept':'application/json' } });
  const tbody = document.getElementById('tbodyTopRegions');
  if(!resp.ok){ if (resp.status===401) { notifyUnauthorized(); tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;padding:1.25rem;">Não autorizado</td></tr>`; return; } const t=await resp.text(); tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;padding:1.25rem;">Erro: ${t}</td></tr>`; return; }
  const json = await resp.json();
  const rows = (json.data||[]);
  if(rows.length===0){ tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;padding:1.25rem;">Sem dados para o período</td></tr>'; return; }
  const totalRevenue = rows.reduce((acc,r)=>acc+Number(r.revenue_cents||0),0) || 1;
  tbody.innerHTML = rows.map((r,idx)=>{
    const pct = (Number(r.revenue_cents||0)/totalRevenue)*100;
    return `<tr><td style=\"text-align:right;\">${idx+1}</td><td>${r.region||'(não informado)'}</td><td style=\"text-align:right;\">${Number(r.orders_count||0)}</td><td style=\"text-align:right;\">${fmtBRLCents(r.revenue_cents||0)}</td><td style=\"text-align:right;\">${pct.toFixed(1)}%</td></tr>`;
  }).join('');
  window.__topRegionsRows = rows;
  renderTopRegionsChart(rows);
}

function exportTopRegionsCsv(){
  const rows = window.__topRegionsRows||[];
  const bom = '\uFEFF';
  const totalRevenue = rows.reduce((acc,r)=>acc+Number(r.revenue_cents||0),0) || 1;
  const header = ['#','Região','Pedidos','Faturamento (BRL)','Percentual (%)'];
  const lines = [header.join(';')].concat(rows.map((r,idx)=>{
    const pct = (Number(r.revenue_cents||0)/totalRevenue)*100;
    return [
      String(idx+1),
      (r.region||'(não informado)'),
      String(Number(r.orders_count||0)),
      fmtBRLCents(r.revenue_cents||0),
      pct.toFixed(1)+'%'
    ].join(';');
  }));
  const csv = bom + lines.join('\n');
  const blob = new Blob([csv], {type:'text/csv;charset=utf-8'});
  const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='top_regioes.csv'; document.body.appendChild(a); a.click(); a.remove();
}

function renderTopRegionsChart(rows){
  const cont = document.getElementById('chartTopRegions');
  if(!cont) return;
  cont.innerHTML = '';
  const data = (rows||[]).slice(0, 10);
  if(data.length===0){ cont.innerHTML = '<div class="muted">Sem dados para o período</div>'; return; }
  const sum = data.reduce((acc,r)=>acc+Number(r.revenue_cents||0),0) || 1;
  const max = Math.max(1, ...data.map(r=>Number(r.revenue_cents||0)));
  data.forEach(r=>{
    const line = document.createElement('div');
    line.style.display = 'flex'; line.style.alignItems = 'center'; line.style.gap = '.5rem';
    const label = document.createElement('div'); label.style.flex = '0 0 240px'; label.style.whiteSpace='nowrap'; label.style.overflow='hidden'; label.style.textOverflow='ellipsis';
    label.textContent = r.region||'(não informado)';
    const barWrap = document.createElement('div'); barWrap.style.flex = '1'; barWrap.style.background = '#f3f4f6'; barWrap.style.borderRadius = '6px'; barWrap.style.height = '24px'; barWrap.style.position='relative';
    const bar = document.createElement('div'); bar.style.height = '100%'; bar.style.width = Math.max(4, Math.round((Number(r.revenue_cents||0)/max)*100))+'%'; bar.style.background = '#364fc7'; bar.style.borderRadius = '6px'; bar.title = 'Faturamento: '+fmtBRLCents(r.revenue_cents||0);
    const value = document.createElement('div'); value.style.position='absolute'; value.style.right='6px'; value.style.top='50%'; value.style.transform='translateY(-50%)'; value.style.color='#fff'; value.style.fontSize='.85em'; value.style.fontWeight='600';
    const pct = (Number(r.revenue_cents||0)/sum)*100; value.textContent = `${fmtBRLCents(r.revenue_cents||0)} (${pct.toFixed(1)}%)`;
    barWrap.appendChild(bar); barWrap.appendChild(value);
    line.appendChild(label); line.appendChild(barWrap); cont.appendChild(line);
  });
}

function exportBySellerCsv(){
  const rows = window.__vendasBySellerRows||[];
  const bom = '\uFEFF';
  const header = ['Vendedor','Pedidos','Faturamento (BRL)','Ticket médio (BRL)'];
  const lines = [header.join(';')].concat(rows.map(r=>[
    (r.seller_name||'-'),
    String(Number(r.orders||0)),
    fmtBRLCents(r.revenue_cents||0),
    fmtBRLCents(r.avg_ticket_cents||0)
  ].join(';')));
  const csv = bom + lines.join('\n');
  const blob = new Blob([csv], {type:'text/csv;charset=utf-8'});
  const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='vendas_por_vendedor.csv'; document.body.appendChild(a); a.click(); a.remove();
}

document.getElementById('btnGerarVendas').addEventListener('click', async ()=>{
  const abcTbody = document.querySelector('#tbl-vendas-abc tbody');
  if (abcTbody) {
    abcTbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:1rem;">Carregando...</td></tr>';
  }
  await Promise.all([renderAdvanced(), renderBySeller(), renderTopProducts(), renderTopRegions(), renderVendasAbc()]);
});
document.getElementById('btnExportarVendasCsv').addEventListener('click', exportBySellerCsv);
document.getElementById('btnVendasSeriePng').addEventListener('click', ()=>{
  const {start,end} = getParams(); exportChartAsPng('chartVendasSerie', `vendas_serie_${start}_a_${end}.png`);
});
document.getElementById('btnExportTopProductsCsv').addEventListener('click', exportTopProductsCsv);
document.getElementById('btnExportTopRegionsCsv').addEventListener('click', exportTopRegionsCsv);
document.getElementById('btnTopProductsPng').addEventListener('click', ()=>{
  const {start,end} = getParams(); exportChartAsPng('chartTopProducts', `top_produtos_${start}_a_${end}.png`);
});
document.getElementById('btnTopRegionsPng').addEventListener('click', ()=>{
  const {start,end} = getParams(); exportChartAsPng('chartTopRegions', `top_regioes_${start}_a_${end}.png`);
});

// Curva ABC de Vendas
async function renderVendasAbc(){
  const {start,end,product,region,seller} = getParams();
  const metric = document.getElementById('abcVendasMetric').value||'valor';
  const th = getVendasAbcThresholds();
  const url = `/api/sales/abc?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&product=${encodeURIComponent(product)}&region=${encodeURIComponent(region)}&seller=${encodeURIComponent(seller)}&metric=${encodeURIComponent(metric)}&a_pct=${encodeURIComponent(th.a_pct)}&b_pct=${encodeURIComponent(th.b_pct)}&c_pct=${encodeURIComponent(th.c_pct)}`;
  const resp = await api(url, { headers: { 'Accept':'application/json' } });
  const tbody = document.getElementById('tbodyVendasAbc');
  if(!resp.ok){ if (resp.status===401) { notifyUnauthorized(); tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;padding:1.25rem;">Não autorizado</td></tr>`; return; } const t=await resp.text(); tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;padding:1.25rem;">Erro: ${t}</td></tr>`; return; }
  const json = await resp.json();
  const rows = (json.items||[]);
  if(rows.length===0){ tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:1.25rem;">Sem dados para o período</td></tr>'; window.__vendasAbcRows = []; return; }
  tbody.innerHTML = rows.map(r=>{
    const cat = (r.categoria||'').toUpperCase();
    const catColor = cat==='A' ? '#d9480f' : (cat==='B' ? '#2b8a3e' : '#364fc7');
    const catStyle = `display:inline-block;padding:.15rem .35rem;border-radius:10px;color:#fff;background:${catColor};font-size:.8em;`;
    return `<tr>`+
      `<td>${r.product_name||('- #' + (r.product_id||''))}</td>`+
      `<td>${r.product_code||''}</td>`+
      `<td style=\"text-align:right;\">${Number(r.quantidade_total||0).toLocaleString('pt-BR')}</td>`+
      `<td style=\"text-align:right;\">${fmtBRL(Number(r.valor_total||0))}</td>`+
      `<td style=\"text-align:right;\">${Number(r.share_pct||0).toFixed(2)}%</td>`+
      `<td style=\"text-align:right;\">${Number(r.cumulative_pct||0).toFixed(2)}%</td>`+
      `<td><span style=\"${catStyle}\">${cat}</span></td>`+
    `</tr>`;
  }).join('');
  window.__vendasAbcRows = rows;
}

function exportVendasAbcCsv(){
  const rows = window.__vendasAbcRows||[];
  if(!rows.length){ alert('Sem dados para exportação'); return; }
  const bom = '\uFEFF';
  const header = ['Produto','Código','Quantidade','Faturamento (BRL)','Participação (%)','Cumulativo (%)','Categoria'];
  const lines = [header.join(';')].concat(rows.map(r=>[
    (r.product_name||('- #' + (r.product_id||''))),
    (r.product_code||''),
    String(Number(r.quantidade_total||0)),
    fmtBRL(Number(r.valor_total||0)),
    Number(r.share_pct||0).toFixed(2)+'%',
    Number(r.cumulative_pct||0).toFixed(2)+'%',
    (r.categoria||'')
  ].join(';')));
  const csv = bom + lines.join('\n');
  const blob = new Blob([csv], {type:'text/csv;charset=utf-8'});
  const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download='curva_abc_vendas.csv'; document.body.appendChild(a); a.click(); a.remove();
}
document.getElementById('btnExportVendasAbcCsv').addEventListener('click', exportVendasAbcCsv);
document.getElementById('abcVendasMetric').addEventListener('change', async ()=>{ await renderVendasAbc(); });

function getVendasAbcThresholds(){
  const aEl = document.getElementById('abc-vendas-a-pct');
  const bEl = document.getElementById('abc-vendas-b-pct');
  const cEl = document.getElementById('abc-vendas-c-pct');
  let a = Math.max(0, Math.min(100, Number(aEl?.value||80)));
  let b = Math.max(0, Math.min(100, Number(bEl?.value||15)));
  let c = Math.max(0, Math.min(100, Number(cEl?.value||5)));
  if ((a+b+c) === 0) { a = 80; b = 15; c = 5; }
  const sum = a+b+c;
  const a_pct = a/sum, b_pct = b/sum, c_pct = c/sum;
  const label = document.getElementById('abc-vendas-threshold-label');
  if (label) label.textContent = `Classificação: A=${Math.round(a_pct*100)}%, B=${Math.round(b_pct*100)}%, C=${Math.round(c_pct*100)}%`;
  return { a_pct, b_pct, c_pct };
}

function exportVendasAbcPdf(){
  try{
    const rows = window.__vendasAbcRows||[];
    if(!rows.length){ alert('Sem dados para exportação'); return; }
    const {start,end,product,region,seller} = getParams();
    const metric = document.getElementById('abcVendasMetric').value||'valor';
    const th = getVendasAbcThresholds();
    const w = window.open('', '_blank');
    const css = `
      body{font-family:Arial,sans-serif;color:#111;padding:24px;}
      h1{font-size:18px;margin:0 0 8px 0;}
      h2{font-size:14px;margin:0 0 18px 0;color:#555;}
      table{width:100%;border-collapse:collapse;}
      th,td{border:1px solid #ddd;padding:6px;}
      thead th{background:#f3f4f6;text-align:left;}
      td.num{text-align:right;}
      .chip{display:inline-block;padding:.15rem .35rem;border-radius:10px;color:#fff;font-size:.9em;}
    `;
    const hdr = `Curva ABC de Vendas (${metric})`;
    const subt = `Período: ${start} a ${end}` +
      (product?` · Produto #${product}`:'') + (region?` · Região ${region}`:'') + (seller?` · Vendedor #${seller}`:'');
    const thLabel = `Classificação: A=${Math.round(th.a_pct*100)}%, B=${Math.round(th.b_pct*100)}%, C=${Math.round(th.c_pct*100)}%`;
    const htmlRows = rows.map(r=>{
      const cat = (r.categoria||'').toUpperCase();
      const catColor = cat==='A' ? '#d9480f' : (cat==='B' ? '#2b8a3e' : '#364fc7');
      return `<tr>`+
        `<td>${r.product_name||('- #' + (r.product_id||''))}</td>`+
        `<td>${r.product_code||''}</td>`+
        `<td class=\"num\">${Number(r.quantidade_total||0).toLocaleString('pt-BR')}</td>`+
        `<td class=\"num\">${fmtBRL(Number(r.valor_total||0))}</td>`+
        `<td class=\"num\">${Number(r.share_pct||0).toFixed(2)}%</td>`+
        `<td class=\"num\">${Number(r.cumulative_pct||0).toFixed(2)}%</td>`+
        `<td><span class=\"chip\" style=\"background:${catColor};\">${cat}</span></td>`+
      `</tr>`;
    }).join('');
    const doc = `<!doctype html><html><head><meta charset=\"utf-8\"><title>${hdr}</title><style>${css}</style></head><body>
      <h1>${hdr}</h1>
      <h2>${subt}</h2>
      <div style=\"margin:6px 0 12px 0;color:#555;\">${thLabel}</div>
      <table><thead><tr><th>Produto</th><th>Código</th><th>Quantidade</th><th>Faturamento</th><th>Participação</th><th>Cumulativo</th><th>Categoria</th></tr></thead>
      <tbody>${htmlRows}</tbody></table>
      <script>window.onload=function(){setTimeout(function(){window.print();},250);};<\/script>
    </body></html>`;
    w.document.write(doc);
    w.document.close();
  }catch(e){ alert('Falha ao gerar PDF'); }
}
document.getElementById('btnExportVendasAbcPdf').addEventListener('click', exportVendasAbcPdf);
['abc-vendas-a-pct','abc-vendas-b-pct','abc-vendas-c-pct'].forEach(id=>{
  const el = document.getElementById(id); if(el){ el.addEventListener('change', async ()=>{ getVendasAbcThresholds(); await renderVendasAbc(); }); }
});

// Exportar PDF da página (multi-página: cada seção card)
async function exportReportPdf(){
  try{
    const cards = Array.from(document.querySelectorAll('main .container .card'));
    if(cards.length===0){ alert('Conteúdo não encontrado para exportação'); return; }
    const { jsPDF } = window.jspdf || window.jspdf_umd || {};
    if(!jsPDF){ alert('Biblioteca PDF indisponível'); return; }
    const doc = new jsPDF({ unit: 'mm', format: 'a4' });
    const pageW = doc.internal.pageSize.getWidth();
    const pageH = doc.internal.pageSize.getHeight();
    const margin = 6;
    for(let i=0;i<cards.length;i++){
      const el = cards[i];
      const canvas = await html2canvas(el, { scale: 2, backgroundColor: '#ffffff' });
      const pxToMm = 0.264583;
      const imgWmm = canvas.width * pxToMm;
      const imgHmm = canvas.height * pxToMm;
      const maxW = pageW - margin*2;
      const maxH = pageH - margin*2;
      const scale = Math.min(maxW/imgWmm, maxH/imgHmm);
      const targetW = imgWmm * scale;
      const targetH = imgHmm * scale;
      const x = (pageW - targetW)/2;
      const y = (pageH - targetH)/2;
      const imgData = canvas.toDataURL('image/jpeg', 0.95);
      if(i>0) doc.addPage();
      doc.addImage(imgData, 'JPEG', x, y, targetW, targetH);
    }
    const {start,end} = getParams();
    doc.save(`relatorio_vendas_${start}_a_${end}.pdf`);
  } catch(e){ console.error(e); alert('Falha ao exportar PDF'); }
}
document.getElementById('btnExportarPdfPagina').addEventListener('click', exportReportPdf);

// Espera token/impersonificação antes de carregar filtros para evitar 401 inicial
async function ensureImpersonatedIfNeeded(){
  const hasUser = !!(localStorage.getItem('auth_token') || readCookie('auth_token'));
  const hasAdmin = !!(localStorage.getItem('admin_token') || readCookie('admin_token'));
  if (!hasUser && hasAdmin) {
    const adminTok = localStorage.getItem('admin_token') || readCookie('admin_token') || '';
    const tenantId = readCookie('x-tenant-id') || 'default';
    try {
      await fetch('/api/admin/tenants/impersonate', {
        method: 'POST',
        headers: { 'Authorization': 'Bearer ' + adminTok, 'Content-Type': 'application/json' },
        body: JSON.stringify({ tenant_id: tenantId }),
        credentials: 'same-origin'
      });
    } catch(_){}
  }
}
async function waitForAuthToken(timeoutMs=2000){
  const start = Date.now();
  while (Date.now() - start < timeoutMs) {
    const tok = localStorage.getItem('auth_token') || readCookie('auth_token');
    if (tok) return tok;
    await new Promise(r=>setTimeout(r, 150));
  }
  return null;
}

(async function init(){
  setDefaultDates();
  await ensureImpersonatedIfNeeded();
  await waitForAuthToken(2000);
  await loadFilters();
  // pronto para gerar
})();
</script>