/* ===== Relatórios gerenciais (dados fictícios) ===== */
const WEEKS=['03/08','10/08','17/08','24/08','31/08','07/09','14/09','21/09'];
const WEEK_VOL=[1510,1580,1490,1620,1700,1655,1730,1690]; // mil litros por semana
const WEEK_COST=[0.031,0.030,0.032,0.029,0.028,0.028,0.027,0.026]; // R$ por litro entregue
const WEEK_ONTIME=[91,92,90,93,94,93,95,94]; // % entregas no prazo
const MIX=[{p:'Diesel S10',v:48,c:'#2f7ddd'},{p:'Gasolina C',v:25,c:'#35aa73'},{p:'Etanol',v:15,c:'#e0a030'},{p:'Diesel S500',v:12,c:'#8265d7'}];

function BarChart({labels,values,fmtV,title,unit,color='#2f7ddd'}) {
  const W=560,H=190,pl=44,pb=26,pt=22;
  const max=Math.max(...values)*1.15, bw=(W-pl-12)/values.length;
  const y=(v)=>pt+(H-pt-pb)*(1-v/max);
  const ticks=[0,max/2,max];
  return <svg viewBox={`0 0 ${W} ${H}`} className="chart-svg" role="img" aria-label={title}>
    {ticks.map((t,i)=><g key={i}><line x1={pl} x2={W-8} y1={y(t)} y2={y(t)} stroke="#e7eaf0"/><text x={pl-6} y={y(t)+3} fontSize="10" fill="#8993a2" textAnchor="end">{fmtV(t)}</text></g>)}
    {values.map((v,i)=>{const x=pl+i*bw+bw*0.2,w=bw*0.6,last=i===values.length-1;return <g key={i}><title>{`${labels[i]}: ${fmtV(v)} ${unit}`}</title><path d={`M${x},${y(0)} V${y(v)+4} Q${x},${y(v)} ${x+4},${y(v)} H${x+w-4} Q${x+w},${y(v)} ${x+w},${y(v)+4} V${y(0)} Z`} fill={color} fillOpacity={last?1:0.45}/>{last&&<text x={x+w/2} y={y(v)-6} fontSize="11" fontWeight="700" fill="#1f2b40" textAnchor="middle">{fmtV(v)}</text>}<text x={x+w/2} y={H-8} fontSize="10" fill="#8993a2" textAnchor="middle">{labels[i]}</text></g>;})}
  </svg>;
}

function HBars({rows,fmtV,color='#2f7ddd'}) {
  const max=Math.max(1,...rows.map(r=>r.v));
  return <div className="hbars">{rows.map(r=><div key={r.label} className="hbar" title={`${r.label}: ${fmtV(r.v)}`}><span className="hb-label">{r.label}{r.sub?<small>{r.sub}</small>:null}</span><div className="hb-track"><i style={{width:`${Math.max(2,r.v/max*100)}%`,background:r.color||color}}/></div><b>{fmtV(r.v)}</b></div>)}</div>;
}

function downloadCsv(name,rows){
  const csv=rows.map(r=>r.map(v=>`"${String(v).replace(/"/g,'""')}"`).join(';')).join('\n');
  const url=URL.createObjectURL(new Blob(['﻿'+csv],{type:'text/csv;charset=utf-8'}));
  const a=document.createElement('a'); a.href=url; a.download=name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(()=>URL.revokeObjectURL(url),1000);
}

