/* ═══════════════════════════════════════════════════════════
   MARKETPLACE PAGE — HaaS · DaaS · SaaS
   + E-Wallet (demo for guests, real for logged users)
   + Affiliate-enabled products
   + Partner products & services
═══════════════════════════════════════════════════════════ */
const { useState: useStateMk, useEffect: useEffectMk, useContext: useContextMk } = React;

/* ── Mock data ──────────────────────────────────────────── */
const MK_ITEMS = [
  { id:'mk_01', cat:'SaaS', kicker:'EventOS · Anual', t:'Plataforma completa', price:24000, display:'€24K', per:'/ano', features:['9 Kernels integrados','Hexis AI ilimitada','D3-BMC dashboards','Suporte prioritário 24/7'], tag:'', side:'empresas', featured:false },
  { id:'mk_02', cat:'DaaS', kicker:'Leads · Pack 100', t:'Leads qualificados', price:4800, display:'€4.8K', per:'/pack', features:['100 decisores validados','MatchScore™ ≥85%','CRM sync nativo','Follow-up sugerido pela IA'], tag:'Best seller', side:'empresas', featured:true },
  { id:'mk_03', cat:'DaaS', kicker:'API · Dados setoriais', t:'Acesso programático', price:1200, display:'€1.2K', per:'/mês', features:['REST + gRPC','Rate-limit 100k/dia','pgvector embeddings','SLA 99.95%'], tag:'', side:'empresas', featured:false },
  { id:'mk_04', cat:'HaaS', kicker:'Stand digital · Premium', t:'Presença expandida', price:8000, display:'€8K', per:'/evento', features:['Landing dedicado','Leads em tempo real','Overlay Hexis','Relatório pós-evento'], tag:'', side:'empresas', featured:false },
  { id:'mk_05', cat:'SaaS', kicker:'White-label', t:'Multi-tenant', price:0, display:'Custom', per:'/SLA', features:['Subdomínio próprio','Branding total','Kernels selecionáveis','Suporte 24/7'], tag:'Enterprise', side:'empresas', featured:false },
  { id:'mk_06', cat:'HaaS', kicker:'Kiosk · Aluguer', t:'Check-in completo', price:2400, display:'€2.4K', per:'/evento', features:['Setup + operação incluídos','Face ID + NFC dual','Briefing Hexis < 10s','Relatório automático'], tag:'', side:'empresas', featured:false },
  { id:'mk_07', cat:'HaaS', kicker:'Ticket Executive', t:'Acesso C-Level', price:480, display:'€480', per:'/evento', features:['Executive Floor acesso','Lounge dedicado Marcianus','Briefing Hexis personalizado','Kit NFC + ID Band'], tag:'', side:'participants', featured:false },
  { id:'mk_08', cat:'SaaS', kicker:'Networking Premium', t:'30 dias de matches', price:120, display:'€120', per:'/mês', features:['MatchScore™ prioritário','10 introduções garantidas','Agenda sincronizada','Follow-up automático'], tag:'Mais escolhido', side:'participants', featured:true },
  { id:'mk_09', cat:'SaaS', kicker:'Hexis Prioritário', t:'Priority Engine', price:60, display:'€60', per:'/evento', features:['Fila zero nos kiosks','Briefing expandido','3 matches VIP','Relatório pós-evento'], tag:'', side:'participants', featured:false },
  { id:'mk_10', cat:'HaaS', kicker:'Wallet · Saldo', t:'Ecossistema unificado', price:0, display:'Flex.', per:'/saldo', features:['Uma conta, um saldo','Cashback em eventos','Stripe + EMIS','Transferível'], tag:'', side:'participants', featured:false },
  { id:'mk_11', cat:'HaaS', kicker:'Mentoria 1:1', t:'Curadoria Marcianus', price:200, display:'€200', per:'/sessão', features:['Mentor validado','60 min + NDA','Follow-up 48h','Gravação opcional'], tag:'', side:'participants', featured:false },
  { id:'mk_12', cat:'HaaS', kicker:'ID Band Marcianus', t:'Hardware pessoal', price:90, display:'€90', per:'/un.', features:['NFC + BLE dual','72h bateria passiva','Wallet integrada','Silicone hipoalergénico'], tag:'New', side:'participants', featured:false },
];

