/* SISTEMA · Inbox — live WhatsApp conversations.
   Refactor v2 (M1-M8): brand-coloured list rows, lead score-first trace, Assumir CTA, hover quick actions.
   Same export name DevInbox — used by both DEV and SISTEMA wrappers. */

// ---------- Brand palette ----------
const BRAND_COLOR = {
  Mimaki: '#e60012',
  BIOND: '#00a86b',
  Decal: '#f59e0b',
  Sensek: '#8b5cf6',
  AllDecor: '#ec4899',
  Digidelta: '#22d3ee',
  Store: '#22d3ee',
  Geral: '#64748b',
};
const brandColor = (b) => BRAND_COLOR[b] || BRAND_COLOR.Geral;

// ---------- Mock data with lead scores ----------
// Snapshot 2026-04-25 02:50 · PostgreSQL produção (heydigi_sessions). Telefones mascarados.
const INBOX = [
  { id: 'jarvis', initials: 'JA', name: 'Jarvis · Olimpo Lda', phone4: '6401', msgs: 27, t: '23:42', env: 'prod',
    brand: 'Mimaki', topic: 'PrintPlan · UJV200 · showroom', score: 82, mode: 'auto', unread: 0,
    preview: 'Mas qual é o preço por metro quadrado?', durationMin: 47 },
  { id: 'rui_leitao', initials: 'RL', name: 'Rui Leitão', phone4: '6423', msgs: 20, t: '18:32', env: 'prod',
    brand: 'Digidelta', topic: 'PrintPlan', score: 91, mode: 'auto', unread: 2,
    preview: 'Confirmo a reunião na próxima quarta-feira às 11h.', durationMin: 22 },
  { id: 'mimaki_5380', initials: 'PG', name: '····5380', company: 'Mimaki', phone4: '5380', msgs: 21, t: '21:15', env: 'prod',
    brand: 'Mimaki', topic: 'UJV200 · pricing', score: 88, mode: 'auto', unread: 0,
    preview: 'Podem mandar proposta para o e-mail?', durationMin: 33 },
  { id: 'jarvis2', initials: 'JA', name: 'Jarvis · Olimpo Lda', phone4: '6401', msgs: 27, t: '23:42', env: 'prod', selected: true,
    brand: 'Mimaki', topic: 'PrintPlan · UJV200 · showroom', score: 82, mode: 'auto', unread: 0,
    preview: 'Queria perceber melhor o que é o printplan…', durationMin: 47 },
  { id: 'ujv_5011', initials: 'UV', name: '····5011', company: 'UJV', phone4: '5011', msgs: 12, t: '20:38', env: 'prod',
    brand: 'Mimaki', topic: 'UJV200', score: 79, mode: 'auto', unread: 0,
    preview: 'Quanto custa a manutenção anual?', durationMin: 18 },
  { id: 'mimaki_7470', initials: 'ML', name: '····7470', company: 'Mimaki', phone4: '7470', msgs: 21, t: '21:31', env: 'prod',
    brand: 'Mimaki', topic: 'UJV200 · consulta técnica', score: 71, mode: 'auto', unread: 0,
    preview: 'O equipamento aceita PVC adesivo?', durationMin: 25 },
  { id: 'rafael', initials: 'RD', name: 'Rafael Rodriguez', company: 'Print Art', phone4: '5741', msgs: 16, t: '15:13', env: 'prod',
    brand: 'AllDecor', topic: 'PrintPlan · Print Art', score: 67, mode: 'humano', unread: 0, takenOver: 'Ana Rodrigues',
    preview: 'Ok obrigado, falamos amanhã.', durationMin: 41 },
  { id: 'joao_p', initials: 'JP', name: 'João Paulino', phone4: '6523', msgs: 9, t: '14:04', env: 'staging',
    brand: 'Geral', topic: 'Staging test', score: 60, mode: 'auto', unread: 0,
    preview: 'Estou a testar o flow.', durationMin: 8 },
  { id: 'decal_2941', initials: 'AN', name: '····5380', company: 'Decoração / Print Art', phone4: '2941', msgs: 21, t: '22:48', env: 'prod',
    brand: 'Decal', topic: 'Decoração / Print Art', score: 54, mode: 'mixed', unread: 1,
    preview: 'Mando-vos as medidas amanhã.', durationMin: 35 },
  { id: 'es_5278', initials: 'ES', name: '····5278', company: 'ES', phone4: '5278', msgs: 10, t: '20:55', env: 'prod',
    brand: 'Geral', topic: 'Consulta geral', score: 45, mode: 'auto', unread: 0,
    preview: 'Não, ainda não decidi nada.', durationMin: 12 },
  { id: 'lorenzo', initials: 'LV', name: 'Lorenzo Varga', phone4: '3905', msgs: 52, t: '16:31', env: 'staging',
    brand: 'Geral', topic: 'Staging test', score: 38, mode: 'auto', unread: 0,
    preview: 'Test message #52.', durationMin: 88 },
  { id: 'filipe', initials: 'FC', name: 'Filipe', phone4: '8056', msgs: 1, t: '21:05', env: 'prod',
    brand: 'Geral', topic: 'Primeiro contacto', score: 22, mode: 'auto', unread: 0,
    preview: 'Olá', durationMin: 1 },
];

// Tag a couple as escalated/awaiting human
INBOX[6].escalated = true;
INBOX[8].awaitingHuman = true;
INBOX[1].awaitingHuman = true;

const CONV = [
  { side: 'user', text: 'Olá! Posso obter mais informações sobre isto?', t: '23:00' },
  { side: 'ai', text: 'Vi o anúncio do PrintPlan e queres evitar o investimento inicial — ter produção própria sem comprometer a tesouraria.\n\nSou a Digi, agente de inteligência artificial treinada pela Digidelta para encontrar a solução certa para o teu volume sem peso no capital.\n\nTens dois minutos para falarmos?', t: '23:01', latency: 2.1 },
  { side: 'user', text: 'Sim', t: '23:04' },
  { side: 'ai', text: 'Ter produção própria sem investimento inicial — equipamento, tintas e assistência num preço fixo por m² produzido. Só pagas quando produces.\n\nVem ver como funciona ao vivo — é como um test drive. Vês o equipamento, tens os números para o teu volume, e ainda há um voucher de 100€ em consumíveis quando vieres.\n\nQual showroom preferes — Lisboa (Prior Velho) ou Norte (Famalicão)?', t: '23:05', latency: 2.4 },
  { side: 'user', text: 'Queria perceber melhor o que é isso do printplan', t: '23:06' },
  { side: 'ai', text: 'O PrintPlan é um serviço de impressão nas tuas instalações onde só pagas os metros que imprimes. Inclui equipamento Mimaki + tintas + assistência técnica tudo num preço único por m².\n\nA diferença é que não compras em finanças nada — é um contrato de serviço. As tintas vêm em consignação, só pagas o que gastas, e se houver problemas com o equipamento não pagas nada extra.\n\nNa demo vês exactamente como funciona e calculamos os números reais para o teu caso. Qual showroom preferes — Lisboa (Prior Velho) ou Norte (Famalicão)?', t: '23:07', latency: 1.9 },
  { side: 'user', text: 'Mas qual é o preço por metro quadrado?', t: '23:10' },
];

