// ── InovaPED — Reposição Inteligente (sugestão de compra real) ──────────
// Usa window.ERP. Cruza estoque × giro × melhor fornecedor histórico.
const TopbarR = window.BuyerParts1.Topbar;

// melhor fornecedor histórico (menor último preço) + custo de referência
function bestSupplier(hist) {
  const byF = {};
  hist.forEach(h => { (byF[h[3]] = byF[h[3]] || []).push(h); });
  const stats = Object.entries(byF).map(([id, hs]) => ({ id: +id, last: hs[0][1], lastDate: hs[0][0], min: Math.min(...hs.map(x => x[1]).filter(x => x > 0)) }));
  stats.sort((a, b) => a.last - b.last);
  return stats[0];
}
function curveThreshold(cv) { return cv === 'A' ? 12 : cv === 'B' ? 6 : cv === 'C' ? 3 : 2; }

function buildSuggestions(ERP) {
  const out = [];
  for (const p of ERP.p) {
    const stock = p[PIDX.est], cv = p[PIDX.cv], hist = p[PIDX.h];
    if (!hist || !hist.length) continue;
    const sold = monthsAgo(p[PIDX.uv]); // meses desde última venda
    if (sold == null || sold > 4) continue;       // só o que girou nos últimos 4 meses
    const thr = curveThreshold(cv);
    if (stock > thr) continue;                      // estoque acima do gatilho → ignora
    const best = bestSupplier(hist);
    const target = Math.max(thr * 2, thr + 4);
    const qty = Math.max(target - stock, thr);
    const urg = stock <= 0 ? 3 : (cv === 'A' ? 2 : 1); // 3=ruptura, 2=crítico curva A, 1=baixo
    out.push({ p, stock, cv, sold, best, qty, cost: best.last * qty, urg });
  }
  out.sort((a, b) => b.urg - a.urg || a.stock - b.stock || b.cost - a.cost);
  return out;
}