/* ── Partner / Collaborator products ───────────────────── */
const PARTNER_ITEMS = [
  { id:'p_01', cat:'Serviço', kicker:'Consultoria · Premium', t:'Estratégia de Evento', price:2500, display:'€2.5K', per:'/sessão', features:['Diagnóstico completo','Plano operacional','Integração CRM','Relatório pós-evento'], partner:'EventPro Lisboa', tag:'Parceiro', side:'empresas', featured:false },
  { id:'p_02', cat:'Logística', kicker:'Transportes · Premium', t:'Transfers Executivos', price:800, display:'€800', per:'/dia', features:['Frota premium','Motorista NDA','Tracking real-time','Faturação automática'], partner:'LuxTransfer PT', tag:'Parceiro', side:'empresas', featured:false },
  { id:'p_03', cat:'Catering', kicker:'Gastronomia · Executiva', t:'Catering C-Level', price:65, display:'€65', per:'/pax', features:['Chef executivo','Menu personalizado','Serviço white-glove','Restrições alimentares'], partner:'Chef Rodrigues', tag:'Parceiro', side:'empresas', featured:false },
  { id:'p_04', cat:'Design', kicker:'Identidade Visual', t:'Branding de Evento', price:3200, display:'€3.2K', per:'/projeto', features:['Brand book completo','Assets digitais + físicos','Signage design','Motion graphics'], partner:'Studio Vox', tag:'Parceiro', side:'empresas', featured:false },
  { id:'p_05', cat:'Imóvel', kicker:'Venue · Premium', t:'Espaço Executivo', price:4500, display:'€4.5K', per:'/dia', features:['Até 500 pax','AV completo incluído','Catering kitchen','Gestão de acesso'], partner:'Spaces Lux', tag:'Parceiro', side:'empresas', featured:false },
  { id:'p_06', cat:'Serviço', kicker:'Talent · Speakers', t:'Oradores Curados', price:1800, display:'€1.8K', per:'/keynote', features:['C-level speaker','Preparação conjunta','Conteúdo personalizado','Follow-up whitepaper'], partner:'TalentOS', tag:'Parceiro', side:'empresas', featured:false },
];

/* ── E-Wallet Mock Transactions ─────────────────────────── */
const DEMO_TRANSACTIONS = [
  { id: 'tx1', type: 'in', desc: 'Cashback · Invicta Forum', amount: 57.6, date: '28 Abr 2026', status: 'completed' },
  { id: 'tx2', type: 'out', desc: 'Networking Premium · Abr', amount: -120, date: '01 Abr 2026', status: 'completed' },
  { id: 'tx3', type: 'in', desc: 'Comissão Afiliado · Cygnus AI', amount: 81.6, date: '28 Mar 2026', status: 'completed' },
  { id: 'tx4', type: 'out', desc: 'Bilhete · Aether Summit VIP', amount: -2400, date: '15 Mar 2026', status: 'completed' },
  { id: 'tx5', type: 'in', desc: 'Recarga · Stripe', amount: 2000, date: '10 Mar 2026', status: 'completed' },
  { id: 'tx6', type: 'pending', desc: 'Comissão Afiliado · FinTech Lisboa', amount: 62.4, date: 'Pendente', status: 'pending' },
];

