/* ===== Carteira de clientes: rating, mapa e comparação ===== */
const MAP_X=(lon)=>(lon+49.2)*410+20, MAP_Y=(lat)=>(-20.05-lat)*410+20;
const baseLetter={'Base própria':'B','Terminal':'T','Usina':'U'};

function RegionMap({list,sel,setSel,bases,showClients=true}) {
  const byCity={};
  const garage=(bases.find(b=>b.garage)||{city:'Barretos'}).city;
  const [gla,glo]=cities[garage];
  return <svg viewBox="0 0 640 530" className="cmap" role="img" aria-label="Mapa da região com bases e clientes">
    <rect x="0" y="0" width="640" height="530" rx="12" fill="#f3f6fa"/>
    {Object.entries(cities).map(([n,[la,lo]])=><g key={n}><circle cx={MAP_X(lo)} cy={MAP_Y(la)} r="3" fill="#b6c0cf"/><text x={MAP_X(lo)>560?MAP_X(lo)-6:MAP_X(lo)+6} y={MAP_Y(la)-6} fontSize="11" fill="#7a8597" textAnchor={MAP_X(lo)>560?'end':'start'}>{n}</text></g>)}
    {showClients&&list.map(c=>{const [la,lo]=cities[c.city];return <line key={'l'+c.id} x1={MAP_X(glo)} y1={MAP_Y(gla)} x2={MAP_X(lo)} y2={MAP_Y(la)} stroke={ratingColor[c.rating]} strokeOpacity="0.35" strokeDasharray="4 4"/>;})}
    {showClients&&list.map(c=>{const [la,lo]=cities[c.city];const k=byCity[c.city]=(byCity[c.city]||0)+1;const dx=(k-1)*28+(bases.some(b=>b.city===c.city)?26:0),r=7+Math.sqrt(c.vol/1e6)*12;return <g key={c.id} className="cpin" onClick={()=>setSel&&setSel(c.id)} role="button" tabIndex={0} aria-label={`${c.name}, rating ${c.rating}`} onKeyDown={e=>{if(e.key==='Enter'&&setSel)setSel(c.id);}}><title>{`${c.name} · ${c.city} · rating ${c.rating} · ${fmt(c.vol)} L/mês`}</title><circle cx={MAP_X(lo)+dx} cy={MAP_Y(la)+14} r={r} fill={ratingColor[c.rating]} fillOpacity={sel===c.id?1:0.82} stroke={sel===c.id?'#111c32':'#fff'} strokeWidth={sel===c.id?3:2}/><text x={MAP_X(lo)+dx} y={MAP_Y(la)+18} fontSize="11" fill="#fff" textAnchor="middle" fontWeight="800">{c.rating}</text></g>;})}
    {bases.map((b,i)=>{const [la,lo]=cities[b.city];const same=bases.filter((x,j)=>j<i&&x.city===b.city).length;return <g key={b.id}><title>{`${b.name} · ${b.products.join(', ')}`}</title><rect x={MAP_X(lo)-10+same*22} y={MAP_Y(la)-10} width="20" height="20" rx="5" fill={b.kind==='Usina'?'#1f7a50':'#111c32'} stroke="#fff" strokeWidth="2"/><text x={MAP_X(lo)+same*22} y={MAP_Y(la)+4} fontSize="10" fill="#fff" textAnchor="middle" fontWeight="800">{baseLetter[b.kind]||'B'}</text></g>;})}
    <g transform="translate(20,486)"><rect width="440" height="30" rx="8" fill="#fff" stroke="#e1e6ee"/>{showClients&&['A','B','C','D'].map((r,i)=><g key={r} transform={`translate(${14+i*40},15)`}><circle r="7" fill={ratingColor[r]}/><text x="11" y="4" fontSize="11" fill="#445067">{r}</text></g>)}<g transform={`translate(${showClients?176:14},8)`}><rect width="14" height="14" rx="4" fill="#111c32"/><text x="20" y="11" fontSize="10" fill="#445067">Base/terminal</text><rect x="100" width="14" height="14" rx="4" fill="#1f7a50"/><text x="120" y="11" fontSize="10" fill="#445067">Usina</text>{showClients&&<text x="168" y="11" fontSize="10" fill="#7a8597">tamanho = volume</text>}</g></g>
  </svg>;
}

