/* Prospecção · DigiBar — barra de prompt para a Digi AI
 * - input com placeholder rotativo
 * - sugestões contextuais (mudam c/ estado)
 * - histórico persistente (localStorage)
 * - colapsável
 * - trace visível quando Digi aplica filtros
 * - chips de bulk actions quando há selecção
 */

const PROSPEC_BULK_ACTIONS = [
  { id: 'emails', icon: 'mail', label: 'Gerar emails', desc: 'personalizados por lead' },
  { id: 'briefing', icon: 'doc', label: 'Briefings', desc: '5 min antes da chamada' },
  { id: 'priorizar', icon: 'phone', label: 'Ordem de chamadas', desc: 'top urgentes primeiro' },
  { id: 'sequence', icon: 'zap', label: 'Sequência multi-canal', desc: 'email → LI → call' },
  { id: 'export', icon: 'download', label: 'Exportar p/ Primavera', desc: 'como novos leads' },
];

// Sugestões contextuais — mudam consoante estado
const prospecSuggestions = (filters, leadsCount) => {
  const s = [];
  const hasFilters = filters.marca.length || filters.abordagem.length || filters.regiao.length || filters.minScore >= 8;

  if (hasFilters && leadsCount > 0 && leadsCount < 100) {
    // Filtros aplicados, lista pequena → acções
    if (filters.marca.length === 1) {
      s.push(`Gera emails personalizados para estes ${leadsCount} leads ${filters.marca[0]}`);
    } else {
      s.push(`Prepara briefings para os top ${Math.min(10, leadsCount)}`);
    }
    s.push('Ordena por urgência para chamada');
    s.push('Exporta para Primavera CRM');
    s.push('Identifica os 3 mais críticos');
  } else if (filters.minScore < 7) {
    s.push('Mostra-me os 9/10 com LinkedIn activo');
    s.push('Top 20 para BIOND esta semana');
    s.push('Leads em Madrid + Barcelona');
    s.push('Quem tem hiring + crescimento detectado');
  } else {
    // Estado neutro
    s.push('Top 20 para abordar esta semana');
    s.push('Distribuidores Mimaki com GMB ≥ 4.5');
    s.push('Financial Directors em Madrid');
    s.push('Prepara chamada para Alejandro');
  }
  return s;
};

const PROSPEC_PLACEHOLDER_EXAMPLES = [
  'mostra-me os 9/10 em Madrid com LinkedIn activo',
  'top 20 distribuidores para BIOND esta semana',
  'prepara email em espanhol para o Alejandro',
  'quem tem hiring + equipamento antigo?',
  'ordena os 40 top-score por urgência de chamada',
  'briefing de 5 min para a reunião com MKM',
];

// ---- Trace (o que a Digi fez) ----
const ProspecDigiTrace = ({ trace, onDismiss }) => {
  if (!trace) return null;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
      padding: '8px 12px', margin: '8px 0 0', borderRadius: 8,
      background: 'color-mix(in oklch, var(--ai-500) 8%, transparent)',
      border: '1px dashed color-mix(in oklch, var(--ai-500) 30%, var(--border))',
      fontSize: 11,
    }}>
      <Icon name="sparkle" size={11} style={{ color: 'var(--ai-500)' }} />
      <span style={{ color: 'var(--ai-500)', fontWeight: 600, fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>DIGI APLICOU</span>
      <span style={{ color: 'var(--text-muted)' }}>{trace.explain}</span>
      {trace.filters && Object.entries(trace.filters).map(([k, v]) => (
        <span key={k} style={{
          padding: '2px 7px', borderRadius: 4, fontSize: 10, fontFamily: 'var(--font-mono)',
          background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)',
        }}>
          {k}: {Array.isArray(v) ? v.join(',') : String(v)}
        </span>
      ))}
      <button onClick={onDismiss} style={{
        marginLeft: 'auto', background: 'transparent', border: 'none',
        color: 'var(--text-muted)', fontSize: 11, cursor: 'pointer', textDecoration: 'underline',
      }}>desfazer</button>
    </div>
  );
};

