// ── InovaPED — Comprador: Leilão Reverso + Mural de Ofertas ─────────────
const Topbar6 = window.BuyerParts1.Topbar;
const ICg = window.IC;
const rep6 = window.BuyerParts1.repById, cat6 = window.BuyerParts1.catById;

// ═══ LEILÃO REVERSO AO VIVO ══════════════════════════════════════════════
function Auction() {
  const a = ICg.AUCTION;
  const [bids, setBids] = useState(() => a.bids.map(b => ({ ...b })));
  const [secs, setSecs] = useState(a.endsIn);
  const [flash, setFlash] = useState(null);

  useEffect(() => {
    const t = setInterval(() => setSecs(s => Math.max(0, s - 1)), 1000);
    return () => clearInterval(t);
  }, []);
  useEffect(() => {
    const t = setInterval(() => {
      setBids(prev => {
        const sorted = [...prev].sort((x, y) => x.price - y.price);
        const leader = sorted[0];
        // um concorrente cobre o líder
        const challenger = prev[Math.floor(Math.random() * prev.length)];
        if (challenger.rep === leader.rep) return prev;
        const newPrice = +(leader.price - (Math.random() * 0.6 + 0.2)).toFixed(2);
        setFlash(challenger.rep); setTimeout(() => setFlash(null), 700);
        return prev.map(b => b.rep === challenger.rep ? { ...b, price: newPrice } : b);
      });
    }, 2600);
    return () => clearInterval(t);
  }, []);

  const ranked = [...bids].sort((x, y) => x.price - y.price);
  const best = ranked[0];
  const mm = String(Math.floor(secs / 60)).padStart(2, '0'), ss = String(secs % 60).padStart(2, '0');

  return (
    <div>
      <Topbar6 title="Leilão Reverso" sub="Disputa ao vivo — quem oferece o menor preço lidera"
        action={<Pill tone="red"><span style={{ width: 7, height: 7, borderRadius: 99, background: T.red, animation: 'icpulse 1s infinite' }} /> AO VIVO</Pill>} />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 16, alignItems: 'start' }}>
        {/* disputa */}
        <Glass>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
            <div>
              <div style={{ fontSize: 12, color: T.mute }}>Item em disputa</div>
              <div style={{ fontWeight: 800, fontSize: 19, fontFamily: 'var(--display)', marginTop: 2 }}>{a.prod}</div>
              <div style={{ fontSize: 12.5, color: T.mute, marginTop: 4 }}>Qtd: {a.qty} un · Último custo R$ {ICg.fmt(a.lastCost)}</div>
            </div>
            <div style={{ textAlign: 'center', padding: '10px 16px', borderRadius: 12, background: T.redBg, border: `1px solid rgba(255,19,48,0.3)` }}>
              <div style={{ fontSize: 11, color: T.redBright, fontWeight: 700 }}>ENCERRA EM</div>
              <div style={{ fontSize: 26, fontWeight: 800, fontFamily: 'var(--display)', fontVariantNumeric: 'tabular-nums', color: T.redBright }}>{mm}:{ss}</div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {ranked.map((b, i) => {
              const r = rep6(b.rep); const lead = i === 0; const eco = a.lastCost - b.price;
              return (
                <div key={b.rep} className={flash === b.rep ? 'valflash' : ''} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px', borderRadius: 13, transition: 'all .4s', background: lead ? 'rgba(0,230,140,0.1)' : flash === b.rep ? 'rgba(255,19,48,0.12)' : T.panel, border: `1.5px solid ${lead ? 'rgba(0,230,140,0.45)' : T.border}` }}>
                  <div style={{ width: 28, height: 28, borderRadius: 99, background: lead ? T.green : T.panelHi, color: lead ? '#04130C' : T.mute, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, fontSize: 13 }}>{i + 1}º</div>
                  <div style={{ width: 36, height: 36, borderRadius: 99, background: r.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, color: '#fff' }}>{r.name[0]}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 14.5 }}>{r.name}</div>
                    <div style={{ fontSize: 11.5, color: T.mute }}>{r.lab} · {r.tax === 'com' ? 'c/ imposto' : 's/ imposto'}</div>
                  </div>
                  {lead && <Pill tone="green"><Icon name="trophy" size={12} color={T.green} /> Liderando</Pill>}
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontWeight: 800, fontSize: 18, fontFamily: 'var(--mono)', fontVariantNumeric: 'tabular-nums', color: lead ? T.green : T.text }}>R$ {ICg.fmt(b.price)}</div>
                    <div style={{ fontSize: 11, color: T.green }}>−R$ {ICg.fmt(eco)}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </Glass>

        {/* resumo lateral */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Glass>
            <div style={{ fontSize: 12, color: T.mute }}>Melhor preço atual</div>
            <div style={{ fontSize: 32, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}>R$ {ICg.fmt(best.price)}</div>
            <div style={{ fontSize: 13, color: T.mute, marginTop: 2 }}>por {rep6(best.rep).name}</div>
            <div style={{ marginTop: 14, padding: 14, borderRadius: 12, background: T.greenBg, border: `1px solid rgba(0,230,140,0.3)` }}>
              <div style={{ fontSize: 12, color: T.green }}>Economia no lote ({a.qty} un)</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: T.green, fontFamily: 'var(--display)' }}>R$ {ICg.fmt((a.lastCost - best.price) * a.qty)}</div>
            </div>
            <button style={{ width: '100%', marginTop: 14, padding: '13px', borderRadius: 12, border: 'none', cursor: '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)', display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="check" size={17} color="#fff" strokeWidth={2.4} /> Arrematar agora</button>
          </Glass>
          <Glass pad={16}>
            <div style={{ fontSize: 12.5, color: T.mute, lineHeight: 1.5 }}><Icon name="shield" size={14} color={T.mute} style={{ verticalAlign:'-2px' }} /> Defina um <b style={{color:T.text}}>preço-limite</b> e o leilão arremata sozinho quando alcançado. <span style={{ color: T.mute2 }}>(lógica no Claude Code)</span></div>
          </Glass>
        </div>
      </div>
    </div>
  );
}

