// ── Inova Cotação — SIMILARIDADE POR PRODUTO ────────────────────────────
// Lista os 24.830 produtos reais (window.ERP). Clicando, abre a ficha do
// produto (movimento + preços) e os SIMILARES pelo princípio ativo real
// (genéricos × marca) com economia comparada. Usa BuyerParts1.Topbar.
const TopbarS9 = window.BuyerParts1.Topbar;

// índices do registro do ERP: [c,ean,n,est,cv,fam,fab,cu,mk,pa,pv,uv,uc,cls,cat,h,sim]
const SPX = { 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, sim:16 };

const SIM_CATC = { med:'#FF3B54', sup:'#FF6B57', gen:'#FFA56B', derm:'#C77DFF', hig:'#4EA8DE', baby:'#FF4D6D', out:'#8A8A92' };
const SIM_CATN = { med:'Medicamentos', sup:'Suplementos', gen:'Genéricos', derm:'Dermocosméticos', hig:'Higiene', baby:'Mamãe & Bebê', out:'Outros' };
const SIM_CATS = [['all','Tudo'],['med','Medicamentos'],['gen','Genéricos'],['sup','Suplementos'],['derm','Dermocosméticos'],['hig','Higiene'],['baby','Mamãe & Bebê'],['out','Outros']];

