// ── Inova Cotação — Representante: Preenchimento (rico) + Confirmação ────
const MHead2 = window.RepPart1.MHead;
const ICf = window.IC;

// estado por produto: { price, validity, tiers:[{qty,price}], open }
function RepFill({ me, quote, onBack, onSubmit }) {
  const isLive = !!(me && me.real && window.api && typeof quote.id === 'number');
  const [liveProducts, setLiveProducts] = useState(null);
  useEffect(() => {
    if (isLive) {
      window.api.get('/rep/quotations/' + quote.id)
        .then(r => setLiveProducts((r.items || []).map(it => ({ id: it.id, name: it.descricao, brand: '', unit: '', cod: it.cod, ean: it.ean, qtd: it.qtd, minha: it.minha_oferta }))))
        .catch(() => setLiveProducts([]));
    }
  }, [isLive, quote.id]);
  const products = isLive ? (liveProducts || []) : ICf.PRODUCTS.filter(p => p.cat === quote.cat);

  const [tax, setTax] = useState('sem'); // padrão: sem imposto
  const [items, setItems] = useState({});
  // (re)inicializa o mapa de itens quando a lista de produtos chega
  useEffect(() => {
    setItems(prev => {
      const next = {};
      products.forEach(p => {
        if (prev[p.id]) { next[p.id] = prev[p.id]; return; }
        next[p.id] = (isLive && p.minha)
          ? { price: String(p.minha.preco || ''), validity: p.minha.validade || '', tiers: [], open: false }
          : { price: '', validity: '', tiers: [], open: false };
      });
      return next;
    });
  }, [products.length]);
  const [combos, setCombos] = useState([]);
  const [bonus, setBonus] = useState([]);
  const [tab, setTab] = useState('itens'); // itens | combos | bonus
  const [tried, setTried] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const num = (v) => parseFloat(String(v || '').replace(',', '.')) || 0;
  const upd = (pid, patch) => setItems(s => ({ ...s, [pid]: { ...(s[pid] || {}), ...patch } }));
  const filled = products.filter(p => num((items[p.id] || {}).price) > 0).length;
  const canSubmit = tax && filled > 0 && !submitting;

  const enviar = async () => {
    setTried(true);
    if (!tax || filled <= 0 || submitting) return;
    if (isLive) {
      setSubmitting(true);
      try {
        for (const p of products) {
          const st = items[p.id] || {}; const preco = num(st.price);
          if (preco <= 0) continue;
          const be = bonus.find(b => b.pid === p.id);
          const bonificacao = be && be.buy > 0 ? `${be.buy}+${be.free}` : null;
          const tiers = (st.tiers || []).filter(t => num(t.qty) > 0 && num(t.price) > 0).map(t => ({ qtd_min: num(t.qty), preco: num(t.price) }));
          await window.api.post('/rep/offers', { quotation_item_id: p.id, preco, com_imposto: tax === 'com' ? 1 : 0, validade: st.validity || null, bonificacao, tiers });
        }
      } catch (e) {}
      setSubmitting(false);
    }
    onSubmit();
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', width: '100%', maxWidth: window.__repDesktop ? 860 : 'none', margin: '0 auto' }}>
      <MHead2 title="Minha Oferta" sub={`${catR(quote.cat).name} · ${quote.items} itens`} back={onBack} />

      {/* ALERTA DE IMPOSTO — obrigatório */}
      <div style={{ margin: '0 18px 10px' }}>
        <div style={{ padding: 14, borderRadius: 16, background: tax ? T.panel : 'rgba(255,200,61,0.1)', border: `1.5px solid ${tried && !tax ? T.redBright : (tax ? T.border : 'rgba(255,200,61,0.45)')}`, boxShadow: tried && !tax ? `0 0 0 4px ${T.redBg}` : 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 9 }}>
            <Icon name="receipt" size={18} color={tax ? T.text : '#FFC83D'} />
            <div style={{ fontSize: 14, fontWeight: 800 }}>Seus preços são com ou sem imposto?</div>
          </div>
          <div style={{ display: 'flex', gap: 9 }}>
            {[['com','Com imposto'],['sem','Sem imposto']].map(([v, label]) => {
              const on = tax === v;
              return <button key={v} onClick={() => setTax(v)} style={{ flex: 1, padding: '11px', borderRadius: 12, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 13.5, border: `1.5px solid ${on ? T.red : T.borderHi}`, color: on ? '#fff' : T.text, background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : T.panel, display:'flex',alignItems:'center',justifyContent:'center',gap:6 }}>{on && <Icon name="check" size={15} color="#fff" strokeWidth={3} />}{label}</button>;
            })}
          </div>
          {tried && !tax && <div style={{ fontSize: 11.5, color: T.redBright, marginTop: 8, fontWeight: 600 }}>Selecione antes de enviar</div>}
        </div>
      </div>

      {/* sub-abas */}
      <div style={{ display: 'flex', gap: 8, padding: '0 18px 10px', flexShrink: 0 }}>
        {[['itens', 'Itens', filled],['combos','Combos', combos.length],['bonus','Bonificação', bonus.length]].map(([id, label, n]) => {
          const on = tab === id;
          return <button key={id} onClick={() => setTab(id)} style={{ flex: 1, padding: '10px', borderRadius: 12, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, border: `1px solid ${on ? T.red : T.border}`, color: on ? T.redBright : T.mute, background: on ? T.redBg : 'transparent', display:'flex',alignItems:'center',justifyContent:'center',gap:6 }}>{label} {n > 0 && <span style={{ fontSize: 11, background: on ? T.red : 'rgba(255,255,255,0.12)', color:'#fff', borderRadius: 99, padding: '1px 7px' }}>{n}</span>}</button>;
        })}
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '2px 18px 20px', display: 'flex', flexDirection: 'column', gap: 11 }}>
        {tab === 'itens'
          ? products.map(p => <ItemCard key={p.id} p={p} st={items[p.id] || { price: '', validity: '', tiers: [], open: false }} upd={(patch) => upd(p.id, patch)} num={num} />)
          : tab === 'combos'
          ? <Combos products={products} items={items} combos={combos} setCombos={setCombos} num={num} />
          : <BonusPanel products={products} bonus={bonus} setBonus={setBonus} />
        }
      </div>

      {/* barra de envio */}
      <div style={{ flexShrink: 0, padding: '12px 18px 28px', borderTop: `1px solid ${T.border}`, background: 'rgba(10,10,11,0.9)', backdropFilter: 'blur(10px)' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 10, fontSize: 12.5 }}>
          <span style={{ color: T.mute }}>{filled}/{products.length} itens · {combos.length} combos</span>
          {tax && <Pill tone={tax === 'com' ? 'mute' : 'white'}>{tax === 'com' ? 'c/ imposto' : 's/ imposto'}</Pill>}
        </div>
        <button onClick={enviar} style={{ width: '100%', padding: '15px', borderRadius: 15, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 15.5, color: '#fff', background: canSubmit ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : 'rgba(255,255,255,0.08)', boxShadow: canSubmit ? '0 8px 24px rgba(255,19,48,0.45)' : 'none', display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="send" size={18} color={canSubmit ? '#fff' : T.mute} /> {submitting ? 'Enviando…' : 'Enviar oferta completa'}</button>
      </div>
    </div>
  );
}