function Reports({clients,sellers,bases,fleet}) {
  const garage=(bases.find(b=>b.garage)||{city:'Barretos'}).city;
  const rated=useMemo(()=>rateClients(clients,sellers,garage),[clients,sellers,garage]);
  const vol=rated.reduce((s,c)=>s+c.vol,0), bruta=rated.reduce((s,c)=>s+c.vol*c.margem,0), logi=rated.reduce((s,c)=>s+c.vol*c.custoL,0), liq=bruta-logi;
  const bySeller=sellers.map(s=>{const m=rated.filter(c=>c.sellerId===s.id);const v=m.reduce((t,c)=>t+c.vol,0);return {s,n:m.length,v,res:m.reduce((t,c)=>t+c.result,0),pm:s.meta?Math.round(v/s.meta*100):0};}).sort((a,b)=>b.res-a.res);
  const top=[...rated].sort((a,b)=>b.result-a.result).slice(0,5);
  const attention=rated.filter(c=>c.rating==='D'||c.atraso>=10).sort((a,b)=>a.score-b.score);
  const kmMonth=fleet.map(t=>({label:t.id,sub:t.plate,v:t.dailyKm*21})).sort((a,b)=>b.v-a.v);
  const c0=WEEK_COST[0],c1=WEEK_COST[WEEK_COST.length-1];
  const exportClients=()=>downloadCsv('viaflux-carteira.csv',[['Cliente','Cidade','Vendedor','Postos','Volume/mês (L)','Margem R$/L','Custo entrega R$/L','Resultado/mês R$','Rating','Nota'],...rated.map(c=>[c.name,c.city,c.seller,c.postos,c.vol,c.margem.toFixed(3).replace('.',','),c.custoL.toFixed(3).replace('.',','),Math.round(c.result),c.rating,c.score])]);
  return <div className="content reports-content">
    <div className="page-heading"><div><p>RELATÓRIOS</p><h1>Resultado do mês</h1><span>Setembro/2026 · números fictícios de demonstração, calculados a partir dos cadastros.</span></div><div className="heading-actions"><button className="secondary" onClick={exportClients}>Exportar carteira (CSV)</button></div></div>
    <section className="kpis">{[
      {l:'Volume vendido',v:`${mi(vol)} L`,s:'soma da carteira'},
      {l:'Faturamento estimado',v:brl(vol*PRECO_MEDIO),s:`a ${brl2(PRECO_MEDIO)}/L médio`},
      {l:'Margem bruta',v:brl(bruta),s:`${brl3(bruta/vol)}/L`},
      {l:'Custo logístico',v:brl(logi),s:`${brl3(logi/vol)}/L entregue`},
      {l:'Resultado líquido',v:brl(liq),s:`${Math.round(liq/bruta*100)}% da margem bruta`,hl:true},
    ].map(k=><article key={k.l} className={k.hl?'hl':''}><span>{k.l}</span><strong>{k.v}</strong><small>{k.s}</small></article>)}</section>
    <section className="insight"><b>Leitura rápida:</b> o custo logístico caiu de {brl3(c0)} para {brl3(c1)} por litro em 8 semanas ({Math.round((c1/c0-1)*100)}%). {bySeller[0]&&<>{bySeller[0].s.name} lidera o resultado da carteira ({brl(bySeller[0].res)}/mês). </>}{attention.length>0&&<>{attention.length} {attention.length===1?'cliente pede':'clientes pedem'} atenção por nota baixa ou atraso no pagamento.</>}</section>
    <div className="rep-grid">
      <section className="panel"><div className="panel-title"><div><h2>Volume vendido por semana</h2><p>Mil litros · últimas 8 semanas</p></div></div><div className="chart-pad"><BarChart labels={WEEKS} values={WEEK_VOL} fmtV={v=>fmt(Math.round(v))} unit="mil L" title="Volume vendido por semana"/></div></section>
      <section className="panel"><div className="panel-title"><div><h2>Custo logístico por litro entregue</h2><p>R$ por litro · quanto menor, melhor</p></div></div><div className="chart-pad"><BarChart labels={WEEKS} values={WEEK_COST} fmtV={v=>v.toFixed(3).replace('.',',')} unit="R$/L" title="Custo logístico por litro" color="#1f9d63"/></div></section>
    </div>
    <section className="panel"><div className="panel-title"><div><h2>Desempenho por vendedor</h2><p>Volume da carteira contra a meta mensal</p></div></div><div className="table-wrap"><table><thead><tr><th>Vendedor</th><th>Clientes</th><th>Volume/mês</th><th>Meta</th><th>Atingido</th><th>Resultado/mês</th></tr></thead><tbody>{bySeller.map(r=><tr key={r.s.id}><td><b className="strong">{r.s.name}</b><small className="cell-sub">{r.s.region}</small></td><td>{r.n}</td><td className="num">{fmt(r.v)} L</td><td className="num">{r.s.meta?`${fmt(r.s.meta)} L`:'—'}</td><td><div className="meta-cell"><div className="meter"><i className={r.pm>=100?'ok':''} style={{width:`${clamp(r.pm)}%`}}/></div><b>{r.s.meta?`${r.pm}%`:'—'}</b></div></td><td className="num strong">{brl(r.res)}</td></tr>)}</tbody></table></div></section>
    <div className="rep-grid">
      <section className="panel"><div className="panel-title"><div><h2>Mix de produtos</h2><p>% do volume do mês</p></div></div><div className="mix"><div className="mix-bar">{MIX.map(m=><i key={m.p} title={`${m.p}: ${m.v}%`} style={{width:`${m.v}%`,background:m.c}}/>)}</div><ul className="mix-legend">{MIX.map(m=><li key={m.p}><span style={{background:m.c}}/>{m.p}<b>{m.v}%</b><small>{fmt(Math.round(vol*m.v/100))} L</small></li>)}</ul></div></section>
      <section className="panel"><div className="panel-title"><div><h2>Top 5 clientes por resultado</h2><p>R$ por mês, depois do custo de entrega</p></div></div><div className="chart-pad"><HBars rows={top.map(c=>({label:c.name,sub:`rating ${c.rating}`,v:c.result}))} fmtV={brl}/></div></section>
    </div>
    <div className="rep-grid">
      <section className="panel"><div className="panel-title"><div><h2>Clientes que pedem atenção</h2><p>Nota D ou atraso de 10 dias ou mais</p></div></div><ul className="attn">{attention.map(c=><li key={c.id}><span className={`rating r${c.rating}`}>{c.rating}</span><div><b>{c.name}</b><small>{c.city} · {c.seller}</small></div><p>{[c.atraso>=10?`${c.atraso} dias de atraso`:null,c.liq<0.07?`margem líquida de ${brl3(c.liq)}/L`:null,c.compras<10?`só ${c.compras} compras/mês`:null].filter(Boolean).join(' · ')||'nota baixa'}</p></li>)}{!attention.length&&<li className="empty">Nenhum cliente em alerta.</li>}</ul></section>
      <section className="panel"><div className="panel-title"><div><h2>Frota: km rodados no mês</h2><p>Estimativa pelo km médio diário × 21 dias úteis</p></div></div><div className="chart-pad"><HBars rows={kmMonth} fmtV={v=>`${fmt(v)} km`} color="#5b6b86"/></div></section>
    </div>
    <section className="panel"><div className="panel-title"><div><h2>Entregas no prazo</h2><p>% por semana · meta operacional 95%</p></div></div><div className="ontime">{WEEKS.map((w,i)=><div key={w} className={WEEK_ONTIME[i]>=95?'ok':''}><b>{WEEK_ONTIME[i]}%</b><small>{w}</small></div>)}</div></section>
  </div>;
}