// ---- Resposta conversacional inline ----
const ProspecDigiAnswer = ({ answer, onDismiss, onAction }) => {
  if (!answer) return null;
  return (
    <div style={{
      margin: '10px 0 0', padding: 14, borderRadius: 10,
      background: 'var(--bg-elev)',
      border: '1px solid color-mix(in oklch, var(--ai-500) 30%, var(--border))',
      boxShadow: '0 4px 16px color-mix(in oklch, var(--ai-500) 6%, transparent)',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: answer.items ? 10 : 0 }}>
        <div style={{
          width: 26, height: 26, borderRadius: 7, flexShrink: 0,
          background: 'linear-gradient(135deg, var(--ai-500), color-mix(in oklch, var(--ai-500) 70%, #000))',
          display: 'grid', placeItems: 'center', color: '#fff',
        }}>
          <Icon name="sparkle" size={13} />
        </div>
        <div style={{ flex: 1, fontSize: 12.5, color: 'var(--text)', lineHeight: 1.55 }}>
          {answer.text}
        </div>
        <button onClick={onDismiss} style={{
          background: 'transparent', border: 'none', color: 'var(--text-muted)',
          cursor: 'pointer', padding: 2,
        }}>
          <Icon name="close" size={12} />
        </button>
      </div>
      {answer.items && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginLeft: 36 }}>
          {answer.items.map((it, i) => (
            <div key={i} style={{
              padding: '8px 10px', borderRadius: 6,
              background: 'var(--bg-sunken)', border: '1px solid var(--border-subtle)',
              fontSize: 11.5, display: 'flex', alignItems: 'center', gap: 8,
            }}>
              {it.kind && <span style={{
                fontSize: 10, fontFamily: 'var(--font-mono)', fontWeight: 700, letterSpacing: '0.04em',
                padding: '2px 6px', borderRadius: 4,
                background: 'color-mix(in oklch, var(--ai-500) 14%, transparent)',
                color: 'var(--ai-500)',
              }}>{it.kind}</span>}
              <span style={{ flex: 1 }}>{it.text}</span>
              {it.action && (
                <button onClick={() => onAction && onAction(it)} style={{
                  background: 'var(--ai-500)', color: '#fff', border: 'none',
                  padding: '4px 10px', borderRadius: 5, fontSize: 11, fontWeight: 600, cursor: 'pointer',
                }}>{it.action}</button>
              )}
            </div>
          ))}
        </div>
      )}
      {answer.followups && (
        <div style={{ marginLeft: 36, marginTop: 10, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {answer.followups.map((f, i) => (
            <button key={i} onClick={() => onAction && onAction({ kind: 'followup', text: f })} style={{
              padding: '4px 9px', borderRadius: 999, fontSize: 10.5,
              background: 'transparent', border: '1px solid var(--border)',
              color: 'var(--text-muted)', cursor: 'pointer', fontFamily: 'inherit',
            }}>↪ {f}</button>
          ))}
        </div>
      )}
    </div>
  );
};

// ---- Bulk actions strip (quando há leads filtrados < 100) ----
const ProspecBulkStrip = ({ count, onAction }) => {
  if (count === 0 || count > 150) return null;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
      padding: '10px 12px', margin: '8px 0 0', borderRadius: 8,
      background: 'color-mix(in oklch, var(--success) 6%, transparent)',
      border: '1px solid color-mix(in oklch, var(--success) 25%, var(--border))',
    }}>
      <span style={{ fontSize: 11, color: 'var(--success)', fontWeight: 600, fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>
        🎯 {count} LEADS · DIGI PODE
      </span>
      {PROSPEC_BULK_ACTIONS.map(a => (
        <button key={a.id} onClick={() => onAction(a)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '5px 10px', borderRadius: 6, fontSize: 11, fontWeight: 500,
          background: 'var(--bg)', border: '1px solid var(--border)',
          color: 'var(--text)', cursor: 'pointer', fontFamily: 'inherit',
          transition: 'all 0.1s',
        }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ai-500)'; e.currentTarget.style.color = 'var(--ai-500)'; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text)'; }}
          title={a.desc}
        >
          <Icon name={a.icon} size={11} />
          {a.label}
        </button>
      ))}
    </div>
  );
};

