/* App shell — routing + footer + global providers */
const { useState: useStateA, useEffect: useEffectA } = React;

const APP_ROUTES = ['home', 'eventos', 'marketplace', 'conteudos', 'pricing', 'sobre', 'entrar', 'criar-experiencia', 'dashboard'];

const getRouteFromLocation = () => {
  if (typeof window === 'undefined') return 'home';
  const params = new URLSearchParams(window.location.search);
  const fromQuery = params.get('page');
  const fromHash = window.location.hash.replace(/^#\/?/, '');
  const candidate = fromQuery || fromHash || 'home';
  return APP_ROUTES.includes(candidate) ? candidate : 'home';
};

const syncRouteToUrl = (page) => {
  if (typeof window === 'undefined' || !window.history?.pushState) return;
  const url = new URL(window.location.href);
  if (page === 'home') url.searchParams.delete('page');
  else url.searchParams.set('page', page);
  url.hash = '';
  window.history.pushState({ page }, '', url.toString());
};

const Footer = ({ onNav }) => (
  <footer className="footer">
    <div className="container">
      <div className="footer-top">
        <div className="footer-brand">
          <Brand />
          <p className="footer-desc">A plataforma que transforma eventos B2B em pipeline auditável. Behavioral UI · Hexis AI · Hardware integrado.</p>
          <span className="footer-cta">Operação ativa · 12 países</span>
          <div className="footer-social">
            <a href="https://linkedin.com/company/marcianus" target="_blank" rel="noopener" aria-label="LinkedIn" onClick={() => { SoundFX.tap(); }}><Icon name="linkedin" size={16} /></a>
            <a href="https://youtube.com/@marcianus" target="_blank" rel="noopener" aria-label="YouTube" onClick={() => { SoundFX.tap(); }}><Icon name="youtube" size={16} /></a>
            <a href="https://x.com/marcianus" target="_blank" rel="noopener" aria-label="X / Twitter" onClick={() => { SoundFX.tap(); }}><Icon name="twitter" size={16} /></a>
            <a href="https://instagram.com/marcianus" target="_blank" rel="noopener" aria-label="Instagram" onClick={() => { SoundFX.tap(); }}><Icon name="instagram" size={16} /></a>
            <a href="https://wa.me/244930179037" target="_blank" rel="noopener" aria-label="WhatsApp" onClick={() => { SoundFX.tap(); }}><Icon name="message-circle" size={16} /></a>
          </div>
        </div>
        <div className="footer-col">
          <h5>Plataforma</h5>
          <a onClick={() => { SoundFX.tap(); onNav('home'); }}>Home</a>
          <a onClick={() => { SoundFX.tap(); onNav('eventos'); }}>Eventos</a>
          <a onClick={() => { SoundFX.tap(); onNav('marketplace'); }}>Marketplace</a>
          <a onClick={() => { SoundFX.tap(); onNav('conteudos'); }}>Conteúdo</a>
        </div>
        <div className="footer-col">
          <h5>Empresa</h5>
          <a onClick={() => { SoundFX.tap(); onNav('sobre'); }}>Sobre Nós</a>
          <a onClick={() => { SoundFX.tap(); onNav('pricing'); }}>Preços</a>
          <a onClick={() => { SoundFX.tap(); onNav('criar-experiencia'); }}>Criar Experiência</a>
          <a onClick={() => { SoundFX.tap(); onNav('entrar'); }}>Entrar</a>
        </div>
        <div className="footer-col">
          <h5>Stack</h5>
          <a onClick={() => { SoundFX.tap(); HexisStore.open(); }}>Hexis AI</a>
          <a onClick={() => { SoundFX.tap(); onNav('marketplace'); ToastBus.push({ icon: 'package', title: 'Kiosk NFC', desc: 'Hardware Marcianus — Kz 1.400.000 · Setup 48h · Plug-and-play.' }); }}>Kiosk NFC</a>
          <a onClick={() => { SoundFX.tap(); onNav('marketplace'); ToastBus.push({ icon: 'qr-code', title: 'NFC Wristband ×100', desc: 'Kz 700.000 · Cada toque regista uma conexão auditável.' }); }}>Wristband</a>
          <a onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'refresh', title: 'CRM Sync', desc: 'HubSpot · Salesforce · Pipedrive — sincronização automática 24h pós-evento. Incluído nos planos Operator e Diamond.', duration: 6000 }); }}>CRM Sync</a>
        </div>
        <div className="footer-col">
          <h5>Legal</h5>
          <a onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'shield-check', title: 'Política de Privacidade', desc: 'Dados cifrados AES-256 · Deploy EU-only (Hetzner) · RGPD/LGPD compliant · Direito ao esquecimento garantido · Sem partilha com terceiros.', duration: 8000 }); }}>Privacidade</a>
          <a onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'file-text', title: 'Termos de Serviço v3.0', desc: 'Vigentes desde Jan 2026 · Contrato SaaS B2B · Cancelamento a qualquer momento nos planos mensais · Reembolso proporcional nos primeiros 30 dias do plano anual.', duration: 8000 }); }}>Termos</a>
          <a onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'cookie', title: 'Política de Cookies', desc: 'Apenas cookies funcionais estritamente necessários. Zero tracking de terceiros. Zero publicidade. Sessão cifrada com TLS 1.3.', duration: 8000 }); }}>Cookies</a>
          <a onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'check-circle', title: 'Compliance Marcianus', desc: 'RGPD ✓ · ISO 27001 (alignment) ✓ · SOC 2 (in progress) · Event Sourcing auditável · Zero vendor lock-in · Deploy EU-only.', duration: 8000 }); }}>Compliance</a>
        </div>
      </div>
      <div className="footer-bottom">
        <span className="copy">© 2026 Marcianus Experience · Luanda · Lisboa · Porto</span>
        <div className="compliance">
          <span className="ok">RGPD ✓</span>
          <span className="ok">ISO 27001 ✓</span>
          <span>SOC 2 in progress</span>
        </div>
      </div>
    </div>
  </footer>
);