// ============================================================
// MAIN
// ============================================================
const DevInbox = ({ onOpenChat }) => {
  const [quickFilter, setQuickFilter] = React.useState('all'); // all | hot | awaiting | escalated
  const [advFilter, setAdvFilter] = React.useState({ marca: 'all', modo: 'all', canal: 'all', periodo: '24h', agente: 'all', score: 0 });
  const [showAdvFilter, setShowAdvFilter] = React.useState(false);
  const [search, setSearch] = React.useState('');
  const [selId, setSelId] = React.useState('jarvis');
  const [tab, setTab] = React.useState('conversa'); // info | conversa | historico | notas
  const [showAIPanel, setShowAIPanel] = React.useState(true);
  const [showInfoDrawer, setShowInfoDrawer] = React.useState(false);
  const [composer, setComposer] = React.useState('');
  const [showShortcuts, setShowShortcuts] = React.useState(false);
  const [hoveredItem, setHoveredItem] = React.useState(null);
  const [expandThinking, setExpandThinking] = React.useState(false);

  // sort by score desc, then time
  const filtered = React.useMemo(() => {
    let list = [...INBOX].sort((a, b) => b.score - a.score);
    if (quickFilter === 'hot') list = list.filter(i => i.score >= 80);
    if (quickFilter === 'awaiting') list = list.filter(i => i.awaitingHuman);
    if (quickFilter === 'escalated') list = list.filter(i => i.escalated);
    if (advFilter.marca !== 'all') list = list.filter(i => i.brand === advFilter.marca);
    if (advFilter.score > 0) list = list.filter(i => i.score >= advFilter.score);
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(i => i.name.toLowerCase().includes(q) || (i.brand || '').toLowerCase().includes(q) || (i.topic || '').toLowerCase().includes(q));
    }
    return list;
  }, [quickFilter, advFilter, search]);

  const counts = {
    all: INBOX.length,
    hot: INBOX.filter(i => i.score >= 80).length,
    awaiting: INBOX.filter(i => i.awaitingHuman).length,
    escalated: INBOX.filter(i => i.escalated).length,
  };

  const current = INBOX.find(i => i.id === selId) || INBOX[0];

  // keyboard shortcuts
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      if (e.key === '?') { setShowShortcuts(true); e.preventDefault(); }
      if (e.key === 'Escape') { setShowShortcuts(false); setShowAdvFilter(false); setShowInfoDrawer(false); }
      if (e.key === 'j' || e.key === 'k') {
        const idx = filtered.findIndex(c => c.id === selId);
        const next = e.key === 'j' ? Math.min(filtered.length - 1, idx + 1) : Math.max(0, idx - 1);
        if (filtered[next]) setSelId(filtered[next].id);
      }
      if (e.key === 'a' || e.key === 'A') alert('Assumir conversa: ' + current.name);
      if (e.key === '/') { e.preventDefault(); document.querySelector('[data-inbox-search]')?.focus(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [filtered, selId, current]);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', height: '100%', minHeight: 0, flex: 1, background: 'var(--bg)', overflow: 'hidden', position: 'relative' }} data-screen-label="SISTEMA · Inbox · Live">

      {/* ============ LEFT: List (300px) ============ */}
      <div style={{ width: 300, borderRight: '1px solid var(--border)', display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--bg-elev)' }}>
        <FilterBar
          quickFilter={quickFilter} setQuickFilter={setQuickFilter}
          counts={counts}
          showAdvFilter={showAdvFilter} setShowAdvFilter={setShowAdvFilter}
          advFilter={advFilter} setAdvFilter={setAdvFilter}
        />
        <SearchRow value={search} onChange={setSearch} />

        {/* List */}
        <div className="scrollbar" style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
          {filtered.length === 0 && (
            <div style={{ padding: 20, textAlign: 'center', color: 'var(--text-dim)', fontSize: 11 }}>Sem conversas com este filtro.</div>
          )}
          {filtered.map(c => (
            <ListItem
              key={c.id}
              c={c}
              selected={c.id === selId}
              hovered={hoveredItem === c.id}
              onSelect={() => setSelId(c.id)}
              onHover={(h) => setHoveredItem(h ? c.id : null)}
            />
          ))}
        </div>

        {/* Keyboard hints footer */}
        <button onClick={() => setShowShortcuts(true)} style={{
          padding: '8px 12px', borderTop: '1px solid var(--border)',
          fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)',
          background: 'transparent', textAlign: 'left',
        }}>
          <span style={{ color: 'var(--text-muted)' }}>J/K</span> navegar · <span style={{ color: 'var(--text-muted)' }}>↵</span> abrir · <span style={{ color: 'var(--text-muted)' }}>A</span> assumir · <span style={{ color: 'var(--text-muted)' }}>/</span> procurar · <span style={{ color: 'var(--text-muted)' }}>?</span> ajuda
        </button>
      </div>

      {/* ============ RIGHT: Thread + Trace ============ */}
      <div style={{ display: 'grid', gridTemplateColumns: showAIPanel ? '1fr 300px' : '1fr', minWidth: 0, minHeight: 0, overflow: 'hidden' }}>
        {/* Thread column */}
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0, minHeight: 0, borderRight: showAIPanel ? '1px solid var(--border)' : 'none' }}>
          <ConvHeader
            current={current} tab={tab} setTab={setTab}
            showAIPanel={showAIPanel} setShowAIPanel={setShowAIPanel}
            onOpenInfo={() => setShowInfoDrawer(true)}
          />

          {tab === 'conversa' && (
            <>
              {/* Mode/Brand context bar */}
              <div style={{
                padding: '6px 18px', borderBottom: '1px solid var(--border)',
                fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)',
                background: 'var(--bg-sunken)', flexShrink: 0,
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: brandColor(current.brand) }} />
                <span>modo {current.mode === 'humano' ? 'humano' : 'clientes'} · marca {current.brand} · WhatsApp +351 ····{current.phone4} · {current.env}</span>
              </div>

              <MessagesArea conv={CONV} brand={current.brand} takenOverBy={current.takenOver} />
              <ActionBar onAssumir={() => alert('Assumir conversa: ' + current.name)} />
              <Composer value={composer} onChange={setComposer} />
            </>
          )}
          {tab === 'info' && <ConvInfoPanel current={current} />}
          {tab === 'historico' && <HistoricoPanel current={current} />}
          {tab === 'notas' && <NotasPanel />}
        </div>

        {/* Right: Live Trace panel */}
        {showAIPanel && (
          <LiveTracePanel
            current={current}
            onOpenChat={onOpenChat}
            expandThinking={expandThinking}
            setExpandThinking={setExpandThinking}
          />
        )}
      </div>

      {/* Info drawer */}
      {showInfoDrawer && <InfoDrawer current={current} onClose={() => setShowInfoDrawer(false)} />}

      {/* Shortcuts modal */}
      {showShortcuts && <ShortcutsModal onClose={() => setShowShortcuts(false)} />}
    </div>
  );
};

