/* Hexis AI — Omnipresent Intelligence Layer v4
   Speed: instant keyword response + async LLM upgrade
   Persistence: session msgs survive page navigation
   BLS: behavioral tracking feeds context
*/
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH, useCallback: useCallbackH } = React;

/* ═══════════════════════════════════════════════════════════
   SESSION STORE — persists conversation across page nav
   Cleared only on explicit close or site reload
═══════════════════════════════════════════════════════════ */
/* Load persisted msgs from localStorage so they survive browser close + close button */
const _STORAGE_KEY = 'hexis_msgs_v2';
const _loadPersisted = () => { try { return JSON.parse(localStorage.getItem(_STORAGE_KEY) || '[]'); } catch { return []; } };
let _sessionMsgs    = _loadPersisted();
let _sessionGreeted = _sessionMsgs.length > 0;  // skip greeting if msgs already exist

/* ═══════════════════════════════════════════════════════════
   HEXIS STORE — alert/open state
═══════════════════════════════════════════════════════════ */
const HexisStore = (() => {
  const subs = new Set();
  let state = {
    open: false,
    seenAt: Date.now() - 1,
    alerts: [
      { id: 'a1', kind: 'success', title: 'Match Premium identificado', body: 'Miguel Tavares · Veridian VC · 98% — janela ótima 14:32–14:50.', at: Date.now() - 60000 * 6, action: 'Ver Match' },
      { id: 'a2', kind: 'warning', title: 'Decisão pendente',           body: 'RFP Banco Invicta expira em 3h. Resposta sugerida pronta.',       at: Date.now() - 60000 * 12, action: 'Responder' },
      { id: 'a3', kind: 'info',    title: 'Pipeline atualizado',        body: '€420K em novas oportunidades atribuídas ao Web Summit.',          at: Date.now() - 60000 * 22 },
    ],
  };
  const notify = () => subs.forEach(fn => fn({ ...state }));
  return {
    get()         { return { ...state }; },
    subscribe(fn) { subs.add(fn); fn({ ...state }); return () => subs.delete(fn); },
    open()        { state = { ...state, open: true, seenAt: Date.now() }; notify(); },
    close()       { state = { ...state, open: false }; notify(); },
    clearHistory(){ _sessionMsgs = []; _sessionGreeted = false; },
    addAlert(a)   {
      const id = 'a_' + Math.random().toString(36).slice(2, 8);
      state = { ...state, alerts: [{ id, at: Date.now(), ...a }, ...state.alerts.slice(0, 19)] };
      notify();
    },
    unreadCount()  { return state.alerts.filter(a => a.at > state.seenAt).length; },
    highestKind()  {
      const order = ['danger', 'warning', 'success', 'info'];
      const unseen = state.alerts.filter(a => a.at > state.seenAt);
      for (const k of order) if (unseen.find(a => a.kind === k)) return k;
      return null;
    },
  };
})();
window.HexisStore = HexisStore;

