// ── InovaPED — Compras & Performance (inteligência de compra) ───────────
// Usa window.ERPSTATS (agregados reais das planilhas) + window.ERP
const TopbarC = window.BuyerParts1.Topbar;

const CAT_META = {
  med:  { name: 'Medicamentos',     color: '#FF1330' },
  sup:  { name: 'Suplementos',      color: '#FF6B57' },
  gen:  { name: 'Genéricos',        color: '#FF9E80' },
  derm: { name: 'Dermocosméticos',  color: '#C77DFF' },
  hig:  { name: 'Higiene',          color: '#4EA8DE' },
  baby: { name: 'Mamãe & Bebê',     color: '#FF4D6D' },
  out:  { name: 'Outros',           color: '#7A7A82' },
};
const brl = (n) => 'R$ ' + (n||0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const brK = (n) => { const a = Math.abs(n); if (a >= 1e6) return 'R$ ' + (n/1e6).toLocaleString('pt-BR',{maximumFractionDigits:2}) + 'M'; if (a >= 1e3) return 'R$ ' + (n/1e3).toLocaleString('pt-BR',{maximumFractionDigits:0}) + 'k'; return brl(n); };
const MES = { '01':'Jan','02':'Fev','03':'Mar','04':'Abr','05':'Mai','06':'Jun','07':'Jul','08':'Ago','09':'Set','10':'Out','11':'Nov','12':'Dez' };
const mesLabel = (ym) => { const [y,m] = ym.split('-'); return MES[m] + '/' + y.slice(2); };

function Compras() {
  const S = window.ERPSTATS;
  if (!S) return <div style={{ padding: 40, color: T.mute }}>Carregando dados de compra…</div>;
  const [tab, setTab] = useState('visao'); // visao | fornec | margem
  const maxMonth = Math.max(...S.months.map(m => m.t));
  const prevTotal = S.months.length > 1 ? S.months[S.months.length-2].t : null;
  const lastTotal = S.months[S.months.length-1].t;
  const momPct = prevTotal ? ((lastTotal - prevTotal) / prevTotal) * 100 : null;

  return (
    <div>
      <TopbarC title="Compras & Performance" sub="Inteligência de compra · dados reais do ERP HOS (jan–mai 2026)"
        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} /> Só comprador</span>
          <ToolBtn icon="receipt">Exportar Excel</ToolBtn>
        </div>} />

      {/* KPIs */}
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(185px, 1fr))' }}>
        <Glass pad={18}><div style={{ fontSize: 12, color: T.mute }}>Total comprado</div><div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}><CountUp value={S.total/1e6} prefix="R$ " suffix="M" decimals={2} /></div><div style={{ fontSize: 11.5, color: T.mute2, marginTop: 2 }}>{S.lines.toLocaleString('pt-BR')} entradas de nota</div></Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 180 }}><div style={{ fontSize: 12, color: T.mute }}>Ticket médio / item</div><div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{brl(S.avgTicket)}</div><div style={{ fontSize: 11.5, color: T.mute2, marginTop: 2 }}>{Math.round(S.totalQtd).toLocaleString('pt-BR')} itens comprados</div></Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 180 }}><div style={{ fontSize: 12, color: T.mute }}>Compra no mês (Mai)</div><div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{brK(lastTotal)}</div><div style={{ marginTop: 3 }}>{momPct != null && <Delta pct={momPct} />} <span style={{ fontSize: 11, color: T.mute2 }}>vs. mês ant.</span></div></Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 180 }}><div style={{ fontSize: 12, color: T.mute }}>Fornecedores ativos</div><div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{S.sups.length}+</div><div style={{ fontSize: 11.5, color: T.mute2, marginTop: 2 }}>distribuidoras & laboratórios</div></Glass>
      </div>

      {/* abas */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        {[['visao','Visão geral','chart'],['fornec','Fornecedores & Laboratórios','box'],['margem','Margem & Lucro','tag']].map(([id,label,icon]) => {
          const on = tab === id;
          return <button key={id} onClick={() => setTab(id)} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '9px 15px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, border: `1px solid ${on ? T.red : T.border}`, color: on ? '#fff' : T.mute, background: on ? T.redBg : 'transparent' }}><Icon name={icon} size={15} color={on ? T.redBright : T.mute} /> {label}</button>;
        })}
      </div>

      {tab === 'visao' && <>
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 16, marginBottom: 16 }}>
          <Glass>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}><div style={{ fontWeight: 700, fontSize: 15 }}>Compras por mês</div><Pill tone="mute">2026</Pill></div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14, height: 210, paddingTop: 10 }}>
              {S.months.map((m, i) => { const h = (m.t / maxMonth) * 165; const last = i === S.months.length-1; return (
                <div key={m.ym} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, height: '100%', justifyContent: 'flex-end' }}>
                  <div style={{ fontSize: 12, fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: last ? T.redBright : T.text }}>{brK(m.t)}</div>
                  <div style={{ width: '100%', maxWidth: 70, height: h, borderRadius: '8px 8px 3px 3px', background: last ? `linear-gradient(180deg, ${T.redBright}, ${T.redDeep})` : T.barNeutral, boxShadow: last ? '0 0 22px rgba(255,19,48,0.4)' : 'none', transition: 'height .6s cubic-bezier(.2,.8,.2,1)' }} />
                  <div style={{ fontSize: 11.5, color: T.mute }}>{mesLabel(m.ym)}</div>
                  <div style={{ fontSize: 10, color: T.mute2 }}>{m.c} notas</div>
                </div>
              ); })}
            </div>
          </Glass>
          <Glass>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 14 }}>Gasto por categoria</div>
            <Donut data={S.cats.map(c => ({ label: CAT_META[c.k].name, value: c.t, color: CAT_META[c.k].color }))} />
          </Glass>
        </div>
        <Glass>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 14 }}>Distribuição por categoria</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {S.cats.map(c => { const pct = (c.t / S.total) * 100; const m = CAT_META[c.k]; return (
              <div key={c.k} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ width: 140, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ width: 9, height: 9, borderRadius: 99, background: m.color }} />{m.name}</div>
                <div style={{ flex: 1, height: 10, borderRadius: 99, background: T.panelHi, overflow: 'hidden' }}><div style={{ width: pct + '%', height: '100%', borderRadius: 99, background: m.color, transition: 'width .7s' }} /></div>
                <div style={{ width: 90, textAlign: 'right', fontWeight: 700, fontVariantNumeric: 'tabular-nums', fontSize: 13 }}>{brK(c.t)}</div>
                <div style={{ width: 46, textAlign: 'right', fontSize: 12, color: T.mute }}>{pct.toFixed(0)}%</div>
              </div>
            ); })}
          </div>
        </Glass>
      </>}

      {tab === 'fornec' && <Glass pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ padding: '16px 18px', borderBottom: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', gap: 9 }}><Icon name="box" size={17} color={T.redBright} /><div style={{ fontWeight: 700, fontSize: 15 }}>Ranking de fornecedores & laboratórios</div><span style={{ fontSize: 12, color: T.mute2 }}>por volume comprado</span></div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
          <thead><tr style={{ background: T.panel }}>
            <th style={thC('left', 40)}>#</th><th style={thC('left')}>Fornecedor</th><th style={thC('right', 90)}>Notas</th><th style={thC('right', 100)}>Produtos</th><th style={thC('right', 130)}>Total comprado</th><th style={thC('left', 160)}>Participação</th>
          </tr></thead>
          <tbody>
            {S.sups.map((f, i) => { const pct = (f.t / S.total) * 100; return (
              <tr key={i} style={{ borderTop: `1px solid ${T.border}` }}>
                <td style={{ ...tdC('left'), color: T.mute2, fontWeight: 700 }}>{i+1}</td>
                <td style={tdC('left')}><div style={{ fontWeight: 600, display: 'flex', alignItems: 'center', gap: 9 }}><span style={{ width: 28, height: 28, borderRadius: 8, background: i < 3 ? T.redBg : T.panelHi, display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name="box" size={14} color={i < 3 ? T.redBright : T.mute} /></span>{f.n}</div></td>
                <td style={{ ...tdC('right'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>{f.c}</td>
                <td style={{ ...tdC('right'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>{f.p}</td>
                <td style={{ ...tdC('right'), fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>{brK(f.t)}</td>
                <td style={tdC('left')}><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><div style={{ flex: 1, height: 7, borderRadius: 99, background: T.panelHi, overflow: 'hidden' }}><div style={{ width: Math.max(3, pct) + '%', height: '100%', borderRadius: 99, background: `linear-gradient(90deg, ${T.redBright}, ${T.redDeep})` }} /></div><span style={{ fontSize: 11.5, color: T.mute, width: 36, textAlign: 'right' }}>{pct.toFixed(1)}%</span></div></td>
              </tr>
            ); })}
          </tbody>
        </table>
      </Glass>}

      {tab === 'margem' && <>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
          <Glass>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4 }}>Distribuição de margem (markup)</div>
            <div style={{ fontSize: 12, color: T.mute2, marginBottom: 16 }}>Quantos produtos em cada faixa de lucro</div>
            {(() => { const b = S.buckets; const max = Math.max(...Object.values(b)); const colors = { '<20': T.redBright, '20-40': '#FF9E80', '40-60': '#FFC83D', '60-100': '#7BF0C0', '100+': T.green }; return (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {Object.entries(b).map(([k, v]) => (
                  <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ width: 70, fontSize: 12.5, fontWeight: 600, color: T.mute }}>{k}%</div>
                    <div style={{ flex: 1, height: 22, borderRadius: 6, background: T.panelHi, overflow: 'hidden' }}><div style={{ width: (v/max*100) + '%', height: '100%', borderRadius: 6, background: colors[k], transition: 'width .7s', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 8 }}><span style={{ fontSize: 11, fontWeight: 800, color: '#0A0A0B' }}>{v}</span></div></div>
                  </div>
                ))}
              </div>
            ); })()}
          </Glass>
          <Glass>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4, display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="arrowUp" size={16} color={T.green} /> Maiores margens</div>
            <div style={{ fontSize: 12, color: T.mute2, marginBottom: 14 }}>Produtos campeões de lucro</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              {S.topMargin.slice(0, 8).map((p, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: i < 7 ? `1px solid ${T.border}` : 'none' }}>
                  <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.n}</div><div style={{ fontSize: 10.5, color: T.mute2, fontVariantNumeric: 'tabular-nums' }}>custo {brl(p.cu)} → venda {brl(p.pv)}</div></div>
                  <Pill tone="green">{p.mk.toFixed(0)}%</Pill>
                </div>
              ))}
            </div>
          </Glass>
        </div>
        <Glass>
          <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4, display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="arrowDown" size={16} color={T.redBright} /> Menores margens — atenção na próxima cotação</div>
          <div style={{ fontSize: 12, color: T.mute2, marginBottom: 14 }}>Produtos onde você mais precisa negociar custo</div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead><tr style={{ background: T.panel }}><th style={thC('left')}>Produto</th><th style={thC('right', 110)}>Custo</th><th style={thC('right', 110)}>Venda</th><th style={thC('right', 90)}>Markup</th></tr></thead>
            <tbody>
              {S.lowMargin.slice(0, 8).map((p, i) => (
                <tr key={i} style={{ borderTop: `1px solid ${T.border}` }}>
                  <td style={tdC('left')}><span style={{ fontWeight: 600 }}>{p.n}</span></td>
                  <td style={{ ...tdC('right'), fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{brl(p.cu)}</td>
                  <td style={{ ...tdC('right'), fontVariantNumeric: 'tabular-nums', color: T.mute }}>{brl(p.pv)}</td>
                  <td style={tdC('right')}><Pill tone={p.mk < 20 ? 'red' : 'mute'}>{p.mk.toFixed(0)}%</Pill></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Glass>
      </>}
    </div>
  );
}
const thC = (a, w) => ({ textAlign: a, padding: '12px 16px', fontSize: 11, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, whiteSpace: 'nowrap', minWidth: w });
const tdC = (a) => ({ textAlign: a, padding: '12px 16px', verticalAlign: 'middle' });

window.BuyerCompras = { Compras };