/* ── E-Wallet Component ─────────────────────────────────── */
const EWallet = ({ user, onNav }) => {
  const isDemo = !user;
  const [balance, setBalance] = useStateMk(isDemo ? 1850 : 1850);
  const [txs] = useStateMk(DEMO_TRANSACTIONS);
  const [activeTab, setActiveTab] = useStateMk('overview');
  const [topUpAmount, setTopUpAmount] = useStateMk(500);
  const [topping, setTopping] = useStateMk(false);

  const handleTopUp = () => {
    if (!user) { onNav('entrar'); return; }
    setTopping(true);
    setTimeout(() => {
      setBalance(b => b + topUpAmount);
      setTopping(false);
      SoundFX.success();
      fireConfetti({ x: window.innerWidth / 2, y: 400 }, ['#FFD700', '#00C48C']);
      ToastBus.push({ kind: 'gold', icon: 'check-circle', title: `+€${topUpAmount.toLocaleString('pt-PT')} adicionados`, desc: 'Saldo atualizado na Wallet Marcianus.' });
    }, 1400);
  };

  const walletActions = [
    { icon: 'arrow-up', label: 'Enviar', action: () => ToastBus.push({ icon: 'send', title: 'Transferência', desc: isDemo ? 'Cria conta para transferir.' : 'Funcionalidade em breve.' }) },
    { icon: 'arrow-down', label: 'Receber', action: () => ToastBus.push({ icon: 'qr-code', title: 'QR Code gerado', desc: 'Mostra para receber pagamentos.' }) },
    { icon: 'refresh', label: 'Recarregar', action: handleTopUp },
    { icon: 'chart-bar', label: 'Histórico', action: () => setActiveTab('history') },
  ];

  return (
    <div className="wallet-panel">
      {isDemo && (
        <div style={{ background: 'rgba(0,209,255,0.08)', border: '1px solid rgba(0,209,255,0.25)', borderRadius: 10, padding: '10px 16px', marginBottom: 20, display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="eye" size={14} color="var(--blue)" />
          <div style={{ flex: 1 }}>
            <span style={{ fontSize: 13, color: 'var(--blue)', fontWeight: 700 }}>Modo Demo — </span>
            <span style={{ fontSize: 13, color: 'var(--text-2)' }}>Estás a ver uma simulação da Wallet. </span>
            <span style={{ fontSize: 13, color: 'var(--purple-soft)', cursor: 'pointer', fontWeight: 700 }} onClick={() => onNav('entrar')}>Cria conta para operações reais →</span>
          </div>
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 24 }}>
        {/* Card */}
        <div className="wallet-card">
          <div className="wallet-balance-label">Saldo disponível</div>
          <div className="wallet-balance">€{balance.toLocaleString('pt-PT', { minimumFractionDigits: 2 })}</div>
          <div style={{ marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <span className="chip chip-success" style={{ fontSize: 9 }}>Wallet · Live</span>
            <span className="chip chip-purple" style={{ fontSize: 9 }}>EU Sovereign</span>
          </div>
          <div className="wallet-card-number">MRCS •••• •••• {user ? '4291' : '0000'}</div>
          <div className="wallet-chip-icon" aria-hidden="true" />
        </div>

        {/* Stats */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { label: 'Cashback acumulado', value: '€138.80', color: 'var(--success)' },
            { label: 'Volume este mês', value: '€2.520', color: 'var(--gold)' },
            { label: 'Comissões afiliado', value: '€144', color: 'var(--purple-soft)' },
          ].map((s, i) => (
            <div key={i} style={{ background: 'var(--surface-3)', borderRadius: 10, padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: 'var(--text-3)' }}>{s.label}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 900, fontSize: 15, color: s.color }}>{s.value}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Actions */}
      <div className="wallet-actions">
        {walletActions.map((a, i) => (
          <button key={i} className="wallet-action-btn" onClick={a.action}>
            <div className="wa-icon"><Icon name={a.icon} size={16} /></div>
            {a.label}
          </button>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginTop: 24, marginBottom: 16, borderBottom: '1px solid var(--border-1)', paddingBottom: 0 }}>
        {[{ id: 'overview', l: 'Visão Geral' }, { id: 'history', l: 'Histórico' }, { id: 'topup', l: 'Recarregar' }].map(t => (
          <button
            key={t.id}
            style={{
              padding: '8px 16px', borderRadius: '8px 8px 0 0', border: 'none', cursor: 'pointer',
              fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase',
              color: activeTab === t.id ? 'var(--purple-soft)' : 'var(--text-3)',
              background: 'none',
              borderBottom: activeTab === t.id ? '2px solid var(--purple)' : '2px solid transparent',
              marginBottom: -1,
              transition: '150ms',
            }}
            onClick={() => setActiveTab(t.id)}
          >{t.l}</button>
        ))}
      </div>

      {activeTab === 'overview' && (
        <div>
          <div style={{ fontSize: 13, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.10em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 10 }}>Últimas transações</div>
          <div className="wallet-transactions">
            {txs.slice(0, 4).map(tx => (
              <div key={tx.id} className="wallet-tx">
                <div className={`wallet-tx-icon ${tx.type}`}>
                  <Icon name={tx.type === 'in' ? 'arrow-down' : tx.type === 'pending' ? 'clock' : 'arrow-up'} size={14} />
                </div>
                <div className="wallet-tx-info">
                  <div className="desc">{tx.desc}</div>
                  <div className="date">{tx.date}</div>
                </div>
                <div className={`wallet-tx-amount ${tx.type}`}>
                  {tx.amount > 0 ? '+' : ''}€{Math.abs(tx.amount).toLocaleString('pt-PT', { minimumFractionDigits: 2 })}
                </div>
              </div>
            ))}
          </div>
          {isDemo && (
            <div style={{ textAlign: 'center', marginTop: 16 }}>
              <button className="btn btn-demo btn-sm" onClick={() => onNav('entrar')}>
                <Icon name="play" size={12} /> Criar conta para operações reais
              </button>
            </div>
          )}
        </div>
      )}

      {activeTab === 'history' && (
        <div className="wallet-transactions">
          {txs.map(tx => (
            <div key={tx.id} className="wallet-tx">
              <div className={`wallet-tx-icon ${tx.type}`}>
                <Icon name={tx.type === 'in' ? 'arrow-down' : tx.type === 'pending' ? 'clock' : 'arrow-up'} size={14} />
              </div>
              <div className="wallet-tx-info">
                <div className="desc">{tx.desc}</div>
                <div className="date">{tx.date} · {tx.status === 'pending' ? '⏳ Pendente' : '✓ Completo'}</div>
              </div>
              <div className={`wallet-tx-amount ${tx.type}`}>
                {tx.amount > 0 ? '+' : ''}€{Math.abs(tx.amount).toLocaleString('pt-PT', { minimumFractionDigits: 2 })}
              </div>
            </div>
          ))}
        </div>
      )}

      {activeTab === 'topup' && (
        <div>
          <div style={{ marginBottom: 16, fontSize: 14, color: 'var(--text-2)', lineHeight: 1.6 }}>
            Recarrega a tua Wallet Marcianus via <strong style={{ color: '#fff' }}>Stripe</strong> ou <strong style={{ color: '#fff' }}>EMIS/Multicaixa</strong>. O saldo é creditado em segundos e pode ser usado em qualquer kernel do ecossistema.
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 16 }}>
            {[100, 250, 500, 1000].map(v => (
              <button
                key={v}
                style={{
                  padding: '10px 8px', borderRadius: 10,
                  border: `1px solid ${topUpAmount === v ? 'var(--gold)' : 'var(--border-1)'}`,
                  background: topUpAmount === v ? 'rgba(255,215,0,0.06)' : 'var(--surface-3)',
                  color: topUpAmount === v ? 'var(--gold)' : 'var(--text-1)',
                  fontFamily: 'var(--font-mono)', fontWeight: 900, fontSize: 14, cursor: 'pointer', transition: '150ms',
                }}
                onClick={() => setTopUpAmount(v)}
              >€{v}</button>
            ))}
          </div>
          <div className="form-group" style={{ marginBottom: 16 }}>
            <label>Valor personalizado (€)</label>
            <input
              className="form-input"
              type="number"
              min={10}
              max={50000}
              value={topUpAmount}
              onChange={e => setTopUpAmount(Math.max(10, +e.target.value))}
            />
          </div>
          <button
            className="btn btn-gold"
            style={{ width: '100%', height: 48 }}
            onClick={handleTopUp}
            disabled={topping}
          >
            {topping ? 'A processar…' : `Recarregar €${topUpAmount.toLocaleString('pt-PT')} →`}
          </button>
          <div style={{ textAlign: 'center', marginTop: 10, fontSize: 11, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>
            Pagamento seguro · Stripe · EMIS · RGPD Compliant
          </div>
        </div>
      )}
    </div>
  );
};

/* ── MARKETPLACE PAGE ────────────────────────────────────── */
const MarketplacePage = ({ onNav }) => {
  const auth = window.useAuth ? window.useAuth() : { user: null };
  const { user } = auth;
  const [side, setSide] = useStateMk('empresas');
  const [showPartners, setShowPartners] = useStateMk(false);
  const [cart, setCart] = useStateMk([]);
  const [walletBalance, setWalletBalance] = useStateMk(1850);
  const [toast, setToast] = useStateMk(null);
  const [checkingOut, setCheckingOut] = useStateMk(false);

  const marcianusItems = MK_ITEMS.filter(o => o.side === side);
  const partnerItems = PARTNER_ITEMS.filter(o => o.side === side);
  const list = showPartners ? partnerItems : marcianusItems;

  const cartTotal = cart.reduce((s, c) => s + (c.price || 0), 0);

  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 3200); };

  const handleAdd = (item) => {
    if (!user) { onNav('entrar'); return; }
    if (item.price === 0) { showToast('Contacto comercial enviado. A equipa Marcianus entrará em contacto em 24h.'); return; }
    if (cart.find(c => c.id === item.id)) { showToast('Item já está no carrinho.'); return; }
    setCart(prev => [...prev, item]);
    showToast(`${item.t} adicionado ao carrinho`);
    SoundFX.tap();
  };

  const handleRemove = (id) => { setCart(prev => prev.filter(c => c.id !== id)); SoundFX.tap(); };

  const handleCheckout = () => {
    if (!user) { onNav('entrar'); return; }
    const liveBalance = window.HexisEngine ? HexisEngine.getProfile().walletBalance : walletBalance;
    if (cartTotal > liveBalance) { showToast('Saldo insuficiente. Recarrega a tua Wallet primeiro.'); return; }
    setCheckingOut(true);
    setTimeout(() => {
      setCheckingOut(false);
      /* Deduct from HexisEngine wallet (authoritative) */
      if (window.HexisEngine) {
        HexisEngine.walletSpend(`Marketplace · ${cart.length} produto${cart.length > 1 ? 's' : ''}`, cartTotal);
        setWalletBalance(HexisEngine.getProfile().walletBalance);
      } else {
        setWalletBalance(b => b - cartTotal);
      }
      setCart([]);
      SoundFX.success();
      fireConfetti({ x: window.innerWidth / 2, y: window.innerHeight / 2 });
      showToast(`Compra concluída! €${cartTotal.toLocaleString('pt-PT')} debitados da Wallet.`);
      if (window.HexisEngine) HexisEngine.awardXP(20, 'Compra no Marketplace');
      if (window.HexisStore) HexisStore.addAlert({ kind: 'success', title: 'Compra no Marketplace', body: `€${cartTotal.toLocaleString('pt-PT')} debitados · ${cart.length} produto${cart.length > 1 ? 's' : ''} adquirido${cart.length > 1 ? 's' : ''}. +20 XP.`, action: 'Ver histórico' });
      if (window.HexisBLS) HexisBLS.track('cta_click', 'marketplace_checkout', cartTotal);
    }, 1400);
  };

  const catColor = (cat) => cat === 'HaaS' ? 'var(--gold)' : cat === 'DaaS' ? 'var(--success)' : cat === 'Serviço' ? 'var(--blue)' : cat === 'Logística' ? 'var(--warning)' : 'var(--purple-soft)';
  const catIcon  = (cat) => cat === 'HaaS' ? '⬡' : cat === 'DaaS' ? '◈' : cat === 'Serviço' ? '⟡' : cat === 'Logística' ? '◆' : '⟡';
  const catBg    = (cat) => cat === 'HaaS'
    ? 'linear-gradient(135deg, rgba(255,215,0,0.12) 0%, rgba(93,63,211,0.08) 100%)'
    : cat === 'DaaS'
      ? 'linear-gradient(135deg, rgba(0,196,140,0.12) 0%, rgba(93,63,211,0.08) 100%)'
      : cat === 'Serviço'
        ? 'linear-gradient(135deg, rgba(0,209,255,0.10) 0%, rgba(93,63,211,0.06) 100%)'
        : 'linear-gradient(135deg, rgba(123,97,255,0.14) 0%, rgba(93,63,211,0.06) 100%)';

  return (
    <>
      {/* Toast */}
      {toast && (
        <div style={{ position: 'fixed', top: 80, right: 20, zIndex: 2100, background: 'var(--surface-3)', border: '1px solid var(--border-purple)', borderRadius: 12, padding: '12px 18px', display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, fontWeight: 700, color: '#fff', boxShadow: '0 16px 40px rgba(0,0,0,0.5)', animation: 'slideInRight 350ms cubic-bezier(0.16,1,0.3,1)' }}
          onClick={() => setToast(null)}>
          <Icon name="check-circle" size={16} color="var(--success)" />{toast}
        </div>
      )}

      {/* Hero */}
      <section className="page-hero mk-hero">
        <div className="container">
          <div className="demo-badge" style={{ marginBottom: 16 }}>Marketplace · Marcianus Ecosystem</div>
          <h1>O Ecossistema Completo.<br/><span className="hl">HaaS, DaaS, SaaS.</span></h1>
          <p className="lead">
            Capacidade, leads e decisões. Faturação unificada. Wallet cross-kernel auditável.
          </p>

          <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', marginTop: 24 }}>
            <div className="mp-tabs">
              <button className={`mp-tab ${side === 'empresas' ? 'active' : ''}`} onClick={() => { setSide('empresas'); setShowPartners(false); }}>Para Empresas</button>
              <button className={`mp-tab ${side === 'participants' ? 'active' : ''}`} onClick={() => { setSide('participants'); setShowPartners(false); }}>Para Participantes</button>
            </div>
            {user && (
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, background: 'var(--surface-2)', padding: '8px 16px', borderRadius: 20, color: 'var(--text-2)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
                Wallet: <strong style={{ color: 'var(--gold)', fontSize: 14 }}>€{walletBalance.toLocaleString('pt-PT')}</strong>
              </div>
            )}
            {!user && (
              <button className="btn btn-demo btn-sm" onClick={() => onNav('criar-experiencia')}>
                <Icon name="play" size={12} /> Demo · Ver tudo em ação
              </button>
            )}
          </div>

          {/* Source toggle */}
          <div style={{ display: 'flex', gap: 6, marginTop: 16 }}>
            <span className={`filter-chip ${!showPartners ? 'on' : ''}`} onClick={() => setShowPartners(false)}>
              <Icon name="cube" size={11} /> Marcianus
            </span>
            <span className={`filter-chip ${showPartners ? 'on' : ''}`} onClick={() => setShowPartners(true)}>
              <Icon name="users" size={11} /> Parceiros
            </span>
          </div>
        </div>
      </section>

      {/* Products grid */}
      <section style={{ paddingTop: 20, paddingBottom: 40 }}>
        <div className="container">
          {showPartners && (
            <div style={{ background: 'rgba(0,209,255,0.06)', border: '1px solid rgba(0,209,255,0.20)', borderRadius: 12, padding: '12px 18px', marginBottom: 24, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
              <Icon name="shield-check" size={14} color="var(--blue)" />
              <span style={{ fontSize: 13, color: 'var(--text-2)' }}>
                Parceiros <strong style={{ color: '#fff' }}>regularizados e validados</strong> pelo Hexis AI. Produtos e serviços com links de afiliado disponíveis.
              </span>
            </div>
          )}
          <div className="offer-grid">
            {list.map((o) => {
              const inCart = !!cart.find(c => c.id === o.id);
              return (
                <div key={o.id} className={`offer-card ${o.featured ? 'featured' : ''}`}>
                  <div style={{ height: 160, position: 'relative', background: catBg(o.cat), display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <span style={{ fontSize: 56, opacity: 0.2, filter: 'blur(1px)' }}>{catIcon(o.cat)}</span>
                    {o.tag && <span className="offer-tag">{o.tag}</span>}
                    <div style={{ position: 'absolute', bottom: 10, left: 12, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(4px)', padding: '3px 8px', borderRadius: 5, fontSize: 10, fontFamily: 'var(--font-mono)', color: catColor(o.cat), border: '1px solid rgba(255,255,255,0.1)' }}>{o.cat}</div>
                    {o.partner && (
                      <div style={{ position: 'absolute', bottom: 10, right: 12, background: 'rgba(0,0,0,0.70)', backdropFilter: 'blur(4px)', padding: '3px 8px', borderRadius: 5, fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--text-3)', border: '1px solid rgba(255,255,255,0.1)' }}>{o.partner}</div>
                    )}
                  </div>

                  <div style={{ padding: '20px 24px', flex: 1, display: 'flex', flexDirection: 'column' }}>
                    <div className="kicker" style={{ marginBottom: 4, fontSize: 10 }}>{o.kicker}</div>
                    <h3 style={{ marginBottom: 8, fontSize: 18, fontWeight: 800 }}>{o.t}</h3>
                    <div className="offer-price">{o.display}<span className="offer-per">{o.per}</span></div>
                    <ul className="offer-features">
                      {o.features.slice(0, 4).map(f => <li key={f}>{f}</li>)}
                    </ul>
                    <div style={{ display: 'flex', gap: 8, marginTop: 'auto' }}>
                      <button
                        className={`btn ${o.featured ? 'btn-gold' : 'btn-primary'} btn-sm`}
                        style={{ flex: 1 }}
                        onClick={() => handleAdd(o)}
                        disabled={inCart}
                      >
                        {inCart ? '✓ Adicionado' : o.price === 0 ? 'Contactar →' : (side === 'empresas' ? 'Comprar →' : 'Adquirir →')}
                      </button>
                      {inCart && (
                        <button className="btn btn-ghost btn-sm" onClick={() => handleRemove(o.id)} title="Remover" aria-label="Remover do carrinho">
                          <Icon name="x" size={13} />
                        </button>
                      )}
                    </div>
                    {/* Affiliate link for partners */}
                    {o.partner && (
                      <button
                        style={{ marginTop: 6, background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, color: 'var(--purple-soft)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', textAlign: 'left', padding: 0 }}
                        onClick={() => {
                          SoundFX.tap();
                          const uuid = 'mrcs-' + Math.random().toString(36).slice(2, 10).toUpperCase();
                          const link = `https://www.marcianusexperience.com/ref/${uuid}`;
                          if (navigator.clipboard) navigator.clipboard.writeText(link).catch(() => {});
                          if (window.HexisBLS) HexisBLS.track('cta_click', 'affiliate_link_gen', o.price || 0);
                          ToastBus.push({ kind: 'gold', icon: 'share', title: 'Link Copiado!', desc: `${link} · 12% comissão por venda · AES-256 UUID` });
                        }}
                      >
                        <Icon name="share" size={10} /> Obter link de afiliado
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* E-Wallet Section */}
      <section style={{ paddingTop: 20, paddingBottom: 40 }}>
        <div className="container">
          <div style={{ marginBottom: 32 }}>
            <span className="eyebrow">E-Wallet Marcianus</span>
            <h2>Um saldo. <span className="hl">Todo o ecossistema.</span></h2>
            <p style={{ color: 'var(--text-2)', fontSize: 16, maxWidth: 580, lineHeight: 1.7, marginTop: 12 }}>
              Compra tickets, stands, leads e hardware com um único saldo. Carregas via Stripe ou EMIS, gastas em qualquer kernel. Transferível, auditável, sem surpresas de faturação.
            </p>
          </div>
          <EWallet user={user} onNav={onNav} />
        </div>
      </section>

      {/* Cart bar */}
      {cart.length > 0 && (
        <div className="cart-bar">
          <div className="cart-items">
            <Icon name="layout-dashboard" size={14} /> {cart.length} item{cart.length !== 1 ? 's' : ''} · {cart.map(c => c.t).join(', ')}
          </div>
          <div className="cart-total">€{cartTotal.toLocaleString('pt-PT')}</div>
          <div className="cart-actions">
            <button className="btn btn-ghost btn-sm" onClick={() => setCart([])}>Esvaziar</button>
            <button className="btn btn-gold btn-sm" onClick={handleCheckout} disabled={checkingOut}>
              {checkingOut ? 'A processar…' : 'Confirmar Compra →'}
            </button>
          </div>
        </div>
      )}

      {/* Final CTA */}
      <section className="final-cta">
        <div className="container">
          <div className="eyebrow" style={{ justifyContent: 'center', display: 'inline-flex' }}>O Próximo Passo</div>
          <h2>O próximo evento pode ser <span className="hl">o mais lucrativo</span> da tua carreira.</h2>
          <p>Entre no ecossistema Marcianus. Hexis analisa o teu perfil em 30 segundos e entrega o primeiro match antes do próximo café.</p>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
            <button className="btn btn-demo btn-lg" onClick={() => { SoundFX.success(); fireConfetti({ x: window.innerWidth / 2, y: 400 }); onNav('criar-experiencia'); }}>
              <Icon name="play" size={16} /> Demo · Criar Experiência
            </button>
            {!user && (
              <button className="btn btn-ghost btn-lg" onClick={() => onNav('entrar')}>
                Criar Conta Gratuita →
              </button>
            )}
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 16, fontFamily: 'var(--font-mono)' }}>Sem cartão · RGPD Compliant · Setup em &lt; 2 min</div>
        </div>
      </section>
    </>
  );
};

window.MarketplacePage = MarketplacePage;