// ═══ MURAL DE OFERTAS / COTAÇÃO INVERSA ══════════════════════════════════
function Mural() {
  const [demands] = useState(ICg.DEMANDS);
  const [newOpen, setNewOpen] = useState(false);
  return (
    <div>
      <Topbar6 title="Mural de Ofertas" sub="Cotação inversa — você publica a demanda, os reps aceitam"
        action={<button onClick={() => setNewOpen(true)} style={{ display:'flex',alignItems:'center',gap:8, padding: '11px 18px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, 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={18} color="#fff" strokeWidth={2.4} /> Publicar demanda</button>} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 14 }}>
        {demands.map(d => { const c = cat6(d.cat); const accepted = d.status === 'aceita'; const r = d.by ? rep6(d.by) : null; return (
          <Glass key={d.id} hover pad={18}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div style={{ display: 'flex', gap: 11 }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: T.redBg, border:`1px solid rgba(255,19,48,0.3)`, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name={c.icon} size={20} color={T.redBright} /></div>
                <div><div style={{ fontWeight: 700, fontSize: 14.5, lineHeight: 1.25 }}>{d.prod}</div><div style={{ fontSize: 12, color: T.mute, marginTop: 2 }}>{c.name} · {d.time}</div></div>
              </div>
              <Pill tone={accepted ? 'green' : 'yellow'}>{accepted ? 'Aceita' : 'Aguardando'}</Pill>
            </div>
            <div style={{ display: 'flex', gap: 20, marginTop: 16 }}>
              <div><div style={{ fontSize: 11, color: T.mute2 }}>Preço-alvo</div><div style={{ fontWeight: 800, fontSize: 19, fontFamily: 'var(--display)', color: T.redBright }}>R$ {ICg.fmt(d.target)}</div></div>
              <div><div style={{ fontSize: 11, color: T.mute2 }}>Quantidade</div><div style={{ fontWeight: 800, fontSize: 19, fontFamily: 'var(--display)' }}>{d.qty} un</div></div>
            </div>
            <div style={{ marginTop: 14, paddingTop: 14, borderTop: `1px solid ${T.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              {accepted
                ? <span style={{ display:'flex',alignItems:'center',gap:8, fontSize: 13 }}><span style={{ width: 24, height: 24, borderRadius: 99, background: r.color, display:'flex',alignItems:'center',justifyContent:'center', fontSize: 11, fontWeight: 800, color:'#fff' }}>{r.name[0]}</span><span style={{ color: T.mute }}>aceita por <b style={{ color: T.text }}>{r.name.split(' ')[0]}</b></span></span>
                : <span style={{ fontSize: 12.5, color: T.mute2 }}>Visível para {ICg.REPS.filter(x => x.cats.includes(d.cat)).length} reps da categoria</span>}
              <Icon name="chevron" size={16} color={T.mute2} />
            </div>
          </Glass>
        ); })}
      </div>
      {newOpen && <NewDemandModal onClose={() => setNewOpen(false)} />}
    </div>
  );
}

function NewDemandModal({ 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: 460, borderRadius: 22, background: T.surface, border: `1px solid ${T.borderHi}`, padding: 26 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
          <div style={{ fontWeight: 800, fontSize: 18, fontFamily: 'var(--display)' }}>Publicar demanda</div>
          <button onClick={onClose} style={{ background: T.panel, border: `1px solid ${T.border}`, borderRadius: 9, width: 34, height: 34, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="x" size={17} color={T.mute} /></button>
        </div>
        <DField label="Produto"><input placeholder="Buscar na base de 25k..." style={dIn()} /></DField>
        <div style={{ display: 'flex', gap: 10 }}>
          <DField label="Preço-alvo (R$)" style={{ flex: 1 }}><input placeholder="0,00" style={dIn()} /></DField>
          <DField label="Quantidade" style={{ flex: 1 }}><input placeholder="120" style={dIn()} /></DField>
        </div>
        <DField label="Validade mínima"><input placeholder="MM/AAAA" style={dIn()} /></DField>
        <button onClick={onClose} style={{ width: '100%', marginTop: 10, padding: '14px', borderRadius: 12, border: 'none', cursor: 'pointer', fontWeight: 800, fontFamily: 'inherit', fontSize: 14.5, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="send" size={17} color="#fff" /> Publicar no mural</button>
      </div>
    </div>
  );
}
function DField({ label, children, style }) { return <div style={{ marginBottom: 13, ...style }}><label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: T.mute, marginBottom: 6 }}>{label}</label>{children}</div>; }
const dIn = () => ({ width: '100%', boxSizing: 'border-box', padding: '12px 13px', borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' });

window.BuyerParts6 = { Auction, Mural };
