// ── Inova Cotação — Comprador: Cotações, Grade, Base ────────────────────
// Topbar (função global de buyer-1), T, Icon, Glass, Pill, Delta já são globais
const ICb = window.IC;
const cat2 = window.BuyerParts1.catById, rep2 = window.BuyerParts1.repById;

// ═══ LISTA DE COTAÇÕES ═══════════════════════════════════════════════════
function Quotes({ onOpenGrid }) {
  const [showNew, setShowNew] = useState(false);
  const [detail, setDetail] = useState(null);
  const [toast, setToast] = useState(null);
  const [, setTick] = useState(0);
  useEffect(() => window.ICLive ? window.ICLive.subscribe(() => setTick(t => t + 1)) : undefined, []);
  const importRef = useRef();
  const fireToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2600); };
  const statusTone = { aberta: 'yellow', finalizada: 'green', rascunho: 'mute' };
  const statusLabel = { aberta: 'Aberta', finalizada: 'Finalizada', rascunho: 'Rascunho' };
  return (
    <div>
      <Topbar title="Gestão de Cotações" sub="Crie e acompanhe cotações por categoria"
        action={<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <GhostAct icon="clock" title="Agendar recorrente">Agendar</GhostAct>
          <GhostAct icon="receipt" title="Importar cotação (CSV/Excel)" onClick={() => { importRef.current && importRef.current.click(); }}>Importar</GhostAct>
          <GhostAct icon="send" title="Exportar cotações (CSV/PDF)" onClick={() => fireToast('Cotações exportadas (CSV) ✓')}>Exportar</GhostAct>
          <NewBtn onClick={() => setShowNew(true)} />
          <input ref={importRef} type="file" accept=".csv,.xls,.xlsx,.xml" style={{ display: 'none' }} onChange={e => { if (e.target.files[0]) fireToast('Planilha "' + e.target.files[0].name + '" importada ✓'); e.target.value = ''; }} />
        </div>} />
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        {[['Todas', true],['Curva A', false],['Abertas', false],['Aguardando resposta', false],['Ruptura total', false],['Recorrentes', false]].map(([l, on]) => (
          <button key={l} style={{ padding: '7px 13px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, border: `1px solid ${on ? T.red : T.border}`, color: on ? T.redBright : T.mute, background: on ? T.redBg : 'transparent' }}>{l}</button>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        {ICb.QUOTES.map(q => {
          const c = cat2(q.cat);
          const prog = q.reps.length ? Math.round(q.responded / q.reps.length * 100) : 0;
          return (
            <Glass key={q.id} hover onClick={() => q.status !== 'rascunho' && onOpenGrid(q)} pad={18} className="qcard">
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                  <div style={{ width: 42, height: 42, 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={21} color={T.redBright} />
                  </div>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 15, letterSpacing: -0.2 }}>{q.title}</div>
                    <div style={{ fontSize: 12.5, color: T.mute, marginTop: 2 }}>{c.name} · {q.items} itens</div>
                  </div>
                </div>
                <Pill tone={statusTone[q.status]}>{statusLabel[q.status]}</Pill>
              </div>
              <button onClick={(e) => { e.stopPropagation(); setDetail(q); }} title="Ver detalhes" style={{ position: 'absolute', top: 16, right: 16, width: 30, height: 30, borderRadius: 8, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', display: 'none', alignItems: 'center', justifyContent: 'center' }} className="qdetail"><Icon name="list" size={15} color={T.mute} /></button>
              <div style={{ display: 'flex', gap: 22, marginTop: 16, fontSize: 12.5 }}>
                <div><div style={{ color: T.mute2, marginBottom: 2 }}>Criada</div><div style={{ fontWeight: 600 }}>{q.created}</div></div>
                <div><div style={{ color: T.mute2, marginBottom: 2 }}>Prazo</div><div style={{ fontWeight: 600 }}>{q.deadline}</div></div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: T.mute2, marginBottom: 2 }}>Respostas {q.responded}/{q.reps.length}</div>
                  <div style={{ height: 6, borderRadius: 99, background: T.panelHi, overflow: 'hidden', marginTop: 6 }}>
                    <div style={{ width: prog + '%', height: '100%', background: `linear-gradient(90deg, ${T.redBright}, ${T.redDeep})`, borderRadius: 99 }} />
                  </div>
                </div>
              </div>
              <div style={{ display: 'flex', marginTop: 14, alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex' }}>
                  {q.reps.map((rid, i) => { const r = rep2(rid); return (
                    <div key={rid} title={r.name} style={{ width: 26, height: 26, borderRadius: 999, background: r.color, border: `2px solid ${T.bg}`, marginLeft: i ? -8 : 0, display:'flex',alignItems:'center',justifyContent:'center', fontSize: 11, fontWeight: 800, color:'#fff' }}>{r.name[0]}</div>
                  ); })}
                  {!q.reps.length && <span style={{ fontSize: 12.5, color: T.mute2 }}>Sem reps selecionados</span>}
                </div>
                {q.status !== 'rascunho'
                  ? <span style={{ fontSize: 12.5, fontWeight: 700, color: T.redBright, display:'flex',alignItems:'center',gap:4 }}>Ver grade <Icon name="chevron" size={14} color={T.redBright}/></span>
                  : <span style={{ fontSize: 12.5, color: T.mute2 }}>Continuar edição</span>}
              </div>
            </Glass>
          );
        })}
      </div>
      {showNew && <NewQuoteModal onClose={() => setShowNew(false)} />}
      {detail && <QuoteDetail quote={detail} onClose={() => setDetail(null)} onGrid={() => { const q = detail; setDetail(null); onOpenGrid(q); }} />}
      {toast && <div style={{ position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 300, display: 'flex', alignItems: 'center', gap: 9, padding: '13px 20px', borderRadius: 13, background: T.surface, border: `1px solid ${T.borderHi}`, boxShadow: '0 16px 50px rgba(0,0,0,0.5)', fontWeight: 700, fontSize: 14, animation: 'icfade .25s ease both' }}><Icon name="check" size={17} color={T.green} strokeWidth={2.6} /> {toast}</div>}
    </div>
  );
}

function GhostAct({ icon, title, children, onClick }) {
  return <button onClick={onClick} title={title} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '11px 14px', borderRadius: 12, border: `1px solid ${T.border}`, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, fontSize: 13, color: T.mute, background: T.panel }}><Icon name={icon} size={15} color={T.mute} /> {children}</button>;
}
function NewBtn({ onClick }) {
  return (
    <button onClick={onClick} 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} /> Nova Cotação</button>
  );
}