// ============================================================
// M2 — Filter Bar
// ============================================================
const FilterBar = ({ quickFilter, setQuickFilter, counts, showAdvFilter, setShowAdvFilter, advFilter, setAdvFilter }) => {
  const filters = [
    { id: 'all', label: 'Todos', count: counts.all, icon: null },
    { id: 'hot', label: 'Hot leads', count: counts.hot, icon: '⚡' },
    { id: 'awaiting', label: 'Aguarda humano', count: counts.awaiting, icon: null },
    { id: 'escalated', label: 'Escaladas', count: counts.escalated, icon: null },
  ];
  return (
    <div style={{ padding: '10px 10px 6px', display: 'flex', gap: 4, flexWrap: 'wrap', alignItems: 'center', flexShrink: 0, position: 'relative' }}>
      {filters.map(f => (
        <button key={f.id} onClick={() => setQuickFilter(f.id)} style={{
          padding: '4px 8px',
          borderRadius: 6,
          border: quickFilter === f.id ? '1px solid var(--ai-500)' : '1px solid var(--border)',
          background: quickFilter === f.id ? 'var(--ai-500)' : 'var(--bg-sunken)',
          color: quickFilter === f.id ? '#fff' : 'var(--text-muted)',
          fontSize: 10.5, fontWeight: 600, fontFamily: 'var(--font-display)', letterSpacing: '0.03em',
          display: 'inline-flex', alignItems: 'center', gap: 4,
          whiteSpace: 'nowrap',
        }}>
          {f.icon && <span style={{ fontSize: 10 }}>{f.icon}</span>}
          {f.label}
          <span style={{
            padding: '0 5px', borderRadius: 3,
            fontSize: 9.5, fontFamily: 'var(--font-mono)', fontWeight: 500,
            background: quickFilter === f.id ? 'rgba(255,255,255,0.18)' : 'var(--surface-muted)',
            color: quickFilter === f.id ? '#fff' : 'var(--text-dim)',
          }}>{f.count}</span>
        </button>
      ))}
      <div style={{ flex: 1 }} />
      <button onClick={() => setShowAdvFilter(v => !v)} style={{
        padding: '4px 8px', borderRadius: 6,
        border: showAdvFilter ? '1px solid var(--ai-500)' : '1px solid var(--border)',
        background: 'var(--bg-sunken)', color: 'var(--text-muted)',
        fontSize: 10.5, fontFamily: 'var(--font-display)', fontWeight: 600,
        display: 'inline-flex', alignItems: 'center', gap: 4,
      }}>
        <Icon name="filter" size={11} />Filtro
        <span style={{ fontSize: 9 }}>▾</span>
      </button>

      {showAdvFilter && (
        <AdvancedFilterDropdown
          advFilter={advFilter} setAdvFilter={setAdvFilter}
          onClose={() => setShowAdvFilter(false)}
        />
      )}
    </div>
  );
};

