/* Header + Hero — auth-aware nav + homepage fold */
const { useState: useStateHd, useEffect: useEffectHd, useRef: useRefHd, useContext: useContextHd } = React;

/* ── TRUSTED BY DATA (top past events ranked by Hexis AI) ── */
const TRUSTED_BY_EVENTS = [
  { initials: 'IC', name: 'Invicta Capital', sector: 'Banca', metric: '€4.2M', label: 'Pipeline' },
  { initials: 'VC', name: 'Veridian Summit', sector: 'Tech', metric: '94%', label: 'Match Score' },
  { initials: 'HB', name: 'Helix Bio', sector: 'Saúde', metric: '92%', label: 'Match Score' },
  { initials: 'AE', name: 'Aether Real Estate', sector: 'Imobiliário', metric: '€5.4M', label: 'Pipeline' },
  { initials: 'CF', name: 'Cygnus AI Forum', sector: 'IA', metric: '95%', label: 'Match Score' },
  { initials: 'SE', name: 'Solaris Energy', sector: 'Energia', metric: '3.8×', label: 'ROI' },
  { initials: 'NV', name: 'Nova Ventures Day', sector: 'VC', metric: '17', label: 'Term sheets' },
  { initials: 'PL', name: 'Porto Leaders', sector: 'Executivo', metric: '186', label: 'Meetings' },
];

/* ── HEADER ─────────────────────────────────────────────── */
const Header = ({ page, onNav }) => {
  const [menuOpen, setMenuOpen] = useStateHd(false);
  const auth = window.useAuth ? window.useAuth() : null;
  const user = auth?.user || null;
  const logout = auth?.logout || (() => {});

  const NAV_LINKS = [
    { id: 'home',        label: 'Home' },
    { id: 'eventos',     label: 'Eventos' },
    { id: 'marketplace', label: 'Marketplace' },
    { id: 'conteudos',   label: 'Conteúdo' },
    { id: 'sobre',       label: 'Sobre' },
  ];

  const handleLogout = () => { logout(); onNav('home'); };

  /* Close menu on page change */
  useEffectHd(() => { setMenuOpen(false); }, [page]);

  /* Close menu on outside click */
  useEffectHd(() => {
    if (!menuOpen) return;
    const close = (e) => {
      if (!e.target.closest('.nav')) setMenuOpen(false);
    };
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [menuOpen]);

  return (
    <nav className="nav" role="navigation" aria-label="Navegação principal">
      <div className="container nav-inner">
        <Brand onClick={() => { SoundFX.tap(); onNav('home'); }} />

        {/* Desktop links — hidden below 1080px via responsive.css */}
        <div className="nav-mid" role="menubar">
          {NAV_LINKS.map(l => (
            <a
              key={l.id}
              role="menuitem"
              className={`nav-link ${page === l.id ? 'active' : ''}`}
              onClick={() => { SoundFX.tap(); onNav(l.id); }}
              tabIndex={0}
              onKeyDown={(e) => e.key === 'Enter' && onNav(l.id)}
            >
              {l.label}
            </a>
          ))}
        </div>

        {/* Desktop right — partially hidden on tablet */}
        <div className="nav-right">
          <button
            className="icon-btn"
            title="Procurar (Ctrl+K)"
            aria-label="Procura global"
            onClick={() => { SoundFX.tap(); HexisStore.open(); ToastBus.push({ icon: 'search', title: 'Procura global', desc: 'Hexis AI pronta para pesquisar eventos, conteúdo e matches.' }); }}
          >
            <Icon name="search" size={16} />
          </button>

          {user ? (
            <>
              <div
                className="nav-user-av"
                title={user.name}
                onClick={() => { SoundFX.tap(); onNav('dashboard'); }}
                role="button"
                tabIndex={0}
              >
                {user.initial || user.name?.[0] || 'U'}
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => { SoundFX.tap(); onNav('dashboard'); }}>Dashboard</button>
              <button className="btn btn-ghost btn-sm" onClick={handleLogout} style={{ color: 'var(--text-3)', borderColor: 'var(--border-1)' }}>Sair</button>
            </>
          ) : (
            <>
              <button className="btn btn-ghost btn-sm" onClick={() => { SoundFX.tap(); onNav('entrar'); }}>Entrar</button>
              <button className="btn btn-demo btn-sm" onClick={() => { SoundFX.success(); onNav('criar-experiencia'); }}>
                Demo <Icon name="play" size={12} />
              </button>
            </>
          )}
        </div>

        {/* Mobile/tablet hamburger — shown ONLY below 1080px via responsive.css */}
        <button
          className="icon-btn mobile-menu-btn"
          aria-label={menuOpen ? 'Fechar menu' : 'Abrir menu'}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(!menuOpen)}
        >
          <Icon name={menuOpen ? 'x' : 'menu'} size={18} />
        </button>
      </div>

      {/* Mobile dropdown menu */}
      {menuOpen && (
        <div className="mobile-menu" role="menu">
          {NAV_LINKS.map(l => (
            <a
              key={l.id}
              role="menuitem"
              className={`nav-link ${page === l.id ? 'active' : ''}`}
              onClick={() => { SoundFX.tap(); onNav(l.id); setMenuOpen(false); }}
            >
              {l.label}
            </a>
          ))}
          <div className="mobile-menu-actions">
            {user ? (
              <>
                <button className="btn btn-ghost" onClick={() => { onNav('dashboard'); setMenuOpen(false); }}>
                  <Icon name="layout-dashboard" size={14} /> Dashboard
                </button>
                <button className="btn btn-ghost" onClick={() => { handleLogout(); setMenuOpen(false); }}>Sair</button>
              </>
            ) : (
              <>
                <button className="btn btn-ghost" onClick={() => { onNav('entrar'); setMenuOpen(false); }}>Entrar</button>
                <button className="btn btn-demo" onClick={() => { onNav('criar-experiencia'); setMenuOpen(false); }}>
                  Demo <Icon name="play" size={12} />
                </button>
              </>
            )}
          </div>
        </div>
      )}
    </nav>
  );
};