// ---- History dropdown ----
const ProspecHistoryDropdown = ({ history, onPick, onClear, onClose }) => (
  <div onClick={e => e.stopPropagation()} style={{
    position: 'absolute', top: '100%', left: 0, right: 0, marginTop: 4, zIndex: 20,
    background: 'var(--bg-elev)', border: '1px solid var(--border)',
    borderRadius: 10, overflow: 'hidden',
    boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
    maxHeight: 320, overflowY: 'auto',
  }}>
    <div style={{
      padding: '8px 12px', fontSize: 10, fontWeight: 700,
      fontFamily: 'var(--font-mono)', letterSpacing: '0.1em',
      color: 'var(--text-muted)', borderBottom: '1px solid var(--border-subtle)',
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    }}>
      <span>HISTÓRICO</span>
      {history.length > 0 && (
        <button onClick={onClear} style={{
          background: 'transparent', border: 'none', color: 'var(--text-muted)',
          fontSize: 10, cursor: 'pointer', textDecoration: 'underline',
          fontFamily: 'inherit',
        }}>limpar</button>
      )}
    </div>
    {history.length === 0 ? (
      <div style={{ padding: 16, fontSize: 11.5, color: 'var(--text-dim)', textAlign: 'center' }}>
        Sem histórico ainda.
      </div>
    ) : history.map((h, i) => (
      <button key={i} onClick={() => onPick(h.q)} style={{
        display: 'flex', alignItems: 'center', gap: 10, width: '100%',
        padding: '8px 12px', background: 'transparent', border: 'none',
        borderTop: i > 0 ? '1px solid var(--border-subtle)' : 'none',
        cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
        transition: 'background 0.1s',
      }}
        onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
      >
        <Icon name="history" size={11} style={{ color: 'var(--text-dim)', flexShrink: 0 }} />
        <span style={{ flex: 1, fontSize: 11.5, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {h.q}
        </span>
        <span style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', flexShrink: 0 }}>
          {h.results}
        </span>
      </button>
    ))}
  </div>
);

// ==== Main DigiBar ====
const ProspecDigiBar = ({
  filtersState, setFilters, setSort, setTab,
  leadsCount, onLeadFocus, onCollapseChange,
}) => {
  const HISTORY_KEY = 'digi-prospec-history';

  const [collapsed, setCollapsed] = React.useState(() => {
    try { return localStorage.getItem('digi-prospec-collapsed') === '1'; } catch { return false; }
  });
  const [query, setQuery] = React.useState('');
  const [history, setHistory] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]'); } catch { return []; }
  });
  const [historyOpen, setHistoryOpen] = React.useState(false);
  const [trace, setTrace] = React.useState(null);
  const [answer, setAnswer] = React.useState(null);
  const [placeholderIdx, setPlaceholderIdx] = React.useState(0);
  const [busy, setBusy] = React.useState(false);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    try { localStorage.setItem('digi-prospec-collapsed', collapsed ? '1' : '0'); } catch {}
    if (onCollapseChange) onCollapseChange(collapsed);
  }, [collapsed]);

  // placeholder rotation
  React.useEffect(() => {
    if (collapsed) return;
    const id = setInterval(() => setPlaceholderIdx(i => (i + 1) % PROSPEC_PLACEHOLDER_EXAMPLES.length), 4000);
    return () => clearInterval(id);
  }, [collapsed]);

  const saveHistory = (q, results) => {
    const newH = [{ q, results, ts: Date.now() }, ...history.filter(h => h.q !== q)].slice(0, 20);
    setHistory(newH);
    try { localStorage.setItem(HISTORY_KEY, JSON.stringify(newH)); } catch {}
  };

  const suggestions = React.useMemo(() => prospecSuggestions(filtersState, leadsCount), [filtersState, leadsCount]);

  // Simulated Digi reasoning — faz pattern matching sobre o prompt
  const handleSubmit = (q) => {
    if (!q.trim()) return;
    setBusy(true);
    setHistoryOpen(false);
    const text = q.toLowerCase();

    // pattern: score
    const scoreMatch = text.match(/(\d)\/10|score\s*(\d)|top\s*(\d+)?/);

    // pattern: cidade
    const cityMap = { 'madrid': 'Madrid', 'barcelona': 'Barcelona', 'valencia': 'Valencia', 'sevilla': 'Sevilla', 'bilbao': 'Bilbao' };
    const cityHit = Object.entries(cityMap).find(([k]) => text.includes(k));
    const regionMap = { 'madrid': 'Madrid', 'andaluc': 'Andalucía', 'catalu': 'Catalunya' };

    // pattern: marca
    const marcas = ['biond', 'mimaki', 'decal', 'sensek'];
    const marcaHit = marcas.find(m => text.includes(m));

    // pattern: sinais
    const linkedinHit = text.includes('linkedin');
    const gmbHit = text.includes('gmb') || /≥\s*4|4\.5/.test(text);
    const hiringHit = text.includes('hiring') || text.includes('contratand');
    const tel = text.includes('tel') || text.includes('chamada') || text.includes('ligar');

    // pattern: intent = action vs filter vs info
    const isEmail = text.includes('email') || text.includes('correio') || text.includes('escrev');
    const isBriefing = text.includes('briefing') || text.includes('reuni') || text.includes('prepara');
    const isExport = text.includes('exporta') || text.includes('primavera');
    const isOrder = text.includes('ordena') || text.includes('urgência') || text.includes('prioriz');

    setTimeout(() => {
      setBusy(false);
      const newFilters = { ...filtersState };
      const tracePieces = [];
      const traceFilters = {};

      // Aplica filtros detectados
      if (scoreMatch) {
        const n = parseInt(scoreMatch[1] || scoreMatch[2] || '8');
        if (!isNaN(n) && n >= 4 && n <= 9) {
          newFilters.minScore = n;
          tracePieces.push(`score ≥ ${n}`);
          traceFilters.score = `≥${n}`;
        }
      }
      if (marcaHit) {
        const proper = { 'biond': 'BIOND', 'mimaki': 'Mimaki', 'decal': 'Decal', 'sensek': 'Sensek' }[marcaHit];
        newFilters.marca = [proper];
        tracePieces.push(`marca ${proper}`);
        traceFilters.marca = proper;
      }
      if (cityHit) {
        // mapear cidade para região aprox
        const reg = prospecRegiaoOf(cityHit[1]);
        if (reg && reg !== 'Outras') {
          newFilters.regiao = [reg];
          tracePieces.push(`região ${reg}`);
          traceFilters.regiao = reg;
        }
      }
      if (linkedinHit) {
        newFilters.temLinkedin = true;
        tracePieces.push('com LinkedIn');
        traceFilters.linkedin = 'sim';
      }
      if (gmbHit) {
        newFilters.gmb45 = true;
        tracePieces.push('GMB ≥ 4.5');
        traceFilters.gmb = '≥4.5';
      }

      // Intenções de acção → resposta conversacional
      if (isEmail) {
        setAnswer({
          text: `Vou preparar **${Math.min(10, leadsCount)} emails personalizados** em espanhol, focados nos sinais de cada lead (hiring, equipamento actual, crescimento). Demoro ~30s.`,
          items: [
            { kind: 'PREVIEW', text: 'Estilo: formal curto · hook: match produto-empresa · CTA: demo de 30 min', action: 'Ver 1º' },
            { kind: 'AÇÕES', text: 'Enviar via Mailchimp · Review manual antes · A/B subjects', action: 'Escolher' },
          ],
          followups: ['Adapta tom para técnico', 'Inclui caso de estudo Lidergraf', 'Em português em vez de espanhol'],
        });
      } else if (isBriefing) {
        setAnswer({
          text: `Briefings de 5 min compilados de 5 fontes: Apollo + GMB + Axesor + LinkedIn + notícias. Cada um tem: perfil do decisor, contexto da empresa, 3 pontos de ancoragem para a chamada.`,
          items: [
            { kind: 'TOP 3', text: 'Alejandro Rodriguez (Grafietic) · Jesus Rodriguez (Grafietic) · Gina Nadal (Arpe Barcelona)', action: 'Abrir' },
          ],
          followups: ['Só Madrid', 'Incluir histórico de concorrência', 'Exportar p/ PDF'],
        });
      } else if (isExport) {
        setAnswer({
          text: `Vou exportar os ${leadsCount} leads filtrados para o Primavera CRM como novos prospects atribuídos ao Daniel. Status inicial: "A contactar".`,
          items: [
            { kind: 'CONFIRMAR', text: `${leadsCount} leads · owner Daniel · pipeline Prospecção ES`, action: 'Exportar' },
          ],
        });
      } else if (isOrder) {
        setSort && setSort('score');
        setAnswer({
          text: `Ordenei por urgência combinada (score + fresh signal + GMB activo). Top 3: focar esta semana. Próximos 7: follow-up em 3 dias.`,
          followups: ['Agendar chamadas para amanhã', 'Ver só top 3', 'Adicionar filtro tel disponível'],
        });
      } else if (tracePieces.length === 0) {
        // Sem padrão claro → resposta genérica informativa
        setAnswer({
          text: `Não consegui mapear essa pergunta a filtros automáticos. Podes reformular ou usar um dos exemplos em baixo — também posso explicar o scoring se preciso.`,
          followups: ['Como é calculado o score?', 'Mostra leads urgentes', 'Ajuda'],
        });
      }

      if (tracePieces.length > 0) {
        setFilters(newFilters);
        setTrace({ explain: tracePieces.join(' + '), filters: traceFilters });
      } else {
        setTrace(null);
      }

      // count será calculado após filtros. Guardamos o query com count aprox
      saveHistory(q, `${tracePieces.length > 0 ? '~filtered' : '—'}`);
      setQuery('');
    }, 500);
  };

  const handleBulkAction = (action) => {
    setAnswer({
      text: `Acção: **${action.label}** · ${action.desc}. Aplicada aos ${leadsCount} leads actualmente filtrados.`,
      items: [
        { kind: action.id.toUpperCase(), text: `Processar ${leadsCount} leads`, action: 'Confirmar' },
      ],
    });
  };

  const handleAnswerAction = (it) => {
    if (it.kind === 'followup') {
      setQuery(it.text);
      inputRef.current?.focus();
    } else {
      alert('Acção: ' + (it.text || it.kind));
    }
  };

  if (collapsed) {
    return (
      <div style={{
        padding: '8px 20px', borderBottom: '1px solid var(--border)',
        background: 'var(--bg-elev)',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <button onClick={() => setCollapsed(false)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '6px 12px', borderRadius: 999,
          background: 'linear-gradient(135deg, var(--ai-500), color-mix(in oklch, var(--ai-500) 70%, #000))',
          color: '#fff', border: 'none', cursor: 'pointer',
          fontSize: 11.5, fontWeight: 600, fontFamily: 'inherit',
          boxShadow: '0 2px 8px color-mix(in oklch, var(--ai-500) 30%, transparent)',
        }}>
          <Icon name="sparkle" size={12} />
          Pergunta à Digi…
        </button>
        <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
          Ex: <em>{PROSPEC_PLACEHOLDER_EXAMPLES[placeholderIdx]}</em>
        </span>
      </div>
    );
  }

  return (
    <div style={{
      padding: '12px 20px 14px', borderBottom: '1px solid var(--border)',
      background: 'linear-gradient(180deg, color-mix(in oklch, var(--ai-500) 3%, var(--bg-elev)) 0%, var(--bg-elev) 100%)',
      position: 'relative',
    }}>
      {/* Input row */}
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ position: 'relative', flex: 1 }}>
          <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{
              width: 22, height: 22, borderRadius: 6,
              background: 'linear-gradient(135deg, var(--ai-500), color-mix(in oklch, var(--ai-500) 70%, #000))',
              display: 'grid', placeItems: 'center', color: '#fff',
            }}>
              <Icon name="sparkle" size={12} />
            </div>
            {busy && (
              <span style={{ fontSize: 10, color: 'var(--ai-500)', fontFamily: 'var(--font-mono)', fontWeight: 700, letterSpacing: '0.1em' }}>
                PENSANDO…
              </span>
            )}
          </div>
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') handleSubmit(query); if (e.key === 'Escape') setHistoryOpen(false); }}
            onFocus={() => setHistoryOpen(false)}
            placeholder={`Pergunta à Digi… ex: "${PROSPEC_PLACEHOLDER_EXAMPLES[placeholderIdx]}"`}
            style={{
              width: '100%', padding: '11px 110px 11px 46px',
              borderRadius: 10, border: '1px solid color-mix(in oklch, var(--ai-500) 30%, var(--border))',
              background: 'var(--bg)', color: 'var(--text)',
              fontSize: 13, fontFamily: 'inherit',
              outline: 'none', transition: 'border 0.1s, box-shadow 0.1s',
            }}
            onFocusCapture={e => { e.target.style.borderColor = 'var(--ai-500)'; e.target.style.boxShadow = '0 0 0 3px color-mix(in oklch, var(--ai-500) 15%, transparent)'; }}
            onBlurCapture={e => { e.target.style.borderColor = 'color-mix(in oklch, var(--ai-500) 30%, var(--border))'; e.target.style.boxShadow = 'none'; }}
          />
          <div style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', display: 'flex', alignItems: 'center', gap: 4 }}>
            <button onClick={() => setHistoryOpen(!historyOpen)}
              title="Histórico"
              style={{
                width: 28, height: 28, borderRadius: 6,
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: 'var(--text-muted)',
                display: 'grid', placeItems: 'center',
              }}>
              <Icon name="history" size={13} />
            </button>
            <button onClick={() => handleSubmit(query)}
              disabled={!query.trim() || busy}
              style={{
                padding: '6px 12px', borderRadius: 7,
                background: query.trim() ? 'var(--ai-500)' : 'var(--bg-sunken)',
                color: query.trim() ? '#fff' : 'var(--text-dim)',
                border: 'none', cursor: query.trim() ? 'pointer' : 'not-allowed',
                fontSize: 11.5, fontWeight: 600, fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 5,
              }}>
              <Icon name="send" size={11} />
              Enviar
            </button>
          </div>

          {historyOpen && <ProspecHistoryDropdown
            history={history}
            onPick={(q) => { setQuery(q); setHistoryOpen(false); inputRef.current?.focus(); }}
            onClear={() => { setHistory([]); try { localStorage.removeItem(HISTORY_KEY); } catch {} }}
            onClose={() => setHistoryOpen(false)}
          />}
        </div>

        <button onClick={() => setCollapsed(true)}
          title="Esconder Digi"
          style={{
            width: 32, height: 32, borderRadius: 7,
            background: 'transparent', border: '1px solid var(--border)',
            color: 'var(--text-muted)', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
          <Icon name="chevron" size={13} />
        </button>
      </div>

      {/* Suggestions */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
        <span style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', marginRight: 4 }}>
          SUGESTÕES
        </span>
        {suggestions.map((s, i) => (
          <button key={i} onClick={() => { setQuery(s); handleSubmit(s); }} style={{
            padding: '4px 10px', borderRadius: 999, fontSize: 11,
            background: 'var(--bg)', border: '1px solid var(--border)',
            color: 'var(--text-muted)', cursor: 'pointer', fontFamily: 'inherit',
            transition: 'all 0.1s',
          }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ai-500)'; e.currentTarget.style.color = 'var(--ai-500)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text-muted)'; }}
          >{s}</button>
        ))}
      </div>

      {/* Trace */}
      <ProspecDigiTrace trace={trace} onDismiss={() => setTrace(null)} />

      {/* Conversational answer */}
      <ProspecDigiAnswer answer={answer} onDismiss={() => setAnswer(null)} onAction={handleAnswerAction} />

      {/* Bulk strip — aparece quando lista filtrada está em tamanho "actuável" */}
      {(filtersState.marca.length > 0 || filtersState.abordagem.length > 0 || filtersState.regiao.length > 0 || filtersState.minScore >= 8) && (
        <ProspecBulkStrip count={leadsCount} onAction={handleBulkAction} />
      )}
    </div>
  );
};

window.ProspecDigiBar = ProspecDigiBar;
