// ── InovaPED — Comprador: Pedidos + Mensagens (chat) ────────────────────
const Topbar5 = window.BuyerParts1.Topbar;
const ICe = window.IC;
const cat5 = window.BuyerParts1.catById, rep5 = window.BuyerParts1.repById;

// ═══ PEDIDOS ═════════════════════════════════════════════════════════════
function Orders() {
  const [filter, setFilter] = useState('all');
  const tone = { 'recebido': 'green', 'em transporte': 'yellow', 'cancelado': 'mute' };
  const list = ICe.ORDERS.filter(o => filter === 'all' || o.status === filter);
  const totalSaving = ICe.ORDERS.filter(o => o.status !== 'cancelado').reduce((s, o) => s + o.saving, 0);
  const totalSpent = ICe.ORDERS.filter(o => o.status !== 'cancelado').reduce((s, o) => s + o.total, 0);
  return (
    <div>
      <Topbar5 title="Pedidos" sub="Histórico de pedidos fechados nas cotações"
        action={<ToolBtnO icon="receipt">Exportar CSV</ToolBtnO>} />
      <div style={{ display: 'grid', gap: 14, marginBottom: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))' }}>
        <Glass pad={16}><div style={{ fontSize: 12, color: T.mute }}>Total comprado</div><div style={{ fontSize: 23, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}><CountUp value={totalSpent} prefix="R$ " decimals={2} /></div></Glass>
        <Glass pad={16} style={{ flex: 1 }}><div style={{ fontSize: 12, color: T.mute }}>Economia acumulada</div><div style={{ fontSize: 23, fontWeight: 800, color: T.green, fontFamily: 'var(--display)', marginTop: 4 }}><CountUp value={totalSaving} prefix="R$ " decimals={2} /></div></Glass>
        <Glass pad={16} style={{ flex: 1 }}><div style={{ fontSize: 12, color: T.mute }}>Pedidos</div><div style={{ fontSize: 23, fontWeight: 800, fontFamily: 'var(--display)', marginTop: 4 }}>{ICe.ORDERS.length}</div></Glass>
      </div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
        {[['all','Todos'],['recebido','Recebidos'],['em transporte','Em transporte'],['cancelado','Cancelados']].map(([v, l]) =>
          <ChipO key={v} on={filter === v} onClick={() => setFilter(v)}>{l}</ChipO>)}
      </div>
      <Glass pad={0} style={{ overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
          <thead><tr style={{ background: T.panel }}>
            <th style={thO('left', 110)}>Pedido</th><th style={thO('left', 110)}>Data</th><th style={thO('left', 150)}>Categoria</th><th style={thO('left', 170)}>Representante</th><th style={thO('center', 70)}>Itens</th><th style={thO('right', 110)}>Total</th><th style={thO('right', 110)}>Economia</th><th style={thO('left', 130)}>Status</th>
          </tr></thead>
          <tbody>
            {list.map(o => { const c = cat5(o.cat), r = rep5(o.rep); return (
              <tr key={o.id} style={{ borderTop: `1px solid ${T.border}` }}>
                <td style={{ ...tdO('left'), fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{o.id}</td>
                <td style={{ ...tdO('left'), color: T.mute }}>{o.date}</td>
                <td style={tdO('left')}><Pill tone="mute"><span style={{ width:7,height:7,borderRadius:99,background:T.redBright }}/>{c.name}</Pill></td>
                <td style={tdO('left')}><span style={{ display:'flex',alignItems:'center',gap:8 }}><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>{r.name.split(' ')[0]}</span></td>
                <td style={{ ...tdO('center'), color: T.mute }}>{o.items}</td>
                <td style={{ ...tdO('right'), fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>R$ {ICe.fmt(o.total)}</td>
                <td style={{ ...tdO('right'), fontWeight: 700, color: o.status === 'cancelado' ? T.mute2 : T.green, fontVariantNumeric: 'tabular-nums' }}>{o.status === 'cancelado' ? '—' : 'R$ ' + ICe.fmt(o.saving)}</td>
                <td style={tdO('left')}><Pill tone={tone[o.status]}>{o.status === 'recebido' ? <Icon name="check" size={12} color={T.green} strokeWidth={3} /> : o.status === 'em transporte' ? <Icon name="box" size={12} color={T.yellow} /> : <Icon name="x" size={12} color={T.mute} />}{o.status}</Pill></td>
              </tr>
            ); })}
          </tbody>
        </table>
      </Glass>
    </div>
  );
}
const thO = (a, w) => ({ textAlign: a, padding: '14px 16px', fontSize: 11.5, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, whiteSpace: 'nowrap', minWidth: w });
const tdO = (a) => ({ textAlign: a, padding: '13px 16px', verticalAlign: 'middle' });
function ChipO({ children, on, onClick }) { return <button onClick={onClick} style={{ padding: '8px 14px', 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' }}>{children}</button>; }
function ToolBtnO({ icon, children, onClick }) { return <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '9px 14px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, fontSize: 13, border: `1px solid ${T.border}`, color: T.mute, background: T.panel }}><Icon name={icon} size={15} color={T.mute} /> {children}</button>; }

// ═══ MENSAGENS — HUB DE NEGOCIAÇÃO ═══════════════════════════════════════
const REPLIES = ['Perfeito, Felipe! Já anoto aqui.', 'Consigo sim, deixa eu verificar o estoque.', 'Fechado! Travo esse preço pra você.', 'Pode deixar, te retorno rapidinho.'];

// mensagens-semente ricas por rep (casca: tipos variados · canal whatsapp|inova)
function seedThreads() {
  return {
    r2: [
      { from: 'sys', type: 'system', text: 'Felipe abriu a cotação <b>Suplementos — Semana 22</b>', action: 'Ver grade', time: '08:40' },
      { from: 'rep', channel: 'inova', type: 'text', text: 'Bom dia Felipe! Já lancei os preços de Suplementos.', time: '08:42' },
      { from: 'rep', channel: 'inova', type: 'file', fileName: 'Tabela_NutriMax_Sem22.xlsx', fileKind: 'xlsx', size: '84 KB', time: '08:42' },
      { from: 'buyer', channel: 'inova', type: 'text', text: 'Show, Rodrigo. O Whey ficou ótimo.', time: '08:45' },
      { from: 'rep', channel: 'whatsapp', type: 'audio', dur: '0:38', time: '08:46', transcript: 'Felipe, sobre a creatina, se você fechar 100 unidades eu consigo a 46,90, tá? Esse preço eu seguro até sexta.' },
      { from: 'sys', type: 'bridge', text: 'Esta conversa continuou no <b>WhatsApp</b>', time: '08:46' },
      { from: 'rep', channel: 'whatsapp', type: 'offer', product: 'Creatina 300g', price: 46.90, qty: 100, valid: '03/2027', time: '08:47' },
      { from: 'buyer', channel: 'inova', type: 'text', text: 'Fechado. Vou montar o pedido ainda hoje.', time: '08:48' },
    ],
    r1: [
      { from: 'buyer', channel: 'whatsapp', type: 'text', text: 'Carla, a Profarma tem previsão de reposição de Genéricos?', time: 'ontem' },
      { from: 'rep', channel: 'whatsapp', type: 'text', text: 'Tem sim! Chega quarta. Já te aviso pra cotar.', time: 'ontem' },
      { from: 'rep', channel: 'whatsapp', type: 'image', fileName: 'tabela_foto.jpg', time: 'ontem' },
    ],
    r4: [
      { from: 'rep', channel: 'inova', type: 'text', text: 'Felipe, atualizei a oferta de fraldas.', time: '14:10' },
      { from: 'rep', channel: 'inova', type: 'offer', product: 'Fralda Premium G', price: 46.00, qty: 80, valid: '09/2026', time: '14:11' },
    ],
  };
}
const LABELS = { aguardando: { l: 'Aguardando', tone: 'yellow' }, negociando: { l: 'Negociando', tone: 'red' }, fechado: { l: 'Fechado', tone: 'green' } };
const CHAT_LABEL = { r2: 'negociando', r1: 'aguardando', r4: 'fechado' };
// canal primário de cada conversa (de onde a maioria das msgs vem)
const CHAT_CHANNEL = { r2: 'inova', r1: 'whatsapp', r4: 'inova' };
const CH = {
  whatsapp: { name: 'WhatsApp', color: '#25D366', icon: 'whatsapp' },
  inova:    { name: 'InovaPED', color: '#FF1330', icon: 'bolt' },
};

function Chat() {
  const reps = ICe.REPS.filter(r => ICe.CHATS[r.id]);
  const [active, setActive] = useState(reps[0].id);
  const [threads, setThreads] = useState(seedThreads);
  const [input, setInput] = useState('');
  const [filter, setFilter] = useState('todos');
  const [showMedia, setShowMedia] = useState(typeof window !== 'undefined' && window.innerWidth > 1180);
  const [typing, setTyping] = useState(false);
  const [pinned, setPinned] = useState({ r2: true });
  const [sendCh, setSendCh] = useState('inova');
  const scrollRef = useRef();
  const fileRef = useRef();
  useEffect(() => { setSendCh(CHAT_CHANNEL[active] || 'inova'); }, [active]);
  useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [active, threads, typing]);

  const addFiles = (fileList) => {
    const files = Array.from(fileList || []);
    if (!files.length) return;
    const now = new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
    const kb = (n) => n < 1024 ? n + ' B' : n < 1048576 ? (n / 1024).toFixed(0) + ' KB' : (n / 1048576).toFixed(1) + ' MB';
    const newMsgs = files.map(f => ({ from: 'buyer', type: /^image\//.test(f.type) ? 'image' : 'file', fileName: f.name, size: kb(f.size), time: now }));
    setThreads(t => ({ ...t, [active]: [...t[active], ...newMsgs] }));
  };

  const send = () => {
    const text = input.trim(); if (!text) return;
    const now = new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
    setThreads(t => ({ ...t, [active]: [...t[active], { from: 'buyer', channel: sendCh, type: 'text', text, time: now }] }));
    setInput(''); setTyping(true);
    setTimeout(() => { setTyping(false); setThreads(t => ({ ...t, [active]: [...t[active], { from: 'rep', channel: sendCh, type: 'text', text: REPLIES[Math.floor(Math.random() * REPLIES.length)], time: now }] })); }, 1600);
  };

  const r = rep5(active);
  const msgs = threads[active];
  const offers = msgs.filter(m => m.type === 'offer');
  const media = msgs.filter(m => m.type === 'file' || m.type === 'image');
  const filteredReps = filter === 'verdes' ? reps.filter(rp => CHAT_LABEL[rp.id] === 'negociando') : reps;
  const order = ICe.ORDERS.find(o => o.rep === active);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Topbar5 title="Mensagens" sub="Hub de negociação — chat, ofertas, áudios e documentos num só lugar"
        action={<button onClick={() => setShowMedia(v => !v)} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '9px 14px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, fontSize: 13, border: `1px solid ${showMedia ? T.borderHi : T.border}`, color: showMedia ? T.text : T.mute, background: showMedia ? T.panelHi : T.panel }}><Icon name="image" size={15} color={showMedia ? T.text : T.mute} /> Galeria de mídia</button>} />
      <Glass pad={0} style={{ flex: 1, display: 'flex', overflow: 'hidden', minHeight: 540 }}>
        {/* lista */}
        <div style={{ width: 268, flexShrink: 0, borderRight: `1px solid ${T.border}`, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '12px 12px 8px', borderBottom: `1px solid ${T.border}` }}>
            <div style={{ position: 'relative', marginBottom: 8 }}>
              <Icon name="search" size={15} color={T.mute2} style={{ position: 'absolute', left: 11, top: 10 }} />
              <input placeholder="Buscar conversa ou termo..." style={{ width: '100%', boxSizing: 'border-box', padding: '8px 10px 8px 34px', borderRadius: 9, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 13, outline: 'none' }} />
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {[['todos', 'Todos'], ['verdes', 'Ofertas verdes']].map(([v, l]) => { const on = filter === v; return <button key={v} onClick={() => setFilter(v)} style={{ flex: 1, padding: '6px', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 700, border: `1px solid ${on ? T.red : T.border}`, color: on ? T.redBright : T.mute, background: on ? T.redBg : 'transparent' }}>{l}</button>; })}
            </div>
          </div>
          <div style={{ flex: 1, overflow: 'auto' }}>
            {filteredReps.map(rp => {
              const th = threads[rp.id]; const last = th[th.length - 1]; const on = active === rp.id;
              const lab = LABELS[CHAT_LABEL[rp.id]];
              const preview = last.type === 'offer' ? '💰 Oferta enviada' : last.type === 'audio' ? '🎙 Áudio' : last.type === 'file' ? '📄 Documento' : last.type === 'image' ? '🖼 Imagem' : last.text;
              return (
                <button key={rp.id} onClick={() => setActive(rp.id)} style={{ width: '100%', display: 'flex', gap: 11, padding: '13px 14px', border: 'none', borderBottom: `1px solid ${T.border}`, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', background: on ? T.redBg : 'transparent', boxShadow: on ? `inset 2px 0 0 ${T.red}` : 'none' }}>
                  <div style={{ position: 'relative', flexShrink: 0 }}>
                    <div style={{ width: 40, height: 40, borderRadius: 99, background: rp.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, color: '#fff' }}>{rp.name[0]}</div>
                    <span style={{ position: 'absolute', bottom: 0, right: 0, width: 11, height: 11, borderRadius: 99, background: T.green, border: `2px solid ${on ? T.surface : T.bg2}` }} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 6 }}><span style={{ fontWeight: 700, fontSize: 13.5, display: 'flex', alignItems: 'center', gap: 5 }}>{rp.name.split(' ')[0]}<Icon name={CH[CHAT_CHANNEL[rp.id]].icon} size={12} color={CH[CHAT_CHANNEL[rp.id]].color} /></span><span style={{ fontSize: 10.5, color: T.mute2 }}>{last.time}</span></div>
                    <div style={{ fontSize: 12, color: T.mute, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{preview}</div>
                    {lab && <span style={{ display: 'inline-block', marginTop: 5, fontSize: 10, fontWeight: 700, padding: '1px 7px', borderRadius: 99, color: T[lab.tone === 'red' ? 'redBright' : lab.tone === 'green' ? 'green' : 'yellow'], background: T[lab.tone === 'red' ? 'redBg' : lab.tone === 'green' ? 'greenBg' : 'yellowBg'] }}>{lab.l}</span>}
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* thread */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 16px', borderBottom: `1px solid ${T.border}`, background: T.panel }}>
            <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 }}>{r.name}</div><div style={{ fontSize: 11.5, color: T.green, display:'flex',alignItems:'center',gap:5 }}><span style={{ width: 7, height: 7, borderRadius: 99, background: T.green }} />{typing ? 'digitando…' : 'online'} · {r.lab}</div></div>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 10px', borderRadius: 99, fontSize: 11.5, fontWeight: 700, color: CH[CHAT_CHANNEL[active]].color, background: CH[CHAT_CHANNEL[active]].color + '1A', border: `1px solid ${CH[CHAT_CHANNEL[active]].color}55` }}><Icon name={CH[CHAT_CHANNEL[active]].icon} size={13} color={CH[CHAT_CHANNEL[active]].color} /> {CH[CHAT_CHANNEL[active]].name}</span>
            <button title="Buscar no chat" style={iconBtn()}><Icon name="search" size={16} color={T.mute} /></button>
            <button title="Etiquetar conversa" style={iconBtn()}><Icon name="tag" size={16} color={T.mute} /></button>
          </div>

          {/* oferta fixada */}
          {pinned[active] && offers[0] && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px', background: T.yellowBg, borderBottom: `1px solid ${T.border}` }}>
              <Icon name="pin" size={15} color={T.yellow} />
              <span style={{ fontSize: 12.5, color: T.text, flex: 1 }}><b>Fixado:</b> {offers[0].product} a <b>R$ {ICe.fmt(offers[0].price)}</b> (≥{offers[0].qty}un) · val. {offers[0].valid}</span>
              <button onClick={() => setPinned(p => ({ ...p, [active]: false }))} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 2 }}><Icon name="x" size={14} color={T.mute} /></button>
            </div>
          )}

          {/* card de pedido vinculado */}
          {order && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 16px', background: T.panel, borderBottom: `1px solid ${T.border}` }}>
              <Icon name="receipt" size={15} color={T.redBright} />
              <span style={{ fontSize: 12.5, color: T.mute, flex: 1 }}>Pedido <b style={{ color: T.text }}>{order.id}</b> · {order.status}</span>
              <Pill tone={order.status === 'recebido' ? 'green' : order.status === 'em transporte' ? 'yellow' : 'mute'}>{order.status}</Pill>
            </div>
          )}

          <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: 18, display: 'flex', flexDirection: 'column', gap: 11 }}>
            {msgs.map((m, i) => <ChatMsg key={i} m={m} />)}
            {typing && <div style={{ alignSelf: 'flex-start', display: 'flex', gap: 4, padding: '12px 16px', borderRadius: 14, background: T.panelHi, border: `1px solid ${T.border}` }}>{[0,1,2].map(d => <span key={d} style={{ width: 6, height: 6, borderRadius: 99, background: T.mute, animation: `icpulse 1s ${d * 0.2}s infinite` }} />)}</div>}
          </div>

          {/* IA de contexto */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '8px 16px', background: T.redBg, borderTop: `1px solid ${T.border}` }}>
            <Icon name="sparkle" size={15} color={T.redBright} />
            <span style={{ fontSize: 12, color: T.text, flex: 1 }}>IA detectou uma oferta de <b>Creatina a R$ 46,90</b> nesta conversa</span>
            <button style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '6px 11px', borderRadius: 9, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 12, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` }}><Icon name="plusGrid" size={13} color="#fff" strokeWidth={2.5} /> Adicionar à grade</button>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '10px 16px 12px', borderTop: `1px solid ${T.border}` }}>
            <button onClick={() => fileRef.current && fileRef.current.click()} title="Anexar PDF, Excel, CSV, imagem, XML, DOCX" style={iconBtn()}><Icon name="paperclip" size={18} color={T.mute} /></button>
            <input ref={fileRef} type="file" multiple onChange={e => { addFiles(e.target.files); e.target.value = ''; }} accept=".pdf,.xls,.xlsx,.csv,.xml,.doc,.docx,.jpg,.jpeg,.png,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/*" style={{ display: 'none' }} />
            <button title="Gravar áudio" style={iconBtn()}><Icon name="mic" size={18} color={T.mute} /></button>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 7 }}>
              <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder={`Mensagem via ${CH[sendCh].name}…`} style={{ width: '100%', boxSizing: 'border-box', padding: '12px 16px', borderRadius: 12, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' }} />
              <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                <span style={{ fontSize: 11, color: T.mute2, fontWeight: 600 }}>Enviar via:</span>
                {['inova', 'whatsapp'].map(ch => { const on = sendCh === ch; return <button key={ch} onClick={() => setSendCh(ch)} style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '4px 10px', borderRadius: 99, cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 700, border: `1px solid ${on ? CH[ch].color : T.border}`, color: on ? CH[ch].color : T.mute, background: on ? CH[ch].color + '14' : 'transparent' }}><Icon name={CH[ch].icon} size={13} color={on ? CH[ch].color : T.mute} /> {CH[ch].name}</button>; })}
              </div>
            </div>
            <button onClick={send} style={{ width: 46, height: 46, borderRadius: 12, border: 'none', cursor: 'pointer', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0, alignSelf: 'flex-start' }}><Icon name="send" size={19} color="#fff" /></button>
          </div>
        </div>

        {/* galeria de mídia lateral */}
        {showMedia && (
          <div style={{ width: 250, flexShrink: 0, borderLeft: `1px solid ${T.border}`, overflow: 'auto', padding: 16 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 12 }}>Ofertas fixadas</div>
            {offers.length ? offers.map((o, i) => (
              <div key={i} style={{ padding: 11, borderRadius: 11, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 8 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700 }}>{o.product}</div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 5 }}><span style={{ fontWeight: 800, color: T.green, fontVariantNumeric: 'tabular-nums' }}>R$ {ICe.fmt(o.price)}</span><span style={{ fontSize: 11, color: T.mute }}>≥{o.qty}un</span></div>
              </div>
            )) : <div style={{ fontSize: 12, color: T.mute2, marginBottom: 14 }}>Nenhuma oferta ainda.</div>}
            <div style={{ fontSize: 12, fontWeight: 700, color: T.mute, textTransform: 'uppercase', letterSpacing: 0.4, margin: '16px 0 12px' }}>Documentos & tabelas</div>
            {media.length ? media.map((m, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: 10, borderRadius: 10, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 7 }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: T.redBg, display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name={m.type === 'image' ? 'image' : 'file'} size={16} color={T.redBright} /></div>
                <div style={{ minWidth: 0 }}><div style={{ fontSize: 12, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.fileName}</div><div style={{ fontSize: 10.5, color: T.mute2 }}>{m.size || 'imagem'}</div></div>
              </div>
            )) : <div style={{ fontSize: 12, color: T.mute2 }}>Nada trocado ainda.</div>}
          </div>
        )}
      </Glass>
    </div>
  );
}
const iconBtn = () => ({ width: 36, height: 36, borderRadius: 10, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 });

// ── bolha de mensagem (multi-tipo) ──────────────────────────────────────
function ChatMsg({ m }) {
  const mine = m.from === 'buyer';
  const [speed, setSpeed] = useState(1);

  // balões de sistema / ponte entre canais
  if (m.type === 'system' || m.type === 'bridge') {
    const bridge = m.type === 'bridge';
    return (
      <div style={{ alignSelf: 'center', maxWidth: '88%', display: 'flex', alignItems: 'center', gap: 8, padding: '7px 13px', borderRadius: 99, background: bridge ? '#25D36618' : T.panel, border: `1px solid ${bridge ? '#25D36655' : T.border}`, margin: '2px 0' }}>
        <Icon name={bridge ? 'whatsapp' : 'bolt'} size={13} color={bridge ? '#25D366' : T.redBright} />
        <span style={{ fontSize: 11.5, color: T.mute, textAlign: 'center' }} dangerouslySetInnerHTML={{ __html: m.text }} />
        {m.action && <button style={{ fontSize: 11.5, fontWeight: 700, color: T.redBright, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>{m.action} →</button>}
      </div>
    );
  }
  const wrap = (inner, w) => <div style={{ alignSelf: mine ? 'flex-end' : 'flex-start', maxWidth: w || '74%' }}>{inner}<div style={{ fontSize: 10.5, color: T.mute2, marginTop: 3, textAlign: mine ? 'right' : 'left', display: 'flex', gap: 4, justifyContent: mine ? 'flex-end' : 'flex-start' }}>{m.time}{mine && <Icon name="check" size={12} color={T.green} strokeWidth={2.5} />}</div></div>;
  const bubble = (bg, content, border) => <div style={{ padding: '10px 14px', borderRadius: mine ? '14px 14px 4px 14px' : '14px 14px 14px 4px', background: bg, color: mine ? '#fff' : T.text, fontSize: 13.5, lineHeight: 1.45, border }}>{content}</div>;
  const myBg = `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`;

  if (m.type === 'offer') return wrap(
    <div style={{ borderRadius: 14, overflow: 'hidden', border: `1.5px solid ${T.green}`, background: T.greenBg }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '8px 12px', background: T.green, color: '#04130C' }}><Icon name="tag" size={14} color="#04130C" /><span style={{ fontWeight: 800, fontSize: 12 }}>OFERTA</span></div>
      <div style={{ padding: 12 }}>
        <div style={{ fontWeight: 700, fontSize: 14 }}>{m.product}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}><span style={{ fontWeight: 800, fontSize: 20, fontFamily: 'var(--display)', color: T.green }}>R$ {ICe.fmt(m.price)}</span><span style={{ fontSize: 11.5, color: T.mute }}>≥{m.qty}un · val. {m.valid}</span></div>
        <button style={{ width: '100%', marginTop: 10, padding: '9px', borderRadius: 10, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 12.5, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center',gap:6 }}><Icon name="plusGrid" size={14} color="#fff" strokeWidth={2.5} /> Adicionar à grade</button>
      </div>
    </div>, 280);

  if (m.type === 'audio') return wrap(
    <div>
      {bubble(mine ? myBg : T.panelHi, <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 200 }}>
        <button style={{ width: 34, height: 34, borderRadius: 99, border: 'none', cursor: 'pointer', background: mine ? 'rgba(255,255,255,0.2)' : T.redBg, display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name="play" size={15} color={mine ? '#fff' : T.redBright} /></button>
        <div style={{ flex: 1 }}><div style={{ height: 3, borderRadius: 99, background: mine ? 'rgba(255,255,255,0.3)' : T.border }}><div style={{ width: '32%', height: '100%', borderRadius: 99, background: mine ? '#fff' : T.redBright }} /></div></div>
        <span style={{ fontSize: 11, opacity: 0.8 }}>{m.dur}</span>
        <button onClick={() => setSpeed(s => s === 1 ? 1.5 : s === 1.5 ? 2 : 1)} style={{ fontSize: 10.5, fontWeight: 800, padding: '2px 6px', borderRadius: 6, border: 'none', cursor: 'pointer', background: mine ? 'rgba(255,255,255,0.2)' : T.panel, color: mine ? '#fff' : T.mute, fontFamily: 'inherit' }}>{speed}x</button>
      </div>, mine ? 'none' : `1px solid ${T.border}`)}
      {m.transcript && <div style={{ marginTop: 6, padding: '8px 11px', borderRadius: 10, background: T.panel, border: `1px solid ${T.border}`, fontSize: 12, color: T.mute, fontStyle: 'italic', maxWidth: 300 }}><Icon name="sparkle" size={11} color={T.redBright} style={{ verticalAlign: '-1px' }} /> "{m.transcript}"</div>}
    </div>);

  if (m.type === 'file' || m.type === 'image') return wrap(
    bubble(mine ? myBg : T.panelHi, <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 180 }}>
      <div style={{ width: 38, height: 38, borderRadius: 9, background: mine ? 'rgba(255,255,255,0.2)' : T.redBg, display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name={m.type === 'image' ? 'image' : 'file'} size={19} color={mine ? '#fff' : T.redBright} /></div>
      <div style={{ minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.fileName}</div><div style={{ fontSize: 11, opacity: 0.75 }}>{m.size || 'imagem'} · toque para abrir</div></div>
    </div>, mine ? 'none' : `1px solid ${T.border}`));

  return wrap(bubble(mine ? myBg : T.panelHi, m.text, mine ? 'none' : `1px solid ${T.border}`));
}

window.BuyerParts5 = { Orders, Chat };