/* ── BOTTOM NAVIGATION (mobile only — rendered via BottomNav component) ── */
const BottomNav = ({ page, onNav }) => {
  const auth = window.useAuth ? window.useAuth() : null;
  const user = auth?.user || null;

  const items = [
    { id: 'home',        label: 'Home',     icon: 'home' },
    { id: 'eventos',     label: 'Eventos',  icon: 'calendar' },
    { id: 'marketplace', label: 'Market',   icon: 'layout-dashboard' },
    { id: 'conteudos',   label: 'Conteúdo', icon: 'newspaper' },
    { id: user ? 'dashboard' : 'criar-experiencia', label: user ? 'Dash' : 'Demo', icon: user ? 'chart-bar' : 'play', isCTA: !user },
  ];

  /* Don't render bottom nav on auth/criar-experiencia pages */
  if (['entrar', 'criar-experiencia'].includes(page)) return null;

  return (
    <nav className="bottom-nav" role="navigation" aria-label="Navegação inferior">
      {items.map(it => (
        <div
          key={it.id}
          className={`bottom-nav-item ${page === it.id ? 'active' : ''} ${it.isCTA ? 'cta-item' : ''}`}
          onClick={() => { SoundFX.tap(); onNav(it.id); }}
          role="button"
          tabIndex={0}
          aria-label={it.label}
        >
          <span className="bn-icon"><Icon name={it.icon} size={18} /></span>
          {it.label}
        </div>
      ))}
    </nav>
  );
};

