// ── Inova Cotação — Comprador: Grade Comparativa + Base ─────────────────
const Topbar3 = window.BuyerParts1.Topbar;
const ICc = window.IC;
const cat3 = window.BuyerParts1.catById, rep3 = window.BuyerParts1.repById;

const thS = (align, w) => ({ textAlign: align, padding: '14px 16px', fontSize: 11.5, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, whiteSpace: 'nowrap', minWidth: w, position: 'sticky', top: 0 });
const tdS = (align) => ({ textAlign: align, padding: '13px 16px', verticalAlign: 'middle' });

// ═══ GRADE COMPARATIVA ═══════════════════════════════════════════════════
function Grid({ quote }) {
  // q seguro: nunca undefined (evita tela preta ao abrir a Grade sem cotação)
  const q = quote || ICc.QUOTES[0] || { id: null, cat: null, reps: [], title: 'Nenhuma cotação', items: 0, responded: 0 };
  const semQuote = q.id == null && !q.reps.length;
  const cat = cat3(q.cat) || { name: q.categoria || '—', icon: 'box' };

  const [search, setSearch] = useState('');
  const [sortBy, setSortBy] = useState('eco');
  const [onlyBelow, setOnlyBelow] = useState(false);
  const [onlyResp, setOnlyResp] = useState(false);
  const [taxFilter, setTaxFilter] = useState('all');
  const [hiddenReps, setHiddenReps] = useState(() => new Set());
  const [selected, setSelected] = useState(() => new Set());
  const [qty, setQty] = useState({});
  const [closed, setClosed] = useState(false);
  const [negotiator, setNegotiator] = useState(false);
  const [onlyShort, setOnlyShort] = useState(false);
  const [markup, setMarkup] = useState(35);
  const [histProd, setHistProd] = useState(null);
  const [histFallback, setHistFallback] = useState(null);
  const [grade, setGrade] = useState(null);

  // Grade VIVA da API (cai no mock se não houver backend/id)
  useEffect(() => {
    let live = true;
    if (q && q.id != null && window.api) {
      window.api.get('/quotations/' + q.id + '/grade').then(g => { if (live) setGrade(g); }).catch(() => {});
    }
    return () => { live = false; };
  }, [q && q.id]);

  const isLive = !!(grade && grade.itens);
  const offMap = {}, valMap = {}, tierMap = {}, offIdMap = {};
  if (isLive) grade.itens.forEach(it => (it.offers || []).forEach(o => {
    const k = it.id + ':' + o.rep_id;
    offMap[k] = o.preco; valMap[k] = o.validade; offIdMap[k] = o.id;
    if (o.tiers && o.tiers.length) tierMap[k] = o.tiers.map(t => ({ qty: t.qtd_min, price: t.preco }));
  }));
  const reps = (q.reps || []).map(rep3).filter(Boolean);
  const products = isLive
    ? grade.itens.map(it => ({ id: it.id, name: it.descricao, brand: it.fabricante || '', cod: it.cod || '', ean: it.ean || '', lastCost: it.custo_ref, cat: q.cat }))
    : ICc.PRODUCTS.filter(p => p.cat === q.cat);

  const offer = isLive ? (pid, rid) => offMap[pid + ':' + rid] : (pid, rid) => ICc.OFFERS[`${pid}:${rid}`];
  const valid = isLive ? (pid, rid) => valMap[pid + ':' + rid] : (pid, rid) => ICc.VALIDITY[`${pid}:${rid}`];
  const getTiers = isLive ? (pid, rid) => tierMap[pid + ':' + rid] : (pid, rid) => ICc.TIERS[`${pid}:${rid}`];
  const getQty = (pid) => qty[pid] == null ? 1 : qty[pid];

  const visibleReps = reps.filter(r => !hiddenReps.has(r.id) && (taxFilter === 'all' || r.tax === taxFilter));
  const bestFor = (p) => {
    let best = null;
    visibleReps.forEach(r => { const o = offer(p.id, r.id); if (o != null && (best == null || o < best.price)) best = { price: o, rid: r.id }; });
    return best;
  };

  let rows = products.map(p => {
    const best = bestFor(p);
    const saving = best ? p.lastCost - best.price : 0;
    const responded = visibleReps.some(r => offer(p.id, r.id) != null);
    const shortVal = visibleReps.some(r => { const v = valid(p.id, r.id); return v && /2026/.test(v); });
    return { p, best, saving, responded, shortVal, below: best && best.price < p.lastCost, varPct: best ? ((best.price - p.lastCost) / p.lastCost) * 100 : 0 };
  });

  // filtros
  const s = search.trim().toLowerCase();
  let shown = rows.filter(r =>
    (!s || r.p.name.toLowerCase().includes(s) || r.p.brand.toLowerCase().includes(s) || r.p.ean.includes(s)) &&
    (!onlyBelow || r.below) && (!onlyResp || r.responded) && (!onlyShort || r.shortVal)
  );
  shown.sort((a, b) => sortBy === 'eco' ? b.saving - a.saving
    : sortBy === 'price' ? (a.best?.price ?? 1e9) - (b.best?.price ?? 1e9)
    : sortBy === 'var' ? a.varPct - b.varPct
    : a.p.name.localeCompare(b.p.name));

  const totalSaving = rows.reduce((acc, r) => acc + (r.below ? r.saving : 0), 0);
  const oppCount = rows.filter(r => r.below).length;
  const avgVar = rows.filter(r => r.best).reduce((a, r) => a + r.varPct, 0) / Math.max(1, rows.filter(r => r.best).length);

  // seleção
  const toggleSel = (pid) => setSelected(s => { const n = new Set(s); n.has(pid) ? n.delete(pid) : n.add(pid); return n; });
  const allShownSelected = shown.length > 0 && shown.every(r => selected.has(r.p.id));
  const toggleAll = () => setSelected(() => allShownSelected ? new Set() : new Set(shown.map(r => r.p.id)));
  const selRows = rows.filter(r => selected.has(r.p.id) && r.best);
  const orderTotal = selRows.reduce((a, r) => a + r.best.price * getQty(r.p.id), 0);
  const orderSaving = selRows.reduce((a, r) => a + (r.below ? r.saving * getQty(r.p.id) : 0), 0);
  const toggleRep = (rid) => setHiddenReps(s => { const n = new Set(s); n.has(rid) ? n.delete(rid) : n.add(rid); return n; });

  const filtersActive = onlyBelow || onlyResp || onlyShort || negotiator || taxFilter !== 'all' || s || hiddenReps.size;

  const [ordering, setOrdering] = useState(false);
  const fecharPedido = async () => {
    if (isLive && window.api) {
      setOrdering(true);
      try {
        const sels = selRows
          .map(r => ({ offer_id: offIdMap[r.p.id + ':' + (r.best && r.best.rid)], qty: getQty(r.p.id) }))
          .filter(x => x.offer_id);
        if (sels.length) {
          await window.api.post('/quotations/' + q.id + '/order', { selections: sels });
          if (window.ICLive) await window.ICLive.reloadQuotes();
        }
      } catch (e) {}
      setOrdering(false);
    }
    setClosed(true);
  };

  return (
    <div style={{ paddingBottom: selected.size ? 90 : 0 }}>
      <Topbar3 title="Grade Comparativa" sub={`${q.title} · ${cat.name} · ${visibleReps.length} reps`}
        action={
          <div style={{ display: 'flex', gap: 8 }}>
            <ToolBtn icon="receipt">Exportar</ToolBtn>
            <ToolBtn icon="bell">Cobrar reps</ToolBtn>
          </div>
        } />

      {/* resumo */}
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))' }}>
        <MiniKpi label="Economia potencial" value={`R$ ${ICc.fmt(totalSaving)}`} color={T.green} />
        <MiniKpi label="Oportunidades" value={oppCount} suffix={`/ ${rows.length} itens`} />
        <MiniKpi label="Variação média" value={`${avgVar.toFixed(1)}%`} color={avgVar <= 0 ? T.green : T.redBright} />
        <MiniKpi label="Respostas" value={q.responded} suffix={`/ ${reps.length} reps`} />
      </div>

      {/* aviso de imposto */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px', borderRadius: 12, background: 'rgba(255,200,61,0.08)', border: '1px solid rgba(255,200,61,0.28)', marginBottom: 14 }}>
        <Icon name="receipt" size={17} color="#FFC83D" />
        <span style={{ fontSize: 12.5, color: '#E8D9A8' }}>Cada rep declara se o preço é <b style={{color:'#FFC83D'}}>com</b> ou <b style={{color:'#FFC83D'}}>sem imposto</b> — veja o selo no topo de cada coluna. Use o filtro de imposto p/ comparar na mesma base.</span>
      </div>

      {/* TOOLBAR de filtros */}
      <Glass pad={14} style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: '1 1 240px', minWidth: 200 }}>
            <Icon name="search" size={16} color={T.mute} style={{ position: 'absolute', left: 12, top: 11 }} />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar produto, marca, EAN..."
              style={{ width: '100%', boxSizing: 'border-box', padding: '9px 12px 9px 38px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13.5, outline: 'none' }} />
          </div>
          {/* ordenação */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 12, color: T.mute2 }}>Ordenar</span>
            <Seg value={sortBy} onChange={setSortBy} opts={[['eco','Economia'],['price','Menor preço'],['var','Variação'],['name','Nome']]} />
          </div>
          {/* imposto */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="receipt" size={14} color={T.mute2} />
            <Seg value={taxFilter} onChange={setTaxFilter} opts={[['all','Todos'],['com','c/ imp.'],['sem','s/ imp.']]} />
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginTop: 12 }}>
          <FChip on={onlyBelow} onClick={() => setOnlyBelow(v => !v)} icon="arrowDown" tone="green">Abaixo do custo</FChip>
          <FChip on={onlyResp} onClick={() => setOnlyResp(v => !v)} icon="check">Só respondidos</FChip>
          <FChip on={onlyShort} onClick={() => setOnlyShort(v => !v)} icon="clock" tone="yellow">Vencimento curto</FChip>
          <button onClick={() => setNegotiator(v => !v)} title="Oculta os nomes dos reps pra escolher sem viés" style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 13px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, border: `1px solid ${negotiator ? T.redBright : T.border}`, color: negotiator ? T.redBright : T.mute, background: negotiator ? T.redBg : 'transparent' }}><Icon name="shield" size={14} color={negotiator ? T.redBright : T.mute} /> Modo Negociador</button>
          <div style={{ width: 1, height: 22, background: T.border, margin: '0 4px' }} />
          <span style={{ fontSize: 12, color: T.mute2 }}>Reps:</span>
          {reps.map(r => { const off = hiddenReps.has(r.id); return (
            <button key={r.id} onClick={() => toggleRep(r.id)} title={off ? 'Mostrar coluna' : 'Ocultar coluna'} style={{
              display: 'flex', alignItems: 'center', gap: 6, padding: '6px 11px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
              border: `1px solid ${off ? T.border : T.borderHi}`, background: off ? 'transparent' : T.panel, color: off ? T.mute2 : T.text, opacity: off ? 0.55 : 1, textDecoration: off ? 'line-through' : 'none',
            }}><span style={{ width: 8, height: 8, borderRadius: 99, background: r.color }} />{r.name.split(' ')[0]}</button>
          ); })}
          {filtersActive ? <button onClick={() => { setOnlyBelow(false); setOnlyResp(false); setOnlyShort(false); setNegotiator(false); setTaxFilter('all'); setSearch(''); setHiddenReps(new Set()); }} style={{ marginLeft: 'auto', fontSize: 12, color: T.redBright, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}><Icon name="x" size={13} color={T.redBright} /> Limpar</button> : null}
        </div>
      </Glass>

      {/* tabela */}
      <Glass pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
            <thead>
              <tr style={{ background: T.panel }}>
                <th style={{ ...thS('center', 44), padding: '14px 0 14px 16px' }}><Check on={allShownSelected} onClick={toggleAll} /></th>
                <th style={thS('left', 260)}>Produto</th>
                <th style={thS('center', 84)}>Qtd</th>
                <th style={thS('right', 104)}>Últ. Custo</th>
                <th style={thS('center', 96)}>Histórico</th>
                {visibleReps.map((r, ri) => (
                  <th key={r.id} style={thS('right', 140)}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3 }}>
                      {negotiator
                        ? <span style={{ display:'flex', alignItems:'center', gap: 6, color: T.mute }}><Icon name="shield" size={12} color={T.mute} />Fornecedor {ri + 1}</span>
                        : <><span style={{ display:'flex', alignItems:'center', gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 99, background: r.color }} />{r.name.split(' ')[0]}</span>
                          <span style={{ fontSize: 10, color: T.mute2, fontWeight: 600, textTransform: 'none', letterSpacing: 0, display:'flex',alignItems:'center',gap:3 }}><Icon name="box" size={10} color={T.mute2} />{r.lab}</span></>}
                      <Pill tone={r.tax === 'com' ? 'mute' : 'white'} style={{ fontSize: 10, padding: '1px 7px' }}>{r.tax === 'com' ? 'c/ imposto' : 's/ imposto'}</Pill>
                    </div>
                  </th>
                ))}
                <th style={thS('right', 92)}>Melhor</th>
                <th style={thS('right', 104)}>Economia</th>
              </tr>
            </thead>
            <tbody>
              {shown.map(({ p, best, saving, below }) => {
                const sel = selected.has(p.id);
                return (
                <tr key={p.id} style={{ borderTop: `1px solid ${T.border}`, background: sel ? 'rgba(255,19,48,0.06)' : 'transparent' }}>
                  <td style={{ ...tdS('center'), paddingLeft: 16 }}><Check on={sel} onClick={() => toggleSel(p.id)} /></td>
                  <td style={tdS('left')}>
                    <div onClick={() => { const ep = window.findERPProduct(p.name); setHistProd(ep || null); setHistFallback(ep ? null : p); }} title="Ver histórico do produto" style={{ fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }} className="prodlink">
                      {p.name}
                      <Icon name="chart" size={13} color={T.mute2} />
                    </div>
                    <div style={{ fontSize: 11.5, color: T.mute2, marginTop: 2 }}>{[p.cod && ('Cód ' + p.cod), p.ean && ('EAN ' + p.ean), p.brand].filter(Boolean).join(' · ')}</div>
                  </td>
                  <td style={tdS('center')}>
                    <input value={getQty(p.id)} onChange={e => setQty(s => ({ ...s, [p.id]: Math.max(0, parseInt(e.target.value.replace(/\D/g, '')) || 0) }))}
                      style={{ width: 54, textAlign: 'center', padding: '7px 4px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13, fontWeight: 700, outline: 'none' }} />
                  </td>
                  <td style={{ ...tdS('right'), color: T.yellow, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(p.lastCost)}</td>
                  <td style={tdS('center')}>{ICc.SPARK[p.id] ? <div style={{ display: 'flex', justifyContent: 'center' }}><SparkLine data={ICc.SPARK[p.id]} /></div> : <span style={{ color: T.mute2 }}>—</span>}</td>
                  {visibleReps.map(r => {
                    const o = offer(p.id, r.id), v = valid(p.id, r.id), isBest = best && best.rid === r.id;
                    if (o == null) return <td key={r.id} style={{ ...tdS('right'), color: T.mute2 }}>—</td>;
                    const pct = ((o - p.lastCost) / p.lastCost) * 100;
                    const good = o < p.lastCost;
                    const tiers = getTiers(p.id, r.id);
                    const cellBg = isBest ? 'rgba(0,230,140,0.16)' : good ? 'rgba(0,230,140,0.06)' : 'rgba(255,19,48,0.06)';
                    return (
                      <td key={r.id} style={{ ...tdS('right'), position: 'relative', background: cellBg, boxShadow: isBest ? `inset 0 0 0 1.5px rgba(0,230,140,0.5)` : 'none' }}>
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
                          <span style={{ fontWeight: 700, fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums', color: isBest ? T.green : good ? '#7BF0C0' : T.text }}>R$ {ICc.fmt(o)}</span>
                          <Delta pct={pct} size={11} />
                          {v && <span style={{ fontSize: 10.5, color: T.mute2, display:'flex',alignItems:'center',gap:3 }}><Icon name="calendar" size={11} color={T.mute2}/> {v}</span>}
                          {tiers && tiers.length > 0 && <span title={tiers.map(t => `≥${t.qty}un: R$ ${ICc.fmt(t.price)}`).join('  ')} style={{ fontSize: 10, color: T.green, fontWeight: 700, display:'flex',alignItems:'center',gap:3, background: 'rgba(0,230,140,0.1)', padding: '1px 6px', borderRadius: 99, marginTop: 1 }}><Icon name="tag" size={10} color={T.green} />≥{tiers[tiers.length-1].qty} R$ {ICc.fmt(tiers[tiers.length-1].price)}</span>}
                        </div>
                      </td>
                    );
                  })}
                  <td style={{ ...tdS('right'), fontWeight: 800, fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums', color: below ? T.green : T.text }}>{best ? 'R$ ' + ICc.fmt(best.price) : '—'}</td>
                  <td style={tdS('right')}>
                    {below
                      ? <span style={{ display:'inline-flex', flexDirection:'column', alignItems:'flex-end', gap:2 }}><span style={{ fontWeight: 800, color: T.green, fontVariantNumeric:'tabular-nums' }}>R$ {ICc.fmt(saving)}</span><Delta pct={((best.price - p.lastCost)/p.lastCost)*100} size={11} /></span>
                      : <span style={{ color: T.mute2 }}>—</span>}
                  </td>
                </tr>
              ); })}
              {!shown.length && <tr><td colSpan={7 + visibleReps.length} style={{ padding: 40, textAlign: 'center', color: T.mute2 }}>Nenhum produto com esses filtros.</td></tr>}
            </tbody>
          </table>
        </div>
      </Glass>

      {/* combos oferecidos pelos reps */}
      {(() => {
        const combos = ICc.COMBOS.filter(c => c.cat === q.cat && visibleReps.some(r => r.id === c.rep));
        if (!combos.length) return null;
        return (
          <Glass style={{ marginTop: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14 }}>
              <Icon name="bolt" size={17} color={T.redBright} />
              <div style={{ fontWeight: 700, fontSize: 15 }}>Combos oferecidos</div>
              <span style={{ fontSize: 12, color: T.mute }}>· ofertas casadas dos representantes</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
              {combos.map(c => {
                const r = rep3(c.rep);
                const baseSum = c.items.reduce((s, pid) => s + (offer(pid, c.rep) ?? ICc.PRODUCTS.find(p => p.id === pid)?.lastCost ?? 0), 0);
                const pct = baseSum > 0 ? ((c.price - baseSum) / baseSum) * 100 : 0;
                return (
                  <div key={c.id} style={{ padding: 14, borderRadius: 14, background: T.panel, border: `1px solid ${T.border}` }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontWeight: 700, fontSize: 14, display:'flex',alignItems:'center',gap:7 }}><Icon name="bolt" size={14} color={T.redBright} />{c.name}</span>
                      <span style={{ display:'flex', alignItems:'center', gap: 5, fontSize: 11.5, color: T.mute }}><span style={{ width: 7, height: 7, borderRadius: 99, background: r.color }} />{r.name.split(' ')[0]}</span>
                    </div>
                    <div style={{ fontSize: 12, color: T.mute2, marginTop: 7 }}>{c.items.map(pid => ICc.PRODUCTS.find(p => p.id === pid)?.name.split(' ').slice(0,2).join(' ')).join('  +  ')}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10 }}>
                      <span style={{ fontWeight: 800, fontSize: 16, fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(c.price)}</span>
                      <span style={{ fontSize: 12, color: T.mute2, textDecoration: 'line-through', fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(baseSum)}</span>
                      <span style={{ marginLeft: 'auto' }}><Delta pct={pct} /></span>
                    </div>
                  </div>
                );
              })}
            </div>
          </Glass>
        );
      })()}

      {/* barra de pedido (sticky) */}
      {selected.size > 0 && (
        <div style={{ position: 'sticky', bottom: 0, marginTop: 16, zIndex: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, rowGap: 10, flexWrap: 'wrap', padding: '14px 20px', borderRadius: 16, background: T.surface2, border: `1px solid ${T.borderHi}`, boxShadow: '0 -8px 40px rgba(0,0,0,0.6)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 34, height: 34, borderRadius: 9, background: T.redBg, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="check" size={18} color={T.redBright} strokeWidth={2.4} /></div>
              <div><div style={{ fontWeight: 800, fontSize: 15 }}>{selected.size} itens</div><div style={{ fontSize: 11.5, color: T.mute2 }}>selecionados p/ pedido</div></div>
            </div>
            <div style={{ width: 1, height: 32, background: T.border }} />
            <div><div style={{ fontSize: 11.5, color: T.mute2 }}>Total do pedido</div><div style={{ fontWeight: 800, fontSize: 17, fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(orderTotal)}</div></div>
            <div><div style={{ fontSize: 11.5, color: T.mute2 }}>Economia</div><div style={{ fontWeight: 800, fontSize: 17, color: T.green, fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(orderSaving)}</div></div>
            <div style={{ width: 1, height: 32, background: T.border }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div>
                <div style={{ fontSize: 11.5, color: T.mute2, display:'flex',alignItems:'center',gap:4 }}><Icon name="chart" size={12} color={T.mute2} /> Markup</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
                  <input value={markup} onChange={e => setMarkup(Math.max(0, parseInt(e.target.value.replace(/\D/g, '')) || 0))} style={{ width: 46, textAlign: 'center', padding: '4px 4px', borderRadius: 7, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, fontWeight: 800, outline: 'none' }} />
                  <span style={{ color: T.mute, fontWeight: 700 }}>%</span>
                </div>
              </div>
              <div><div style={{ fontSize: 11.5, color: T.mute2 }}>Venda estimada</div><div style={{ fontWeight: 800, fontSize: 16, fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(orderTotal * (1 + markup / 100))}</div></div>
              <div><div style={{ fontSize: 11.5, color: T.mute2 }}>Lucro bruto</div><div style={{ fontWeight: 800, fontSize: 16, color: T.green, fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(orderTotal * (markup / 100))}</div></div>
            </div>
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 10 }}>
              <button onClick={() => setSelected(new Set())} style={{ padding: '11px 16px', borderRadius: 11, border: `1px solid ${T.border}`, background: 'transparent', color: T.mute, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13.5 }}>Limpar</button>
              <button onClick={fecharPedido} disabled={ordering} style={{ display:'flex',alignItems:'center',gap:8, padding: '11px 22px', borderRadius: 11, border: 'none', cursor: ordering ? 'wait' : 'pointer', fontWeight: 800, fontFamily: 'inherit', fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 6px 20px rgba(255,19,48,0.45)', opacity: ordering ? 0.7 : 1 }}><Icon name="bolt" size={17} color="#fff" /> {ordering ? 'Fechando…' : 'Fechar pedido'}</button>
            </div>
          </div>
        </div>
      )}

      {closed && <OrderDone count={selRows.length} total={orderTotal} saving={orderSaving} onClose={() => { setClosed(false); setSelected(new Set()); }} />}
      {histProd && <ProductDetail p={histProd} onClose={() => setHistProd(null)} />}
      {histFallback && <SimpleHist p={histFallback} reps={visibleReps} offer={offer} onClose={() => setHistFallback(null)} />}
    </div>
  );
}

// histórico simples quando não há match no ERP (usa dados da cotação)
function SimpleHist({ p, reps, offer, onClose }) {
  const spark = ICc.SPARK[p.id] || [];
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.62)', backdropFilter: 'blur(7px)', zIndex: 200, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 'min(560px, 96vw)', height: '100%', overflow: 'auto', background: `linear-gradient(180deg, ${T.surface}, ${T.bg})`, borderLeft: `1px solid ${T.borderHi}`, boxShadow: '-30px 0 80px rgba(0,0,0,0.6)', animation: 'icRight .3s cubic-bezier(.2,.8,.2,1) both' }}>
        <div style={{ padding: '20px 24px', borderBottom: `1px solid ${T.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div><h2 style={{ margin: 0, fontSize: 20, fontWeight: 800, fontFamily: 'var(--display)' }}>{p.name}</h2><div style={{ fontSize: 12.5, color: T.mute, marginTop: 4 }}>{p.brand} · EAN {p.ean}</div></div>
          <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="x" size={18} color={T.mute} /></button>
        </div>
        <div style={{ padding: 24 }}>
          <div style={{ padding: 16, borderRadius: 14, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 16 }}>
            <div style={{ fontSize: 12, color: T.mute2 }}>Último custo de referência</div>
            <div style={{ fontSize: 24, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 3 }}>R$ {ICc.fmt(p.lastCost)}</div>
          </div>
          {spark.length > 1 && <div style={{ marginBottom: 16 }}>
            <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 8 }}>Tendência de custo</div>
            <Glass pad={16}><div style={{ height: 80 }}><SparkLine data={spark} w={480} h={80} color={spark[spark.length-1] >= spark[0] ? T.redBright : T.green} /></div></Glass>
          </div>}
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 8 }}>Ofertas desta cotação</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {reps.map(r => { const o = offer(p.id, r.id); if (o == null) return null; const pct = ((o - p.lastCost)/p.lastCost)*100; return (
              <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', borderRadius: 12, background: T.panel, border: `1px solid ${T.border}` }}>
                <span style={{ width: 9, height: 9, borderRadius: 99, background: r.color }} />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 13.5 }}>{r.name}</div><div style={{ fontSize: 11, color: T.mute2 }}>{r.lab} · {r.tax === 'com' ? 'c/ imposto' : 's/ imposto'}</div></div>
                <div style={{ textAlign: 'right' }}><div style={{ fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>R$ {ICc.fmt(o)}</div><Delta pct={pct} size={11} /></div>
              </div>
            ); })}
          </div>
          <div style={{ marginTop: 16, fontSize: 12, color: T.mute2, display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="box" size={14} color={T.mute2} /> Sem correspondência na base ERP — exibindo dados da cotação.</div>
        </div>
      </div>
    </div>
  );
}

function MiniKpi({ label, value, suffix, color }) {
  return <Glass pad={16} style={{ flex: '1 1 160px' }}><div style={{ fontSize: 12, color: T.mute }}>{label}</div><div style={{ fontSize: 23, fontWeight: 800, color: color || T.text, fontFamily: 'var(--display)', marginTop: 4 }}>{value}{suffix && <span style={{ fontSize: 14, color: T.mute, fontWeight: 600 }}> {suffix}</span>}</div></Glass>;
}
function ToolBtn({ icon, children, onClick }) {
  return <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '9px 14px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, fontSize: 13, border: `1px solid ${T.border}`, color: T.mute, background: T.panel }}><Icon name={icon} size={15} color={T.mute} /> {children}</button>;
}
function Seg({ value, onChange, opts }) {
  return <div style={{ display: 'flex', gap: 2, padding: 3, borderRadius: 10, background: T.panel, border: `1px solid ${T.border}` }}>
    {opts.map(([v, l]) => { const on = value === v; return <button key={v} onClick={() => onChange(v)} style={{ padding: '6px 11px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 500, color: on ? '#fff' : T.mute, background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : 'transparent' }}>{l}</button>; })}
  </div>;
}
function FChip({ on, onClick, icon, children, tone }) {
  const c = tone === 'green' ? T.green : T.redBright;
  const bg = tone === 'green' ? T.greenBg : T.redBg;
  return <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 13px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, border: `1px solid ${on ? c : T.border}`, color: on ? c : T.mute, background: on ? bg : 'transparent' }}><Icon name={icon} size={14} color={on ? c : T.mute} /> {children}</button>;
}
function Check({ on, onClick }) {
  return <button onClick={onClick} style={{ width: 20, height: 20, borderRadius: 6, border: `1.5px solid ${on ? T.red : T.borderHi}`, background: on ? T.red : 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>{on && <Icon name="check" size={13} color="#fff" strokeWidth={3} />}</button>;
}
function OrderDone({ count, total, saving, onClose }) {
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200, padding: 30 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 440, borderRadius: 22, background: T.surface, border: `1px solid ${T.borderHi}`, padding: 34, textAlign: 'center' }}>
        <div style={{ width: 66, height: 66, borderRadius: 999, background: T.greenBg, border: `1px solid rgba(0,230,140,0.4)`, display:'flex',alignItems:'center',justifyContent:'center', margin: '0 auto 18px' }}><Icon name="check" size={34} color={T.green} strokeWidth={2.4} /></div>
        <div style={{ fontWeight: 800, fontSize: 21, fontFamily: 'var(--display)' }}>Pedido fechado!</div>
        <div style={{ color: T.mute, fontSize: 14, marginTop: 8 }}>{count} itens enviados aos representantes vencedores nos melhores preços. Avisos disparados no sistema.</div>
        <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
          <div style={{ flex: 1, padding: 14, borderRadius: 13, background: T.panel, border: `1px solid ${T.border}` }}><div style={{ fontSize: 11.5, color: T.mute2 }}>Total</div><div style={{ fontWeight: 800, fontSize: 18, marginTop: 2 }}>R$ {ICc.fmt(total)}</div></div>
          <div style={{ flex: 1, padding: 14, borderRadius: 13, background: T.greenBg, border: `1px solid rgba(0,230,140,0.3)` }}><div style={{ fontSize: 11.5, color: T.green }}>Economia</div><div style={{ fontWeight: 800, fontSize: 18, marginTop: 2, color: T.green }}>R$ {ICc.fmt(saving)}</div></div>
        </div>
        <button onClick={onClose} style={{ marginTop: 22, width: '100%', padding: '13px', borderRadius: 12, border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` }}>Concluir</button>
      </div>
    </div>
  );
}

// ═══ BASE DE PRODUTOS ════════════════════════════════════════════════════
function Base() {
  const [q, setQ] = useState('');
  const [cat, setCat] = useState('all');
  const [sortBy, setSortBy] = useState('name');
  const norm = (s) => s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
  const nq = norm(q);
  const semHits = nq ? (ICc.SEMANTIC[nq] || Object.keys(ICc.SEMANTIC).filter(k => nq.includes(k)).flatMap(k => ICc.SEMANTIC[k])) : [];
  const matches = (p) => {
    if (!q) return true;
    if (p.name.toLowerCase().includes(q.toLowerCase()) || p.brand.toLowerCase().includes(q.toLowerCase()) || p.ean.includes(q)) return true;
    return semHits.some(kw => p.name.toLowerCase().includes(kw.toLowerCase()));
  };
  let list = ICc.PRODUCTS.filter(p => (cat === 'all' || p.cat === cat) && matches(p));
  list = [...list].sort((a, b) => sortBy === 'cost' ? b.lastCost - a.lastCost : sortBy === 'costAsc' ? a.lastCost - b.lastCost : a.name.localeCompare(b.name));
  return (
    <div>
      <Topbar3 title="Base de Produtos" sub="25.000 produtos sincronizados do ERP HOS · Último custo de referência"
        action={<ToolBtn icon="box">Sincronizar HOS</ToolBtn>} />
      <Glass pad={14} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: '1 1 300px', minWidth: 220 }}>
            <Icon name="search" size={16} color={T.mute} style={{ position: 'absolute', left: 12, top: 11 }} />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar produto, marca ou EAN..."
              style={{ width: '100%', boxSizing: 'border-box', padding: '9px 12px 9px 38px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13.5, outline: 'none' }} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 12, color: T.mute2 }}>Ordenar</span>
            <Seg value={sortBy} onChange={setSortBy} opts={[['name','Nome'],['cost','Maior custo'],['costAsc','Menor custo']]} />
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 12 }}>
          <Chip on={cat === 'all'} onClick={() => setCat('all')}>Todas</Chip>
          {ICc.CATEGORIES.map(c => <Chip key={c.id} on={cat === c.id} onClick={() => setCat(c.id)}>{c.name}</Chip>)}
        </div>
      </Glass>
      <Glass pad={0} style={{ overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
          <thead><tr style={{ background: T.panel }}>
            <th style={thS('left')}>Produto</th><th style={thS('left', 140)}>Categoria</th><th style={thS('left', 110)}>EAN</th><th style={thS('left', 70)}>Un.</th><th style={thS('right', 120)}>Último Custo</th>
          </tr></thead>
          <tbody>
            {list.map(p => { const c = cat3(p.cat); return (
              <tr key={p.id} style={{ borderTop: `1px solid ${T.border}` }}>
                <td style={tdS('left')}><div style={{ fontWeight: 600 }}>{p.name}</div><div style={{ fontSize: 11.5, color: T.mute2 }}>{p.brand}</div></td>
                <td style={tdS('left')}><Pill tone="mute"><span style={{ width:7,height:7,borderRadius:99,background:T.redBright }}/>{c.name}</Pill></td>
                <td style={{ ...tdS('left'), color: T.mute, fontVariantNumeric:'tabular-nums' }}>{p.ean}</td>
                <td style={{ ...tdS('left'), color: T.mute }}>{p.unit}</td>
                <td style={{ ...tdS('right'), fontWeight: 700, fontVariantNumeric:'tabular-nums' }}>R$ {ICc.fmt(p.lastCost)}</td>
              </tr>
            ); })}
          </tbody>
        </table>
      </Glass>
      <div style={{ fontSize: 12.5, color: T.mute2, marginTop: 12, textAlign: 'center' }}>
        {semHits.length > 0 && <span style={{ color: T.green, fontWeight: 600 }}><Icon name="sparkle" size={12} color={T.green} style={{ verticalAlign: '-2px' }} /> Busca semântica ativa — interpretando "{q}" · </span>}
        Exibindo {list.length} de 25.000 produtos · amostra do MVP
      </div>
    </div>
  );
}
function Chip({ children, on, onClick }) {
  return <button onClick={onClick} style={{ padding: '8px 13px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, border: `1px solid ${on ? T.red : T.border}`, color: on ? T.redBright : T.mute, background: on ? T.redBg : 'transparent', whiteSpace:'nowrap' }}>{children}</button>;
}

window.BuyerParts3 = { Grid, Base };
