// Relatório de vendas por vendedor
// initSellers(state, { fmtBRL })

export function initSellers(state, { fmtBRL }){
  const el = {
    start: document.getElementById('svStart'),
    end: document.getElementById('svEnd'),
    apply: document.getElementById('svApply'),
    exportBtn: document.getElementById('svExport'),
    rows: document.getElementById('svRows'),
    canvas: document.getElementById('sellerChart'),
  };

  if (state?.filters?.start && el.start) el.start.value = state.filters.start;
  if (state?.filters?.end && el.end) el.end.value = state.filters.end;

  function toISO(s){
    if (!s) return '';
    const d = (typeof window !== 'undefined' && typeof window.parseDateBR === 'function') ? window.parseDateBR(s) : new Date(s);
    if (!d || isNaN(d)) return String(s);
    const pad = (n)=> String(n).padStart(2,'0');
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
  }

  let abort = null;
  const svState = { items: [], page: 1, perPage: 5 };

  function csvEscape(s){
    const v = (s==null?'':String(s));
    if (/[",\n]/.test(v)) return '"' + v.replace(/"/g,'""') + '"';
    return v;
  }

  function exportCsv(data){
    const header = ['Vendedor','Pedidos','Faturamento','Ticket Medio'];
    const lines = [header.join(',')].concat((data||[]).map(r => [
      csvEscape(r.seller_name||r.seller||'-'),
      r.orders||0,
      (r.revenue_cents ? (r.revenue_cents/100).toFixed(2) : (r.revenue||0).toFixed(2)),
      (r.avg_ticket_cents ? (r.avg_ticket_cents/100).toFixed(2) : (r.avg_ticket||0).toFixed(2)),
    ].join(',')));
    const blob = new Blob([lines.join('\n')], { type:'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `vendas-vendedor-${Date.now()}.csv`; a.click();
    URL.revokeObjectURL(url);
  }

  function drawChart(canvas, data){
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const W = canvas.width, H = canvas.height;
    ctx.clearRect(0,0,W,H);
    const pad = 40;
    const items = (data||[]);
    const values = items.map(i => i.revenue_cents ? i.revenue_cents/100 : (i.revenue||0));
    const max = Math.max(1, ...values);
    const barW = Math.max(18, (W - pad*2) / Math.max(1, items.length) * 0.6);
    const step = (W - pad*2) / Math.max(1, items.length);
    // axes
    ctx.strokeStyle = '#ddd'; ctx.lineWidth = 1; ctx.beginPath();
    ctx.moveTo(pad, pad); ctx.lineTo(pad, H-pad); ctx.lineTo(W-pad, H-pad); ctx.stroke();
    // bars
    items.forEach((it, idx) => {
      const v = (it.revenue_cents ? it.revenue_cents/100 : (it.revenue||0));
      const x = pad + idx*step + (step - barW)/2;
      const h = (H - pad*2) * (v / max);
      // Receita deve aparecer em azul
      ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--color-revenue-blue') || '#2563eb';
      ctx.fillRect(x, H-pad-h, barW, h);
      // label seller
      ctx.fillStyle = '#555';
      ctx.font = '12px system-ui, -apple-system, Segoe UI, Roboto';
      const name = String(it.seller_name||it.seller||'');
      ctx.save();
      ctx.translate(x + barW/2, H-pad+12);
      ctx.rotate(-Math.PI/6);
      ctx.textAlign = 'right';
      ctx.fillText(name.slice(0,12), 0, 0);
      ctx.restore();
    });

    // Tooltip simples (PT-BR)
    let tip;
    const showTip = (text, mx, my) => {
      if (!tip) { tip = document.createElement('div'); tip.style.position='absolute'; tip.style.background='#111'; tip.style.color='#fff'; tip.style.padding='6px 8px'; tip.style.borderRadius='6px'; tip.style.fontSize='12px'; tip.style.pointerEvents='none'; tip.style.boxShadow='0 4px 16px rgba(0,0,0,0.2)'; canvas.parentNode.appendChild(tip); }
      tip.textContent = text; const rect = canvas.getBoundingClientRect(); tip.style.left = (mx - rect.left + 12) + 'px'; tip.style.top = (my - rect.top - 24) + 'px'; tip.style.display='block';
    };
    const hideTip = ()=>{ if (tip) tip.style.display='none'; };
    canvas.onmousemove = (e)=>{
      const rect = canvas.getBoundingClientRect(); const mx = e.clientX; const my = e.clientY;
      const xInCanvas = mx - rect.left; const yInCanvas = my - rect.top;
      // detectar barra
      for (let idx=0; idx<items.length; idx++){
        const x = pad + idx*step + (step - barW)/2;
        const v = (items[idx].revenue_cents ? items[idx].revenue_cents/100 : (items[idx].revenue||0));
        const h = (H - pad*2) * (v / max);
        const bx=x, by=H-pad-h, bw=barW, bh=h;
        if (xInCanvas>=bx && xInCanvas<=bx+bw && yInCanvas>=by && yInCanvas<=by+bh){
          showTip(`${String(items[idx].seller_name||items[idx].seller||'-')}: ${fmtBRL(v)}`, mx, my);
          return;
        }
      }
      hideTip();
    };
    canvas.onmouseleave = hideTip;
  }

  async function fetchJson(url, { signal }){
    try {
      const res = await apiRequest(url, { headers: { 'Accept':'application/json' }, signal });
      if (!res.ok) throw new Error(String(res.status));
      return await res.json();
    } catch(e){
      return { data: [] };
    }
  }

  function renderTable(rows, data){
    if (!rows) return;
    const html = (data||[]).map(r => {
      const orders = r.orders || 0;
      const revenue = fmtBRL(r.revenue_cents ? r.revenue_cents/100 : (r.revenue||0));
      const avg = fmtBRL(r.avg_ticket_cents ? r.avg_ticket_cents/100 : (r.avg_ticket||0));
      return `<tr><td>${escapeHtml(r.seller_name||r.seller||'-')}</td><td>${orders}</td><td class="income">${revenue}</td><td class="income">${avg}</td></tr>`;
    }).join('');
    rows.innerHTML = html || '<tr><td colspan="4" class="muted">Sem dados</td></tr>';
  }

  function renderPaged(){
    const total = svState.items.length;
    const maxPage = Math.max(1, Math.ceil(total / svState.perPage));
    if (svState.page > maxPage) svState.page = maxPage;
    const start = (svState.page - 1) * svState.perPage;
    const slice = svState.items.slice(start, start + svState.perPage);
    renderTable(el.rows, slice);
    const wrap = el.rows?.closest('.table-responsive');
    if (wrap) {
      if (total > svState.perPage) {
        wrap.style.maxHeight = '260px';
        wrap.style.overflowY = 'auto';
      } else {
        wrap.style.maxHeight = '';
        wrap.style.overflowY = '';
      }
    }
    let pager = document.getElementById('svPagination');
    if (!pager) {
      pager = document.createElement('div');
      pager.id = 'svPagination';
      pager.style.display = 'flex';
      pager.style.alignItems = 'center';
      pager.style.justifyContent = 'flex-end';
      pager.style.gap = '0.5rem';
      pager.style.marginTop = '0.5rem';
      wrap?.parentNode?.appendChild(pager);
    }
    if (total > svState.perPage) {
      pager.innerHTML = `
        <button class="btn btn-secondary" id="svPrev">Anterior</button>
        <span class="muted">Página ${svState.page} de ${maxPage}</span>
        <button class="btn btn-secondary" id="svNext">Próximo</button>
      `;
      pager.style.display = 'flex';
      pager.querySelector('#svPrev')?.addEventListener('click', ()=>{ if (svState.page > 1) { svState.page--; renderPaged(); } });
      pager.querySelector('#svNext')?.addEventListener('click', ()=>{ if (svState.page < maxPage) { svState.page++; renderPaged(); } });
    } else {
      pager.style.display = 'none';
    }
  }

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

  async function load(){
    if (abort) abort.abort();
    abort = new AbortController();
    const q = new URLSearchParams();
    if (el.start?.value) q.set('start', toISO(el.start.value));
    if (el.end?.value) q.set('end', toISO(el.end.value));
    q.set('per_page','100');
    const json = await fetchJson(`/api/sales/by-seller?${q.toString()}`, { signal: abort.signal });
    const data = json.data || json.items || [];
    svState.items = data;
    svState.page = 1;
    renderPaged();
    drawChart(el.canvas, data);
    // hook doc: nada a fazer aqui
  }

  el.apply?.addEventListener('click', load);
  el.exportBtn?.addEventListener('click', async () => {
    const q = new URLSearchParams();
    if (el.start?.value) q.set('start', toISO(el.start.value));
    if (el.end?.value) q.set('end', toISO(el.end.value));
    const json = await fetchJson(`/api/sales/by-seller?${q.toString()}`, { signal: (abort||{}).signal });
    const data = json.data || json.items || [];
    exportCsv(data);
  });

  load();
}