/* ── HERO ────────────────────────────────────────────────── */
const Hero = ({ onNav }) => {
  const [tickerIdx, setTickerIdx] = useStateHd(0);
  const phrases = ['Networking', 'Reuniões', 'Cocktails', 'Ruído'];
  useEffectHd(() => {
    const t = setInterval(() => setTickerIdx(i => (i + 1) % phrases.length), 2400);
    return () => clearInterval(t);
  }, []);

  const [pipeline, setPipeline] = useStateHd(8.4);
  useEffectHd(() => {
    const t = setInterval(() => setPipeline(p => +(p + (Math.random() * 0.04 - 0.01)).toFixed(2)), 1800);
    return () => clearInterval(t);
  }, []);

  return (
    <>
    <section className="hero hero-fold">
      <div className="container">
        <div className="hero-grid">
          <div className="hero-headline-wrap">
            <span className="hero-pretitle"><span className="live-dot" />Marcianus Experience · v3 Live</span>
            <h1 className="hero-h1-tight">
              Acabou o <span className="strikeword">{phrases[tickerIdx]}</span>.<br />
              Começou a <span className="hl">decisão de negócio.</span>
            </h1>
            <p className="hero-sub hero-sub-tight">
              Eventos B2B com inteligência comportamental. Cada handshake medido, cada conexão pontuada, cada minuto reconvertido em pipeline.
            </p>
            <div className="hero-actions">
              {/* CTA 1 of 3 — Demo na hero */}
              <button
                className="btn btn-gold"
                onClick={() => { SoundFX.success(); fireConfetti({ x: window.innerWidth / 2, y: 360 }, ['#FFD700', '#7B61FF', '#A78BFA']); onNav('criar-experiencia'); }}
                aria-label="Ver demonstração da plataforma"
              >
                Demo <Icon name="play" size={16} />
              </button>
              <button className="btn btn-glass" onClick={() => { SoundFX.tap(); onNav('marketplace'); }}>
                <Icon name="layout-dashboard" size={16} /> Ver Marketplace
              </button>
              <span className="hexis-hint">Hexis AI a operar</span>
            </div>
            <div className="hero-trust">
              <span className="live">Operação ativa</span>
              <span>· 7 sectores · 12 países · €54M pipeline 2025</span>
            </div>
          </div>

          <div className="hero-visual hero-visual-clean">
            <div className="hero-frame">
              <img src="assets/samsung-kiosk.png" alt="Kiosk Marcianus NFC Check-in" loading="lazy" />
              <div className="scan" aria-hidden="true" />
              <div className="hero-frame-overlay">
                <span className="chip chip-success chip-live">Live</span>
                <div className="hero-frame-meta">
                  <div className="hf-row"><span className="hf-k">Match avg</span><span className="hf-v">94%</span></div>
                  <div className="hf-row"><span className="hf-k">Conexões</span><span className="hf-v">186</span></div>
                  <div className="hf-row"><span className="hf-k">Pipeline</span><span className="hf-v gold">€1.82M</span></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    {/* Metrics */}
    <section className="page-section metrics-section">
      <div className="container">
        <div className="section-head">
          <div className="left">
            <span className="eyebrow">Performance em Tempo Real</span>
            <h2>Números que <span className="hl">falam por si</span>.</h2>
            <p className="section-lead">Cada evento Marcianus gera dados auditáveis. Estas métricas são médias das últimas 90 operações ativas.</p>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
          <div className="hero-metric-cell metric-card">
            <div className="n purple"><AnimNum value={94} suffix="%" /> <span className="up"><Icon name="arrow-up" size={9} /> +6</span></div>
            <div className="l">Match Score Médio</div>
            <div className="metric-desc">Calculado por similaridade vetorial (pgvector) entre perfis de participantes — sem LLM.</div>
            <div className="spark"><Sparkline data={[60, 65, 72, 78, 82, 86, 90, 94]} color="#A78BFA" /></div>
          </div>
          <div className="hero-metric-cell metric-card">
            <div className="n">€<AnimNum value={pipeline} decimals={2} />M <span className="up"><Icon name="arrow-up" size={9} /> +12%</span></div>
            <div className="l">Pipeline / Evento</div>
            <div className="metric-desc">Pipeline qualificado gerado por evento, medido 30 dias pós check-in. Fonte: CRM sync auditado.</div>
            <div className="spark"><Sparkline data={[3.2, 4.1, 5.0, 5.8, 6.4, 7.1, 7.8, 8.4]} color="#00C48C" /></div>
          </div>
          <div className="hero-metric-cell metric-card">
            <div className="n gold"><AnimNum value={3.4} decimals={1} />× <span className="up"><Icon name="arrow-up" size={9} /> ROI</span></div>
            <div className="l">Retorno vs. Tradicional</div>
            <div className="metric-desc">Comparação com eventos sem plataforma de matching. Dados de 318 entrevistas · State of B2B 2025.</div>
            <div className="spark"><Sparkline data={[1.0, 1.4, 1.8, 2.2, 2.5, 2.9, 3.2, 3.4]} color="#FFD700" /></div>
          </div>
        </div>
      </div>
    </section>

    {/* Trusted By — powered by Hexis AI (best past events auto-selected) */}
    <section className="page-section" style={{ paddingTop: 64, paddingBottom: 64, borderTop: '1px solid var(--border-1)' }}>
      <div className="container">
        <div className="section-head">
          <div className="left">
            <span className="eyebrow">Trusted By · Hexis AI Selection</span>
            <h2>Líderes que já <span className="hl">confiam</span> no sistema.</h2>
            <p className="section-lead">
              Os eventos de topo são selecionados automaticamente pelo Hexis AI com base em Match Score, pipeline gerado e feedback dos participantes.
            </p>
          </div>
          {/* CTA 2 of 3 — Demo na secção Trusted By */}
          <div className="right">
            <span className="demo-badge">Hexis AI · Auto-ranked</span>
          </div>
        </div>

        <div className="trusted-by-grid">
          {TRUSTED_BY_EVENTS.map((e, i) => (
            <div key={i} className="trusted-by-card" onClick={() => { SoundFX.tap(); onNav('eventos'); ToastBus.push({ kind: 'gold', icon: 'star', title: `${e.name} · Case Study`, desc: `${e.metric} ${e.label} · Sector: ${e.sector} · Hexis Score top 5% · Ver detalhes nos Eventos.` }); }}>
              <div className="trusted-by-logo">{e.initials}</div>
              <div className="trusted-by-name">{e.name}</div>
              <div className="trusted-by-metric">{e.metric}</div>
              <div className="trusted-by-label">{e.label}</div>
              <div style={{ marginTop: 8 }}>
                <span className="chip chip-purple" style={{ fontSize: 9 }}>{e.sector}</span>
              </div>
            </div>
          ))}
        </div>

        {/* CTA 3 of 3 — Demo no final da secção Trusted By */}
        <div style={{ textAlign: 'center', marginTop: 40 }}>
          <p style={{ color: 'var(--text-3)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 16 }}>
            O teu evento pode ser o próximo a entrar nesta lista.
          </p>
          <button
            className="btn btn-demo"
            onClick={() => { SoundFX.success(); fireConfetti({ x: window.innerWidth / 2, y: 400 }); onNav('criar-experiencia'); }}
          >
            <Icon name="play" size={14} /> Ver Demo · Criar Experiência
          </button>
        </div>
      </div>
    </section>

    {/* ── BEHAVIORAL ENGINE TEASER ── */}
    <section className="page-section" style={{ borderTop: '1px solid var(--border-1)', background: 'linear-gradient(135deg, rgba(123,97,255,0.05), rgba(0,209,255,0.03))' }}>
      <div className="container">
        <div className="section-head">
          <div className="left">
            <span className="eyebrow">Behavioral Design B2B</span>
            <h2>6 Game Types. Um só <span className="hl-grad">motor de decisão</span>.</h2>
            <p className="section-lead">
              O Sistema Marcianus™ orquestra engajamento através de engenharia comportamental — não entretenimento. Cada interação captura dados, cada dado melhora o próximo match.
            </p>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 32 }}>
          {[
            { id: 'MQ', name: 'Match Quest™',         desc: 'Maximiza qualidade de conexões por similaridade vectorial. XP por compatibilidade alta.',              color: '#7B61FF', icon: 'target' },
            { id: 'SB', name: 'Social Breaker™',      desc: 'Reduz barreira de interação com missões progressivas. Match probability >85% obrigatório.',           color: '#00C48C', icon: 'users' },
            { id: 'QK', name: 'Queue Killer™',        desc: 'Converte tempo morto em engajamento com micro-desafios de 30–60s e quizzes contextuais.',             color: '#00D1FF', icon: 'zap' },
            { id: 'ND', name: 'Network Domination™',  desc: 'Leaderboard de mérito real: quantidade × qualidade × profundidade. Cria status competitivo.',          color: '#FF7849', icon: 'trophy' },
            { id: 'KA', name: 'Knowledge Arena™',     desc: 'Quizzes ao vivo durante palestras. Active recall + testing effect aumentam retenção cognitiva.',       color: '#FFD700', icon: 'book' },
            { id: 'ME', name: 'Mission Engine™',      desc: 'Redireciona fluxo físico com missões dinâmicas. Se sala congestionada → duplica XP na zona vazia.',   color: '#A78BFA', icon: 'map-pin' },
          ].map(g => (
            <div key={g.id} className="card card-purple" style={{ borderColor: g.color + '30', cursor: 'pointer' }}
              onClick={() => {
                SoundFX.tap();
                if (window.InfiniteGameWidget && window._hexisGameOpen) {
                  window._hexisGameOpen(g.name);
                } else {
                  ToastBus.push({ kind: 'gold', icon: g.icon, title: g.name, desc: `${g.desc.slice(0, 80)}… · Joga no Dashboard ou nos Eventos.` });
                  onNav('dashboard');
                }
              }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: g.color + '18', border: `1px solid ${g.color}40`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: g.color, flexShrink: 0 }}>
                  <Icon name={g.icon} size={18} />
                </div>
                <div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: g.color, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase' }}>{g.id}</div>
                  <div style={{ fontWeight: 800, fontSize: 14, color: '#fff' }}>{g.name}</div>
                </div>
              </div>
              <p style={{ fontSize: 13, color: 'var(--text-2)', lineHeight: 1.6, margin: 0 }}>{g.desc}</p>
            </div>
          ))}
        </div>
        <div style={{ padding: '16px 20px', borderRadius: 12, background: 'rgba(123,97,255,0.06)', border: '1px solid var(--border-purple)', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-3)', lineHeight: 1.8, marginBottom: 32 }}>
          <span style={{ color: 'var(--purple-soft)' }}>Loop central:</span> Input → Event → Graph → <span style={{ color: '#00D1FF' }}>Hexis AI</span> → Decision → Action → Feedback → <span style={{ color: '#00C48C' }}>Aprendizagem</span>
        </div>
        <div style={{ textAlign: 'center' }}>
          <button className="btn btn-ghost" onClick={() => { SoundFX.tap(); onNav('dashboard'); }}>
            <Icon name="layout-dashboard" size={15} /> Ver Hub Operacional
          </button>
        </div>
      </div>
    </section>
    </>
  );
};

window.Header = Header;
window.Hero = Hero;
window.BottomNav = BottomNav;