const AdvancedFilterDropdown = ({ advFilter, setAdvFilter, onClose }) => {
  const set = (k, v) => setAdvFilter({ ...advFilter, [k]: v });
  const row = (label, k, options) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0' }}>
      <label style={{ width: 64, fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{label}</label>
      <select value={advFilter[k]} onChange={e => set(k, e.target.value)} style={{
        flex: 1, padding: '4px 6px', borderRadius: 4,
        background: 'var(--bg-sunken)', border: '1px solid var(--border)',
        color: 'var(--text)', fontSize: 11,
      }}>
        {options.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
      </select>
    </div>
  );
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 30 }} />
      <div style={{
        position: 'absolute', top: 'calc(100% - 4px)', right: 8, width: 280, zIndex: 40,
        background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 8,
        padding: '10px 12px', boxShadow: '0 16px 40px rgba(0,0,0,0.4)',
      }}>
        <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', letterSpacing: '0.06em', marginBottom: 4 }}>FILTRO AVANÇADO</div>
        {row('Marca', 'marca', [
          { v: 'all', l: 'Todas' }, { v: 'Mimaki', l: 'Mimaki' }, { v: 'BIOND', l: 'BIOND' },
          { v: 'Decal', l: 'Decal' }, { v: 'Sensek', l: 'Sensek' }, { v: 'AllDecor', l: 'AllDecor' },
          { v: 'Digidelta', l: 'Digidelta' }, { v: 'Store', l: 'Store' },
        ])}
        {row('Modo', 'modo', [
          { v: 'all', l: 'Todos' }, { v: 'clientes', l: 'Clientes' }, { v: 'colab', l: 'Colaboradores' }, { v: 'dev', l: 'Dev' },
        ])}
        {row('Canal', 'canal', [
          { v: 'all', l: 'Todos' }, { v: 'whatsapp', l: 'WhatsApp' }, { v: 'chat', l: 'Chat' }, { v: 'crm', l: 'CRM' },
        ])}
        {row('Período', 'periodo', [
          { v: '1h', l: '1h' }, { v: '6h', l: '6h' }, { v: '24h', l: '24h' }, { v: '7d', l: '7d' }, { v: '30d', l: '30d' },
        ])}
        {row('Agente', 'agente', [
          { v: 'all', l: 'Todos' }, { v: 'digi', l: 'Digi AI' }, { v: 'humano', l: 'Humano' }, { v: 'mixed', l: 'Mixed' },
        ])}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0' }}>
          <label style={{ width: 64, fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>Score</label>
          <input type="range" min="0" max="100" step="5" value={advFilter.score}
            onChange={e => set('score', parseInt(e.target.value, 10))}
            style={{ flex: 1, accentColor: 'var(--ai-500)' }} />
          <span style={{ width: 32, fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text)', textAlign: 'right' }}>≥{advFilter.score}</span>
        </div>
        <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
          <button onClick={() => setAdvFilter({ marca: 'all', modo: 'all', canal: 'all', periodo: '24h', agente: 'all', score: 0 })}
            className="btn btn-xs btn-ghost" style={{ flex: 1 }}>Limpar</button>
          <button onClick={onClose} className="btn btn-xs btn-primary" style={{ flex: 1 }}>Aplicar</button>
        </div>
      </div>
    </>
  );
};

const SearchRow = ({ value, onChange }) => (
  <div style={{ padding: '0 10px 10px', flexShrink: 0 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 10px', background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 6 }}>
      <Icon name="search" size={12} style={{ color: 'var(--text-dim)' }} />
      <input
        data-inbox-search
        value={value} onChange={e => onChange(e.target.value)}
        placeholder="Procurar conversa, cliente, marca…"
        style={{ flex: 1, background: 'transparent', border: 0, outline: 0, color: 'inherit', fontSize: 11.5 }}
      />
      <span style={{ fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', padding: '1px 4px', border: '1px solid var(--border)', borderRadius: 3 }}>⌘K</span>
    </div>
  </div>
);

// ============================================================
// M1 — List Item (~52px tall, brand-coloured rail)
// ============================================================
const ListItem = ({ c, selected, hovered, onSelect, onHover }) => {
  const scoreColor = c.score >= 80 ? '#10b981' : c.score >= 60 ? '#f59e0b' : 'var(--text-dim)';
  const railColor = selected ? 'var(--ai-500)' : brandColor(c.brand);

  return (
    <button
      onClick={onSelect}
      onMouseEnter={() => onHover(true)}
      onMouseLeave={() => onHover(false)}
      style={{
        width: '100%', padding: '8px 10px 8px 13px',
        display: 'flex', gap: 9, alignItems: 'center',
        background: selected ? 'rgba(34,211,238,0.08)' : (hovered ? 'var(--bg-hover)' : 'transparent'),
        borderLeft: `3px solid ${railColor}`,
        borderBottom: '1px solid var(--border)',
        textAlign: 'left',
        position: 'relative',
        minHeight: 52,
      }}>
      <div style={{
        width: 32, height: 32, borderRadius: '50%',
        background: 'var(--surface-muted)', color: 'var(--text)',
        display: 'grid', placeItems: 'center',
        fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11,
        flexShrink: 0,
        border: `1.5px solid ${brandColor(c.brand)}`,
      }}>
        {c.initials}
        {c.unread > 0 && (
          <span style={{
            position: 'absolute', width: 8, height: 8, borderRadius: '50%',
            background: '#22d3ee', top: 6, left: 35,
            border: '2px solid var(--bg-elev)',
          }} />
        )}
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        {/* Row 1 */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{
            fontSize: 12, fontWeight: c.unread > 0 ? 700 : 600,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            flex: 1, color: 'var(--text)',
          }}>{c.name}{c.company ? ' · ' + c.company : ''}</span>
          <span style={{
            padding: '1px 5px', borderRadius: 3, fontSize: 9.5, fontWeight: 700,
            fontFamily: 'var(--font-mono)',
            background: c.score >= 80 ? 'rgba(16,185,129,0.15)' : c.score >= 60 ? 'rgba(245,158,11,0.15)' : 'var(--surface-muted)',
            color: scoreColor, flexShrink: 0,
          }}>{c.score}</span>
          <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', flexShrink: 0 }}>{c.t}</span>
        </div>

        {/* Row 2 — preview, replaced by phone on hover */}
        <div style={{ marginTop: 2, fontSize: 10.5, color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', position: 'relative', height: 14 }}>
          {hovered ? (
            <span className="font-mono" style={{ color: 'var(--text-dim)' }}>+351 ····{c.phone4}</span>
          ) : (
            c.preview
          )}
        </div>
      </div>

      {/* Hover quick actions (right side) */}
      {hovered && (
        <>
          <div style={{
            position: 'absolute', top: 4, right: 6, display: 'flex', gap: 0,
            background: 'var(--bg-elev)', border: '1px solid var(--border)',
            borderRadius: 4, padding: 0, zIndex: 2,
          }} onClick={(e) => e.stopPropagation()}>
            <span title="Pin" style={iconPipBtn}>📌</span>
            <span title="Mute" style={iconPipBtn}>🔇</span>
            <span title="Marcar como lida" style={iconPipBtn}>✓</span>
            <span title="Mais" style={iconPipBtn}>⋯</span>
          </div>
          {/* env badge top-right */}
          <span style={{
            position: 'absolute', top: 4, left: 18,
            padding: '0 4px', fontSize: 8, fontFamily: 'var(--font-mono)', borderRadius: 2,
            background: c.env === 'prod' ? 'rgba(16,185,129,0.15)' : 'rgba(245,158,11,0.15)',
            color: c.env === 'prod' ? '#10b981' : '#f59e0b',
            zIndex: 2,
          }}>{c.env}</span>
        </>
      )}

      {/* Status badges (visible always when special) */}
      {!hovered && (c.escalated || c.awaitingHuman) && (
        <span style={{
          position: 'absolute', top: 4, right: 8,
          padding: '0 4px', fontSize: 8.5, fontFamily: 'var(--font-mono)', borderRadius: 2, fontWeight: 600,
          background: c.escalated ? 'rgba(239,68,68,0.15)' : 'rgba(245,158,11,0.15)',
          color: c.escalated ? '#ef4444' : '#f59e0b',
        }}>{c.escalated ? 'esc' : 'h'}</span>
      )}
    </button>
  );
};

const iconPipBtn = {
  width: 22, height: 22, display: 'grid', placeItems: 'center',
  fontSize: 10, color: 'var(--text-muted)', cursor: 'pointer',
};

// ============================================================
// M3 — Conversation Header
// ============================================================
const ConvHeader = ({ current, tab, setTab, showAIPanel, setShowAIPanel, onOpenInfo }) => {
  const [moreOpen, setMoreOpen] = React.useState(false);
  const scoreColor = current.score >= 80 ? '#10b981' : current.score >= 60 ? '#f59e0b' : 'var(--text-dim)';
  const modeColor = current.mode === 'humano' ? '#f59e0b' : current.mode === 'mixed' ? '#8b5cf6' : '#22d3ee';

  return (
    <div style={{ flexShrink: 0, borderBottom: '1px solid var(--border)' }}>
      {/* Row 1 */}
      <div style={{ padding: '10px 18px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 36, height: 36, borderRadius: '50%',
          background: 'var(--surface-muted)', color: 'var(--text)',
          display: 'grid', placeItems: 'center',
          fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13,
          border: `2px solid ${brandColor(current.brand)}`,
          flexShrink: 0,
        }}>{current.initials}</div>

        <div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span className="font-display" style={{ fontSize: 14.5, fontWeight: 700 }}>{current.name}{current.company ? ' · ' + current.company : ''}</span>

          <span style={{
            padding: '2px 7px', borderRadius: 4, fontSize: 9.5, fontWeight: 700,
            background: brandColor(current.brand), color: '#fff',
            letterSpacing: '0.04em', textTransform: 'uppercase',
          }}>{current.brand}</span>

          <span style={{
            padding: '2px 6px', borderRadius: 4, fontSize: 10, fontWeight: 700,
            background: current.score >= 80 ? 'rgba(16,185,129,0.18)' : current.score >= 60 ? 'rgba(245,158,11,0.18)' : 'var(--surface-muted)',
            color: scoreColor,
            fontFamily: 'var(--font-mono)',
            display: 'inline-flex', alignItems: 'center', gap: 3,
          }}>{current.score} {current.score >= 80 && <span>⚡</span>}</span>

          <span style={{
            padding: '2px 7px', borderRadius: 4, fontSize: 10, fontWeight: 600,
            background: 'transparent', border: `1px solid ${modeColor}`, color: modeColor,
            fontFamily: 'var(--font-mono)', textTransform: 'lowercase',
          }}>{current.takenOver ? `humano · ${current.takenOver.split(' ')[0]}` : current.mode}</span>

          <span className="font-mono" style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>
            {current.msgs} msgs · {current.durationMin}m
          </span>
        </div>

        <div style={{ position: 'relative' }}>
          <button onClick={() => setMoreOpen(v => !v)} className="btn btn-xs btn-ghost"><Icon name="more" size={12} /></button>
          {moreOpen && (
            <>
              <div onClick={() => setMoreOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 30 }} />
              <div style={{
                position: 'absolute', top: '100%', right: 0, marginTop: 4, zIndex: 40,
                background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 6,
                width: 180, padding: 4, boxShadow: '0 12px 30px rgba(0,0,0,0.4)',
              }}>
                {['Wake-up', 'Follow-up', 'Disponibilidade', 'Pin', 'Mute', 'Export'].map(item => (
                  <button key={item} onClick={() => setMoreOpen(false)} style={menuItemStyle}>{item}</button>
                ))}
              </div>
            </>
          )}
        </div>

        <button onClick={onOpenInfo} className="btn btn-xs"><Icon name="info" size={11} />Info</button>
        <button onClick={() => setShowAIPanel(v => !v)} className="btn btn-xs" title="Painel Digi AI">
          <Icon name="sparkle" size={11} />{showAIPanel ? 'Fechar' : 'Digi'}
        </button>
      </div>

      {/* Tab strip */}
      <div style={{ padding: '0 18px', display: 'flex', gap: 0, borderTop: '1px solid var(--border)' }}>
        {[
          { id: 'conversa', label: 'Conversa' },
          { id: 'info', label: 'Info' },
          { id: 'historico', label: 'Histórico' },
          { id: 'notas', label: 'Notas' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 12px',
            fontSize: 11, fontFamily: 'var(--font-display)', fontWeight: 600, letterSpacing: '0.06em',
            background: 'transparent',
            color: tab === t.id ? 'var(--text)' : 'var(--text-muted)',
            borderBottom: tab === t.id ? '2px solid var(--ai-500)' : '2px solid transparent',
            marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>
    </div>
  );
};

const menuItemStyle = {
  width: '100%', padding: '6px 10px', textAlign: 'left',
  background: 'transparent', border: 0, color: 'var(--text)',
  fontSize: 11, fontFamily: 'var(--font-display)', borderRadius: 4,
  cursor: 'pointer',
};

// ============================================================
// M6 — Messages
// ============================================================
const MessagesArea = ({ conv, brand, takenOverBy }) => {
  const [hoveredIdx, setHoveredIdx] = React.useState(null);
  return (
    <div className="scrollbar" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '14px 18px 16px', background: 'var(--bg)', display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Day separator */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '4px 0' }}>
        <span style={{ flex: 1, height: 1, background: 'var(--border)' }} />
        <span style={{ fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', letterSpacing: '0.06em' }}>24 ABR 2026</span>
        <span style={{ flex: 1, height: 1, background: 'var(--border)' }} />
      </div>

      {conv.map((m, i) => (
        <MessageBubble key={i} m={m} brand={brand} takenOverBy={takenOverBy} hovered={hoveredIdx === i} onHover={(h) => setHoveredIdx(h ? i : null)} />
      ))}

      {/* Pending AI reply */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0', color: 'var(--text-muted)' }}>
        <span className="ai-dot" style={{ animation: 'ai-shimmer 1.5s infinite' }} />
        <span className="font-mono" style={{ fontSize: 10.5 }}>Digi está a compor resposta · 3.2s · Opus 4.7</span>
      </div>
    </div>
  );
};

const MessageBubble = ({ m, brand, takenOverBy, hovered, onHover }) => {
  const isUser = m.side === 'user';
  return (
    <div onMouseEnter={() => onHover(true)} onMouseLeave={() => onHover(false)}
      style={{ display: 'flex', flexDirection: 'column', alignItems: isUser ? 'flex-end' : 'flex-start', position: 'relative' }}>
      {/* AI header */}
      {!isUser && (
        <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: takenOverBy ? '#f59e0b' : 'var(--ai-500)', marginBottom: 4, display: 'flex', alignItems: 'center', gap: 4, paddingLeft: 2 }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: takenOverBy ? '#f59e0b' : 'var(--ai-500)' }} />
          {takenOverBy ? `${takenOverBy} · humano` : 'Digi AI · auto'}
          {m.latency && <span style={{ color: 'var(--text-dim)', marginLeft: 4 }}>· respondido em {m.latency}s</span>}
        </div>
      )}

      <div style={{
        maxWidth: '76%',
        padding: '9px 13px',
        borderRadius: isUser ? '14px 14px 4px 14px' : '4px 14px 14px 14px',
        background: isUser ? '#22d3ee' : '#111827',
        color: isUser ? '#0a0e1a' : 'var(--text)',
        border: !isUser ? '1px solid var(--border)' : 'none',
        fontSize: 13, lineHeight: 1.5,
        whiteSpace: 'pre-wrap',
        position: 'relative',
        fontWeight: isUser ? 500 : 400,
      }}>
        {m.text}
      </div>

      {/* Timestamp + read receipt below */}
      <div style={{ marginTop: 3, fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 4, paddingRight: isUser ? 4 : 0, paddingLeft: !isUser ? 4 : 0 }}>
        <span>{m.t}</span>
        {isUser && <span style={{ color: 'var(--ai-500)' }}>✓✓</span>}
      </div>

      {/* Hover actions */}
      {hovered && (
        <div style={{
          position: 'absolute', top: -10, right: isUser ? 0 : 'auto', left: isUser ? 'auto' : 0,
          display: 'flex', gap: 0,
          background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 4,
          fontSize: 10, padding: 0, zIndex: 2,
        }}>
          {[['📋', 'Copy'], ['❝', 'Quote'], ['🚩', 'Flag'], ['✦', 'Pergunta Digi']].map(([i, t]) => (
            <span key={t} title={t} style={iconPipBtn}>{i}</span>
          ))}
        </div>
      )}
    </div>
  );
};

// ============================================================
// M4 — Action Bar + Composer
// ============================================================
const ActionBar = ({ onAssumir }) => (
  <div style={{
    padding: '8px 14px', borderTop: '1px solid var(--border)',
    display: 'flex', gap: 8, alignItems: 'center', background: 'var(--bg-elev)', flexShrink: 0, flexWrap: 'wrap',
  }}>
    <button className="btn btn-xs btn-ghost"><span style={{ width: 6, height: 6, borderRadius: '50%', background: '#22d3ee' }} />Wake-up</button>
    <button className="btn btn-xs btn-ghost"><span style={{ width: 6, height: 6, borderRadius: '50%', background: '#10b981' }} />Follow-up</button>
    <button className="btn btn-xs btn-ghost"><Icon name="calendar" size={11} />Disponibilidade</button>

    <div style={{ flex: 1 }} />

    <button style={{
      padding: '4px 8px', background: 'transparent', border: 0,
      color: 'var(--text-muted)', fontSize: 11, fontFamily: 'var(--font-display)',
      display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer',
      textDecoration: 'underline', textDecorationStyle: 'dotted', textUnderlineOffset: 3,
    }}>
      <Icon name="flag" size={11} />Marcar para revisão
    </button>

    <button onClick={onAssumir} title="Assumir conversa (A)" style={{
      padding: '7px 16px', borderRadius: 6,
      background: '#22d3ee', color: '#0a0e1a',
      border: 'none',
      fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-display)', letterSpacing: '0.05em',
      display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
      boxShadow: '0 4px 12px rgba(34,211,238,0.25)',
    }}>
      ASSUMIR CONVERSA <span style={{ fontSize: 14 }}>→</span>
    </button>
  </div>
);

const Composer = ({ value, onChange }) => {
  const [plusOpen, setPlusOpen] = React.useState(false);
  return (
    <div style={{ padding: 10, borderTop: '1px solid var(--border)', background: 'var(--bg-elev)', display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0, position: 'relative' }}>
      <button onClick={() => setPlusOpen(v => !v)} className="btn btn-xs" title="Acções rápidas">
        <Icon name="plus" size={12} /><span style={{ fontSize: 10 }}>▾</span>
      </button>
      {plusOpen && (
        <>
          <div onClick={() => setPlusOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 30 }} />
          <div style={{
            position: 'absolute', bottom: 'calc(100% + 4px)', left: 8, zIndex: 40,
            background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 6,
            width: 180, padding: 4, boxShadow: '0 -8px 20px rgba(0,0,0,0.4)',
          }}>
            {['Anexar ficheiro', 'Template', 'Inserir KB snippet', 'Quote'].map(item => (
              <button key={item} onClick={() => setPlusOpen(false)} style={menuItemStyle}>{item}</button>
            ))}
          </div>
        </>
      )}
      <input
        value={value} onChange={e => onChange(e.target.value)}
        placeholder="Escreve uma mensagem como humano…"
        style={{ flex: 1, background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 6, padding: '8px 12px', color: 'inherit', fontSize: 13, outline: 'none' }}
      />
      <button className="btn btn-sm btn-primary" title="Enter para enviar · Shift+Enter para nova linha"><Icon name="send" size={12} />Enviar</button>
    </div>
  );
};

// ============================================================
// M5 — Live Trace Panel (right, lead-score-first)
// ============================================================
const LiveTracePanel = ({ current, onOpenChat, expandThinking, setExpandThinking }) => {
  const scoreColor = current.score >= 80 ? '#10b981' : current.score >= 60 ? '#f59e0b' : '#64748b';
  const tier = current.score >= 80 ? 'hot' : current.score >= 60 ? 'warm' : current.score >= 40 ? 'lukewarm' : 'cold';
  return (
    <aside className="scrollbar" style={{ overflowY: 'auto', minHeight: 0, background: 'var(--bg-elev)', display: 'flex', flexDirection: 'column' }}>
      {/* === Block 1: LEAD SCORE === */}
      <div style={{ padding: 14, borderBottom: '1px solid var(--border)' }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', marginBottom: 6 }}>DIGI AI · LEAD SCORE</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
          <span className="font-display" style={{ fontSize: 44, fontWeight: 700, color: scoreColor, lineHeight: 1 }}>{current.score}</span>
          {current.score >= 80 && <span style={{ fontSize: 22 }}>⚡</span>}
          <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginLeft: 'auto' }}>/100</span>
        </div>
        <div style={{ height: 6, background: 'var(--border)', borderRadius: 3, overflow: 'hidden' }}>
          <div style={{ width: `${current.score}%`, height: '100%', background: scoreColor, borderRadius: 3 }} />
        </div>
        <div style={{ marginTop: 6, fontSize: 10, fontFamily: 'var(--font-mono)', color: scoreColor, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 700 }}>{tier}</div>

        <div style={{ marginTop: 12, padding: 10, background: 'var(--bg-sunken)', borderRadius: 6, border: '1px solid var(--border)' }}>
          <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', marginBottom: 4, letterSpacing: '0.05em' }}>▸ RECOMENDAÇÃO</div>
          <div style={{ fontSize: 11.5, lineHeight: 1.5, color: 'var(--text)' }}>
            {current.score >= 80 ? `${current.takenOver ? current.takenOver : 'Ana Rodrigues'} contacta em 2h. Perguntou preço 3×.`
              : current.score >= 60 ? 'Manter Digi AI em auto. Próximo follow-up amanhã 10h.'
              : 'Lead frio — adicionar a sequência de nurture (KB + content).'}
          </div>
          <button style={{
            marginTop: 10, width: '100%', padding: '6px 10px', borderRadius: 5,
            background: current.score >= 80 ? '#22d3ee' : 'transparent',
            color: current.score >= 80 ? '#0a0e1a' : 'var(--ai-500)',
            border: current.score >= 80 ? 'none' : '1px solid var(--border)',
            fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-display)', letterSpacing: '0.04em',
            cursor: 'pointer',
          }}>
            {current.score >= 80 ? 'ATRIBUIR ANA →' : 'VER PLANO →'}
          </button>
        </div>
      </div>

      {/* === Block 2: O que está a pensar (collapsed) === */}
      <button onClick={() => setExpandThinking(v => !v)} style={{
        padding: '10px 14px', borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'transparent', textAlign: 'left', width: '100%',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: 10, color: 'var(--text-dim)' }}>{expandThinking ? '▾' : '▸'}</span>
          <span style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>O QUE ESTÁ A PENSAR</span>
        </div>
        <span style={{ fontSize: 10, color: 'var(--text-dim)' }}>{expandThinking ? '−' : '+'}</span>
      </button>
      {expandThinking && (
        <div style={{ padding: '0 14px 12px', fontSize: 11.5, lineHeight: 1.5, color: 'var(--text-muted)', borderBottom: '1px solid var(--border)' }}>
          Lead em fase de comparação — terceira vez que pergunta preço. Sinal claro: preço é o bloqueio. Próxima resposta deve dar <strong style={{ color: 'var(--text)' }}>faixa</strong> (€0.8–€2.2/m²) e reforçar convite ao showroom para número exato.
        </div>
      )}

      {/* === Block 3: RAG === */}
      <div style={{ padding: 14, borderBottom: '1px solid var(--border)' }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', marginBottom: 8 }}>RAG · 5 FONTES ACTIVAS</div>
        {[
          { k: 'store_kb', ch: 'printplan/overview', rel: 0.94 },
          { k: 'mimaki_kb', ch: 'ujv200/specs', rel: 0.88 },
          { k: 'store_kb', ch: 'printplan/pricing', rel: 0.82 },
          { k: 'mimaki_man.', ch: 'ujv200/manual-pt', rel: 0.79 },
          { k: 'showroom', ch: 'prior-velho/agenda', rel: 0.71 },
        ].map((s, i) => (
          <button key={i} style={{
            width: '100%', padding: '5px 0', display: 'grid', gridTemplateColumns: '70px 1fr 38px 30px',
            gap: 6, alignItems: 'center', background: 'transparent', textAlign: 'left',
            borderBottom: i < 4 ? '1px solid color-mix(in oklch, var(--border) 60%, transparent)' : 'none',
          }}>
            <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--ai-500)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.k}</span>
            <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.ch}</span>
            <div style={{ height: 4, background: 'var(--border)', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{ width: `${s.rel * 100}%`, height: '100%', background: 'var(--ai-500)' }} />
            </div>
            <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text)', textAlign: 'right' }}>{s.rel.toFixed(2)}</span>
          </button>
        ))}
      </div>

      {/* === Block 4: SP/FRAMEs === */}
      <div style={{ padding: 14, borderBottom: '1px solid var(--border)' }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', marginBottom: 8 }}>SP / FRAMEs ACTIVOS</div>
        {[
          { id: 'SP_CLIENTES', v: 'v1.12.4' },
          { id: 'FRAME-PROSPECCAO', v: 'v1.2' },
          { id: 'FRAME-SIMULACAO-FIN', v: 'v2.0' },
          { id: 'FRAME-TROUBLESHOOT', v: 'v1.0' },
          { id: 'brand.mimaki', v: 'v1.0.5' },
        ].map((s, i) => (
          <button key={s.id} style={{
            width: '100%', padding: '4px 0', display: 'flex', justifyContent: 'space-between',
            background: 'transparent', textAlign: 'left',
            borderBottom: i < 4 ? '1px solid color-mix(in oklch, var(--border) 60%, transparent)' : 'none',
            fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-muted)',
          }}>
            <span style={{ color: 'var(--text)' }}>{s.id}</span>
            <span>{s.v}</span>
          </button>
        ))}
      </div>

      {/* === Block 5: Métricas 2x2 === */}
      <div style={{ padding: 14, borderBottom: '1px solid var(--border)' }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', marginBottom: 8 }}>MÉTRICAS</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
          {[['Duração', current.durationMin + 'm'], ['Turnos', '7'], ['Tokens', '12.4k'], ['Custo', '$0.38']].map(([k, v]) => (
            <div key={k} style={{ padding: '8px 10px', background: 'var(--bg-sunken)', borderRadius: 5, border: '1px solid var(--border)' }}>
              <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>{k}</div>
              <div className="font-display" style={{ fontWeight: 700, fontSize: 14, marginTop: 2 }}>{v}</div>
            </div>
          ))}
        </div>
        <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', marginTop: 8 }}>
          Modelo: Opus 4.7 · p50: 2.1s
        </div>
      </div>

      {/* Footer */}
      <div style={{ padding: 12, display: 'flex', gap: 6, borderTop: '1px solid var(--border)', marginTop: 'auto' }}>
        <button className="btn btn-xs btn-ai" style={{ flex: 1, justifyContent: 'center' }} onClick={onOpenChat}><Icon name="sparkle" size={11} />Perguntar Digi</button>
        <button className="btn btn-xs" style={{ flex: 1, justifyContent: 'center' }}><Icon name="doc" size={11} />Trace</button>
      </div>
    </aside>
  );
};

// ============================================================
// Info / Histórico / Notas tabs
// ============================================================
const ConvInfoPanel = ({ current }) => (
  <div style={{ padding: 24, flex: 1, overflowY: 'auto', background: 'var(--bg)' }}>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, maxWidth: 700 }}>
      {[
        ['Contacto', current.name + (current.company ? ' · ' + current.company : '')],
        ['Telefone', '+351 ····' + current.phone4],
        ['Marca', current.brand || '—'],
        ['Modo', current.mode === 'humano' ? `humano · ${current.takenOver}` : current.mode],
        ['Tópico', current.topic || '—'],
        ['Ambiente', current.env],
        ['Total mensagens', current.msgs],
        ['Duração', current.durationMin + ' min'],
        ['Lead score', current.score + '/100'],
        ['Última atividade', current.t + ' · hoje'],
      ].map(([k, v]) => (
        <div key={k} style={{ padding: 12, border: '1px solid var(--border)', borderRadius: 6, background: 'var(--bg-elev)' }}>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{k}</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>{v}</div>
        </div>
      ))}
    </div>
  </div>
);

const HistoricoPanel = ({ current }) => (
  <div style={{ padding: 24, flex: 1, overflowY: 'auto', background: 'var(--bg)' }}>
    <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', marginBottom: 12, letterSpacing: '0.06em' }}>HISTÓRICO · 5 INTERAÇÕES PRÉVIAS</div>
    {[
      { d: '23 Abr', t: 'WhatsApp', s: 'Pediu catálogo PrintPlan' },
      { d: '15 Abr', t: 'Showroom', s: 'Visita Prior Velho · viu UJV200' },
      { d: '02 Abr', t: 'Email', s: 'Cotação enviada · €36k' },
      { d: '21 Mar', t: 'WhatsApp', s: 'Primeiro contacto via Instagram' },
      { d: '15 Mar', t: 'Anúncio', s: 'Click no anúncio Meta · PrintPlan' },
    ].map((h, i) => (
      <div key={i} style={{ padding: '10px 12px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 12 }}>
        <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)', width: 60, flexShrink: 0 }}>{h.d}</span>
        <span style={{
          padding: '1px 6px', borderRadius: 3, fontSize: 9.5, fontFamily: 'var(--font-mono)', fontWeight: 600,
          background: 'var(--surface-muted)', color: 'var(--text-muted)', height: 16,
        }}>{h.t}</span>
        <span style={{ fontSize: 12, color: 'var(--text)' }}>{h.s}</span>
      </div>
    ))}
  </div>
);

const NotasPanel = () => (
  <div style={{ padding: 24, flex: 1, overflowY: 'auto', background: 'var(--bg)' }}>
    <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12 }}>
      <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', letterSpacing: '0.06em', flex: 1 }}>NOTAS · 2</span>
      <button className="btn btn-xs btn-primary"><Icon name="plus" size={11} />Nota</button>
    </div>
    {[
      { who: 'Ana Rodrigues', when: '23:42 · hoje', t: 'Cliente quer fechar até dia 30. Pediu desconto adicional — passei para Daniel aprovar.' },
      { who: 'Digi AI', when: '21:15 · ontem', t: 'Perguntou 3× pelo preço. Sinal forte de intenção. Recomendo escalar para humano.' },
    ].map((n, i) => (
      <div key={i} style={{ padding: 12, border: '1px solid var(--border)', borderRadius: 6, background: 'var(--bg-elev)', marginBottom: 8 }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', display: 'flex', gap: 6, marginBottom: 4 }}>
          <span style={{ color: n.who === 'Digi AI' ? 'var(--ai-500)' : 'var(--text-muted)' }}>{n.who}</span> · <span>{n.when}</span>
        </div>
        <div style={{ fontSize: 12, lineHeight: 1.5 }}>{n.t}</div>
      </div>
    ))}
  </div>
);

// ============================================================
// Drawer + Shortcuts modal
// ============================================================
const InfoDrawer = ({ current, onClose }) => (
  <>
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 50 }} />
    <aside style={{
      position: 'absolute', right: 0, top: 0, bottom: 0, width: 380, zIndex: 60,
      background: 'var(--bg-elev)', borderLeft: '1px solid var(--border)',
      display: 'flex', flexDirection: 'column',
      boxShadow: '-12px 0 30px rgba(0,0,0,0.4)',
    }}>
      <header style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div className="font-display" style={{ flex: 1, fontSize: 14, fontWeight: 600 }}>Info da conversa</div>
        <button onClick={onClose} className="btn btn-xs btn-ghost"><Icon name="close" size={12} /></button>
      </header>
      <div className="scrollbar" style={{ flex: 1, overflowY: 'auto', padding: 18 }}>
        <ConvInfoPanel current={current} />
      </div>
    </aside>
  </>
);

