// ── InovaPED — Base de Produtos REAL (ERP HOS) + Ficha com histórico ────
// Dados reais em window.ERP. Registro: [c,ean,nome,est,curva,fam,fab,custo,mk,pa,pv,uv,uc,cls,cat,hist[]]
// hist item: [data,custoUnit,qtd,fornIdx] · suppliers[idx]=[nome,cnpj]
const Topbar9 = window.BuyerParts1.Topbar;
const ICp = window.IC;

const PIDX = { c:0, ean:1, n:2, est:3, cv:4, fam:5, fab:6, cu:7, mk:8, pa:9, pv:10, uv:11, uc:12, cls:13, cat:14, h:15 };
const fmtBRL = (n) => (n==null||isNaN(n)) ? '—' : n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const fmtDate = (s) => { if(!s) return '—'; const p = s.split('-'); return p.length===3 ? `${p[2]}/${p[1]}/${p[0].slice(2)}` : s; };
const monthsAgo = (s) => { if(!s) return null; const d = new Date(s); const now = new Date('2026-06-01'); return Math.round((now-d)/(1000*60*60*24*30)); };

const ERP_CATS = [
  { id: 'all',  name: 'Tudo' },
  { id: 'med',  name: 'Medicamentos' },
  { id: 'gen',  name: 'Genéricos' },
  { id: 'sup',  name: 'Suplementos' },
  { id: 'derm', name: 'Dermocosméticos' },
  { id: 'hig',  name: 'Higiene' },
  { id: 'baby', name: 'Mamãe & Bebê' },
  { id: 'out',  name: 'Outros' },
];

function curveColor(cv) { return cv === 'A' ? '#00E68C' : cv === 'B' ? '#FFC83D' : cv === 'C' ? '#FF9E80' : T.mute; }