function simBRL(n) { return (n==null||isNaN(n)) ? '—' : n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
function simDate(s) { if(!s) return '—'; const p = String(s).split('-'); return p.length===3 ? `${p[2]}/${p[1]}/${p[0].slice(2)}` : s; }
function simA(hex, a) { const h=(hex||'#888').replace('#',''); const f=h.length===3?h.split('').map(c=>c+c).join(''):h; const n=parseInt(f,16); return `rgba(${(n>>16)&255},${(n>>8)&255},${n&255},${a})`; }
function simCurve(cv) { const c=(cv||'').charAt(0); return c==='1'||cv==='A'?'#00E68C': c==='2'||cv==='B'?'#FFC83D': c==='3'||cv==='C'?'#FF9E80': T.mute2; }

// princípio ativo "real" do campo PA (descarta vazios / não informado)
function paOf(p) {
  const v = (p[SPX.pa]||'').toString().trim().toUpperCase();
  if (!v || v==='.' || v==='0' || v.startsWith('NAO INFORM') || v.startsWith('NÃO INFORM') || v.startsWith('NAO IDENT') || v.startsWith('NÃO IDENT')) return '';
  return v;
}
function firstTok(name) { const m=(name||'').toUpperCase().match(/[A-ZÀ-Ú]{4,}/); return m?m[0]:null; }

// ════════════════════════════════════════════════════════════════════════
// MOTOR DE PRINCÍPIO ATIVO CANÔNICO
// Agrupa por equivalência terapêutica REAL (mesmo princípio ativo).
// Combinações (ex.: Losartana + Hidroclorotiazida) formam grupo PRÓPRIO,
// nunca se misturam com o mono. Fontes: campo PA, nome do genérico e um
// dicionário curado de marcas → ativo. Validado contra os dados reais.
// ════════════════════════════════════════════════════════════════════════
const SIM_SA = s => (s||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toUpperCase();
// formas farmacêuticas / sufixos de sal — removidos pra achar o ativo puro
const SIM_SALT = new Set(['POTASSICA','POTASSICO','SODICA','SODICO','CALCICA','CALCICO','MAGNESICO','MONOIDRATADA','MONOHIDRATADA','DIIDRATADO','DICLORIDRATO','CLORIDRATO','BROMIDRATO','BROMETO','MALEATO','BESILATO','MESILATO','SULFATO','FOSFATO','DIFOSFATO','NITRATO','ACETATO','TARTARATO','FUMARATO','SUCCINATO','VALERATO','DIPROPIONATO','PROPIONATO','ESTEARATO','PALMITATO','PAMOATO','CIPIONATO','ENANTATO','DECANOATO','TROMETAMOL','AXETIL','ETEXILATO','MEDOXOMILA','CILEXETILA','DInicotinato','DE','DA','DO','D']);
const SIM_FORM = new Set(['COMPRIMIDO','COMPRIMIDOS','COMP','CPDS','CPD','CPR','CP','COMPR','CDR','CDRS','CAPS','CAPSULA','CAPSULAS','CAP','DRAGEAS','DRAGEA','ML','MG','MCG','UI','G','KG','L','GTS','GOTAS','SUSP','SUSPENSAO','SOL','SOLUCAO','XPE','XAROPE','CREME','POMADA','GEL','LOCAO','FR','FRASCO','AMP','AMPOLA','SACHE','SACHES','ENV','ENVELOPE','BISNAGA','SPRAY','JATO','JATOS','REFIL','EFERV','EFERVESCENTE','REV','REVESTIDO','REVEST','LIB','LENTA','PROLONG','PROLONGADA','ER','XR','SL','C','PG','LV','UN','POTE','BLISTER','ORAL','INJ','INJETAVEL','SUS','VO','ADULTO','INFANTIL','PED','PEDIATRICO','SHOT','STICK','TABS','FLOWPACK']);
const SIM_COMBO_ABBR = { HCTZ:'HIDROCLOROTIAZIDA', HTCZ:'HIDROCLOROTIAZIDA', HCT:'HIDROCLOROTIAZIDA' };
// dicionário curado: marca (sem PA cadastrado) → princípio ativo. Combos com " + ".
const SIM_BRAND = {
  'CORUS':'LOSARTANA', 'CORUS H':'LOSARTANA + HIDROCLOROTIAZIDA',
  'MICARDIS':'TELMISARTANA', 'MICARDIS HCT':'TELMISARTANA + HIDROCLOROTIAZIDA', 'MICARDIS ANLO':'TELMISARTANA + ANLODIPINO',
  'NAPRIX':'RAMIPRIL', 'NAPRIX D':'RAMIPRIL + HIDROCLOROTIAZIDA', 'NAPRIX A':'RAMIPRIL + ANLODIPINO',
  'PURAN':'LEVOTIROXINA', 'PURAN T':'LEVOTIROXINA', 'SYNTHROID':'LEVOTIROXINA', 'EUTHYROX':'LEVOTIROXINA', 'LEVOID':'LEVOTIROXINA',
  'ASPIRINA':'ACIDO ACETILSALICILICO', 'AAS':'ACIDO ACETILSALICILICO',
  'MONTELAIR':'MONTELUCASTE', 'SINGULAIR':'MONTELUCASTE',
  'GLIFAGE':'METFORMINA', 'GLUCOFORMIN':'METFORMINA',
  'ANLO':'ANLODIPINO', 'PRESSAT':'ANLODIPINO',
  'SELOZOK':'METOPROLOL', 'ATENOL':'ATENOLOL',
  'PROFENID':'CETOPROFENO', 'VOLTAREN':'DICLOFENACO', 'CATAFLAM':'DICLOFENACO',
  'TYLENOL':'PARACETAMOL', 'NOVALGINA':'DIPIRONA', 'DORICO':'DIPIRONA',
  'RIVOTRIL':'CLONAZEPAM', 'FRONTAL':'ALPRAZOLAM', 'LEXAPRO':'ESCITALOPRAM',
  'PANTOZOL':'PANTOPRAZOL', 'NEXIUM':'ESOMEPRAZOL', 'LOSEC':'OMEPRAZOL',
  'CRESTOR':'ROSUVASTATINA', 'VYTORIN':'EZETIMIBA + SINVASTATINA', 'LIPITOR':'ATORVASTATINA',
};
function simClActive(s) {
  let x = SIM_SA(s).replace(/[()]/g,' ');
  x = x.replace(/\b(HCTZ|HTCZ|HCT)\b/g, m => ' ' + SIM_COMBO_ABBR[m] + ' ');
  const parts = x.split('+');
  const cores = parts.map(part => {
    const toks = part.split(/[^A-Z0-9\/.,%-]+/).filter(Boolean);
    const out = [];
    for (const tk of toks) { if (/\d/.test(tk)) continue; if (SIM_SALT.has(tk)) continue; if (SIM_FORM.has(tk)) continue; out.push(tk); }
    return out.join(' ').trim();
  }).map(c => c.trim()).filter(Boolean);
  return [...new Set(cores)].sort().join(' + ');
}
function simBrandLookup(core) {
  const toks = core.split(' ');
  for (let n = Math.min(2, toks.length); n >= 1; n--) { const k = toks.slice(0, n).join(' '); if (SIM_BRAND[k]) return SIM_BRAND[k]; }
  return null;
}
// princípio ativo canônico do produto (string) ou '' se indeterminado
function canonActive(p) {
  const name = p[SPX.n] || '', pa = p[SPX.pa] || '';
  const nameCombo = /\+|\b(HCTZ|HTCZ|HCT)\b/i.test(name);
  const nameCore = simClActive(name);
  const bk = simBrandLookup(nameCore);
  if (bk) return simClActive(bk);
  if (paOf(p) && !nameCombo) { const c = simClActive(pa); if (c) return c; }
  return nameCore;
}
// rótulo amigável (Title Case) do ativo
function activeLabel(k) {
  if (!k) return '';
  const dosePos = k.indexOf(' · ');
  const base = dosePos >= 0 ? k.slice(0, dosePos) : k;
  const dose = dosePos >= 0 ? k.slice(dosePos) : '';
  return base.toLowerCase().split(' ').map(w => w === '+' ? '+' : (w.charAt(0).toUpperCase() + w.slice(1))).join(' ') + dose;
}

// ════════════════════════════════════════════════════════════════════════
// CHAVE DE GRUPO = princípio ativo (col. Similaridade OFICIAL do ERP, com
// fallback ao motor canônico) + DOSAGEM (mg). Assim 50mg ≠ 25mg ≠ 100mg, e
// combinações (50/12.5) ficam isoladas do mono. Respeita o agrupador do HOS.
// ════════════════════════════════════════════════════════════════════════
const SIM_NORM = s => (s||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toUpperCase().replace(/\s*\+\s*/g,'+').replace(/\s+/g,' ').trim();
// dosagem normalizada extraída do nome (em mg quando possível; combos "50/12.5mg")
function doseSig(name) {
  const s = SIM_SA(name);
  const m = s.match(/(\d+(?:[.,]\d+)?(?:\s*\/\s*\d+(?:[.,]\d+)?)?)\s*(MG|MCG|UI|G)\b/);
  if (!m) { const pm = s.match(/(\d+(?:[.,]\d+)?)\s*%/); return pm ? pm[1].replace(',','.') + '%' : ''; }
  let num = m[1].replace(/\s+/g,'').replace(',','.'); const unit = m[2];
  if (num.includes('/')) return num + unit.toLowerCase();
  let mg = parseFloat(num);
  if (unit === 'G') mg *= 1000; else if (unit === 'MCG') mg /= 1000; else if (unit === 'UI') return mg + 'ui';
  return (Math.round(mg * 1000) / 1000) + 'mg';
}
// princípio ativo base (string) — oficial do ERP ou heurístico
function activeOf(p) {
  const off = SIM_NORM(p[SPX.sim]);
  if (off && off !== '.' && off !== '0') return off;
  return SIM_NORM(canonActive(p));
}
// chave de grupo completa (ativo + dose)
function groupKeyOf(p) {
  const a = activeOf(p);
  if (!a) return '';
  const d = doseSig(p[SPX.n]);
  return a + (d ? ' · ' + d : '');
}
// tipo regulatório: 'eti' (ético/referência), 'gen' (genérico), 'sim' (similar)
function medType(p) {
  const cls = SIM_SA(p[SPX.cls] || '');
  const act = activeOf(p);
  const name = SIM_SA(p[SPX.n] || '');
  const isGenName = act && name.startsWith(act.split('+')[0].split(' ')[0]);
  if (cls.includes('GENERICO')) return 'gen';
  if (cls.includes('SIMILAR')) return 'sim';
  if (cls === 'ANTIBIOTICO' || cls.includes('ETICO') || cls === 'MEDICAMENTOS') return isGenName ? 'gen' : 'eti';
  return isGenName ? 'gen' : 'sim';
}
const SIM_TYPE_ORDER = { eti: 0, gen: 1, sim: 2 };
const SIM_TYPE_LABEL = { eti: 'Ético / Referência', gen: 'Genérico', sim: 'Similar' };
const SIM_TYPE_SHORT = { eti: 'Ético', gen: 'Genérico', sim: 'Similar' };
const SIM_TYPE_COLOR = { eti: '#C77DFF', gen: '#00E68C', sim: '#4EA8DE' };

window.SimBits = { SPX, SIM_CATC, SIM_CATN, paOf, canonActive, activeLabel, activeOf, groupKeyOf, doseSig, medType, SIM_TYPE_ORDER, SIM_TYPE_LABEL, SIM_TYPE_SHORT, SIM_TYPE_COLOR, firstTok, simBRL, simDate, simA, simCurve };

// ── mini sparkline do custo (movimento) ─────────────────────────────────
function SimSpark({ hist }) {
  const pts = (hist || []).slice().reverse().map(h => h[1]).filter(v => v > 0);
  if (pts.length < 2) return null;
  const w = 240, h = 56, min = Math.min(...pts), max = Math.max(...pts), rng = max - min || 1;
  const xs = i => (i/(pts.length-1))*w;
  const ys = v => h - 6 - ((v-min)/rng)*(h-14);
  const line = pts.map((v,i) => (i?'L':'M') + xs(i).toFixed(1) + ' ' + ys(v).toFixed(1)).join(' ');
  const up = pts[pts.length-1] >= pts[0];
  const col = up ? T.red : T.green;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" style={{ display: 'block', maxWidth: 280 }}>
      <defs><linearGradient id="simspk" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={simA(col,0.3)} /><stop offset="100%" stopColor={simA(col,0)} /></linearGradient></defs>
      <path d={`${line} L ${w} ${h} L 0 ${h} Z`} fill="url(#simspk)" />
      <path d={line} fill="none" stroke={col} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ strokeDasharray: 600, strokeDashoffset: 600, animation: 'dxDraw 1s ease forwards' }} />
    </svg>
  );
}