// ── card de item (expansível: unitário + faixas por quantidade) ─────────
function ItemCard({ p, st, upd, num }) {
  const base = num(st.price);
  const has = base > 0;
  const addTier = () => upd({ tiers: [...st.tiers, { qty: '', price: '' }], open: true });
  const setTier = (i, k, v) => { const t = st.tiers.slice(); t[i] = { ...t[i], [k]: v.replace(/[^0-9.,]/g, '') }; upd({ tiers: t }); };
  const delTier = (i) => upd({ tiers: st.tiers.filter((_, j) => j !== i) });

  return (
    <div style={{ borderRadius: 15, background: T.panel, border: `1px solid ${has ? 'rgba(0,230,140,0.35)' : T.border}`, overflow: 'hidden' }}>
      <div onClick={() => upd({ open: !st.open })} style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 14, lineHeight: 1.3 }}>{p.name}</div>
          <div style={{ fontSize: 11.5, color: T.mute2, marginTop: 2 }}>{[p.cod && ('Cód ' + p.cod), p.ean && ('EAN ' + p.ean), p.brand].filter(Boolean).join(' · ') || p.unit}</div>
        </div>
        {has
          ? <div style={{ textAlign:'right' }}><div style={{ fontWeight: 800, fontVariantNumeric:'tabular-nums', fontSize: 14, color: T.green }}>R$ {ICf.fmt(base)}</div>{st.tiers.filter(t=>num(t.price)>0).length>0 && <div style={{ fontSize: 10.5, color: T.mute }}>+{st.tiers.filter(t=>num(t.price)>0).length} faixa(s)</div>}</div>
          : <span style={{ fontSize: 12, color: T.mute2 }}>tocar p/ preço</span>}
        <Icon name="chevron" size={16} color={T.mute} style={{ transform: st.open ? 'rotate(90deg)' : 'none', transition:'transform .2s' }} />
      </div>

      {st.open && (
        <div style={{ padding: '0 14px 14px', borderTop: `1px solid ${T.border}` }}>
          <div style={{ display: 'flex', gap: 9, marginTop: 12 }}>
            <div style={{ flex: 1.1 }}>
              <label style={lblS()}>Preço unitário (R$)</label>
              <div style={{ position: 'relative' }}>
                <span style={{ position:'absolute', left: 12, top: 12, color: T.mute2, fontSize: 14, fontWeight: 600 }}>R$</span>
                <input inputMode="decimal" value={st.price} onChange={e => upd({ price: e.target.value.replace(/[^0-9.,]/g, '') })} placeholder="0,00" style={{ ...inS(), paddingLeft: 38, fontWeight: 700 }} />
              </div>
            </div>
            <div style={{ flex: 1 }}>
              <label style={lblS()}>Validade</label>
              <input value={st.validity} onChange={e => upd({ validity: e.target.value })} placeholder="MM/AAAA" style={inS()} />
            </div>
          </div>

          {/* faixas por quantidade */}
          <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <label style={{ ...lblS(), marginBottom: 0, display:'flex',alignItems:'center',gap:6 }}><Icon name="tag" size={13} color={T.mute}/> Preço por quantidade</label>
            <button onClick={addTier} style={{ fontSize: 12, fontWeight: 700, color: T.redBright, background: 'none', border: 'none', cursor: 'pointer', fontFamily:'inherit', display:'flex',alignItems:'center',gap:3 }}><Icon name="plus" size={13} color={T.redBright} strokeWidth={2.4}/> faixa</button>
          </div>
          {st.tiers.length === 0 && <div style={{ fontSize: 11.5, color: T.mute2, marginTop: 6 }}>Ofereça preço melhor para volume maior (ex: a partir de 50un).</div>}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginTop: 8 }}>
            {st.tiers.map((t, i) => {
              const tp = num(t.price);
              const pct = base > 0 && tp > 0 ? ((tp - base) / base) * 100 : null;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <div style={{ display:'flex', alignItems:'center', gap: 5, flex: 0.8 }}>
                    <span style={{ fontSize: 11.5, color: T.mute }}>≥</span>
                    <input inputMode="numeric" value={t.qty} onChange={e => setTier(i, 'qty', e.target.value)} placeholder="qtd" style={{ ...inS(), padding: '9px 8px', textAlign:'center' }} />
                    <span style={{ fontSize: 11.5, color: T.mute }}>un</span>
                  </div>
                  <div style={{ position: 'relative', flex: 1 }}>
                    <span style={{ position:'absolute', left: 9, top: 10, color: T.mute2, fontSize: 12.5 }}>R$</span>
                    <input inputMode="decimal" value={t.price} onChange={e => setTier(i, 'price', e.target.value)} placeholder="0,00" style={{ ...inS(), padding: '9px 8px 9px 30px', fontWeight: 700 }} />
                  </div>
                  <div style={{ width: 56, textAlign:'right' }}>{pct != null && <Delta pct={pct} size={11} />}</div>
                  <button onClick={() => delTier(i)} style={{ background:'none', border:'none', cursor:'pointer', padding: 2 }}><Icon name="x" size={15} color={T.mute2}/></button>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

// ── combos / ofertas casadas ────────────────────────────────────────────
function Combos({ products, items, combos, setCombos, num }) {
  const [building, setBuilding] = useState(false);
  const [name, setName] = useState('');
  const [sel, setSel] = useState([]);
  const [price, setPrice] = useState('');

  const baseSum = sel.reduce((s, pid) => s + num(items[pid].price), 0);
  const cp = num(price);
  const pct = baseSum > 0 && cp > 0 ? ((cp - baseSum) / baseSum) * 100 : null;
  const toggle = (pid) => setSel(s => s.includes(pid) ? s.filter(x => x !== pid) : [...s, pid]);
  const save = () => { if (sel.length >= 2 && cp > 0) { setCombos(c => [...c, { id: Date.now(), name: name || 'Combo', productIds: sel, price: cp }]); setBuilding(false); setName(''); setSel([]); setPrice(''); } };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
      <div style={{ display:'flex', alignItems:'center', gap: 9, padding: '4px 2px' }}>
        <Icon name="bolt" size={17} color={T.redBright} />
        <div style={{ fontSize: 13, color: T.mute, lineHeight: 1.4 }}>Crie <b style={{color:T.text}}>combos</b> (2+ itens juntos) com preço fechado. O % de economia é calculado sozinho.</div>
      </div>

      {combos.map(c => {
        const bs = c.productIds.reduce((s, pid) => s + num(items[pid].price), 0);
        const p = bs > 0 ? ((c.price - bs) / bs) * 100 : null;
        return (
          <div key={c.id} style={{ padding: 14, borderRadius: 15, background: T.panel, border: `1px solid ${T.border}` }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <div style={{ fontWeight: 700, fontSize: 14, display:'flex',alignItems:'center',gap:7 }}><Icon name="bolt" size={15} color={T.redBright}/> {c.name}</div>
              <button onClick={() => setCombos(x => x.filter(k => k.id !== c.id))} style={{ background:'none',border:'none',cursor:'pointer' }}><Icon name="x" size={16} color={T.mute2}/></button>
            </div>
            <div style={{ fontSize: 12, color: T.mute, marginTop: 6 }}>{c.productIds.map(pid => products.find(p => p.id === pid)?.name.split(' ').slice(0,2).join(' ')).join(' + ')}</div>
            <div style={{ display:'flex', alignItems:'center', gap: 10, marginTop: 10 }}>
              <span style={{ fontWeight: 800, fontSize: 16, fontVariantNumeric:'tabular-nums' }}>R$ {ICf.fmt(c.price)}</span>
              {p != null && <Delta pct={p} />}
            </div>
          </div>
        );
      })}

      {building ? (
        <div style={{ padding: 14, borderRadius: 15, background: T.panel, border: `1.5px solid ${T.red}` }}>
          <label style={lblS()}>Nome do combo</label>
          <input value={name} onChange={e => setName(e.target.value)} placeholder="Ex: Kit Treino" style={inS()} />
          <label style={{ ...lblS(), marginTop: 12 }}>Itens do combo (toque p/ incluir)</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {products.map(p => { const on = sel.includes(p.id); return (
              <button key={p.id} onClick={() => toggle(p.id)} style={{ padding: '7px 11px', borderRadius: 99, cursor:'pointer', fontFamily:'inherit', fontSize: 12, fontWeight: 600, border: `1px solid ${on ? T.red : T.border}`, color: on ? T.redBright : T.mute, background: on ? T.redBg : 'transparent' }}>{p.name.split(' ').slice(0,2).join(' ')}</button>
            ); })}
          </div>
          {baseSum > 0 && <div style={{ fontSize: 12, color: T.mute, marginTop: 10 }}>Soma dos unitários: <b style={{color:T.text}}>R$ {ICf.fmt(baseSum)}</b></div>}
          <div style={{ display: 'flex', gap: 9, marginTop: 10, alignItems:'flex-end' }}>
            <div style={{ flex: 1 }}>
              <label style={lblS()}>Preço do combo (R$)</label>
              <div style={{ position:'relative' }}><span style={{ position:'absolute', left: 12, top: 12, color: T.mute2, fontSize: 14 }}>R$</span><input inputMode="decimal" value={price} onChange={e => setPrice(e.target.value.replace(/[^0-9.,]/g,''))} placeholder="0,00" style={{ ...inS(), paddingLeft: 38, fontWeight: 700 }} /></div>
            </div>
            {pct != null && <div style={{ paddingBottom: 11 }}><Delta pct={pct} /></div>}
          </div>
          <div style={{ display: 'flex', gap: 9, marginTop: 12 }}>
            <button onClick={() => setBuilding(false)} style={{ flex: 1, padding: '11px', borderRadius: 12, border: `1px solid ${T.border}`, background:'transparent', color: T.mute, fontWeight: 600, fontFamily:'inherit', cursor:'pointer' }}>Cancelar</button>
            <button onClick={save} disabled={sel.length < 2 || cp <= 0} style={{ flex: 1.4, padding: '11px', borderRadius: 12, border: 'none', cursor: sel.length>=2&&cp>0?'pointer':'not-allowed', fontWeight: 800, fontFamily:'inherit', color:'#fff', opacity: sel.length>=2&&cp>0?1:0.4, background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` }}>Salvar combo</button>
          </div>
        </div>
      ) : (
        <button onClick={() => setBuilding(true)} style={{ padding: '14px', borderRadius: 15, border: `1.5px dashed ${T.borderHi}`, background: 'transparent', color: T.text, fontWeight: 700, fontFamily: 'inherit', fontSize: 14, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="plus" size={18} color={T.redBright} strokeWidth={2.4}/> Criar combo</button>
      )}
    </div>
  );
}

const lblS = () => ({ display: 'block', fontSize: 11, color: T.mute, fontWeight: 600, marginBottom: 5 });
const inS = () => ({ width: '100%', boxSizing: 'border-box', padding: '11px 12px', borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' });

// ── BONIFICAÇÃO (compre X leve Y, desconto extra, à vista) ──────────────
function BonusPanel({ products, bonus, setBonus }) {
  const [building, setBuilding] = useState(false);
  const [pid, setPid] = useState('');
  const [buy, setBuy] = useState('');
  const [free, setFree] = useState('');
  const [disc, setDisc] = useState('');
  const [obs, setObs] = useState('');
  const n = (v) => parseInt(String(v).replace(/\D/g, '')) || 0;
  const save = () => { if (pid && (n(buy) > 0 || n(disc) > 0)) { setBonus(b => [...b, { id: Date.now(), pid, buy: n(buy), free: n(free), disc: n(disc), obs }]); setBuilding(false); setPid(''); setBuy(''); setFree(''); setDisc(''); setObs(''); } };
  const lbl = { display: 'block', fontSize: 11, color: T.mute, fontWeight: 600, marginBottom: 5 };
  const inp = { width: '100%', boxSizing: 'border-box', padding: '11px 12px', borderRadius: 11, border: `1px solid ${T.border}`, background: 'rgba(0,0,0,0.25)', color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '4px 2px' }}>
        <Icon name="tag" size={17} color={T.green} />
        <div style={{ fontSize: 13, color: T.mute, lineHeight: 1.4 }}>Ofereça <b style={{ color: T.text }}>bonificação</b> (ex: 10+2 = compre 10 leve 12) ou <b style={{ color: T.text }}>desconto extra</b> para fechar mais.</div>
      </div>

      {bonus.map(b => { const p = products.find(x => x.id === b.pid); return (
        <div key={b.id} style={{ padding: 14, borderRadius: 15, background: T.greenBg, border: `1px solid rgba(0,230,140,0.3)` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontWeight: 700, fontSize: 13.5 }}>{p ? p.name : 'Produto'}</span>
            <button onClick={() => setBonus(x => x.filter(k => k.id !== b.id))} style={{ background: 'none', border: 'none', cursor: 'pointer' }}><Icon name="x" size={16} color={T.mute2} /></button>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
            {b.buy > 0 && <Pill tone="green"><Icon name="check" size={11} color={T.green} strokeWidth={3} />{b.buy}+{b.free} (leve {b.buy + b.free})</Pill>}
            {b.disc > 0 && <Pill tone="green">{b.disc}% desconto extra</Pill>}
          </div>
          {b.obs && <div style={{ fontSize: 11.5, color: T.mute, marginTop: 7 }}>{b.obs}</div>}
        </div>
      ); })}

      {building ? (
        <div style={{ padding: 14, borderRadius: 15, background: T.panel, border: `1.5px solid ${T.green}` }}>
          <label style={lbl}>Produto</label>
          <select value={pid} onChange={e => setPid(e.target.value)} style={{ ...inp, marginBottom: 12 }}>
            <option value="">Selecione…</option>
            {products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <label style={lbl}>Bonificação (compre X, leve grátis Y)</label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <input inputMode="numeric" value={buy} onChange={e => setBuy(e.target.value)} placeholder="compre" style={{ ...inp, textAlign: 'center' }} />
            <span style={{ fontWeight: 800, color: T.green }}>+</span>
            <input inputMode="numeric" value={free} onChange={e => setFree(e.target.value)} placeholder="grátis" style={{ ...inp, textAlign: 'center' }} />
            {n(buy) > 0 && <span style={{ fontSize: 12, color: T.green, fontWeight: 700, whiteSpace: 'nowrap' }}>leve {n(buy) + n(free)}</span>}
          </div>
          <label style={lbl}>Desconto extra à vista (%)</label>
          <input inputMode="numeric" value={disc} onChange={e => setDisc(e.target.value)} placeholder="ex: 5" style={{ ...inp, marginBottom: 12 }} />
          <label style={lbl}>Observação (opcional)</label>
          <input value={obs} onChange={e => setObs(e.target.value)} placeholder="ex: válido p/ pedido acima de R$ 2.000" style={{ ...inp, marginBottom: 12 }} />
          <div style={{ display: 'flex', gap: 9 }}>
            <button onClick={() => setBuilding(false)} style={{ flex: 1, padding: '11px', borderRadius: 12, border: `1px solid ${T.border}`, background: 'transparent', color: T.mute, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer' }}>Cancelar</button>
            <button onClick={save} disabled={!pid || (n(buy) <= 0 && n(disc) <= 0)} style={{ flex: 1.4, padding: '11px', borderRadius: 12, border: 'none', cursor: pid && (n(buy) > 0 || n(disc) > 0) ? 'pointer' : 'not-allowed', fontWeight: 800, fontFamily: 'inherit', color: '#fff', opacity: pid && (n(buy) > 0 || n(disc) > 0) ? 1 : 0.4, background: `linear-gradient(135deg, ${T.green}, #0AA968)` }}>Salvar bonificação</button>
          </div>
        </div>
      ) : (
        <button onClick={() => setBuilding(true)} style={{ padding: '14px', borderRadius: 15, border: `1.5px dashed ${T.borderHi}`, background: 'transparent', color: T.text, fontWeight: 700, fontFamily: 'inherit', fontSize: 14, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="plus" size={18} color={T.green} strokeWidth={2.4} /> Adicionar bonificação</button>
      )}
    </div>
  );
}

// ── CONFIRMAÇÃO ────────────────────────────────────────────────────────
function RepDone({ quote, onBack }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '40px 30px', textAlign: 'center' }}>
      <div style={{ width: 80, height: 80, borderRadius: 999, background: T.greenBg, border: `1.5px solid rgba(0,230,140,0.4)`, display:'flex',alignItems:'center',justifyContent:'center', marginBottom: 22 }}><Icon name="check" size={42} color={T.green} strokeWidth={2.4} /></div>
      <div style={{ fontSize: 24, fontWeight: 800, fontFamily: 'var(--display)' }}>Oferta enviada!</div>
      <div style={{ color: T.mute, fontSize: 14.5, marginTop: 10, lineHeight: 1.5 }}>Felipe recebeu seus preços, faixas por quantidade e combos de <b style={{color:T.text}}>{(catR(quote.cat) || { name: quote.categoria || 'sua categoria' }).name}</b>. Aviso entregue na central do sistema.</div>
      <button onClick={onBack} style={{ marginTop: 28, padding: '14px 30px', borderRadius: 14, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 15, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 8px 24px rgba(255,19,48,0.45)' }}>Voltar ao portal</button>
    </div>
  );
}

window.RepPart2 = { RepFill, RepDone };