/* ═══════════════════════════════════════════════════════════
   BLS — Behavioral Learning Stream (Edge capture)
   Tracks scroll, dwell, CTAs → feeds HexisEngine context
═══════════════════════════════════════════════════════════ */
const HexisBLS = (() => {
  const _buffer = [];
  const _sessionHash = 'bls_' + Math.random().toString(36).slice(2, 10);
  let _lastFlush = Date.now();

  const track = (type, target, value) => {
    _buffer.push({ type, target, value, ts: new Date().toISOString() });
    // Feed HexisEngine immediately for local context updates
    if (window.HexisEngine) {
      if (type === 'cta_click') HexisEngine.trackClick(target);
      if (type === 'page_view') HexisEngine.trackPage(target);
    }
    // Batch flush every 8 seconds
    if (Date.now() - _lastFlush > 8000 && _buffer.length > 0) flush();
  };

  const flush = () => {
    if (_buffer.length === 0) return;
    const batch = _buffer.splice(0, _buffer.length);
    _lastFlush = Date.now();
    const token = window.getAuthToken ? window.getAuthToken() : null;
    const userId = window.getAuthUser ? window.getAuthUser()?.id : null;
    const headers = { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) };
    const base = (typeof API_BASE !== 'undefined') ? API_BASE : 'https://api.marcianusexperience.com/api/v1';
    // Fire-and-forget each event, matching analytics schema: { action, category, label, value, user_id }
    batch.forEach(ev => {
      fetch(`${base}/analytics/track`, {
        method: 'POST', headers,
        body: JSON.stringify({
          user_id:    userId,
          session_id: _sessionHash,
          action:     ev.type,
          category:   ev.type.includes('scroll') ? 'engagement' : ev.type.includes('chat') ? 'assistant' : 'navigation',
          label:      ev.target,
          value:      typeof ev.value === 'number' ? ev.value : 1,
          metadata:   { page: window.location.pathname },
        }),
        signal: AbortSignal.timeout(3000),
      }).catch(() => {}); // silent fail — BLS is non-blocking
    });
  };

  // Scroll depth tracker
  const initScroll = () => {
    let _maxScroll = 0;
    document.addEventListener('scroll', () => {
      const pct = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
      if (pct > _maxScroll + 10) {
        _maxScroll = pct;
        track('scroll_depth', window.location.pathname, pct);
      }
    }, { passive: true });
  };

  setTimeout(initScroll, 1000);
  setInterval(flush, 8000);

  return { track };
})();
window.HexisBLS = HexisBLS;