function BaseERP() {
  const ERP = window.ERP || { p: [], s: [] };
  const [q, setQ] = useState('');
  const [cat, setCat] = useState('all');
  const [sort, setSort] = useState('rel');
  const [stock, setStock] = useState('all');
  const [sel, setSel] = useState(null);
  const [limit, setLimit] = useState(50);

  const norm = (s) => (s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  const nq = norm(q);

  const filtered = useMemo(() => {
    let list = ERP.p;
    if (cat !== 'all') list = list.filter(p => p[PIDX.cat] === cat);
    if (stock === 'in') list = list.filter(p => p[PIDX.est] > 0);
    else if (stock === 'out') list = list.filter(p => p[PIDX.est] <= 0);
    if (nq) {
      const terms = nq.split(/\s+/).filter(Boolean);
      list = list.filter(p => { const hay = norm(p[PIDX.n] + ' ' + p[PIDX.fab] + ' ' + p[PIDX.pa] + ' ' + p[PIDX.ean] + ' ' + p[PIDX.c]); return terms.every(t => hay.includes(t)); });
    }
    const arr = [...list];
    if (sort === 'costDesc') arr.sort((a,b) => b[PIDX.cu] - a[PIDX.cu]);
    else if (sort === 'costAsc') arr.sort((a,b) => a[PIDX.cu] - b[PIDX.cu]);
    else if (sort === 'stock') arr.sort((a,b) => b[PIDX.est] - a[PIDX.est]);
    else if (sort === 'name') arr.sort((a,b) => a[PIDX.n].localeCompare(b[PIDX.n]));
    return arr;
  }, [nq, cat, sort, stock]);

  useEffect(() => { setLimit(50); }, [nq, cat, sort, stock]);

  const stats = useMemo(() => {
    let inStock = 0, cost = 0;
    for (const p of ERP.p) { if (p[PIDX.est] > 0) { inStock++; cost += p[PIDX.cu]*p[PIDX.est]; } }
    return { inStock, outStock: ERP.p.length - inStock, cost };
  }, []);

  return (
    <div>
      <Topbar9 title="Base de Produtos" sub={`${ERP.p.length.toLocaleString('pt-BR')} produtos ativos · custo, histórico e fornecedores · ERP HOS`}
        action={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: T.mute2 }}><Icon name="shield" size={13} color={T.mute2} /> Visível só ao comprador</span>
          <ToolBtn icon="box">Sincronizar HOS</ToolBtn>
        </div>} />

      {/* KPIs */}
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))' }}>
        <Glass pad={16}><div style={{ fontSize: 12, color: T.mute }}>Catálogo ativo</div><div style={{ fontSize: 23, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{ERP.p.length.toLocaleString('pt-BR')}</div></Glass>
        <Glass pad={16} style={{ flex: 1, minWidth: 150 }}><div style={{ display:'flex',alignItems:'center',gap:6, fontSize: 12, color: T.mute }}><span style={{ width:8,height:8,borderRadius:99,background:T.green }} />Com estoque</div><div style={{ fontSize: 23, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}>{stats.inStock.toLocaleString('pt-BR')}</div></Glass>
        <Glass pad={16} style={{ flex: 1, minWidth: 150 }}><div style={{ display:'flex',alignItems:'center',gap:6, fontSize: 12, color: T.mute }}><span style={{ width:8,height:8,borderRadius:99,background:T.mute2 }} />Sem estoque</div><div style={{ fontSize: 23, fontWeight: 800, color: T.mute, fontFamily: 'var(--display)', marginTop: 4 }}>{stats.outStock.toLocaleString('pt-BR')}</div></Glass>
        <Glass pad={16} style={{ flex: 1, minWidth: 150 }}><div style={{ fontSize: 12, color: T.mute }}>Capital em estoque</div><div style={{ fontSize: 23, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}>R$ {(stats.cost/1000).toLocaleString('pt-BR',{maximumFractionDigits:0})}k</div></Glass>
      </div>

      {/* busca + filtros */}
      <Glass pad={14} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: '1 1 320px', minWidth: 240 }}>
            <Icon name="search" size={17} color={T.mute} style={{ position: 'absolute', left: 13, top: 12 }} />
            <input value={q} onChange={e => setQ(e.target.value)} autoFocus placeholder="Buscar produto, fabricante, princípio ativo, EAN ou código…"
              style={{ width: '100%', boxSizing: 'border-box', padding: '11px 14px 11px 40px', borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' }} />
            {q && <button onClick={() => setQ('')} style={{ position: 'absolute', right: 10, top: 9, width: 26, height: 26, borderRadius: 7, border: 'none', background: T.panelHi, color: T.mute, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="x" size={14} color={T.mute} /></button>}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 12, color: T.mute2 }}>Ordenar</span>
            <Seg value={sort} onChange={setSort} opts={[['rel','Relevância'],['costDesc','Maior custo'],['costAsc','Menor custo'],['stock','Estoque']]} />
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 12, alignItems: 'center' }}>
          {ERP_CATS.map(c => <Chip key={c.id} on={cat === c.id} onClick={() => setCat(c.id)}>{c.name}</Chip>)}
          <span style={{ width: 1, height: 22, background: T.border, margin: '0 4px' }} />
          <Chip on={stock === 'all'} onClick={() => setStock('all')}>Estoque: todos</Chip>
          <Chip on={stock === 'in'} onClick={() => setStock('in')}>Com estoque</Chip>
          <Chip on={stock === 'out'} onClick={() => setStock('out')}>Sem estoque</Chip>
        </div>
      </Glass>

      {/* resultados */}
      <Glass pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead><tr style={{ background: T.panel }}>
              <th style={thE('left', 320)}>Produto</th>
              <th style={thE('center', 56)}>Curva</th>
              <th style={thE('right', 80)}>Estoque</th>
              <th style={thE('right', 110)}>Custo atual</th>
              <th style={thE('right', 110)}>Preço venda</th>
              <th style={thE('right', 78)}>Markup</th>
              <th style={thE('left', 130)}>Últ. compra</th>
              <th style={thE('center', 90)}>Fornec.</th>
              <th style={thE('right', 40)}></th>
            </tr></thead>
            <tbody>
              {filtered.slice(0, limit).map(p => {
                const nForn = new Set(p[PIDX.h].map(x => x[3])).size;
                const lastH = p[PIDX.h][0];
                return (
                  <tr key={p[PIDX.c]} onClick={() => setSel(p)} className="erp-row" style={{ borderTop: `1px solid ${T.border}`, cursor: 'pointer' }}>
                    <td style={tdE('left')}>
                      <div style={{ fontWeight: 600 }}>{p[PIDX.n]}</div>
                      <div style={{ fontSize: 11, color: T.mute2, marginTop: 2 }}>{p[PIDX.fab]}{p[PIDX.pa] ? ' · ' + p[PIDX.pa] : ''} · cód {p[PIDX.c]}</div>
                    </td>
                    <td style={tdE('center')}>{p[PIDX.cv] ? <span style={{ display: 'inline-flex', width: 22, height: 22, borderRadius: 6, alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, color: curveColor(p[PIDX.cv]), background: curveColor(p[PIDX.cv]) + '22' }}>{p[PIDX.cv]}</span> : <span style={{ color: T.mute2 }}>—</span>}</td>
                    <td style={{ ...tdE('right'), fontVariantNumeric: 'tabular-nums', color: p[PIDX.est] > 0 ? T.text : T.mute2, fontWeight: p[PIDX.est] > 0 ? 600 : 400 }}>{p[PIDX.est]}</td>
                    <td style={{ ...tdE('right'), fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>R$ {fmtBRL(p[PIDX.cu])}</td>
                    <td style={{ ...tdE('right'), fontVariantNumeric: 'tabular-nums', color: T.mute }}>R$ {fmtBRL(p[PIDX.pv])}</td>
                    <td style={{ ...tdE('right'), fontVariantNumeric: 'tabular-nums', fontWeight: 600, color: p[PIDX.mk] >= 40 ? T.green : T.text }}>{p[PIDX.mk] ? p[PIDX.mk].toFixed(0) + '%' : '—'}</td>
                    <td style={{ ...tdE('left'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>{fmtDate(lastH[0])}<span style={{ fontSize: 10.5, color: T.mute2 }}> · R$ {fmtBRL(lastH[1])}</span></td>
                    <td style={tdE('center')}>{nForn >= 2 ? <Pill tone="green" style={{ fontSize: 10 }}>{nForn} fornec.</Pill> : <span style={{ fontSize: 11.5, color: T.mute2 }}>1</span>}</td>
                    <td style={tdE('center')}><Icon name="chevron" size={15} color={T.mute2} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {filtered.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: T.mute2 }}><Icon name="search" size={28} color={T.mute2} /><div style={{ marginTop: 8 }}>Nenhum produto encontrado para "{q}"</div></div>}
      </Glass>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, marginTop: 14 }}>
        <span style={{ fontSize: 12.5, color: T.mute2 }}>Exibindo {Math.min(limit, filtered.length).toLocaleString('pt-BR')} de {filtered.length.toLocaleString('pt-BR')}</span>
        {limit < filtered.length && <button onClick={() => setLimit(l => l + 100)} style={{ padding: '8px 18px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>Carregar mais</button>}
      </div>

      {sel && <ProductDetail p={sel} onClose={() => setSel(null)} />}
    </div>
  );
}
const thE = (a, w) => ({ textAlign: a, padding: '12px 14px', fontSize: 11, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, whiteSpace: 'nowrap', minWidth: w, position: 'sticky', top: 0, background: T.surface });
const tdE = (a) => ({ textAlign: a, padding: '11px 14px', verticalAlign: 'middle' });

// ═══ FICHA DO PRODUTO — histórico de custos + fornecedores ═══════════════
function ProductDetail({ p, onClose }) {
  const ERP = window.ERP;
  const hist = p[PIDX.h];
  const sup = (i) => ERP.s[i] || ['—', ''];

  // comparativo por fornecedor
  const byForn = {};
  hist.forEach(h => { const id = h[3]; (byForn[id] = byForn[id] || []).push(h); });
  const fornStats = Object.entries(byForn).map(([id, hs]) => {
    const prices = hs.map(h => h[1]).filter(x => x > 0);
    const last = hs[0];
    return { id: +id, name: sup(+id)[0], cnpj: sup(+id)[1], count: hs.length, last: last[1], lastDate: last[0], min: Math.min(...prices), avg: prices.reduce((a,b)=>a+b,0)/prices.length };
  }).sort((a,b) => a.last - b.last);
  const cheapest = fornStats.length ? fornStats[0] : null;

  // série de custo (mais antigo → recente)
  const series = [...hist].reverse().map(h => h[1]).filter(x => x > 0);
  const minS = Math.min(...series), maxS = Math.max(...series);
  const lastCost = hist[0][1];
  const prevCost = hist.length > 1 ? hist[1][1] : null;
  const deltaPct = prevCost ? ((lastCost - prevCost) / prevCost) * 100 : null;

  const kpi = (label, value, sub, color) => <div style={{ flex: 1, minWidth: 110 }}><div style={{ fontSize: 11, color: T.mute2 }}>{label}</div><div style={{ fontSize: 19, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 3, color: color || T.text }}>{value}</div>{sub && <div style={{ fontSize: 11, color: T.mute2, marginTop: 1 }}>{sub}</div>}</div>;

  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(680px, 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' }}>
        {/* header */}
        <div style={{ position: 'sticky', top: 0, zIndex: 5, padding: '20px 24px', background: T.surface, borderBottom: `1px solid ${T.border}` }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                {p[PIDX.cv] && <span style={{ display: 'inline-flex', width: 22, height: 22, borderRadius: 6, alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, color: curveColor(p[PIDX.cv]), background: curveColor(p[PIDX.cv]) + '22' }}>{p[PIDX.cv]}</span>}
                <Pill tone="mute" style={{ fontSize: 10.5 }}>{p[PIDX.cls]}</Pill>
              </div>
              <h2 style={{ margin: 0, fontSize: 21, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.4, lineHeight: 1.15 }}>{p[PIDX.n]}</h2>
              <div style={{ fontSize: 12.5, color: T.mute, marginTop: 5 }}>{p[PIDX.fab]}{p[PIDX.pa] ? ' · ' + p[PIDX.pa] : ''}</div>
              <div style={{ fontSize: 11.5, color: T.mute2, marginTop: 3, fontVariantNumeric: 'tabular-nums' }}>EAN {p[PIDX.ean]} · cód {p[PIDX.c]}{p[PIDX.fam] ? ' · ' + p[PIDX.fam] : ''}</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', flexShrink: 0 }}><Icon name="x" size={18} color={T.mute} /></button>
          </div>
        </div>

        <div style={{ padding: 24 }}>
          {/* KPIs */}
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', padding: 16, borderRadius: 16, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 16 }}>
            {kpi('Custo atual', 'R$ ' + fmtBRL(p[PIDX.cu]))}
            {kpi('Preço de venda', 'R$ ' + fmtBRL(p[PIDX.pv]))}
            {kpi('Markup', (p[PIDX.mk]||0).toFixed(0) + '%', null, p[PIDX.mk] >= 40 ? T.green : T.text)}
            {kpi('Estoque', String(p[PIDX.est]), p[PIDX.uv] ? 'últ. venda ' + fmtDate(p[PIDX.uv]) : null, p[PIDX.est] > 0 ? T.text : T.redBright)}
          </div>

          {/* tendência de custo */}
          <div style={{ marginBottom: 16 }}>
            <SectionTitle icon="chart" title="Evolução do custo de compra" right={deltaPct != null ? <Delta pct={deltaPct} /> : null} />
            <Glass pad={16}>
              <CostSpark series={series} />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, fontSize: 11.5, color: T.mute2 }}>
                <span>Menor: <b style={{ color: T.green }}>R$ {fmtBRL(minS)}</b></span>
                <span>Médio: <b style={{ color: T.text }}>R$ {fmtBRL(series.reduce((a,b)=>a+b,0)/series.length)}</b></span>
                <span>Maior: <b style={{ color: T.redBright }}>R$ {fmtBRL(maxS)}</b></span>
                <span>{hist.length} compras</span>
              </div>
            </Glass>
          </div>

          {/* comparativo de fornecedores */}
          <div style={{ marginBottom: 16 }}>
            <SectionTitle icon="box" title="De quem você comprou" right={<span style={{ fontSize: 11.5, color: T.mute2 }}>{fornStats.length} fornecedor(es)</span>} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {fornStats.map((f, i) => {
                const best = i === 0 && fornStats.length > 1;
                return (
                  <div key={f.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 13, background: best ? T.greenBg : T.panel, border: `1px solid ${best ? 'rgba(0,230,140,0.35)' : T.border}` }}>
                    <div style={{ width: 34, height: 34, borderRadius: 9, background: best ? 'rgba(0,230,140,0.2)' : T.panelHi, display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name="box" size={17} color={best ? T.green : T.mute} /></div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 700, fontSize: 13.5, display: 'flex', alignItems: 'center', gap: 7 }}>{f.name}{best && <Pill tone="green" style={{ fontSize: 9.5 }}>melhor preço</Pill>}</div>
                      <div style={{ fontSize: 11, color: T.mute2, fontVariantNumeric: 'tabular-nums' }}>CNPJ {f.cnpj || '—'} · {f.count} compra(s) · última {fmtDate(f.lastDate)}</div>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0 }}>
                      <div style={{ fontWeight: 800, fontSize: 15, color: best ? T.green : T.text, fontVariantNumeric: 'tabular-nums' }}>R$ {fmtBRL(f.last)}</div>
                      <div style={{ fontSize: 10.5, color: T.mute2 }}>mín R$ {fmtBRL(f.min)}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* histórico completo */}
          <div>
            <SectionTitle icon="receipt" title="Histórico de compras" />
            <Glass pad={0} style={{ overflow: 'hidden' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                <thead><tr style={{ background: T.panel }}>
                  <th style={thE('left', 90)}>Data</th><th style={thE('left', 170)}>Fornecedor</th><th style={thE('right', 60)}>Qtd</th><th style={thE('right', 90)}>Custo un.</th><th style={thE('right', 60)}>Var.</th>
                </tr></thead>
                <tbody>
                  {hist.map((h, i) => {
                    const prev = hist[i+1];
                    const vp = prev && prev[1] > 0 ? ((h[1] - prev[1]) / prev[1]) * 100 : null;
                    return (
                      <tr key={i} style={{ borderTop: `1px solid ${T.border}` }}>
                        <td style={{ ...tdE('left'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>{fmtDate(h[0])}</td>
                        <td style={tdE('left')}><div style={{ fontWeight: 600 }}>{sup(h[3])[0]}</div></td>
                        <td style={{ ...tdE('right'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>{h[2]}</td>
                        <td style={{ ...tdE('right'), fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>R$ {fmtBRL(h[1])}</td>
                        <td style={tdE('right')}>{vp != null ? <Delta pct={vp} size={10.5} /> : <span style={{ color: T.mute2 }}>—</span>}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </Glass>
          </div>

          <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
            <button style={{ flex: 1, padding: '13px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="plus" size={17} color="#fff" strokeWidth={2.4} /> Incluir em cotação</button>
            <button style={{ padding: '13px 18px', borderRadius: 12, border: `1px solid ${T.border}`, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 14, color: T.text, background: T.panel }}>Etiqueta de gôndola</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function SectionTitle({ icon, title, right }) {
  return <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}><Icon name={icon} size={16} color={T.redBright} /><span style={{ fontWeight: 700, fontSize: 14.5 }}>{title}</span><span style={{ marginLeft: 'auto' }}>{right}</span></div>;
}

function CostSpark({ series }) {
  if (!series.length) return null;
  const w = 600, h = 90, pad = 8;
  const min = Math.min(...series), max = Math.max(...series), rng = max - min || 1;
  const X = i => pad + (i / Math.max(1, series.length - 1)) * (w - pad*2);
  const Y = v => (h - pad) - ((v - min) / rng) * (h - pad*2);
  const pts = series.map((v, i) => [X(i), Y(v)]);
  const line = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = line + ` L ${X(series.length-1).toFixed(1)} ${h-pad} L ${X(0).toFixed(1)} ${h-pad} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 90, display: 'block' }} preserveAspectRatio="none">
      <defs><linearGradient id="csg" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={T.redBright} stopOpacity="0.3" /><stop offset="100%" stopColor={T.redBright} stopOpacity="0" /></linearGradient></defs>
      <path d={area} fill="url(#csg)" />
      <path d={line} fill="none" stroke={T.redBright} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="2.5" fill={i === pts.length-1 ? T.redBright : T.surface} stroke={T.redBright} strokeWidth="1.5" vectorEffect="non-scaling-stroke" />)}
    </svg>
  );
}

window.BuyerERP = { BaseERP };

// localizador: acha o melhor produto real do ERP por nome (p/ abrir histórico da grade)
window.findERPProduct = function(name) {
  const ERP = window.ERP; if (!ERP) return null;
  const norm = (s) => (s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'');
  const terms = norm(name).split(/\s+/).filter(t => t.length >= 3);
  let best = null, bestScore = 0;
  for (const p of ERP.p) {
    const hay = norm(p[2] + ' ' + p[6]);
    let score = 0;
    for (const t of terms) if (hay.includes(t)) score += t.length;
    if (score > bestScore) { bestScore = score; best = p; }
  }
  return bestScore >= 4 ? best : null;
};
window.ProductDetail = ProductDetail;