// ═══ MODAL NOVA COTAÇÃO (categoria → produtos → disparar) ════════════════
function NewQuoteModal({ onClose }) {
  const [step, setStep] = useState(1);
  const [cat, setCat] = useState(null);
  const [titulo, setTitulo] = useState('');
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [searching, setSearching] = useState(false);
  const [items, setItems] = useState({}); // cod -> {cod, nome, ean, custo, qtd}
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [erro, setErro] = useState('');
  const eligibleReps = cat ? ICb.REPS.filter(r => r.cats.includes(cat)) : [];
  const itemList = Object.values(items);

  // busca no catálogo real (debounce)
  useEffect(() => {
    if (step !== 2 || query.trim().length < 2) { setResults([]); return; }
    setSearching(true);
    const id = setTimeout(() => {
      window.api.get('/products?q=' + encodeURIComponent(query.trim()) + '&pageSize=15')
        .then(r => setResults(r.items || [])).catch(() => setResults([])).then(() => setSearching(false));
    }, 280);
    return () => clearTimeout(id);
  }, [query, step]);

  const add = (p) => setItems(s => s[p.cod] ? s : { ...s, [p.cod]: { cod: p.cod, nome: p.nome, ean: p.ean, custo: p.custo, qtd: 1 } });
  const setQty = (cod, q) => setItems(s => ({ ...s, [cod]: { ...s[cod], qtd: Math.max(1, parseInt(String(q).replace(/\D/g, '')) || 1) } }));
  const rm = (cod) => setItems(s => { const n = { ...s }; delete n[cod]; return n; });

  // Colar planilha do Excel: detecta código/EAN + quantidade por linha
  const [pasteMsg, setPasteMsg] = useState('');
  const parsePaste = async (text) => {
    if (!text || !text.trim()) return;
    const linhas = text.split(/\r?\n/).map(r => r.split('\t').map(c => c.trim())).filter(r => r.some(c => c));
    const parsed = [];
    for (const cells of linhas) {
      const nums = cells.map(c => c.replace(/\s/g, ''));
      let code = null, qty = 1;
      for (const c of nums) { if (/^\d{6,14}$/.test(c)) { code = c; break; } } // EAN/código
      for (const c of nums) { if (c !== code && /^\d{1,5}$/.test(c)) { qty = parseInt(c, 10) || 1; break; } } // qtd
      if (code) parsed.push({ code, qty });
    }
    if (!parsed.length) { setPasteMsg('Não detectei código/EAN nas linhas coladas.'); return; }
    setPasteMsg('processando…');
    try {
      const r = await window.api.post('/products/lookup', { codes: parsed.map(p => p.code) });
      let added = 0, miss = 0;
      setItems(s => {
        const n = { ...s };
        r.items.forEach((it, i) => {
          if (it.product) { const q = parsed[i].qty; const prev = n[it.product.cod] ? n[it.product.cod].qtd : 0; n[it.product.cod] = { cod: it.product.cod, nome: it.product.nome, ean: it.product.ean, custo: it.product.custo, qtd: prev + q }; added++; }
          else miss++;
        });
        return n;
      });
      setPasteMsg(`${added} produto(s) adicionado(s)${miss ? ' · ' + miss + ' não encontrado(s)' : ''}.`);
    } catch (e) { setPasteMsg('Falha ao processar.'); }
  };

  const dispararReal = async () => {
    if (busy) return; setBusy(true); setErro('');
    try {
      const tit = titulo.trim() || ('Cotação ' + cat2(cat).name + ' — ' + new Date().toLocaleDateString('pt-BR'));
      const its = itemList.map(it => ({ cod: it.cod, qtd: it.qtd }));
      const q = await window.api.post('/quotations', { titulo: tit, category_id: cat, items: its });
      await window.api.post('/quotations/' + q.id + '/dispatch', {});
      if (window.ICLive) await window.ICLive.reloadQuotes();
      setSent(true);
    } catch (e) { setErro(e.data && e.data.error ? e.data.error : (e.message || 'falha ao disparar')); }
    setBusy(false);
  };
  const inS = { width: '100%', boxSizing: 'border-box', padding: '11px 13px', borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' };

  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: 100, padding: 30 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 580, maxHeight: '88vh', display: 'flex', flexDirection: 'column', borderRadius: 22, background: T.surface, border: `1px solid ${T.borderHi}`, boxShadow: '0 30px 90px rgba(0,0,0,0.7)' }}>
        <div style={{ padding: '20px 24px', borderBottom: `1px solid ${T.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
          <div>
            <div style={{ fontWeight: 800, fontSize: 18, fontFamily: 'var(--display)' }}>Nova Cotação</div>
            <div style={{ fontSize: 12.5, color: T.mute }}>Passo {sent ? 3 : step} de 3 · {step === 1 ? 'categoria' : step === 2 ? 'produtos' : 'disparo'}</div>
          </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>

        {sent ? (
          <div style={{ padding: 40, textAlign: 'center' }}>
            <div style={{ width: 64, height: 64, borderRadius: 999, background: T.greenBg, border: `1px solid rgba(0,230,140,0.4)`, display:'flex',alignItems:'center',justifyContent:'center', margin: '0 auto 18px' }}><Icon name="check" size={32} color={T.green} strokeWidth={2.4} /></div>
            <div style={{ fontWeight: 800, fontSize: 20, fontFamily: 'var(--display)' }}>Cotação disparada!</div>
            <div style={{ color: T.mute, fontSize: 14, marginTop: 8, maxWidth: 390, marginInline: 'auto' }}>
              {itemList.length} produto(s) enviados a {eligibleReps.length} representante(s) de <b style={{color:T.text}}>{cat2(cat).name}</b>. As respostas aparecem na Grade Comparativa.
            </div>
            <div><button onClick={onClose} style={{ marginTop: 22, padding: '11px 26px', borderRadius: 12, border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` }}>Concluir</button></div>
          </div>
        ) : step === 1 ? (
          <div style={{ padding: 24, overflow: 'auto' }}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 4 }}>1. Categoria & título</div>
            <div style={{ fontSize: 12.5, color: T.mute, marginBottom: 16 }}>Só os reps dessa categoria recebem a cotação.</div>
            <input value={titulo} onChange={e => setTitulo(e.target.value)} placeholder="Título (opcional) — ex: Reposição Junho" style={{ ...inS, marginBottom: 14 }} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {ICb.CATEGORIES.map(c => {
                const on = cat === c.id;
                return (
                  <button key={c.id} onClick={() => setCat(c.id)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 14, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', background: on ? T.redBg : T.panel, border: `1.5px solid ${on ? T.red : T.border}`, color: T.text }}>
                    <div style={{ width: 38, height: 38, borderRadius: 10, background: on ? 'rgba(255,19,48,0.2)' : T.panelHi, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name={c.icon} size={20} color={on ? T.redBright : T.mute} /></div>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>{c.name}</div>
                  </button>
                );
              })}
            </div>
            <ModalFooter right={<PrimaryBtn disabled={!cat} onClick={() => setStep(2)}>Escolher produtos</PrimaryBtn>} />
          </div>
        ) : step === 2 ? (
          <>
          <div style={{ padding: '20px 24px 12px', flexShrink: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 8 }}>2. Produtos para cotar <span style={{ color: T.mute, fontWeight: 600 }}>· {itemList.length} selecionado(s)</span></div>
            <div style={{ position: 'relative' }}>
              <Icon name="search" size={16} color={T.mute} style={{ position: 'absolute', left: 13, top: 13 }} />
              <input autoFocus value={query} onChange={e => setQuery(e.target.value)} placeholder="Buscar no catálogo (nome, código ou EAN)…" style={{ ...inS, paddingLeft: 40 }} />
            </div>
            <textarea onPaste={e => { const t = e.clipboardData.getData('text'); if (t && t.includes('\t') || (t && t.split(/\r?\n/).length > 1)) { e.preventDefault(); parsePaste(t); } }}
              placeholder="📋 ou cole uma planilha do Excel aqui (Ctrl+V) — detecta EAN/código + quantidade"
              style={{ width: '100%', boxSizing: 'border-box', marginTop: 8, height: 40, resize: 'none', padding: '10px 12px', borderRadius: 10, border: `1px dashed ${T.borderHi}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 12.5, outline: 'none' }} />
            {pasteMsg && <div style={{ marginTop: 6, fontSize: 12, fontWeight: 600, color: (pasteMsg.includes('não') || pasteMsg.includes('Falha')) ? T.redBright : pasteMsg === 'processando…' ? T.mute : T.green }}>{pasteMsg}</div>}
          </div>
          <div style={{ flex: 1, overflow: 'auto', padding: '0 24px' }}>
            {/* resultados da busca */}
            {query.trim().length >= 2 && (
              <div style={{ marginBottom: 14 }}>
                {searching && <div style={{ fontSize: 12.5, color: T.mute2, padding: '6px 0' }}>buscando…</div>}
                {!searching && !results.length && <div style={{ fontSize: 12.5, color: T.mute2, padding: '6px 0' }}>Nenhum produto encontrado.</div>}
                {results.map(p => (
                  <div key={p.cod} onClick={() => add(p)} className="erp-row" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 10, cursor: 'pointer', border: `1px solid ${items[p.cod] ? 'rgba(0,230,140,0.4)' : T.border}`, marginBottom: 6, background: items[p.cod] ? T.greenBg : 'transparent' }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.nome}</div>
                      <div style={{ fontSize: 11, color: T.mute2 }}>Cód {p.cod}{p.ean ? ' · EAN ' + p.ean : ''} · custo R$ {ICb.fmt(p.custo)}</div>
                    </div>
                    <Icon name={items[p.cod] ? 'check' : 'plus'} size={16} color={items[p.cod] ? T.green : T.redBright} strokeWidth={2.4} />
                  </div>
                ))}
              </div>
            )}
            {/* itens selecionados */}
            {itemList.length > 0 && (
              <div>
                <div style={{ fontSize: 11.5, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 8 }}>Itens da cotação</div>
                {itemList.map(it => (
                  <div key={it.cod} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderRadius: 10, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 6 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.nome}</div>
                      <div style={{ fontSize: 11, color: T.mute2 }}>Cód {it.cod}{it.ean ? ' · EAN ' + it.ean : ''}</div>
                    </div>
                    <input value={it.qtd} onChange={e => setQty(it.cod, e.target.value)} title="Quantidade" style={{ width: 60, textAlign: 'center', padding: '7px 4px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.bg, color: T.text, fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 700, outline: 'none' }} />
                    <span style={{ fontSize: 11, color: T.mute2 }}>un</span>
                    <button onClick={() => rm(it.cod)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 3 }}><Icon name="x" size={15} color={T.mute2} /></button>
                  </div>
                ))}
              </div>
            )}
            {!itemList.length && query.trim().length < 2 && <div style={{ textAlign: 'center', color: T.mute2, fontSize: 13, padding: '30px 0' }}>Busque e toque nos produtos para adicionar à cotação.</div>}
          </div>
          <div style={{ padding: '12px 24px 20px', flexShrink: 0, borderTop: `1px solid ${T.border}` }}>
            <ModalFooter left={<GhostBtn onClick={() => setStep(1)}>Voltar</GhostBtn>} right={<PrimaryBtn disabled={!itemList.length} onClick={() => setStep(3)}>Revisar disparo</PrimaryBtn>} />
          </div>
          </>
        ) : (
          <div style={{ padding: 24, overflow: 'auto' }}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 4 }}>3. Disparar para {cat2(cat).name}</div>
            <div style={{ fontSize: 12.5, color: T.mute, marginBottom: 16 }}>{itemList.length} produto(s) · {eligibleReps.length} representante(s) recebem o aviso no sistema.</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {eligibleReps.map(r => (
                <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 12, background: T.panel, border: `1px solid ${T.border}` }}>
                  <div style={{ width: 34, height: 34, borderRadius: 999, 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 }}>{r.name}</div>
                    <div style={{ fontSize: 12, color: T.mute }}>{r.contact}</div>
                  </div>
                  <Pill tone={r.tax === 'com' ? 'mute' : 'white'}>{r.tax === 'com' ? 'c/ imposto' : 's/ imposto'}</Pill>
                </div>
              ))}
              {!eligibleReps.length && <div style={{ fontSize: 12.5, color: T.redBright }}>Nenhum representante ativo nessa categoria.</div>}
            </div>
            {erro && <div style={{ marginTop: 14, padding: '10px 14px', borderRadius: 11, background: T.redBg, border: `1px solid rgba(255,19,48,0.3)`, color: T.redBright, fontSize: 13 }}>{erro}</div>}
            <ModalFooter left={<GhostBtn onClick={() => setStep(2)}>Voltar</GhostBtn>} right={<PrimaryBtn disabled={busy || !eligibleReps.length} onClick={dispararReal}><Icon name="bell" size={17} color="#fff" /> {busy ? 'Disparando…' : `Disparar p/ ${eligibleReps.length} reps`}</PrimaryBtn>} />
          </div>
        )}
      </div>
    </div>
  );
}
function ModalFooter({ left, right }) { return <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 22 }}>{left || <span/>}{right}</div>; }
function PrimaryBtn({ children, onClick, disabled }) {
  return <button onClick={onClick} disabled={disabled} style={{ display:'flex',alignItems:'center',gap:8, padding: '11px 20px', borderRadius: 12, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 14, color: '#fff', opacity: disabled ? 0.4 : 1, background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: disabled ? 'none' : '0 6px 18px rgba(255,19,48,0.4)' }}>{children}</button>;
}
function GhostBtn({ children, onClick }) {
  return <button onClick={onClick} style={{ padding: '11px 20px', borderRadius: 12, border: `1px solid ${T.border}`, cursor: 'pointer', fontWeight: 600, fontFamily: 'inherit', fontSize: 14, color: T.mute, background: 'transparent' }}>{children}</button>;
}

// ═══ DETALHE DA COTAÇÃO (modal — casca) ══════════════════════════════════
function QuoteDetail({ quote: q, onClose, onGrid }) {
  const c = cat2(q.cat);
  const products = ICb.PRODUCTS.filter(p => p.cat === q.cat).slice(0, q.items);
  const prob = q.status === 'finalizada' ? 100 : q.reps.length ? Math.min(96, 40 + q.responded / q.reps.length * 55) : 12;
  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: 560, maxHeight: '88vh', overflow: 'auto', borderRadius: 22, background: T.surface, border: `1px solid ${T.borderHi}`, boxShadow: '0 30px 90px rgba(0,0,0,0.6)' }}>
        <div style={{ padding: '20px 24px', borderBottom: `1px solid ${T.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 42, height: 42, 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={21} color={T.redBright} /></div>
            <div><div style={{ fontWeight: 800, fontSize: 17, fontFamily: 'var(--display)' }}>{q.title}</div><div style={{ fontSize: 12.5, color: T.mute }}>{c.name} · criada {q.created}</div></div>
          </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>
        <div style={{ padding: 24 }}>
          {/* probabilidade preditiva + prazo */}
          <div style={{ display: 'flex', gap: 12, marginBottom: 18 }}>
            <div style={{ flex: 1, padding: 14, borderRadius: 13, background: T.panel, border: `1px solid ${T.border}` }}>
              <div style={{ fontSize: 11.5, color: T.mute2 }}>Probabilidade de fechamento</div>
              <div style={{ fontWeight: 800, fontSize: 20, fontFamily: 'var(--display)', color: prob > 70 ? T.green : prob > 40 ? T.yellow : T.redBright, marginTop: 2 }}>{Math.round(prob)}%</div>
              <div style={{ height: 5, borderRadius: 99, background: 'rgba(128,128,128,0.18)', overflow: 'hidden', marginTop: 6 }}><div style={{ width: prob + '%', height: '100%', background: prob > 70 ? T.green : prob > 40 ? T.yellow : T.redBright }} /></div>
            </div>
            <div style={{ flex: 1, padding: 14, borderRadius: 13, background: T.panel, border: `1px solid ${T.border}` }}>
              <div style={{ fontSize: 11.5, color: T.mute2 }}>Prazo de resposta</div>
              <div style={{ fontWeight: 800, fontSize: 20, fontFamily: 'var(--display)', marginTop: 2 }}>{q.deadline}</div>
              <div style={{ fontSize: 11, color: T.mute, marginTop: 4 }}>Reps respondem em ~4h</div>
            </div>
          </div>
          {/* reps */}
          <div style={{ fontSize: 12.5, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 9 }}>Representantes ({q.reps.length})</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginBottom: 18 }}>
            {q.reps.map((rid, i) => { const r = rep2(rid); const resp = i < q.responded; return (
              <div key={rid} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '10px 12px', borderRadius: 11, background: T.panel, border: `1px solid ${T.border}` }}>
                <div style={{ width: 30, height: 30, borderRadius: 99, background: r.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, fontSize: 12, color: '#fff' }}>{r.name[0]}</div>
                <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 13.5 }}>{r.name}</div><div style={{ fontSize: 11.5, color: T.mute }}>{r.lab}</div></div>
                <Pill tone={resp ? 'green' : 'mute'}>{resp ? <><Icon name="check" size={11} color={T.green} strokeWidth={3} /> respondeu</> : 'aguardando'}</Pill>
              </div>
            ); })}
          </div>
          {/* itens */}
          <div style={{ fontSize: 12.5, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 9 }}>Itens ({products.length})</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {products.map(p => (
              <div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '9px 12px', borderRadius: 10, background: T.panel, border: `1px solid ${T.border}`, fontSize: 13 }}>
                <span style={{ fontWeight: 500 }}>{p.name}</span>
                <span style={{ color: T.mute, fontVariantNumeric: 'tabular-nums' }}>R$ {ICb.fmt(p.lastCost)}</span>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
            <button onClick={onClose} style={{ flex: 1, padding: '12px', borderRadius: 12, border: `1px solid ${T.border}`, background: 'transparent', color: T.mute, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer', fontSize: 14 }}>Fechar</button>
            {q.status !== 'rascunho' && <button onClick={onGrid} style={{ flex: 1.4, padding: '12px', borderRadius: 12, border: 'none', cursor: 'pointer', fontWeight: 800, fontFamily: 'inherit', fontSize: 14, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center',gap:7 }}><Icon name="table" size={16} color="#fff" /> Abrir grade comparativa</button>}
          </div>
        </div>
      </div>
    </div>
  );
}

window.BuyerParts2 = { Quotes };