function Clients({clients,sellers,bases,go}) {
  const garage=(bases.find(b=>b.garage)||{city:'Barretos'}).city;
  const all=useMemo(()=>rateClients(clients,sellers,garage),[clients,sellers,garage]);
  const [seller,setSeller]=useState('Todos');
  const [sel,setSel]=useState('C-01');
  const list=all.filter(c=>seller==='Todos'||c.sellerId===seller).sort((a,b)=>b.score-a.score);
  const cur=all.find(c=>c.id===sel)||list[0];
  const big=all.find(c=>c.id==='C-02'), good=all.find(c=>c.id==='C-01');
  const totalResult=list.reduce((s,c)=>s+c.result,0);
  return <div className="content clients-content">
    <div className="page-heading"><div><p>COMERCIAL</p><h1>Carteira de clientes</h1><span>Quem dá mais resultado depois de pagar a entrega, não só quem compra mais litros.</span></div><div className="heading-actions"><label className="seller-filter">Vendedor<select id="seller" value={seller} onChange={e=>setSeller(e.target.value)}><option value="Todos">Todos</option>{sellers.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}</select></label><button className="secondary" onClick={()=>go('cadastros','vendedores')}>Gerenciar cadastros</button></div></div>
    {big&&good&&<section className="compare"><div className="cmp-intro"><span>VOLUME NÃO É TUDO</span><strong>Quem compra mais nem sempre deixa mais dinheiro</strong><p>O custo de entrega (distância, tamanho da carga, restrição de acesso) come a margem. Por isso a nota olha o resultado líquido.</p></div>
      {[big,good].map(c=><div key={c.id} className="cmp-card" onClick={()=>setSel(c.id)}><div className="cmp-top"><b>{c.name}</b><span className={`rating r${c.rating}`}>{c.rating}</span></div><p className="cmp-meta">{c.postos} {c.postos===1?'posto':'postos'} · {c.city} · {c.km} km da base</p><dl><div><dt>Volume/mês</dt><dd>{fmt(c.vol)} L</dd></div><div><dt>Margem bruta</dt><dd>{brl3(c.margem)}/L</dd></div><div><dt>Custo de entrega</dt><dd>{brl3(c.custoL)}/L</dd></div><div className="hl"><dt>Resultado/mês</dt><dd>{brl(c.result)}</dd></div></dl></div>)}
      {good.result>big.result&&<p className="cmp-verdict">O <b>{good.name}</b> compra {fmt(Math.max(0,big.vol-good.vol))} L a menos por mês e deixa <b>{brl(good.result-big.result)} a mais</b>.</p>}
    </section>}
    <div className="clients-grid">
      <section className="panel map-panel"><div className="panel-title"><div><h2>Mapa da carteira</h2><p>Cor = rating · tamanho = volume · quadrados = bases de carregamento. Clique num cliente.</p></div></div><RegionMap list={list} sel={cur&&cur.id} setSel={setSel} bases={bases}/></section>
      <section className="panel detail-panel">{cur&&<>
        <div className="panel-title"><div><h2>{cur.name}</h2><p>{cur.city} · vendedor(a) {cur.seller}</p></div><span className={`rating big r${cur.rating}`}>{cur.rating}</span></div>
        <div className="detail-body">
          <p className="score-line">Nota <b>{cur.score}</b>/100{cur.note?` · ${cur.note}`:''}</p>
          <div className="calc">
            <p><span>Volume por mês</span><b>{fmt(cur.vol)} L</b></p>
            <p><span>Margem bruta</span><b>{brl3(cur.margem)}/L</b></p>
            <p><span>Custo de entrega<small>2 × {cur.km} km × R$ 7,20 ÷ {fmt(cur.carga)} L por viagem</small></span><b>− {brl3(cur.custoL)}/L</b></p>
            <p className="tot"><span>Margem líquida</span><b>{brl3(cur.liq)}/L</b></p>
            <p className="tot"><span>Resultado por mês</span><b>{brl(cur.result)}</b></p>
          </div>
          <div className="parts">{cur.parts.map(p=><div key={p.label}><p><span>{p.label}</span><small>peso {p.w}%</small><b>{Math.round(p.v)}</b></p><div className="meter"><i style={{width:`${p.v}%`,background:ratingColor[cur.rating]}}/></div></div>)}</div>
          <p className="kv"><span>Postos</span><b>{cur.postos}</b><span>Atraso médio no pagamento</span><b>{cur.atraso} {cur.atraso===1?'dia':'dias'}</b><span>Compras por mês</span><b>{cur.compras}</b></p>
        </div></>}
      </section>
    </div>
    <section className="panel orders"><div className="panel-title"><div><h2>Ranking da carteira</h2><p>{list.length} clientes · resultado somado {brl(totalResult)}/mês · pesos da nota são hipótese a validar</p></div></div><div className="table-wrap"><table><thead><tr><th>Rating</th><th>Cliente</th><th>Vendedor</th><th>Postos</th><th>Volume/mês</th><th>Margem bruta</th><th>Custo entrega</th><th>Resultado/mês</th><th>Pagamento</th></tr></thead><tbody>{list.map(c=><tr key={c.id} className={cur&&cur.id===c.id?'row-on':''} onClick={()=>setSel(c.id)}><td><span className={`rating r${c.rating}`}>{c.rating}</span> <small>{c.score}</small></td><td><b className="strong">{c.name}</b><small className="cell-sub">{c.city} · {c.km} km</small></td><td>{c.seller}</td><td>{c.postos}</td><td className="num">{fmt(c.vol)} L</td><td className="num">{brl3(c.margem)}</td><td className="num">{brl3(c.custoL)}</td><td className="num strong">{brl(c.result)}</td><td>{c.atraso===0?'Em dia':`${c.atraso} ${c.atraso===1?'dia':'dias'} de atraso`}</td></tr>)}{!list.length&&<tr><td colSpan="9">Nenhum cliente para este vendedor.</td></tr>}</tbody></table></div></section>
  </div>;
}
