// ── InovaPED — Comparador de Distribuidoras (cotação externa) ───────────
// Busca um produto nos 24k e mostra preço / estoque / % / prazo em TODAS as
// distribuidoras ao mesmo tempo. Na casca os números são simulados de forma
// determinística (hash do produto × distribuidora). A integração real (API
// B2B / robô logado) é do Claude Code — ver CLAUDE.md §0.6.
const TopbarDist = window.BuyerParts1.Topbar;

// distribuidoras reais que o cliente usa
const DISTRIBS = [
  { id: 'panpharma', nome: 'Panpharma',  cor: '#E2231A', site: 'panpharma.com.br' },
  { id: 'smartped',  nome: 'SmartPed',   cor: '#2A8FEB', site: 'smartped.com.br' },
  { id: 'stcruz',    nome: 'Santa Cruz', cor: '#00A859', site: 'stcruz.com.br' },
  { id: 'farmafoco', nome: 'Farmafoco',  cor: '#FF8A1F', site: 'farmafoco.com.br' },
  { id: 'profarma',  nome: 'Profarma',   cor: '#9B5DE5', site: 'profarma.com.br' },
  { id: 'cooplogin', nome: 'Cooplogin',  cor: '#00C2B8', site: 'cooplogin.com.br' },
];
const PRAZOS = ['28 dias', '35 dias', '42/56 dias', '21 dias', '30 dias', '28/42 dias'];

function distA(hex, a) { const h=(hex||'#888').replace('#',''); const n=parseInt(h.length===3?h.split('').map(c=>c+c).join(''):h,16); return `rgba(${(n>>16)&255},${(n>>8)&255},${n&255},${a})`; }
const distBRL = n => (n==null||isNaN(n)) ? '—' : n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
// hash determinístico 0..1
function hash01(str) { let h = 2166136261; for (let i=0;i<str.length;i++){ h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } return ((h >>> 0) % 10000) / 10000; }

// gera a oferta simulada de uma distribuidora para um produto
function offerFor(prod, d) {
  const base = prod[7] || 1; // custo HOS
  const seed = hash01(prod[0] + d.id);
  const seed2 = hash01(d.id + prod[0]);
  const factor = 0.88 + seed * 0.26;          // -12% a +14% sobre o custo
  const price = +(base * factor).toFixed(2);
  const hasStock = seed2 > 0.18;              // ~82% têm estoque
  const stock = hasStock ? Math.round(20 + seed2 * 900) : 0;
  const prazo = PRAZOS[Math.floor(seed2 * PRAZOS.length) % PRAZOS.length];
  const semImposto = seed > 0.6;
  return { price, stock, hasStock, prazo, semImposto };
}

function DistKpi({ label, value, sub, color }) {
  const c = color || T.red;
  return <Glass pad={16} style={{ position:'relative', overflow:'hidden' }}>
    <div style={{ position:'absolute', top:0, left:0, right:0, height:3, background:`linear-gradient(90deg, ${c}, ${distA(c,0)})` }} />
    <div style={{ fontSize:12, color:T.mute, fontWeight:600 }}>{label}</div>
    <div style={{ fontSize:24, fontWeight:800, fontFamily:'var(--display)', letterSpacing:-0.5, marginTop:8, color:c }}>{value}</div>
    {sub && <div style={{ fontSize:11.5, color:T.mute2, marginTop:3 }}>{sub}</div>}
  </Glass>;
}