const AuthGuard = ({ onNav, children }) => {
  const auth = window.useAuth ? window.useAuth() : null;
  const user = auth?.user || null;
  useEffectA(() => {
    if (!user) onNav('entrar');
  }, [user]);
  if (!user) return null;
  return children;
};

const PageRouter = ({ page, onNav }) => {
  const HP  = window.HomePage;
  const EP  = window.EventsPage;
  const CP  = window.ContentPage;
  const PP  = window.PricingPage;
  const AP  = window.AboutPage;
  const DP  = window.DashboardPage;
  const MKP = window.MarketplacePage;
  const CEP = window.CriarExperienciaPage;
  const ENT = window.EntrarPage;
  const IB  = window.HexisInsightBar;

  const pageEl = (() => {
    if (page === 'home'              && HP)  return <HP onNav={onNav} />;
    if (page === 'eventos'           && EP)  return <EP onNav={onNav} />;
    if (page === 'marketplace'       && MKP) return <MKP onNav={onNav} />;
    if (page === 'conteudos'         && CP)  return <CP onNav={onNav} />;
    if (page === 'pricing'           && PP)  return <PP onNav={onNav} />;
    if (page === 'sobre'             && AP)  return <AP onNav={onNav} />;
    if (page === 'entrar'            && ENT) return <ENT onNav={onNav} />;
    if (page === 'criar-experiencia' && CEP) return <CEP onNav={onNav} />;
    if (page === 'dashboard'         && DP)  return (
      <AuthGuard onNav={onNav}><DP onNav={onNav} /></AuthGuard>
    );
    return null;
  })();

  return (
    <>
      {IB && page !== 'entrar' && React.createElement(IB, { page })}
      {pageEl}
    </>
  );
};

const App = () => {
  const [page, setPage] = useStateA(getRouteFromLocation);
  const onNav = (p, opts = {}) => {
    const next = APP_ROUTES.includes(p) ? p : 'home';
    setPage(next);
    if (!opts.replaceUrl) syncRouteToUrl(next);
    if (window.HexisEngine) HexisEngine.trackClick(`nav_${next}`);
  };
  window._appNav = onNav;  // exposed for HexisPopup suggestion routing

  useEffectA(() => {
    const handler = () => setPage(getRouteFromLocation());
    window.addEventListener('popstate', handler);
    return () => window.removeEventListener('popstate', handler);
  }, []);

  useEffectA(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [page]);

  /* Track page changes in HexisEngine */
  useEffectA(() => {
    if (window.HexisEngine) HexisEngine.trackPage(page);
    if (window.MarcianusAPI) MarcianusAPI.track({ action: 'page_view', category: 'navigation', label: page });
  }, [page]);

  /* Keyboard shortcut Ctrl+K */
  useEffectA(() => {
    const handler = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        HexisStore.open();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  const showFooter = !['entrar', 'criar-experiencia'].includes(page);
  const showHexis  = page !== 'entrar';

  const AP = window.AuthProvider;
  if (!AP) return <div style={{ color: '#fff', padding: 40, fontFamily: 'monospace' }}>A carregar…</div>;

  return (
    <AP>
      <div className="global-bg" />
      <div className="scene">
        <div className="scene-orb a" />
        <div className="scene-orb b" />
        <div className="scene-orb c" />
      </div>

      <Header page={page} onNav={onNav} />
      <PageRouter page={page} onNav={onNav} />

      {showFooter && <Footer onNav={onNav} />}
      {window.BottomNav && React.createElement(window.BottomNav, { page, onNav })}
      <ToastHost />
      {showHexis && <><HexisFab /><HexisPopup /></>}
    </AP>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