/* ═══════════════════════════════════════════════════════════
   INSIGHT BAR — inline contextual recommendations
═══════════════════════════════════════════════════════════ */
const HexisInsightBar = ({ page }) => {
  const [recs, setRecs]           = useStateH([]);
  const [idx, setIdx]             = useStateH(0);
  const [dismissed, setDismissed] = useStateH(false);

  useEffectH(() => {
    if (!window.HexisEngine) return;
    setRecs(HexisEngine.getPageRecs(page));
    setIdx(0);
    setDismissed(false);
  }, [page]);

  useEffectH(() => {
    if (recs.length <= 1) return;
    const t = setInterval(() => setIdx(i => (i + 1) % recs.length), 8000);
    return () => clearInterval(t);
  }, [recs]);

  if (dismissed || recs.length === 0) return null;
  const r = recs[idx];
  const kindColors = { success: '#00C48C', warning: '#FFD700', danger: '#FF3B5C', info: '#00D1FF', gold: '#FFD700' };
  const col = kindColors[r.kind] || '#7B61FF';

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '9px 16px', background: col + '0D', borderBottom: `1px solid ${col}25`, fontSize: 13 }}>
      <div style={{ width: 24, height: 24, borderRadius: 6, background: col + '20', display: 'flex', alignItems: 'center', justifyContent: 'center', color: col, flexShrink: 0 }}>
        <Icon name={r.icon || 'sparkles'} size={13} />
      </div>
      <div style={{ flex: 1, color: 'var(--text-2)', lineHeight: 1.4 }}>
        <strong style={{ color: col, marginRight: 6 }}>Hexis AI</strong>{r.title} — {r.body}
      </div>
      {r.action && (
        <button
          style={{ flexShrink: 0, padding: '4px 12px', borderRadius: 6, background: col + '18', border: `1px solid ${col}40`, color: col, fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap' }}
          onClick={() => { SoundFX.tap(); HexisBLS.track('cta_click', r.action, 1); setDismissed(true); }}>
          {r.action}
        </button>
      )}
      {recs.length > 1 && (
        <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
          {recs.map((_, i) => <div key={i} style={{ width: 5, height: 5, borderRadius: '50%', background: i === idx ? col : col + '40', transition: 'background 0.3s' }} />)}
        </div>
      )}
      <button style={{ flexShrink: 0, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-3)', padding: '0 4px' }} onClick={() => setDismissed(true)}>
        <Icon name="x" size={12} />
      </button>
    </div>
  );
};
window.HexisInsightBar = HexisInsightBar;

/* ═══════════════════════════════════════════════════════════
   FAB — floating action button
═══════════════════════════════════════════════════════════ */
const HexisFab = () => {
  const [s, setS] = useStateH(HexisStore.get());
  useEffectH(() => HexisStore.subscribe(setS), []);
  const unread    = s.alerts.filter(a => a.at > s.seenAt).length;
  const kind      = HexisStore.highestKind ? HexisStore.highestKind() : null;
  const showLight = unread > 0 && !s.open;
  return (
    <button className="hexis-fab" aria-label="Abrir Hexis AI"
      onClick={() => { SoundFX.tap(); s.open ? HexisStore.close() : HexisStore.open(); }}>
      <span className="symbol">⟡</span>
      <span className={`alert-light ${kind || ''} ${showLight ? '' : 'hidden'}`}>{unread > 9 ? '9+' : unread}</span>
    </button>
  );
};

/* ═══════════════════════════════════════════════════════════
   MAIN POPUP
═══════════════════════════════════════════════════════════ */
const HexisPopup = () => {
  const [s, setS]             = useStateH(HexisStore.get());
  const [profile, setProfile] = useStateH(window.HexisEngine ? HexisEngine.getProfile() : {});
  const [tab, setTab]         = useStateH('chat');
  const [msgs, setMsgsState]  = useStateH(_sessionMsgs);
  const [input, setInput]     = useStateH('');
  const [busy, setBusy]       = useStateH(false);   // true while instant response shown + LLM upgrading
  const scrollRef             = useRefH(null);
  const inputRef              = useRefH(null);
  const msgsRef               = useRefH(_sessionMsgs);
  const popupRef              = useRefH(null);

  // Persist msgs to module variable + localStorage whenever they change
  const setMsgs = (updater) => {
    setMsgsState(prev => {
      const next = typeof updater === 'function' ? updater(prev) : updater;
      _sessionMsgs = next;
      msgsRef.current = next;
      try { localStorage.setItem(_STORAGE_KEY, JSON.stringify(next.slice(-60))); } catch {}
      return next;
    });
  };

  useEffectH(() => HexisStore.subscribe(setS), []);
  useEffectH(() => {
    if (!window.HexisEngine) return;
    return HexisEngine.subscribe(p => setProfile({ ...p }));
  }, []);

  /* ── Click-outside closes popup ──────────────────────────── */
  useEffectH(() => {
    if (!s.open) return;
    const onDown = (e) => {
      if (popupRef.current && !popupRef.current.contains(e.target)) {
        // Don't close if clicking the FAB itself
        if (e.target.closest('.hexis-fab')) return;
        HexisStore.close();
      }
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [s.open]);

  /* ── Show greeting only if no session history ─────────────── */
  useEffectH(() => {
    if (!s.open) return;
    if (_sessionGreeted && _sessionMsgs.length > 0) {
      // Restore existing conversation
      setMsgsState(_sessionMsgs);
      return;
    }
    _sessionGreeted = true;
    const authUser = window.getAuthUser ? getAuthUser() : null;
    const isGuest  = !authUser;
    const p        = window.HexisEngine ? HexisEngine.getProfile() : {};
    const page     = p.currentPage || 'home';
    const mis      = (p.misScore || 0.30).toFixed(2);
    const firstName = authUser?.name?.split(' ')[0] || null;

    let greeting;
    let suggestions;

    if (isGuest) {
      const guestGreetings = {
        home:               `Olá! Sou o Hexis AI — o motor de inteligência da Marcianus. Analiso comportamento B2B e identifico conexões de alto valor. Faz login para matching personalizado.`,
        entrar:             `Bem-vindo! Cria uma conta gratuita ou faz login para aceder ao matching B2B, dashboard e Hexis AI completo.`,
        eventos:            `Temos 6 eventos confirmados para 2026 — de FinTech Lisboa ao Marcianus Summit (600 pax, 25 Out). Login para recomendações personalizadas.`,
        pricing:            `Planos desde €0 (Starter) até Enterprise. Para recomendação personalizada ao teu perfil, faz login ou fala connosco.`,
        sobre:              `A Marcianus nasceu para acabar com eventos sem resultado mensurável. Posso agendar uma call com o fundador Israel Nzambi.`,
        conteudos:          `10 peças disponíveis — 4 gratuitas. Gratuito em destaque: "A morte do networking espontâneo" (6 min). O que preferes?`,
        marketplace:        `Kiosk NFC, Hexis AI Live, Pack Leads — produtos para eventos B2B de alto valor. Login para ver preços personalizados.`,
        'criar-experiencia':`Para criar uma experiência Marcianus, preciso de conhecer o teu perfil. Login para iniciar o Briefing Inteligente.`,
      };
      greeting    = guestGreetings[page] || `Olá! Sou o Hexis AI da Marcianus. Faz login para matching B2B personalizado e dashboard completo.`;
      suggestions = ['Criar Conta Grátis', 'Ver Eventos', 'Como funciona?'];
    } else {
      const activeMissions = window.HexisEngine ? HexisEngine.getActiveMissions().length : 0;
      const authGreetings = {
        home:               `Olá ${firstName}! MIS atual: ${mis}. ${HexisStore.get().alerts.length} alertas. O que queres optimizar hoje?`,
        eventos:            `FinTech Lisboa 2026 está LIVE agora. Próximo: Aether Real Estate (20 Mai). Qual te interessa?`,
        dashboard:          `Hub operacional: ${activeMissions} missões ativas. Por onde queres começar?`,
        marketplace:        `Marketplace: saldo €${(p.walletBalance || 0).toLocaleString('pt-PT')}. Produto recomendado: Hexis AI Live.`,
        'criar-experiencia':`Briefing ligado para o teu perfil (${p.sector || 'Tech'} · ${p.role || 'Executivo'}). Pronto para guiar o setup.`,
        pricing:            `Posso calcular o ROI esperado para o teu perfil. Ou ver plano recomendado?`,
        sobre:              `Posso agendar uma call com o founder Israel Nzambi. Tens disponibilidade esta semana?`,
        conteudos:          `10 peças disponíveis. Gratuitos: "A morte do networking espontâneo" e Podcast #08. O que preferes?`,
        entrar:             `Olá ${firstName}! Já estás autenticado. Vai ao Dashboard para ver o teu perfil completo.`,
      };
      greeting    = authGreetings[page] || `Olá ${firstName}. MIS ${mis}. O que precisas?`;
      const recs  = window.HexisEngine ? HexisEngine.getPageRecs(page) : [];
      suggestions = recs.length > 0 ? recs.slice(0, 3).map(r => r.action) : ['Ver matches', 'Próximo evento', 'Resumo do dia'];
    }

    const greetMsg = { id: 1, from: 'hexis', text: greeting, suggestions };
    _sessionMsgs = [greetMsg];
    msgsRef.current = [greetMsg];
    setMsgsState([greetMsg]);
  }, [s.open]);

  /* ── Auto-scroll to bottom ─────────────────────────────────── */
  useEffectH(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs]);

  /* ── Scroll to bottom when popup opens ─────────────────────── */
  useEffectH(() => {
    if (!s.open) return;
    const id = setTimeout(() => {
      if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }, 80);
    return () => clearTimeout(id);
  }, [s.open]);

  /* ── Respond: instant local → async LLM upgrade ────────────── */
  /* Strip LLM markdown so it renders as clean text */
  const stripMd = (t) => (t || '')
    .replace(/\*\*([^*]+)\*\*/g, '$1')
    .replace(/\*([^*]+)\*/g, '$1')
    .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
    .replace(/#{1,6}\s+/gm, '')
    .replace(/^[\s]*[-*]\s+/gm, '• ')
    .trim();

  const respond = useCallbackH(async (userText) => {
    if (!userText.trim() || busy) return;
    SoundFX.tap();
    HexisBLS.track('hexis_chat', userText.slice(0, 60), 1);
    if (window.HexisEngine) HexisEngine.trackClick('hexis_chat');

    const page    = window.HexisEngine ? HexisEngine.getProfile().currentPage : 'home';
    const msgId   = Date.now();
    const history = msgsRef.current.filter(m => m.id !== 1);

    const local = window.HexisLocal
      ? HexisLocal.respond(userText, page)
      : { text: 'Hexis AI a iniciar…', suggestions: ['Ver Eventos', 'Ver Preços', 'Como funciona?'], fromLocal: true };

    setBusy(true);
    setMsgs(prev => [...prev, { id: msgId, from: 'hexis', text: local.text, suggestions: local.suggestions, fromLLM: false, fromLocal: true }]);
    SoundFX.notify();

    const onToken = (partial) => {
      if (!partial || typeof partial !== 'string') return;
      setMsgs(prev => prev.map(m => m.id === msgId
        ? { ...m, text: stripMd(partial), thinking: false, fromLLM: true, fromLocal: false }
        : m
      ));
    };

    try {
      const result = window.HexisBackend
        ? await window.HexisBackend.chat(userText, history, page, onToken)
        : window.HexisOllama
          ? await window.HexisOllama.streamResponse(userText, history, page, onToken)
          : null;

      if (result?.fromLLM === true && result?.text && result.text.length > 15) {
        setMsgs(prev => prev.map(m => m.id === msgId
          ? { ...m, text: stripMd(result.text), thinking: false, fromLLM: true, fromLocal: false, suggestions: result.suggestions?.length ? result.suggestions : local.suggestions }
          : m
        ));
      }
    } catch (_) { /* local response stays */ }
    finally { setBusy(false); }
  }, [busy]);


  const send = (text) => {
    const t = (text || input).trim();
    if (!t || busy) return;
    const userMsg = { id: Date.now() - 1, from: 'me', text: t };
    setMsgs(prev => [...prev, userMsg]);
    setInput('');
    respond(t);
  };

  /* Close — do NOT clear history; conversation persists (localStorage) */
  const handleClose = () => { SoundFX.tap(); HexisStore.close(); };

  /* Nova Conversa — explicit user action to reset */
  const newConversation = () => {
    try { localStorage.removeItem(_STORAGE_KEY); } catch {}
    _sessionMsgs    = [];
    _sessionGreeted = false;
    msgsRef.current = [];
    setMsgsState([]);
    HexisStore.close();
    setTimeout(() => HexisStore.open(), 80);
  };

  const lp = window.HexisEngine ? HexisEngine.getLevelProgress() : { level: 1, tier: 'bronze', xp: 0, pct: 0, xpToNext: 200 };
  const activeMissions = window.HexisEngine ? HexisEngine.getActiveMissions() : [];
  const authUser = window.getAuthUser ? getAuthUser() : null;
  const isGuest  = !authUser;

  // User avatar initials
  const userInitials = authUser?.name
    ? authUser.name.split(' ').slice(0, 2).map(w => w[0]).join('').toUpperCase()
    : 'Tu';

  if (!s.open) return null;

  return (
    <div className="hexis-popup" ref={popupRef} role="dialog" aria-label="Hexis AI">
      {/* Header */}
      <div className="hexis-popup-head">
        <div className="hexis-avatar">⟡</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="ttl">Hexis AI · {(profile.currentPage || 'home').toUpperCase()}</div>
          <div className="stat" style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
            {isGuest ? (
              <span style={{ fontSize: 10, color: 'var(--text-3)' }}>modo visitante · login para MIS completo</span>
            ) : (
              <span>MIS {(profile.misScore || 0.30).toFixed(2)} · L{lp.level} {lp.tier}</span>
            )}
            {busy && (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--purple-soft)', background: 'rgba(123,97,255,0.12)', border: '1px solid rgba(123,97,255,0.3)', borderRadius: 4, padding: '1px 5px' }}>
                <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--purple-soft)', display: 'inline-block', animation: 'pulse 1s infinite' }} />
                a melhorar…
              </span>
            )}
          </div>
        </div>
        <div className="actions">
          <button className="icon-btn" title="Nova Conversa" onClick={newConversation} style={{ fontSize: 10, letterSpacing: 0.3, padding: '3px 6px', borderRadius: 5 }}>
            <Icon name="rotate-ccw" size={13} />
          </button>
          <button className="icon-btn" title="Som" onClick={() => { const m = !SoundFX.isMuted(); SoundFX.setMuted(m); ToastBus.push({ title: m ? 'Som silenciado' : 'Som ativado', icon: m ? 'volume-x' : 'volume-2' }); }}>
            <Icon name={SoundFX.isMuted() ? 'volume-x' : 'volume-2'} size={16} />
          </button>
          <button className="icon-btn" title="Fechar" onClick={handleClose}>
            <Icon name="x" size={16} />
          </button>
        </div>
      </div>

      {/* XP progress — only for authenticated users */}
      {!isGuest && (
        <div style={{ padding: '7px 14px', borderBottom: '1px solid rgba(255,255,255,0.06)', background: 'rgba(123,97,255,0.04)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-3)', marginBottom: 3 }}>
            <span>{(profile.xp || 0).toLocaleString()} XP · {(lp.tier || 'bronze').toUpperCase()}</span>
            <span>{lp.xpToNext} XP para L{lp.level + 1}</span>
          </div>
          <div style={{ height: 3, background: 'rgba(255,255,255,0.08)', borderRadius: 2 }}>
            <div style={{ height: '100%', width: `${lp.pct || 0}%`, background: 'linear-gradient(90deg, #7B61FF, #A78BFA)', borderRadius: 2, transition: 'width 0.6s ease' }} />
          </div>
        </div>
      )}

      {/* Tabs */}
      <div style={{ display: 'flex', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
        {[
          { id: 'chat',     label: 'Chat' },
          { id: 'alerts',   label: `Alertas${s.alerts.filter(a => a.at > s.seenAt).length > 0 ? ' · ' + s.alerts.filter(a => a.at > s.seenAt).length : ''}` },
          { id: 'missions', label: `Missões${activeMissions.length > 0 ? ' · ' + activeMissions.length : ''}` },
        ].map(t => (
          <button key={t.id} onClick={() => { SoundFX.tap(); setTab(t.id); }}
            style={{ flex: 1, padding: '8px 4px', background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 700, color: tab === t.id ? 'var(--purple-soft)' : 'var(--text-3)', borderBottom: tab === t.id ? '2px solid var(--purple-soft)' : '2px solid transparent', transition: 'all 0.2s' }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* ── CHAT TAB ──────────────────────────────────────────── */}
      {tab === 'chat' && (
        <>
          <div className="hexis-msgs" ref={scrollRef}>
            {msgs.map(m => (
              <div key={m.id} className={`msg from-${m.from}`}>
                <div className="avatar">
                  {m.from === 'hexis' ? '⟡' : userInitials}
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div className="bubble">
                    {(m.fromLLM ? stripMd(m.text) : m.text)}
                    {m.fromLLM === true && (
                      <span title="Resposta gerada pelo LLM" style={{ marginLeft: 6, fontSize: 9, fontFamily: 'var(--font-mono)', color: 'rgba(123,97,255,0.5)', verticalAlign: 'middle' }}>⟡llm</span>
                    )}
                    {m.fromLocal === true && !m.fromLLM && (
                      <span title="Resposta local" style={{ marginLeft: 6, fontSize: 9, fontFamily: 'var(--font-mono)', color: 'rgba(0,209,255,0.45)', verticalAlign: 'middle' }}>⟡local</span>
                    )}
                  </div>
                  {m.suggestions?.length > 0 && (
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                      {m.suggestions.map((sg, i) => (
                        <button key={i} className="sg-chip"
                          onClick={() => {
                            SoundFX.tap();
                            HexisBLS.track('suggestion_click', sg, 1);
                            const t = sg.toLowerCase();
                            const nav = window._appNav;
                            /* Route lookup — maps suggestion text patterns to navigation or external actions */
                            const ROUTES = [
                              { match: ['whatsapp', '+244', 'pedir orçamento', 'pedir orcamento'], action: () => window.open('https://wa.me/244930179037', '_blank') },
                              { match: ['linkedin', 'ver linkedin'], action: () => window.open('https://linkedin.com/company/marcianus', '_blank') },
                              { match: ['ver eventos', 'próximo evento', 'proximo evento', 'eventos 2026', 'comprar bilhete'], action: () => nav && (nav('eventos'), HexisStore.close()) },
                              { match: ['criar conta', 'registar', 'login', 'entrar'], action: () => nav && (nav('entrar'), HexisStore.close()) },
                              { match: ['ver preços', 'ver precos', 'ver planos', 'pricing', 'demo gratuita'], action: () => nav && (nav('pricing'), HexisStore.close()) },
                              { match: ['marketplace', 'ver marketplace'], action: () => nav && (nav('marketplace'), HexisStore.close()) },
                              { match: ['dashboard', 'hub', 'ver pipeline'], action: () => nav && (nav('dashboard'), HexisStore.close()) },
                              { match: ['criar experiência', 'criar experiencia', 'briefing'], action: () => nav && (nav('criar-experiencia'), HexisStore.close()) },
                              { match: ['sobre', 'quem somos', 'sobre nós', 'ver sobre'], action: () => nav && (nav('sobre'), HexisStore.close()) },
                              { match: ['conteúdos', 'conteudos', 'ver conteúdos', 'ver conteudos', 'playbook', 'podcast'], action: () => nav && (nav('conteudos'), HexisStore.close()) },
                              { match: ['voltar ao início', 'voltar ao inicio', 'início', 'home'], action: () => nav && (nav('home'), HexisStore.close()) },
                              { match: ['ver missões', 'ver missoes', 'missões ativas'], action: () => setTab('missions') },
                              { match: ['falar com fundador', 'contactar', 'equipa', 'suporte'], action: () => window.open('https://wa.me/244930179037', '_blank') },
                            ];
                            const route = ROUTES.find(r => r.match.some(m => t.includes(m)));
                            if (route) { route.action(); }
                            else { send(sg); } // informational — send as chat query
                          }}>
                          {sg}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>

          <div className="hexis-input-row">
            <input
              ref={inputRef}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !busy) send(); }}
              placeholder={busy ? 'Hexis a pensar…' : 'Pergunta à Hexis…'}
              autoComplete="off"
            />
            <button className="send" onClick={() => !busy && send()} title="Enviar" disabled={busy}>
              <Icon name="send" size={15} />
            </button>
          </div>
        </>
      )}

      {/* ── ALERTS TAB ────────────────────────────────────────── */}
      {tab === 'alerts' && (
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {isGuest && (
            <div style={{ padding: '10px 12px', borderRadius: 10, background: 'rgba(123,97,255,0.07)', border: '1px solid rgba(123,97,255,0.2)', fontSize: 12, color: 'var(--text-2)' }}>
              <div style={{ fontWeight: 700, color: '#A78BFA', marginBottom: 4 }}>⟡ Alertas personalizados</div>
              Faz login para receber alertas de match, pipeline e janelas de oportunidade em tempo real.
              <br />
              <button style={{ marginTop: 8, padding: '4px 10px', borderRadius: 6, background: 'rgba(123,97,255,0.15)', border: '1px solid rgba(123,97,255,0.3)', color: '#A78BFA', fontSize: 11, fontWeight: 700, cursor: 'pointer' }}
                onClick={() => { send('Criar conta'); setTab('chat'); }}>Criar Conta Grátis →</button>
            </div>
          )}
          {s.alerts.filter(a => isGuest ? a.forGuest : true).slice(0, 12).map(a => {
            const cols = { success: '#00C48C', warning: '#FFD700', danger: '#FF3B5C', info: '#00D1FF' };
            const col  = cols[a.kind] || '#7B61FF';
            return (
              <div key={a.id} style={{ padding: '10px 12px', borderRadius: 10, background: col + '0A', border: `1px solid ${col}25` }}>
                <div style={{ fontWeight: 700, fontSize: 13, color: col, marginBottom: 2 }}>{a.title}</div>
                <div style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: a.action ? 8 : 0, lineHeight: 1.4 }}>{a.body}</div>
                {a.action && (
                  <button style={{ padding: '4px 10px', borderRadius: 6, background: col + '18', border: `1px solid ${col}40`, color: col, fontSize: 11, fontWeight: 700, cursor: 'pointer' }}
                    onClick={() => { SoundFX.tap(); send(a.action); setTab('chat'); }}>
                    {a.action} →
                  </button>
                )}
              </div>
            );
          })}
          {s.alerts.filter(a => isGuest ? a.forGuest : true).length === 0 && !isGuest && (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-3)', fontSize: 13 }}>Sem alertas de momento.</div>
          )}
        </div>
      )}

      {/* ── MISSIONS TAB ──────────────────────────────────────── */}
      {tab === 'missions' && (
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {isGuest && (
            <>
              <div style={{ padding: '10px 12px', borderRadius: 10, background: 'rgba(0,209,255,0.06)', border: '1px solid rgba(0,209,255,0.2)' }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: '#00D1FF', textTransform: 'uppercase', marginBottom: 4 }}>Missão Disponível · +50 XP</div>
                <div style={{ fontWeight: 700, fontSize: 13, color: '#fff', marginBottom: 4 }}>Cria a tua conta gratuita</div>
                <div style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 8 }}>Regista-te para desbloquear matching B2B, dashboard e missões com recompensas reais.</div>
                <button style={{ padding: '5px 12px', borderRadius: 7, background: 'rgba(0,209,255,0.15)', border: '1px solid rgba(0,209,255,0.3)', color: '#00D1FF', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}
                  onClick={() => { SoundFX.success(); setTab('chat'); send('Criar conta gratuita'); }}>Aceitar missão</button>
              </div>
              <div style={{ padding: '10px 12px', borderRadius: 10, background: 'rgba(255,215,0,0.06)', border: '1px solid rgba(255,215,0,0.2)' }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: '#FFD700', textTransform: 'uppercase', marginBottom: 4 }}>Missão Disponível · +10 XP</div>
                <div style={{ fontWeight: 700, fontSize: 13, color: '#fff', marginBottom: 4 }}>Explora os Eventos 2026</div>
                <div style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 8 }}>Vê os 10 eventos B2B confirmados para 2026 e identifica oportunidades.</div>
                <button style={{ padding: '5px 12px', borderRadius: 7, background: 'rgba(255,215,0,0.15)', border: '1px solid rgba(255,215,0,0.3)', color: '#FFD700', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}
                  onClick={() => { SoundFX.tap(); setTab('chat'); send('Ver eventos 2026'); }}>Aceitar missão</button>
              </div>
            </>
          )}
          {!isGuest && activeMissions.length === 0 && (
            <div style={{ padding: 20, textAlign: 'center', color: 'var(--text-3)', fontSize: 13 }}>Sem missões ativas agora. Navega para o Dashboard ou Eventos para desbloquear.</div>
          )}
          {!isGuest && activeMissions.map(m => {
            const pct = Math.round((m.elapsed / m.timeLimit) * 100);
            return (
              <div key={m.id} style={{ padding: '10px 12px', borderRadius: 10, background: m.color + '0A', border: `1px solid ${m.color}30` }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: m.color, textTransform: 'uppercase', marginBottom: 4 }}>{m.game} · +{m.reward.xp} XP</div>
                <div style={{ fontWeight: 700, fontSize: 13, color: '#fff', marginBottom: 6 }}>{m.title}</div>
                <div style={{ height: 3, background: 'rgba(255,255,255,0.08)', borderRadius: 2, marginBottom: 8 }}>
                  <div style={{ height: '100%', width: `${pct}%`, background: m.color, borderRadius: 2 }} />
                </div>
                <button style={{ padding: '5px 12px', borderRadius: 7, background: m.color + '20', border: `1px solid ${m.color}50`, color: m.color, fontSize: 12, fontWeight: 700, cursor: 'pointer' }}
                  onClick={() => { SoundFX.success(); if (window.HexisEngine) HexisEngine.acceptMission(m.id); setTab('chat'); send(`Aceitar missão ${m.game}`); }}>
                  Aceitar missão
                </button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

window.HexisFab        = HexisFab;
window.HexisPopup      = HexisPopup;
window.HexisInsightBar = HexisInsightBar;