function Distribuidoras() {
  const ERP = window.ERP || { p: [], s: [] };
  const P = ERP.p;
  const [q, setQ] = React.useState('');
  const [sel, setSel] = React.useState(null);

  const results = React.useMemo(() => {
    const s = q.trim().toLowerCase();
    if (s.length < 2) return [];
    const out = [];
    for (let i=0;i<P.length && out.length<8;i++){ const p=P[i];
      if ((p[2]&&p[2].toLowerCase().includes(s)) || String(p[0]).includes(s) || String(p[1]).includes(s)) out.push(p); }
    return out;
  }, [q]);

  // produto selecionado → ofertas de todas as distribuidoras
  const board = React.useMemo(() => {
    if (!sel) return null;
    const offers = DISTRIBS.map(d => ({ d, ...offerFor(sel, d) }));
    const withStock = offers.filter(o => o.hasStock);
    const best = withStock.slice().sort((a,b)=>a.price-b.price)[0];
    const worst = withStock.slice().sort((a,b)=>b.price-a.price)[0];
    const avg = withStock.reduce((s,o)=>s+o.price,0)/(withStock.length||1);
    return { offers, best, worst, avg, nStock: withStock.length };
  }, [sel]);

  return (
    <div>
      <TopbarDist title="Distribuidoras" sub="Pesquise um produto e compare preço, estoque e condição em todas as distribuidoras"
        action={<Pill tone="mute"><Icon name="box" size={13} color={T.mute} /> {DISTRIBS.length} conectadas</Pill>} />

      {/* aviso integração */}
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 16px', borderRadius:12, background:distA(T.blue,0.08), border:`1px solid ${distA(T.blue,0.25)}`, marginBottom:16 }}>
        <Icon name="bolt" size={18} color={T.blue} />
        <span style={{ fontSize:13, color:T.text }}>Busca unificada em <b>Panpharma, SmartPed, Santa Cruz, Farmafoco, Profarma e Cooplogin</b>. <span style={{ color:T.mute2 }}>Preços de demonstração — a conexão ao vivo (API B2B / robô logado) é configurada na implantação.</span></span>
      </div>

      {/* busca */}
      <Glass pad={14} style={{ marginBottom:16, position:'relative', zIndex:20 }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'0 14px', height:46, borderRadius:12, background:T.panel, border:`1px solid ${T.border}` }}>
          <Icon name="search" size={18} color={T.mute} />
          <input value={q} onChange={e=>{ setQ(e.target.value); }} placeholder="Buscar produto, código ou EAN para cotar nas distribuidoras…" style={{ flex:1, background:'transparent', border:'none', outline:'none', color:T.text, fontSize:14.5, fontFamily:'inherit' }} />
          {q && <button onClick={()=>{ setQ(''); }} style={{ background:'none', border:'none', cursor:'pointer', display:'flex' }}><Icon name="x" size={16} color={T.mute2} /></button>}
        </div>
        {results.length > 0 && (
          <div style={{ marginTop:10, display:'flex', flexDirection:'column', gap:2 }}>
            {results.map((p,i)=>(
              <div key={i} onClick={()=>{ setSel(p); setQ(''); }} style={{ display:'flex', alignItems:'center', gap:11, padding:'10px 12px', borderRadius:10, cursor:'pointer' }}
                onMouseEnter={e=>e.currentTarget.style.background=T.panel} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <Icon name="box" size={15} color={T.mute2} />
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13.5, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{p[2]}</div>
                  <div style={{ fontSize:11, color:T.mute2, fontFamily:'var(--mono)' }}>#{p[0]} · {p[6]||'—'} · custo HOS R$ {distBRL(p[7])}</div>
                </div>
                <Icon name="chevron" size={14} color={T.mute2} />
              </div>
            ))}
          </div>
        )}
      </Glass>

      {!board && (
        <Glass><div style={{ padding:'46px 20px', textAlign:'center', color:T.mute }}>
          <Icon name="search" size={32} color={T.mute2} /><div style={{ marginTop:12, fontSize:14.5 }}>Busque um produto para comparar as distribuidoras.</div>
          <div style={{ fontSize:12.5, color:T.mute2, marginTop:6 }}>Ex.: "dipirona", "losartana", "whey"…</div>
        </div></Glass>
      )}

      {board && (
        <div>
          {/* cabeçalho do produto */}
          <Glass style={{ marginBottom:16 }}>
            <div style={{ display:'flex', flexWrap:'wrap', gap:12, alignItems:'center', justifyContent:'space-between' }}>
              <div style={{ minWidth:0 }}>
                <div style={{ fontSize:'clamp(18px,2.2vw,24px)', fontWeight:800, fontFamily:'var(--display)', letterSpacing:-0.5 }}>{sel[2]}</div>
                <div style={{ fontSize:12.5, color:T.mute, marginTop:4, fontFamily:'var(--mono)' }}>#{sel[0]} · EAN {sel[1]||'—'} · {sel[6]||'—'} · custo HOS R$ {distBRL(sel[7])}</div>
              </div>
              <button onClick={()=>setSel(null)} style={{ padding:'8px 14px', borderRadius:10, border:`1px solid ${T.border}`, background:T.panel, color:T.text, fontWeight:600, fontFamily:'inherit', cursor:'pointer', fontSize:13 }}>Limpar</button>
            </div>
          </Glass>

          {/* KPIs */}
          <div style={{ display:'grid', gap:14, marginBottom:16, gridTemplateColumns:'repeat(auto-fit, minmax(180px,1fr))' }}>
            <DistKpi label="Melhor preço" value={board.best?'R$ '+distBRL(board.best.price):'—'} sub={board.best?board.best.d.nome:'sem estoque'} color={T.green} />
            <DistKpi label="Distribuidoras c/ estoque" value={board.nStock+' de '+DISTRIBS.length} sub="disponível agora" color={T.blue} />
            <DistKpi label="Preço médio" value={'R$ '+distBRL(board.avg)} sub="entre as com estoque" color={T.yellow} />
            <DistKpi label="Economia vs. pior" value={board.best&&board.worst?((board.worst.price-board.best.price)/board.worst.price*100).toFixed(0)+'%':'—'} sub="melhor vs. mais caro" color={T.red} />
          </div>

          {/* tabela comparativa */}
          <Glass pad={0} style={{ overflow:'hidden' }}>
            <div style={{ overflowX:'auto' }}>
              <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13.5, minWidth:680 }}>
                <thead><tr style={{ color:T.mute, textAlign:'left', fontSize:11, textTransform:'uppercase', letterSpacing:0.4, background:T.panel }}>
                  <th style={{ padding:'13px 16px', fontWeight:700 }}>Distribuidora</th>
                  <th style={{ padding:'13px 16px', fontWeight:700, textAlign:'right' }}>Preço</th>
                  <th style={{ padding:'13px 16px', fontWeight:700, textAlign:'center' }}>Estoque</th>
                  <th style={{ padding:'13px 16px', fontWeight:700, textAlign:'center' }}>Imposto</th>
                  <th style={{ padding:'13px 16px', fontWeight:700 }}>Prazo</th>
                  <th style={{ padding:'13px 16px', fontWeight:700, textAlign:'right' }}>vs. melhor</th>
                </tr></thead>
                <tbody>
                  {board.offers.slice().sort((a,b)=>{ if(a.hasStock!==b.hasStock) return a.hasStock?-1:1; return a.price-b.price; }).map((o,i)=>{
                    const isBest = board.best && o.d.id===board.best.d.id;
                    const diff = board.best ? ((o.price-board.best.price)/board.best.price*100) : 0;
                    return (
                      <tr key={o.d.id} className="erp-row" style={{ borderTop:`1px solid ${T.border}`, background:isBest?distA(T.green,0.06):(o.hasStock?'transparent':distA('#FF4D4D',0.04)) }}>
                        <td style={{ padding:'13px 16px' }}>
                          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                            <span style={{ width:10, height:10, borderRadius:3, background:o.d.cor, flexShrink:0 }} />
                            <div>
                              <div style={{ fontWeight:700, display:'flex', alignItems:'center', gap:8 }}>{o.d.nome}{isBest && <span style={{ fontSize:9.5, fontWeight:800, padding:'2px 6px', borderRadius:5, background:distA(T.green,0.16), color:T.green }}>MELHOR</span>}</div>
                              <div style={{ fontSize:10.5, color:T.mute2 }}>{o.d.site}</div>
                            </div>
                          </div>
                        </td>
                        <td style={{ padding:'13px 16px', textAlign:'right', fontFamily:'var(--mono)', fontWeight:800, fontSize:15, color:isBest?T.green:T.text }}>{o.hasStock?'R$ '+distBRL(o.price):'—'}</td>
                        <td style={{ padding:'13px 16px', textAlign:'center', fontFamily:'var(--mono)' }}>{o.hasStock?<span style={{ color:T.text }}>{o.stock}</span>:<span style={{ color:'#FF6B6B', fontWeight:600 }}>zerado</span>}</td>
                        <td style={{ padding:'13px 16px', textAlign:'center' }}>{o.hasStock?<Pill tone={o.semImposto?'yellow':'mute'}>{o.semImposto?'sem imp.':'c/ imp.'}</Pill>:<span style={{ color:T.mute2 }}>—</span>}</td>
                        <td style={{ padding:'13px 16px', color:T.mute, fontFamily:'var(--mono)', fontSize:12.5 }}>{o.hasStock?o.prazo:'—'}</td>
                        <td style={{ padding:'13px 16px', textAlign:'right' }}>{o.hasStock?(isBest?<span style={{ color:T.green, fontWeight:700, fontSize:12 }}>menor</span>:<Delta pct={diff} size={11.5} />):<span style={{ color:T.mute2 }}>—</span>}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
            <div style={{ display:'flex', flexWrap:'wrap', gap:10, justifyContent:'flex-end', padding:16, borderTop:`1px solid ${T.border}` }}>
              <button style={{ display:'inline-flex', alignItems:'center', gap:8, padding:'10px 18px', borderRadius:11, border:`1px solid ${T.border}`, background:T.panel, color:T.text, fontWeight:700, fontFamily:'inherit', cursor:'pointer', fontSize:13 }}><Icon name="refresh" size={15} color={T.text} /> Atualizar preços</button>
              <button style={{ display:'inline-flex', alignItems:'center', gap:8, padding:'10px 18px', borderRadius:11, border:'none', cursor:'pointer', fontFamily:'inherit', fontSize:13, fontWeight:700, color:'#fff', background:`linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow:'0 4px 14px rgba(255,19,48,0.3)' }}><Icon name="check" size={15} color="#fff" /> Comprar no melhor preço</button>
            </div>
          </Glass>
        </div>
      )}
    </div>
  );
}

window.BuyerDistrib = { Distribuidoras };