function Reposicao() {
  const ERP = window.ERP;
  const sugg = useMemo(() => buildSuggestions(ERP), []);
  const [cat, setCat] = useState('all');
  const [urg, setUrg] = useState('all');
  const [picked, setPicked] = useState(() => new Set());
  const [limit, setLimit] = useState(40);

  const list = useMemo(() => sugg.filter(s =>
    (cat === 'all' || s.p[PIDX.cat] === cat) &&
    (urg === 'all' || (urg === 'rupt' && s.urg === 3) || (urg === 'crit' && s.urg === 2) || (urg === 'baixo' && s.urg === 1))
  ), [cat, urg]);

  const ruptN = sugg.filter(s => s.urg === 3).length;
  const critN = sugg.filter(s => s.urg === 2).length;
  const totalCost = sugg.reduce((a, s) => a + s.cost, 0);
  const pickedCost = sugg.filter(s => picked.has(s.p[PIDX.c])).reduce((a, s) => a + s.cost, 0);

  const toggle = (cod) => setPicked(s => { const n = new Set(s); n.has(cod) ? n.delete(cod) : n.add(cod); return n; });
  const sup = (i) => ERP.s[i] || ['—', ''];
  useEffect(() => { setLimit(40); }, [cat, urg]);

  const urgBadge = (u) => u === 3 ? <Pill tone="red"><span className="ruptdot" style={{ width: 6, height: 6, borderRadius: 99, background: T.redBright }} />Ruptura</Pill>
    : u === 2 ? <Pill tone="red" style={{ opacity: 0.85 }}>Crítico A</Pill>
    : <Pill tone="mute">Baixo</Pill>;

  return (
    <div>
      <TopbarR title="Reposição Inteligente" sub="O que comprar agora · estoque × giro × melhor fornecedor histórico"
        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></div>} />

      {/* KPIs */}
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))' }}>
        <Glass pad={18}><div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12, color: T.mute }}><span style={{ width: 8, height: 8, borderRadius: 99, background: T.redBright }} />Em ruptura</div><div style={{ fontSize: 26, fontWeight: 800, color: T.redBright, fontFamily: 'var(--display)', marginTop: 4 }}>{ruptN}</div><div style={{ fontSize: 11.5, color: T.mute2 }}>estoque zerado e girando</div></Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 170 }}><div style={{ fontSize: 12, color: T.mute }}>Estoque crítico (curva A)</div><div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{critN}</div><div style={{ fontSize: 11.5, color: T.mute2 }}>alto giro, repor já</div></Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 170 }}><div style={{ fontSize: 12, color: T.mute }}>Itens sugeridos</div><div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{sugg.length}</div><div style={{ fontSize: 11.5, color: T.mute2 }}>precisam de compra</div></Glass>
        <Glass pad={18} style={{ flex: 1, minWidth: 170 }}><div style={{ fontSize: 12, color: T.mute }}>Investimento estimado</div><div style={{ fontSize: 26, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}>R$ {(totalCost/1000).toLocaleString('pt-BR',{maximumFractionDigits:0})}k</div><div style={{ fontSize: 11.5, color: T.mute2 }}>no melhor preço histórico</div></Glass>
      </div>

      {/* filtros */}
      <Glass pad={12} style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}><span style={{ fontSize: 12, color: T.mute2 }}>Urgência</span><Seg value={urg} onChange={setUrg} opts={[['all','Todas'],['rupt','Ruptura'],['crit','Crítico A'],['baixo','Baixo']]} /></div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{ERP_CATS.map(c => <Chip key={c.id} on={cat === c.id} onClick={() => setCat(c.id)}>{c.name}</Chip>)}</div>
        </div>
      </Glass>

      {/* tabela */}
      <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('center', 40)}></th>
              <th style={thE('left', 300)}>Produto</th>
              <th style={thE('center', 80)}>Urgência</th>
              <th style={thE('right', 70)}>Estoque</th>
              <th style={thE('left', 90)}>Últ. venda</th>
              <th style={thE('left', 200)}>Melhor fornecedor</th>
              <th style={thE('right', 90)}>Custo un.</th>
              <th style={thE('right', 80)}>Sugerido</th>
              <th style={thE('right', 110)}>Investir</th>
            </tr></thead>
            <tbody>
              {list.slice(0, limit).map(s => {
                const on = picked.has(s.p[PIDX.c]);
                return (
                  <tr key={s.p[PIDX.c]} onClick={() => toggle(s.p[PIDX.c])} className="erp-row" style={{ borderTop: `1px solid ${T.border}`, cursor: 'pointer', background: on ? T.redBg : 'transparent' }}>
                    <td style={tdE('center')}><span style={{ width: 19, height: 19, borderRadius: 6, border: `1.5px solid ${on ? T.red : T.borderHi}`, background: on ? T.red : 'transparent', display:'inline-flex',alignItems:'center',justifyContent:'center' }}>{on && <Icon name="check" size={13} color="#fff" strokeWidth={3} />}</span></td>
                    <td style={tdE('left')}><div style={{ fontWeight: 600 }}>{s.p[PIDX.n]}</div><div style={{ fontSize: 11, color: T.mute2, marginTop: 2 }}>{s.p[PIDX.fab]} · curva {s.cv || '—'}</div></td>
                    <td style={tdE('center')}>{urgBadge(s.urg)}</td>
                    <td style={{ ...tdE('right'), fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: s.stock <= 0 ? T.redBright : T.text }}>{s.stock}</td>
                    <td style={{ ...tdE('left'), color: T.mute, fontVariantNumeric: 'tabular-nums' }}>{s.sold <= 0 ? 'este mês' : `há ${s.sold}m`}</td>
                    <td style={tdE('left')}><div style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="box" size={13} color={T.green} /><span style={{ fontWeight: 600, fontSize: 12.5 }}>{sup(s.best.id)[0]}</span></div><div style={{ fontSize: 10.5, color: T.mute2 }}>últ. {fmtDate(s.best.lastDate)} · mín R$ {fmtBRL(s.best.min)}</div></td>
                    <td style={{ ...tdE('right'), fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: T.green }}>R$ {fmtBRL(s.best.last)}</td>
                    <td style={{ ...tdE('right'), fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>{s.qty}</td>
                    <td style={{ ...tdE('right'), fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>R$ {fmtBRL(s.cost)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {list.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: T.mute2 }}>Nenhum item nesse filtro 🎉</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, list.length)} de {list.length}</span>
        {limit < list.length && <button onClick={() => setLimit(l => l + 60)} 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>

      {/* barra de ação */}
      {picked.size > 0 && (
        <div style={{ position: 'sticky', bottom: 16, marginTop: 16, zIndex: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap', padding: '14px 20px', borderRadius: 16, background: `linear-gradient(180deg, ${T.surface2 || T.surface}, ${T.surface})`, border: `1px solid ${T.borderHi}`, boxShadow: '0 -8px 40px rgba(0,0,0,0.5)' }}>
            <div><div style={{ fontSize: 11.5, color: T.mute2 }}>Selecionados</div><div style={{ fontWeight: 800, fontSize: 18, fontFamily: 'var(--display)' }}>{picked.size} itens</div></div>
            <div><div style={{ fontSize: 11.5, color: T.mute2 }}>Investimento</div><div style={{ fontWeight: 800, fontSize: 18, color: T.green, fontVariantNumeric: 'tabular-nums' }}>R$ {fmtBRL(pickedCost)}</div></div>
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 10 }}>
              <button onClick={() => setPicked(new Set())} style={{ padding: '11px 18px', borderRadius: 12, border: `1px solid ${T.border}`, background: 'transparent', color: T.mute, fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, cursor: 'pointer' }}>Limpar</button>
              <button style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 20px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 6px 20px rgba(255,19,48,0.45)' }}><Icon name="plus" size={17} color="#fff" strokeWidth={2.4} /> Gerar cotação de reposição</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.BuyerRepos = { Reposicao };