// ── linha de KPI da ficha ───────────────────────────────────────────────
function SimMetric({ label, value, sub, color }) {
  return (
    <div style={{ flex: '1 1 130px', padding: '13px 15px', borderRadius: 12, background: T.panel, border: `1px solid ${T.border}` }}>
      <div style={{ fontSize: 11.5, color: T.mute, fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 21, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.4, marginTop: 4, color: color || T.text }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: T.mute2, marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

// ── FICHA DO PRODUTO + SIMILARIDADE ─────────────────────────────────────
function SimDetail({ prod, groupByKey, onBack, onSelect, sups }) {
  const p = prod;
  const key = groupKeyOf(p);
  const cat = p[SPX.cat];
  const hist = (p[SPX.h] || []);

  // similares: mesma chave (princípio ativo oficial + dose). Combos isolados.
  const sims = React.useMemo(() => {
    const g = (key && groupByKey[key]) ? groupByKey[key] : [];
    return g.filter(q => q !== p).slice().sort((a,b) => (a[SPX.cu]||1e9) - (b[SPX.cu]||1e9));
  }, [p, key]);

  // agrupa por tipo regulatório (ético → genérico → similar), menor custo dentro
  const sections = React.useMemo(() => {
    const by = { eti: [], gen: [], sim: [] };
    for (const q of sims) by[medType(q)].push(q);
    const cheapestCost = sims.length ? sims[0][SPX.cu] : null;
    return ['eti','gen','sim'].filter(t => by[t].length).map(t => ({ type: t, items: by[t], cheapestCost }));
  }, [sims]);

  const cheapest = sims.length ? sims[0][SPX.cu] : null;
  const myCost = p[SPX.cu];
  const econVsCheapest = (cheapest != null && myCost) ? ((myCost - cheapest) / myCost * 100) : 0;
  const activeName = activeLabel(key);
  const myType = medType(p);

  return (
    <div>
      <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: T.text, marginBottom: 16 }}>
        <Icon name="chevron" size={15} color={T.text} style={{ transform: 'rotate(180deg)' }} /> Voltar à lista
      </button>

      {/* Cabeçalho do produto */}
      <Glass style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'flex-start', justifyContent: 'space-between' }}>
          <div style={{ minWidth: 0, flex: '1 1 300px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 7, flexWrap: 'wrap' }}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: SIM_CATC[cat] || T.mute }} />
              <Pill tone="mute">{SIM_CATN[cat] || cat}</Pill>
              {key && <span style={{ fontSize: 11.5, fontWeight: 800, padding: '3px 9px', borderRadius: 99, background: simA(SIM_TYPE_COLOR[myType], 0.16), color: SIM_TYPE_COLOR[myType], textTransform: 'uppercase', letterSpacing: 0.4 }}>{SIM_TYPE_SHORT[myType]}</span>}
              <Pill tone="mute"><span style={{ color: simCurve(p[SPX.cv]) }}>● </span>Curva {p[SPX.cv] || '—'}</Pill>
              {p[SPX.est] > 0 ? <Pill tone="green">{p[SPX.est]} em estoque</Pill> : <Pill tone="red">Sem estoque</Pill>}
            </div>
            <h2 style={{ margin: 0, fontSize: 'clamp(20px, 2.4vw, 27px)', fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.5, lineHeight: 1.1 }}>{p[SPX.n]}</h2>
            <div style={{ fontSize: 12.5, color: T.mute, marginTop: 6, fontFamily: 'var(--mono)' }}>
              #{p[SPX.c]} · EAN {p[SPX.ean] || '—'} · {p[SPX.fab] || 'fabricante n/d'}
            </div>
            {key && <div style={{ marginTop: 9, display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 11px', borderRadius: 99, background: simA(T.blue, 0.12), border: `1px solid ${simA(T.blue,0.3)}`, fontSize: 12.5, fontWeight: 600, color: T.blue }}>
              <Icon name="shield" size={13} color={T.blue} /> {activeName}
            </div>}
          </div>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 11, marginTop: 18 }}>
          <SimMetric label="Custo atual" value={'R$ ' + simBRL(p[SPX.cu])} color={T.text} />
          <SimMetric label="Preço de venda" value={'R$ ' + simBRL(p[SPX.pv])} sub="praticado na loja" />
          <SimMetric label="Markup" value={(p[SPX.mk] != null ? p[SPX.mk].toFixed(0) : '—') + '%'} color={T.green} />
          <SimMetric label="Última compra" value={simDate(p[SPX.uc])} sub={hist.length ? hist.length + ' entradas' : 'sem histórico'} />
        </div>
      </Glass>

      {/* Movimento (histórico de compra) */}
      <Glass style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14 }}>
          <Icon name="chart" size={17} color={T.redBright} />
          <div style={{ fontWeight: 700, fontSize: 15 }}>Movimento do produto</div>
          <span style={{ fontSize: 12, color: T.mute }}>· histórico de custo de entrada</span>
        </div>
        {hist.length >= 1 ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1.4fr)', gap: 18 }} className="dxresp2">
            <div>
              <SimSpark hist={hist} />
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: T.mute2, marginTop: 4 }}>
                <span>{simDate(hist[hist.length-1][0])}</span><span>{simDate(hist[0][0])}</span>
              </div>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                <thead><tr style={{ color: T.mute, textAlign: 'left' }}>
                  <th style={{ padding: '6px 8px', fontWeight: 600 }}>Data</th>
                  <th style={{ padding: '6px 8px', fontWeight: 600, textAlign: 'right' }}>Custo un.</th>
                  <th style={{ padding: '6px 8px', fontWeight: 600, textAlign: 'right' }}>Qtd</th>
                  <th style={{ padding: '6px 8px', fontWeight: 600 }}>Fornecedor</th>
                </tr></thead>
                <tbody>
                  {hist.slice(0, 6).map((h, i) => {
                    const sup = sups[h[3]];
                    return (
                      <tr key={i} style={{ borderTop: `1px solid ${T.border}` }}>
                        <td style={{ padding: '7px 8px', fontFamily: 'var(--mono)', color: T.mute }}>{simDate(h[0])}</td>
                        <td style={{ padding: '7px 8px', fontFamily: 'var(--mono)', fontWeight: 700, textAlign: 'right' }}>R$ {simBRL(h[1])}</td>
                        <td style={{ padding: '7px 8px', fontFamily: 'var(--mono)', textAlign: 'right', color: T.mute }}>{h[2]}</td>
                        <td style={{ padding: '7px 8px', color: T.mute, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 200 }}>{sup ? sup[0].replace(/ (LTDA|S\/A|ME|EIRELI).*$/i,'') : '—'}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        ) : (
          <div style={{ padding: '20px 0', color: T.mute, fontSize: 13.5 }}>Sem histórico de compra registrado para este item.</div>
        )}
      </Glass>

      {/* SIMILARIDADE */}
      <Glass>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 4, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <Icon name="bolt" size={17} color={T.green} />
            <div style={{ fontWeight: 700, fontSize: 16 }}>Similaridade</div>
            <span style={{ fontSize: 12.5, color: T.mute }}>· {sims.length} {sims.length === 1 ? 'equivalente' : 'equivalentes'} em outros laboratórios</span>
          </div>
          {key ? <Pill tone="green">{activeName}</Pill> : <Pill tone="yellow">princípio ativo não identificado</Pill>}
        </div>
        <div style={{ fontSize: 12.5, color: T.mute, marginBottom: 16 }}>
          {key
            ? <>Todos os produtos com o princípio ativo <b style={{ color: T.text }}>{activeName}</b> — ordenados do menor custo ao maior. Combinações ficam em grupo separado.</>
            : <>Não foi possível determinar o princípio ativo deste item com segurança. Nenhum equivalente é exibido para evitar comparação incorreta.</>}
        </div>

        {sims.length > 0 && econVsCheapest > 1 && (
          <div className="ruptglow" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', borderRadius: 12, background: simA(T.green, 0.08), border: `1px solid ${simA(T.green,0.3)}`, marginBottom: 14 }}>
            <Icon name="trophy" size={20} color={T.green} />
            <div style={{ fontSize: 13.5, color: T.text }}>
              Trocando por <b>{sims[0][SPX.fab] || 'equivalente'}</b> o custo cai de <b>R$ {simBRL(myCost)}</b> para <b style={{ color: T.green }}>R$ {simBRL(cheapest)}</b> — economia de <b style={{ color: T.green }}>{econVsCheapest.toFixed(0)}%</b> por unidade.
            </div>
          </div>
        )}

        {sims.length > 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {sections.map(sec => (
              <div key={sec.type}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 3, background: SIM_TYPE_COLOR[sec.type] }} />
                  <span style={{ fontSize: 12.5, fontWeight: 800, color: SIM_TYPE_COLOR[sec.type], textTransform: 'uppercase', letterSpacing: 0.5 }}>{SIM_TYPE_LABEL[sec.type]}</span>
                  <span style={{ fontSize: 12, color: T.mute2 }}>· {sec.items.length}</span>
                  <div style={{ flex: 1, height: 1, background: T.border }} />
                </div>
                <div style={{ overflowX: 'auto', margin: '0 -4px' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 640 }}>
                    <thead><tr style={{ color: T.mute, textAlign: 'left', fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.4 }}>
                      <th style={{ padding: '6px 10px', fontWeight: 700 }}>Produto</th>
                      <th style={{ padding: '6px 10px', fontWeight: 700 }}>Laboratório</th>
                      <th style={{ padding: '6px 10px', fontWeight: 700, textAlign: 'center' }}>Estoque</th>
                      <th style={{ padding: '6px 10px', fontWeight: 700, textAlign: 'center' }}>Últ. compra</th>
                      <th style={{ padding: '6px 10px', fontWeight: 700, textAlign: 'right' }}>Custo</th>
                      <th style={{ padding: '6px 10px', fontWeight: 700, textAlign: 'right' }}>P. venda</th>
                      <th style={{ padding: '6px 10px', fontWeight: 700, textAlign: 'right' }}>vs. atual</th>
                    </tr></thead>
                    <tbody>
                      {sec.items.map((qr, i) => {
                        const diff = myCost ? ((qr[SPX.cu] - myCost) / myCost * 100) : 0;
                        const cheaper = qr[SPX.cu] < myCost;
                        const isBest = qr[SPX.cu] === sec.cheapestCost;
                        return (
                          <tr key={i} className="erp-row" onClick={() => onSelect(qr)} style={{ borderTop: `1px solid ${T.border}`, cursor: 'pointer' }}>
                            <td style={{ padding: '9px 10px', maxWidth: 240 }}>
                              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                {isBest && <span style={{ fontSize: 9.5, fontWeight: 800, padding: '2px 6px', borderRadius: 5, background: simA(T.green,0.16), color: T.green, whiteSpace: 'nowrap' }}>MELHOR</span>}
                                <span className="prodlink" style={{ fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{qr[SPX.n]}</span>
                              </div>
                            </td>
                            <td style={{ padding: '9px 10px', color: T.mute, whiteSpace: 'nowrap', maxWidth: 150, overflow: 'hidden', textOverflow: 'ellipsis' }}>{qr[SPX.fab] || '—'}</td>
                            <td style={{ padding: '9px 10px', textAlign: 'center', color: qr[SPX.est] > 0 ? T.text : T.mute2, fontFamily: 'var(--mono)' }}>{qr[SPX.est]}</td>
                            <td style={{ padding: '9px 10px', textAlign: 'center', color: T.mute, fontFamily: 'var(--mono)', fontSize: 12 }}>{simDate(qr[SPX.uc])}</td>
                            <td style={{ padding: '9px 10px', textAlign: 'right', fontFamily: 'var(--mono)', fontWeight: 700, color: cheaper ? T.green : T.text }}>R$ {simBRL(qr[SPX.cu])}</td>
                            <td style={{ padding: '9px 10px', textAlign: 'right', fontFamily: 'var(--mono)', color: T.mute }}>R$ {simBRL(qr[SPX.pv])}</td>
                            <td style={{ padding: '9px 10px', textAlign: 'right' }}><Delta pct={diff} size={11.5} /></td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ padding: '16px 0', color: T.mute, fontSize: 13.5 }}>Este é o único item com esse princípio ativo e dosagem na base.</div>
        )}
      </Glass>
    </div>
  );
}

// ── VIEW PRINCIPAL — lista dos 24k + busca/filtro → ficha ───────────────
function Similaridade() {
  const ERP = window.ERP || { p: [], s: [] };
  const P = ERP.p, sups = ERP.s;
  const [q, setQ] = React.useState('');
  const [cat, setCat] = React.useState('all');
  const [onlyPA, setOnlyPA] = React.useState(false);
  const [sel, setSel] = React.useState(null);
  const [limit, setLimit] = React.useState(50);

  // índice chave (princípio ativo oficial + dose) → grupo de produtos
  const groupByKey = React.useMemo(() => {
    const g = {};
    for (const p of P) { const k = groupKeyOf(p); if (k) (g[k] = g[k] || []).push(p); }
    return g;
  }, []);

  const filtered = React.useMemo(() => {
    const s = q.trim().toLowerCase();
    const out = [];
    for (const p of P) {
      if (cat !== 'all' && p[SPX.cat] !== cat) continue;
      const k = groupKeyOf(p);
      if (onlyPA && !(k && groupByKey[k] && groupByKey[k].length > 1)) continue;
      if (s) {
        const hit = (p[SPX.n] && p[SPX.n].toLowerCase().includes(s)) || String(p[SPX.c]).includes(s) || String(p[SPX.ean]).includes(s) || (k && k.toLowerCase().includes(s));
        if (!hit) continue;
      }
      out.push(p);
    }
    out.sort((a,b) => (b[SPX.est]||0) - (a[SPX.est]||0));
    return out;
  }, [q, cat, onlyPA]);

  React.useEffect(() => { setLimit(50); }, [q, cat, onlyPA]);

  if (sel) return (
    <SimDetail prod={sel} groupByKey={groupByKey} sups={sups} onBack={() => setSel(null)} onSelect={(p) => { setSel(p); }} />
  );

  const shown = filtered.slice(0, limit);
  return (
    <div>
      <TopbarS9 title="Similaridade por Produto" sub={`${P.length.toLocaleString('pt-BR')} produtos reais do ERP HOS · compare genéricos e equivalentes`}
        action={<Pill tone="mute"><Icon name="shield" size={13} color={T.mute} /> {Object.keys(groupByKey).length.toLocaleString('pt-BR')} grupos equivalentes</Pill>} />

      {/* Busca + filtros */}
      <Glass pad={14} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '0 13px', height: 42, borderRadius: 11, background: T.panel, border: `1px solid ${T.border}`, flex: '1 1 300px', minWidth: 240 }}>
            <Icon name="search" size={16} color={T.mute} />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar por produto, princípio ativo, código ou EAN…" style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: T.text, fontSize: 13.5, fontFamily: 'inherit' }} />
            {q && <button onClick={() => setQ('')} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex' }}><Icon name="x" size={15} color={T.mute2} /></button>}
          </div>
          <button onClick={() => setOnlyPA(v => !v)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '0 14px', height: 42, borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap',
            background: onlyPA ? simA(T.blue, 0.14) : T.panel, color: onlyPA ? T.blue : T.mute, border: `1px solid ${onlyPA ? simA(T.blue,0.4) : T.border}` }}>
            <Icon name="shield" size={15} color={onlyPA ? T.blue : T.mute} /> Só com equivalentes
          </button>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 13 }}>
          {SIM_CATS.map(([id, name]) => {
            const on = cat === id;
            const c = id === 'all' ? T.text : SIM_CATC[id];
            return (
              <button key={id} onClick={() => setCat(id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 12px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 600, whiteSpace: 'nowrap',
                background: on ? simA(c, 0.16) : T.panel, color: on ? c : T.mute, border: `1px solid ${on ? simA(c,0.45) : T.border}` }}>
                {id !== 'all' && <span style={{ width: 8, height: 8, borderRadius: 3, background: c }} />}{name}
              </button>
            );
          })}
        </div>
      </Glass>

      {/* contagem */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, fontSize: 12.5, color: T.mute, padding: '0 4px', flexWrap: 'wrap', gap: 6 }}>
        <span><b style={{ color: T.text }}>{filtered.length.toLocaleString('pt-BR')}</b> produtos{q || cat !== 'all' || onlyPA ? ' filtrados' : ''}</span>
        <span>clique num produto para ver o movimento e os similares</span>
      </div>

      {/* Tabela */}
      <Glass pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 680 }}>
            <thead><tr style={{ color: T.mute, textAlign: 'left', fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.4, background: T.panel }}>
              <th style={{ padding: '12px 14px', fontWeight: 700 }}>Produto</th>
              <th style={{ padding: '12px 14px', fontWeight: 700 }}>Princípio ativo</th>
              <th style={{ padding: '12px 14px', fontWeight: 700, textAlign: 'center' }}>Curva</th>
              <th style={{ padding: '12px 14px', fontWeight: 700, textAlign: 'center' }}>Estoque</th>
              <th style={{ padding: '12px 14px', fontWeight: 700, textAlign: 'right' }}>Custo</th>
              <th style={{ padding: '12px 14px', fontWeight: 700, textAlign: 'right' }}>P. venda</th>
              <th style={{ padding: '12px 14px', fontWeight: 700, textAlign: 'center' }}>Similares</th>
            </tr></thead>
            <tbody>
              {shown.map((p, i) => {
                const k = groupKeyOf(p);
                const nSim = k && groupByKey[k] ? (groupByKey[k].length - 1) : 0;
                return (
                  <tr key={p[SPX.c] + '-' + i} className="erp-row" onClick={() => setSel(p)} style={{ borderTop: `1px solid ${T.border}`, cursor: 'pointer' }}>
                    <td style={{ padding: '11px 14px', maxWidth: 280 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                        <span style={{ width: 8, height: 8, borderRadius: 3, background: SIM_CATC[p[SPX.cat]] || T.mute, flexShrink: 0 }} />
                        <div style={{ minWidth: 0 }}>
                          <div className="prodlink" style={{ fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p[SPX.n]}</div>
                          <div style={{ fontSize: 10.5, color: T.mute2, fontFamily: 'var(--mono)' }}>#{p[SPX.c]} · {p[SPX.fab] || '—'}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '11px 14px', color: k ? T.blue : T.mute2, fontSize: 12, whiteSpace: 'nowrap', maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis' }}>{k ? activeLabel(k) : '—'}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'center', fontFamily: 'var(--mono)', fontWeight: 700, color: simCurve(p[SPX.cv]) }}>{p[SPX.cv] || '—'}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'center', fontFamily: 'var(--mono)', color: p[SPX.est] > 0 ? T.text : T.mute2 }}>{p[SPX.est]}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', fontFamily: 'var(--mono)', fontWeight: 700 }}>R$ {simBRL(p[SPX.cu])}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'right', fontFamily: 'var(--mono)', color: T.mute }}>R$ {simBRL(p[SPX.pv])}</td>
                    <td style={{ padding: '11px 14px', textAlign: 'center' }}>
                      {nSim > 0 ? <span style={{ fontSize: 11.5, fontWeight: 700, padding: '3px 9px', borderRadius: 99, background: simA(T.green,0.14), color: T.green }}>{nSim}</span> : <span style={{ color: T.mute2 }}>—</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {filtered.length > limit && (
          <div style={{ padding: 14, textAlign: 'center', borderTop: `1px solid ${T.border}` }}>
            <button onClick={() => setLimit(l => l + 50)} style={{ padding: '9px 20px', borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: T.text }}>
              Carregar mais ({(filtered.length - limit).toLocaleString('pt-BR')} restantes)
            </button>
          </div>
        )}
        {filtered.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: T.mute }}>Nenhum produto encontrado.</div>}
      </Glass>
    </div>
  );
}

window.BuyerSimil = { Similaridade };