const ShortcutsModal = ({ onClose }) => {
  const groups = [
    { title: 'Navegação', items: [['J / K', 'mover entre conversas'], ['↵', 'abrir / responder'], ['Esc', 'fechar painéis']] },
    { title: 'Acções', items: [['A', 'assumir conversa'], ['R', 'responder rápido'], ['F', 'marcar para revisão'], ['P', 'pin']] },
    { title: 'Filtros', items: [['/', 'procurar'], ['1-4', 'quick filters'], ['⌘K', 'command palette']] },
    { title: 'Conversa', items: [['⌘↵', 'enviar'], ['⇧↵', 'nova linha'], ['⌘C', 'copiar mensagem']] },
  ];
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 100, display: 'grid', placeItems: 'center' }}>
        <div onClick={e => e.stopPropagation()} style={{
          width: 560, maxHeight: '80vh', overflow: 'auto',
          background: 'var(--bg-elev)', border: '1px solid var(--border)', borderRadius: 12,
          padding: 24, boxShadow: '0 24px 60px rgba(0,0,0,0.5)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
            <div className="font-display" style={{ flex: 1, fontSize: 18, fontWeight: 700 }}>Atalhos</div>
            <button onClick={onClose} className="btn btn-xs btn-ghost"><Icon name="close" size={12} /></button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
            {groups.map(g => (
              <div key={g.title}>
                <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', letterSpacing: '0.08em', marginBottom: 8 }}>{g.title.toUpperCase()}</div>
                {g.items.map(([k, v]) => (
                  <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0' }}>
                    <kbd style={{
                      padding: '2px 6px', fontSize: 10, fontFamily: 'var(--font-mono)',
                      background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 3,
                      minWidth: 32, textAlign: 'center',
                    }}>{k}</kbd>
                    <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{v}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

window.DevInbox = DevInbox;
