/* ═══════════════════════════════════════════════════════════
   CRIAR EXPERIÊNCIA — Multi-step briefing wizard
   Hexis AI: confidence scoring · smart fill · personalized recs
═══════════════════════════════════════════════════════════ */
const { useState: useStateCE, useEffect: useEffectCE, useMemo: useMemoC, useRef: useRefCE } = React;

/* ── Hexis AI confidence engine (client-side) ─────────────── */
const computeConfidence = (stepId, optValue, profile) => {
  const role    = (profile?.role || '').toLowerCase();
  const sector  = (profile?.sector || '').toLowerCase();
  const intent  = (profile?.intent || '').toLowerCase();
  const interests = (profile?.interests_confirmed || []).map(i => i.toLowerCase());
  const mis     = profile?.misScore || 0.5;

  const match = (keywords) => keywords.some(k =>
    role.includes(k) || sector.includes(k) || intent.includes(k) || interests.some(i => i.includes(k))
  );

  if (stepId === 'tipo') {
    const map = {
      Summit:     match(['ceo','founder','cto','coo','managing','summit','conference','eventtech']) ? 0.91 : 0.62,
      Workshop:   match(['cto','director','head','formação','saas','tech']) ? 0.85 : 0.55,
      Networking: match(['ceo','founder','managing','investor','captação','networking']) ? 0.94 : 0.60,
      Roadshow:   match(['coo','sales','vp','roadshow','expansion','expansão']) ? 0.82 : 0.51,
      Hackathon:  match(['cto','founder','inovação','tech','saas','startup']) ? 0.79 : 0.48,
      Outro:      0.38,
    };
    return Math.min(0.98, (map[optValue] || 0.50) * (0.85 + mis * 0.15));
  }
  if (stepId === 'setor') {
    const map = {
      FinTech:    match(['fintech','finance','banking','crypto','payment']) ? 0.93 : 0.55,
      'Energia':  match(['energy','energia','esg','oil','renewabl','green']) ? 0.88 : 0.52,
      'SaaS B2B': match(['saas','software','cloud','tech','eventtech']) ? 0.92 : 0.58,
      AgriTech:   match(['agri','food','farm','rural']) ? 0.80 : 0.44,
      HealthTech: match(['health','bio','med','saúde']) ? 0.85 : 0.49,
      Outro:      0.40,
    };
    return Math.min(0.98, (map[optValue] || 0.50) * (0.88 + mis * 0.12));
  }
  if (stepId === 'escala') {
    const map = {
      micro:    match(['ceo','founder','managing','investor','captação']) ? 0.88 : 0.56,
      pequeno:  match(['cto','director','workshop','formação']) ? 0.85 : 0.60,
      medio:    match(['summit','conference','coo','sales']) ? 0.90 : 0.65,
      grande:   match(['ceo','founder','managing']) ? 0.84 : 0.58,
    };
    return Math.min(0.98, (map[optValue] || 0.60) * (0.90 + mis * 0.10));
  }
  if (stepId === 'objetivo') {
    const map = {
      Pipeline:   match(['sales','vp','ceo','pipeline','lead']) ? 0.93 : 0.62,
      Captação:   match(['founder','captação','investor','série','vc']) ? 0.96 : 0.50,
      Parcerias:  match(['ceo','coo','partner','parceria']) ? 0.87 : 0.60,
      Branding:   match(['cmo','branding','marketing','visibilidade']) ? 0.85 : 0.55,
      Formação:   match(['cto','director','formação','upskilling']) ? 0.82 : 0.52,
      Lançamento: match(['cto','founder','product','launch','lançamento']) ? 0.88 : 0.56,
    };
    return Math.min(0.98, (map[optValue] || 0.60) * (0.90 + mis * 0.10));
  }
  return 0.60;
};

const getBestOption = (stepId, opts, profile) =>
  opts.reduce((best, o) => {
    const c = computeConfidence(stepId, o.v, profile);
    return c > (best.score || 0) ? { opt: o, score: c } : best;
  }, {}).opt;

/* ── Hexis step messages ──────────────────────────────────── */
const HEXIS_STEP_MSG = (stepId, data, profile) => {
  const name = profile?.name?.split(' ')[0] || 'Executivo';
  const count = Math.floor(240 + Math.random() * 160);
  if (stepId === 'tipo') {
    if (!data.tipo) return `Analisei ${count} eventos similares ao teu perfil (${profile?.role}, ${profile?.sector}). Vou recomendar o formato com maior probabilidade de ROI para ti.`;
    return `Ótima escolha, ${name}. ${data.tipo} tem MatchScore médio de ${Math.round(86 + computeConfidence('tipo', data.tipo, profile) * 10)}% no teu sector. Prossegue para afinação do setor.`;
  }
  if (stepId === 'setor') {
    if (!data.setor) return `Com base no teu histórico de ${profile?.interests_confirmed?.slice(0, 2).join(' + ') || 'EventTech'}, tenho 3 setores com ≥85% de match para o formato ${data.tipo}.`;
    return `${data.setor} × ${data.tipo}: combinação com pipeline estimado de €${(2.1 + computeConfidence('setor', data.setor, profile) * 5).toFixed(1)}M nos próximos 90 dias.`;
  }
  if (stepId === 'escala') {
    if (!data.escala) return `Para ${data.tipo} em ${data.setor}, o Hexis calculou a escala ótima com base em ${count} eventos comparáveis. Vê as minhas recomendações abaixo.`;
    return `Escala ${data.escala} alinhada com eventos históricos semelhantes. Custo operacional estimado: €${data.escala === 'micro' ? '8.400' : data.escala === 'pequeno' ? '18.600' : data.escala === 'medio' ? '42.000' : '95.000'}.`;
  }
  if (stepId === 'objetivo') {
    if (!data.objetivo.length) return `Análise comportamental indica que o teu perfil tende a maximizar resultados em ${['Pipeline','Captação','Parcerias'].join(' + ')}. Seleciona até 3 KPIs.`;
    return `KPIs selecionados: ${data.objetivo.join(' · ')}. O Hexis configurará o algoritmo de matchmaking para estes objetivos. Pronto para construir o teu stack.`;
  }
  return 'O Hexis está a calibrar o setup operacional para a tua experiência.';
};

/* ── Hexis AI side panel per step ─────────────────────────── */
const HexisStepPanel = ({ stepId, data, profile, opts, onSmartFill, stepXP }) => {
  const [visible, setVisible] = useStateCE(false);
  const [analysisText, setAnalysisText] = useStateCE('');
  const fullText = HEXIS_STEP_MSG(stepId, data, profile);

  useEffectCE(() => {
    setVisible(false);
    setAnalysisText('');
    const t1 = setTimeout(() => setVisible(true), 200);
    return () => clearTimeout(t1);
  }, [stepId]);

  /* Typewriter effect */
  useEffectCE(() => {
    if (!visible) return;
    let i = 0;
    setAnalysisText('');
    const iv = setInterval(() => {
      i++;
      setAnalysisText(fullText.slice(0, i));
      if (i >= fullText.length) clearInterval(iv);
    }, 18);
    return () => clearInterval(iv);
  }, [visible, fullText]);

  const topOpt = getBestOption(stepId, opts, profile);

  return (
    <div
      className="ce-hexis"
      style={{
        opacity: visible ? 1 : 0,
        transform: visible ? 'translateY(0)' : 'translateY(8px)',
        transition: 'opacity 0.4s, transform 0.4s',
      }}
    >
      <div className="ce-hexis-head">
        <span style={{ color: 'var(--purple-soft)', fontSize: 20, animation: 'pulse 2s infinite' }}>⟡</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 }}>
            Hexis AI · Assistente de Briefing
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, background: 'rgba(123,97,255,0.15)', border: '1px solid rgba(123,97,255,0.3)', borderRadius: 4, padding: '1px 6px', color: 'var(--purple-soft)' }}>
              MIS {(profile?.misScore || 0.72).toFixed(2)}
            </span>
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-3)' }}>Análise comportamental · {Math.round((profile?.misScore || 0.72) * 100)}% calibrado ao teu perfil</div>
        </div>
        <button
          className="btn btn-sm"
          style={{ background: 'rgba(123,97,255,0.12)', border: '1px solid rgba(123,97,255,0.25)', color: 'var(--purple-soft)', fontSize: 11, whiteSpace: 'nowrap', flexShrink: 0 }}
          onClick={() => { SoundFX.success(); onSmartFill(topOpt); }}
        >
          ⟡ Smart Fill
        </button>
      </div>

      {/* Typewriter analysis */}
      <div className="ce-hexis-msg" style={{ borderLeft: '2px solid rgba(123,97,255,0.4)', paddingLeft: 10, marginBottom: 12 }}>
        {analysisText}
        {analysisText.length < fullText.length && (
          <span style={{ display: 'inline-block', width: 8, height: 13, background: 'var(--purple-soft)', borderRadius: 1, marginLeft: 2, animation: 'pulse 0.6s infinite' }} />
        )}
      </div>

      {/* Confidence scores */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {opts.slice(0, 4).map(o => {
          const c = computeConfidence(stepId, o.v, profile);
          const pct = Math.round(c * 100);
          const isTop = o.v === topOpt?.v;
          return (
            <div key={o.v} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 11, color: isTop ? 'var(--purple-soft)' : 'var(--text-3)', minWidth: 88, fontWeight: isTop ? 700 : 400, lineHeight: 1.3 }}>{o.l}</span>
              <div style={{ flex: 1, height: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{
                  height: '100%',
                  width: `${pct}%`,
                  background: isTop ? 'var(--purple-soft)' : c > 0.75 ? 'rgba(0,196,140,0.7)' : 'rgba(255,255,255,0.2)',
                  borderRadius: 2,
                  transition: 'width 0.6s ease',
                }} />
              </div>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: isTop ? 'var(--purple-soft)' : c > 0.75 ? 'var(--success)' : 'var(--text-3)', minWidth: 34, textAlign: 'right', fontWeight: isTop ? 900 : 400 }}>
                {pct}%
              </span>
              {isTop && <span style={{ fontSize: 9, background: 'rgba(123,97,255,0.2)', border: '1px solid rgba(123,97,255,0.4)', borderRadius: 4, padding: '1px 5px', color: 'var(--purple-soft)', fontFamily: 'var(--font-mono)', fontWeight: 900 }}>REC</span>}
            </div>
          );
        })}
      </div>

      {/* XP chip */}
      <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--text-3)' }}>
        <span style={{ color: 'var(--gold)', fontWeight: 700, fontFamily: 'var(--font-mono)' }}>+{stepXP} XP</span>
        ao concluir este passo · Hexis calibra em tempo real
      </div>
    </div>
  );
};

/* ── Products catalog ─────────────────────────────────────── */
const CE_PRODUCTS = [
  { id: 'cp_01', source: 'Marcianus', cat: 'HaaS', name: 'Kiosk NFC Check-in', desc: 'Setup completo + operação incluídos. Face ID + NFC.', price: 2400, per: '/evento', tag: '', rec: ['Summit','Networking','Roadshow'] },
  { id: 'cp_02', source: 'Marcianus', cat: 'SaaS', name: 'Hexis AI Live', desc: 'Motor de matchmaking em tempo real durante o evento.', price: 1200, per: '/evento', tag: 'Recomendado', rec: ['Summit','Networking','Hackathon'] },
  { id: 'cp_03', source: 'Marcianus', cat: 'DaaS', name: 'Pack Leads Qualificados', desc: '50 decisores validados · MatchScore ≥85%.', price: 2400, per: '/pack', tag: '', rec: ['Summit','Roadshow'] },
  { id: 'cp_04', source: 'Marcianus', cat: 'HaaS', name: 'NFC Wristbands × 100', desc: 'Identidade física. Regista cada conexão e interação.', price: 1200, per: '/100un.', tag: '', rec: ['Summit','Workshop','Networking'] },
  { id: 'cp_05', source: 'Marcianus', cat: 'SaaS', name: 'D3-BMC Dashboard', desc: 'Analytics em tempo real durante e pós-evento.', price: 600, per: '/evento', tag: '', rec: ['Summit','Networking','Roadshow','Hackathon'] },
  { id: 'cp_06', source: 'Parceiro', partner: 'EventPro Lisboa', cat: 'Serviço', name: 'Gestão de Evento Completa', desc: 'Equipa de produção, logística e coordenação no local.', price: 4500, per: '/evento', tag: '', rec: ['Summit','Roadshow'] },
  { id: 'cp_07', source: 'Parceiro', partner: 'Chef Rodrigues', cat: 'Catering', name: 'Catering Executivo', desc: 'Menu personalizado · Serviço white-glove · Chef residente.', price: 65, per: '/pax', tag: '', rec: ['Networking','Summit'] },
  { id: 'cp_08', source: 'Parceiro', partner: 'Studio Vox', cat: 'Design', name: 'Identidade Visual do Evento', desc: 'Brand book + assets digitais + signage design.', price: 3200, per: '/projeto', tag: '', rec: ['Summit','Hackathon','Roadshow'] },
  { id: 'cp_09', source: 'Parceiro', partner: 'LuxTransfer PT', cat: 'Logística', name: 'Transfers VIP', desc: 'Frota premium. Motoristas NDA. Tracking real-time.', price: 800, per: '/dia', tag: '', rec: ['Networking','Summit'] },
  { id: 'cp_10', source: 'Parceiro', partner: 'Spaces Lux', cat: 'Venue', name: 'Venue Executivo Premium', desc: 'Espaço até 500 pax. AV completo. Gestão de acesso.', price: 4500, per: '/dia', tag: '', rec: ['Summit','Networking'] },
  { id: 'cp_11', source: 'Parceiro', partner: 'TalentOS', cat: 'Talent', name: 'Keynote Speaker C-Level', desc: 'Orador validado. Preparação conjunta. Follow-up whitepaper.', price: 1800, per: '/keynote', tag: '', rec: ['Summit','Hackathon'] },
];

const catColor = { HaaS: 'var(--gold)', SaaS: 'var(--purple-soft)', DaaS: 'var(--success)', Serviço: 'var(--blue)', Catering: 'var(--warning)', Design: 'var(--purple-soft)', Logística: 'var(--warning)', Venue: 'var(--text-1)', Talent: 'var(--blue)' };

/* ── Products step ────────────────────────────────────────── */
const ProductsStep = ({ cart, setCart, data }) => {
  const [filter, setFilter] = useStateCE('Recomendados');
  const [hexisNote, setHexisNote] = useStateCE(true);

  const recommended = CE_PRODUCTS.filter(p => p.rec?.includes(data.tipo));
  const list = filter === 'Recomendados'
    ? recommended
    : filter === 'Todos' ? CE_PRODUCTS
    : CE_PRODUCTS.filter(p => p.source === filter || p.cat === filter);

  const inCart = (id) => cart.some(c => c.id === id);
  const toggle = (p) => {
    if (inCart(p.id)) setCart(prev => prev.filter(c => c.id !== p.id));
    else { setCart(prev => [...prev, p]); SoundFX.tap(); if (window.HexisEngine) HexisEngine.awardXP(5, 'Produto adicionado'); }
  };

  const total = cart.reduce((s, p) => s + p.price, 0);

  return (
    <div>
      {hexisNote && (
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '12px 14px', background: 'rgba(123,97,255,0.06)', border: '1px solid rgba(123,97,255,0.2)', borderRadius: 10, marginBottom: 16 }}>
          <span style={{ color: 'var(--purple-soft)', fontSize: 18, flexShrink: 0 }}>⟡</span>
          <div style={{ flex: 1, fontSize: 13, color: 'var(--text-2)', lineHeight: 1.55 }}>
            <strong style={{ color: 'var(--purple-soft)' }}>Hexis AI</strong> selecionou <strong style={{ color: '#fff' }}>{recommended.length} produtos</strong> recomendados para o teu evento <strong style={{ color: '#fff' }}>{data.tipo} · {data.setor}</strong>. Confiança de seleção ≥87%.
          </div>
          <button style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-3)', flexShrink: 0 }} onClick={() => setHexisNote(false)}><Icon name="x" size={14} /></button>
        </div>
      )}
      <div className="filter-bar" style={{ flexWrap: 'wrap', marginBottom: 16 }}>
        {['Recomendados', 'Todos', 'Marcianus', 'Parceiro', 'HaaS', 'SaaS', 'Talent'].map(s => (
          <span key={s} className={`filter-chip ${filter === s ? 'on' : ''}`} onClick={() => setFilter(s)}>{s === 'Recomendados' ? `⟡ Recomendados (${recommended.length})` : s}</span>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, maxHeight: 400, overflowY: 'auto', paddingRight: 4 }}>
        {list.map(p => (
          <div
            key={p.id}
            style={{
              border: `1px solid ${inCart(p.id) ? 'var(--gold)' : p.rec?.includes(data.tipo) && filter !== 'Todos' ? 'rgba(123,97,255,0.35)' : 'var(--border-1)'}`,
              borderRadius: 12, padding: 14, cursor: 'pointer',
              background: inCart(p.id) ? 'rgba(255,215,0,0.04)' : p.rec?.includes(data.tipo) ? 'rgba(123,97,255,0.03)' : 'var(--surface-3)',
              transition: '150ms', position: 'relative',
            }}
            onClick={() => toggle(p)}
          >
            {p.tag && <span style={{ position: 'absolute', top: 8, right: 8, padding: '2px 7px', borderRadius: 999, background: 'var(--purple)', color: '#fff', fontSize: 9, fontFamily: 'var(--font-mono)', fontWeight: 900 }}>{p.tag}</span>}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
              <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', fontWeight: 700, color: catColor[p.cat] || 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.10em' }}>{p.cat}</span>
              {p.partner && <span style={{ fontSize: 9, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>· {p.partner}</span>}
            </div>
            <div style={{ fontWeight: 800, fontSize: 13, color: '#fff', marginBottom: 4 }}>{p.name}</div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', lineHeight: 1.4, marginBottom: 8 }}>{p.desc}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 900, fontSize: 14, color: inCart(p.id) ? 'var(--gold)' : '#fff' }}>
                €{p.price.toLocaleString('pt-PT')}<span style={{ fontSize: 10, color: 'var(--text-3)', fontWeight: 400 }}>{p.per}</span>
              </span>
              <span style={{ fontSize: 13, color: inCart(p.id) ? 'var(--gold)' : 'var(--text-3)' }}>{inCart(p.id) ? '✓' : '+'}</span>
            </div>
          </div>
        ))}
      </div>

      {cart.length > 0 && (
        <div style={{ marginTop: 14, padding: '12px 16px', background: 'rgba(255,215,0,0.06)', border: '1px solid rgba(255,215,0,0.25)', borderRadius: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 13, color: 'var(--text-2)' }}>
            <strong style={{ color: '#fff' }}>{cart.length}</strong> {cart.length === 1 ? 'item' : 'items'} selecionados
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 900, fontSize: 16, color: 'var(--gold)' }}>
            Total est.: €{total.toLocaleString('pt-PT')}
          </div>
        </div>
      )}
    </div>
  );
};

/* ── Step XP values ───────────────────────────────────────── */
const STEP_XP = [30, 25, 20, 35, 15];

/* ── Main step definitions ───────────────────────────────── */
const STEPS_CE = [
  {
    id: 'tipo',
    title: 'Que tipo de experiência queres criar?',
    sub: 'O Hexis AI analisou o teu perfil e calculou a compatibilidade para cada formato.',
    field: 'tipo',
    opts: [
      { v: 'Summit',     l: 'Summit / Conferência',   d: 'Palco principal · Painéis · 100+ participantes' },
      { v: 'Workshop',   l: 'Workshop / Formação',    d: 'Prático · Certificado · 10–50 participantes' },
      { v: 'Networking', l: 'Networking Privado',     d: 'C-Level · Deal flow · 30 convidados' },
      { v: 'Roadshow',   l: 'Roadshow B2B',           d: 'Multi-cidade · Expansão · Pipeline regional' },
      { v: 'Hackathon',  l: 'Hackathon / Demo Day',   d: 'Inovação · Startups · Investidores' },
      { v: 'Outro',      l: 'Experiência customizada',d: 'Definimos juntos o formato ideal' },
    ],
  },
  {
    id: 'setor',
    title: 'Qual é o setor ou vertical do evento?',
    sub: 'O Hexis filtra participantes com base no teu sector de actuação e histórico.',
    field: 'setor',
    opts: [
      { v: 'FinTech',    l: 'FinTech',       d: 'Finanças · Pagamentos · Crypto · Banking' },
      { v: 'Energia',    l: 'Energia & ESG', d: 'Renováveis · Sustentabilidade · Oil & Gas' },
      { v: 'SaaS B2B',   l: 'SaaS B2B',      d: 'Software · Plataformas · Cloud' },
      { v: 'AgriTech',   l: 'AgriTech',      d: 'Agricultura · Alimentação · Rural Tech' },
      { v: 'HealthTech', l: 'HealthTech',    d: 'Saúde · Biotech · MedTech' },
      { v: 'Outro',      l: 'Outro Setor',   d: 'Retail · Media · Telecom · GovTech' },
    ],
  },
  {
    id: 'escala',
    title: 'Qual a escala esperada do evento?',
    sub: 'Estimativa de participantes e localização — o Hexis calcula custo operacional.',
    field: 'escala',
    opts: [
      { v: 'micro',    l: 'Micro (< 30)',    d: 'Reunião privada · Muito selectivo' },
      { v: 'pequeno',  l: 'Pequeno (30–100)',d: 'Workshop · Networking focado' },
      { v: 'medio',    l: 'Médio (100–500)', d: 'Conferência regional · Summit' },
      { v: 'grande',   l: 'Grande (500+)',   d: 'Summit nacional · Feira · Roadshow' },
    ],
  },
  {
    id: 'objetivo',
    title: 'Qual o objetivo principal?',
    sub: 'Define os KPIs que o Hexis vai usar para calibrar o algoritmo de matchmaking.',
    field: 'objetivo',
    multi: true,
    opts: [
      { v: 'Pipeline',  l: 'Gerar pipeline B2B',      d: 'Leads qualificados e MatchScore™' },
      { v: 'Captação',  l: 'Captação de investimento', d: 'Conexão com VCs / Angels' },
      { v: 'Parcerias', l: 'Parcerias estratégicas',   d: 'Deal flow e integrações' },
      { v: 'Branding',  l: 'Branding de marca',        d: 'Visibilidade e autoridade' },
      { v: 'Formação',  l: 'Formação corporativa',     d: 'Upskilling com certificação' },
      { v: 'Lançamento',l: 'Lançar produto',           d: 'Go-to-market com audiência certa' },
    ],
  },
];

/* ── MAIN PAGE ─────────────────────────────────────────────── */
const CriarExperienciaPage = ({ onNav }) => {
  const auth = window.useAuth ? window.useAuth() : { user: null };
  const { user } = auth;

  const [step, setStep]           = useStateCE(0);
  const [data, setData]           = useStateCE({ tipo: '', setor: '', escala: '', objetivo: [] });
  const [submitted, setSubmitted] = useStateCE(false);
  const [name, setName]           = useStateCE('');
  const [email, setEmail]         = useStateCE('');
  const [msg, setMsg]             = useStateCE('');
  const [productCart, setProductCart] = useStateCE([]);
  const [profile, setProfile]     = useStateCE(null);
  const [hexisAnalyzing, setHexisAnalyzing] = useStateCE(false);

  /* Sync HexisEngine profile */
  useEffectCE(() => {
    if (window.HexisEngine) {
      setProfile(HexisEngine.getProfile());
      return HexisEngine.subscribe(p => setProfile({ ...p }));
    }
  }, []);

  /* Prefill name/email if logged in */
  useEffectCE(() => {
    if (user) {
      if (user.name) setName(user.name);
      if (user.email) setEmail(user.email);
    }
  }, [user]);

  const totalSteps     = STEPS_CE.length + 1; /* +1 products */
  const isProductsStep = step === STEPS_CE.length;
  const s              = !isProductsStep ? STEPS_CE[step] : null;

  const toggle = (arr, val) => arr.includes(val) ? arr.filter(x => x !== val) : [...arr, val];
  const sel    = (k, v) => setData(d => ({ ...d, [k]: v }));

  const canNext = () => {
    if (isProductsStep) return true;
    if (s.multi) return data[s.field].length > 0;
    return !!data[s.field];
  };

  /* Smart fill — auto-select best option for current step */
  const handleSmartFill = (opt) => {
    if (!opt || !s) return;
    if (s.multi) sel(s.field, data[s.field].includes(opt.v) ? data[s.field] : [...data[s.field], opt.v]);
    else sel(s.field, opt.v);
    ToastBus.push({ kind: 'gold', icon: 'zap', title: 'Smart Fill · Hexis AI', desc: `"${opt.l}" selecionado com ${Math.round(computeConfidence(s.id, opt.v, profile) * 100)}% de confiança.` });
  };

  const next = async () => {
    if (step < totalSteps - 1) {
      /* Award XP for completing a wizard step */
      const xp = STEP_XP[step] || 20;
      if (window.HexisEngine) HexisEngine.awardXP(xp, `Briefing Passo ${step + 1}`);
      /* Simulate Hexis "thinking" on transition */
      if (!isProductsStep) {
        setHexisAnalyzing(true);
        setTimeout(() => setHexisAnalyzing(false), 600);
      }
      setStep(prev => prev + 1);
      return;
    }
    if (!user && !email.trim()) return;
    if (window.HexisEngine) HexisEngine.awardXP(50, 'Briefing Completo');
    setSubmitted(true);
    if (window.MarcianusAPI) {
      MarcianusAPI.track({ action: 'criar_experiencia_submit', category: 'conversion', label: data.tipo });
      MarcianusAPI.createEvent({
        title: `${data.tipo || 'Experiencia'} ${data.setor || 'Marcianus'}`,
        subtitle: `Briefing Hexis AI · ${data.objetivo.join(', ')}`,
        sector: data.setor || 'Multi-sector',
        venue_name: data.local || 'A definir',
        venue_city: data.local || 'Lisboa',
        starts_at: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30).toISOString(),
        ends_at: new Date(Date.now() + 1000 * 60 * 60 * 24 * 31).toISOString(),
        max_attendees: Number((data.escala || '').match(/\d+/)?.[0] || 100),
        price_base: productCart.reduce((sum, p) => sum + p.price, 0),
        pipeline_target: 1000000,
        is_private: true,
      });
    }
    SoundFX.success();
    fireConfetti({ x: window.innerWidth / 2, y: window.innerHeight / 2 });
  };

  /* ── Success screen ─────────────────────────────────────── */
  if (submitted) {
    const cartTotal = productCart.reduce((sum, p) => sum + p.price, 0);
    const matchEst  = profile ? Math.round(82 + (profile.misScore || 0.7) * 15) : 89;
    return (
      <div className="onb-shell">
        <div className="onb-card" style={{ textAlign: 'center', maxWidth: 560 }}>
          <div style={{ fontSize: 52, marginBottom: 16 }}>🚀</div>
          <div className="eyebrow" style={{ justifyContent: 'center', marginBottom: 8 }}>Briefing Recebido · Hexis Calibrado</div>
          <h2 style={{ fontSize: '1.6rem', fontWeight: 900, letterSpacing: '-0.03em', marginBottom: 12 }}>
            Experiência <span className="hl">em preparação.</span>
          </h2>
          <p style={{ color: 'var(--text-2)', lineHeight: 1.65, marginBottom: 24 }}>
            O Hexis AI gerou o setup operacional para o teu <strong style={{ color: 'var(--text-1)' }}>{data.tipo}</strong> em <strong style={{ color: 'var(--text-1)' }}>{data.setor}</strong>. MatchScore estimado: <strong style={{ color: 'var(--purple-soft)' }}>{matchEst}%</strong>. Proposta em 48h.
          </p>

          <div className="brief-summary">
            <div className="brief-row"><span>Tipo</span><strong>{data.tipo}</strong></div>
            <div className="brief-row"><span>Setor</span><strong>{data.setor}</strong></div>
            <div className="brief-row"><span>Escala</span><strong>{data.escala}</strong></div>
            <div className="brief-row"><span>Objetivos</span><strong>{data.objetivo.join(' · ')}</strong></div>
            <div className="brief-row"><span>Match Score est.</span><strong style={{ color: 'var(--purple-soft)' }}>{matchEst}%</strong></div>
            {productCart.length > 0 && (
              <div className="brief-row"><span>Produtos ({productCart.length})</span><strong style={{ color: 'var(--gold)' }}>€{cartTotal.toLocaleString('pt-PT')} est.</strong></div>
            )}
            {profile && (
              <div className="brief-row"><span>XP ganho</span><strong style={{ color: 'var(--gold)' }}>+{STEP_XP.slice(0, step).reduce((a, b) => a + b, 50)} XP</strong></div>
            )}
          </div>

          {/* Hexis confirmation note */}
          <div style={{ marginTop: 16, marginBottom: 20, padding: '12px 16px', background: 'rgba(123,97,255,0.06)', border: '1px solid rgba(123,97,255,0.2)', borderRadius: 10, display: 'flex', alignItems: 'flex-start', gap: 10 }}>
            <span style={{ color: 'var(--purple-soft)', fontSize: 16 }}>⟡</span>
            <div style={{ fontSize: 12, color: 'var(--text-2)', lineHeight: 1.55, textAlign: 'left' }}>
              O Hexis AI analisou <strong style={{ color: '#fff' }}>{Math.floor(320 + (profile?.tapCount || 10) * 3)} eventos similares</strong> e preparou um briefing operacional personalizado. A equipa Marcianus receberá a proposta completa com setup de hardware, matchmaking e analytics.
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
            <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => onNav('home')}>← Início</button>
            {!user && <button className="btn btn-gold" style={{ flex: 2 }} onClick={() => onNav('entrar')}>Criar Conta Grátis →</button>}
            {user && <button className="btn btn-gold" style={{ flex: 2 }} onClick={() => onNav('dashboard')}>Ver Dashboard →</button>}
          </div>
        </div>
      </div>
    );
  }

  const currentStepDef = s || null;

  return (
    <div className="onb-shell" style={{ alignItems: 'stretch', padding: '120px 0 80px' }}>
      <div style={{ width: '100%', maxWidth: 860, margin: '0 auto', padding: '0 24px' }}>

        {/* Header */}
        <div style={{ marginBottom: 40, display: 'flex', alignItems: 'center', gap: 16 }}>
          <button className="btn btn-ghost btn-sm" onClick={() => step === 0 ? onNav('eventos') : setStep(prev => prev - 1)}>
            ← {step === 0 ? 'Eventos' : 'Voltar'}
          </button>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
              <div className="eyebrow" style={{ margin: 0 }}>Criar Experiência · Passo {step + 1}/{totalSteps}</div>
              {hexisAnalyzing && (
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--purple-soft)', animation: 'pulse 0.8s infinite' }}>⟡ Hexis a calibrar…</span>
              )}
            </div>
            <div className="ce-progress">
              <div className="ce-progress-fill" style={{ width: `${((step + 1) / totalSteps) * 100}%` }} />
            </div>
          </div>
          {profile && (
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)', textAlign: 'right', flexShrink: 0 }}>
              <div style={{ color: 'var(--gold)', fontWeight: 700 }}>+{STEP_XP[step] || 20} XP</div>
              <div>próximo passo</div>
            </div>
          )}
        </div>

        {/* Two-column layout: step card + Hexis panel */}
        <div style={{ display: 'grid', gridTemplateColumns: isProductsStep ? '1fr' : '1fr 320px', gap: 20, alignItems: 'start' }}>

          {/* ── LEFT: Step card ──────────────────────────── */}
          <div className="ce-card">
            {isProductsStep ? (
              <>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 8, gap: 12 }}>
                  <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(1.3rem,3vw,1.7rem)', letterSpacing: '-0.03em', textTransform: 'uppercase', margin: 0 }}>
                    Adiciona produtos e serviços
                  </h2>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, background: 'rgba(123,97,255,0.15)', border: '1px solid rgba(123,97,255,0.3)', borderRadius: 4, padding: '3px 8px', color: 'var(--purple-soft)', flexShrink: 0, alignSelf: 'center' }}>OPCIONAL</span>
                </div>
                <p style={{ color: 'var(--text-2)', marginBottom: 20, lineHeight: 1.6, fontSize: 14 }}>
                  O Hexis pré-selecionou os produtos com maior impacto para o teu {data.tipo} em {data.setor}. Ajustas com a equipa Marcianus após proposta.
                </p>
                <ProductsStep cart={productCart} setCart={setProductCart} data={data} />
              </>
            ) : (
              <>
                <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 'clamp(1.3rem,3vw,1.9rem)', letterSpacing: '-0.03em', marginBottom: 6, textTransform: 'uppercase' }}>
                  {s.title}
                </h2>
                <p style={{ color: 'var(--text-2)', marginBottom: 28, lineHeight: 1.6, fontSize: 13 }}>{s.sub}</p>

                <div className={`ce-opts ${s.multi ? 'multi' : ''}`}>
                  {s.opts.map(o => {
                    const isSelected = s.multi ? data[s.field].includes(o.v) : data[s.field] === o.v;
                    const conf       = profile ? computeConfidence(s.id, o.v, profile) : null;
                    const confPct    = conf ? Math.round(conf * 100) : null;
                    const isTopRec   = profile && getBestOption(s.id, s.opts, profile)?.v === o.v;

                    return (
                      <div
                        key={o.v}
                        className={`ce-opt ${isSelected ? 'sel' : ''}`}
                        style={{ position: 'relative' }}
                        onClick={() => {
                          SoundFX.tap();
                          if (s.multi) sel(s.field, toggle(data[s.field], o.v));
                          else sel(s.field, o.v);
                        }}
                        role="option"
                        aria-selected={isSelected}
                        tabIndex={0}
                        onKeyDown={(e) => e.key === 'Enter' && (s.multi ? sel(s.field, toggle(data[s.field], o.v)) : sel(s.field, o.v))}
                      >
                        {isTopRec && !isSelected && (
                          <span style={{ position: 'absolute', top: 8, right: 8, fontSize: 8, fontFamily: 'var(--font-mono)', fontWeight: 900, color: 'var(--purple-soft)', background: 'rgba(123,97,255,0.15)', border: '1px solid rgba(123,97,255,0.3)', padding: '2px 5px', borderRadius: 4 }}>
                            ⟡ REC
                          </span>
                        )}
                        <h5>{o.l}</h5>
                        <p>{o.d}</p>
                        {confPct !== null && (
                          <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
                            <div style={{ flex: 1, height: 3, background: 'rgba(255,255,255,0.08)', borderRadius: 2 }}>
                              <div style={{ height: '100%', width: `${confPct}%`, background: isSelected ? 'var(--purple-soft)' : isTopRec ? 'var(--success)' : 'rgba(255,255,255,0.3)', borderRadius: 2, transition: 'width 0.5s' }} />
                            </div>
                            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: isSelected ? 'var(--purple-soft)' : isTopRec ? 'var(--success)' : 'var(--text-3)', fontWeight: 700 }}>{confPct}%</span>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>

                {/* Contact fields on last wizard step (not logged in) */}
                {step === STEPS_CE.length - 1 && !user && (
                  <div style={{ marginTop: 28, paddingTop: 28, borderTop: '1px solid var(--border-1)' }}>
                    <div className="eyebrow" style={{ marginBottom: 16 }}>Contacto para a proposta</div>
                    <div style={{ display: 'grid', gap: 14 }}>
                      <div className="form-group">
                        <label>O teu nome</label>
                        <input className="form-input" value={name} onChange={e => setName(e.target.value)} placeholder="João Silva" />
                      </div>
                      <div className="form-group">
                        <label>Email corporativo *</label>
                        <input className="form-input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="nome@empresa.com" />
                      </div>
                      <div className="form-group">
                        <label>Mensagem adicional (opcional)</label>
                        <textarea className="form-input" value={msg} onChange={e => setMsg(e.target.value)} placeholder="Data prevista, cidade, orçamento estimado…" rows={3} style={{ resize: 'vertical' }} />
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}

            <div style={{ display: 'flex', gap: 12, marginTop: 28 }}>
              <button
                className="btn btn-gold"
                style={{ flex: 1, height: 48, fontSize: 15, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}
                disabled={!canNext() || (step === STEPS_CE.length - 1 && !user && !email.trim())}
                onClick={next}
              >
                {step < totalSteps - 1
                  ? isProductsStep ? 'Continuar → Resumo' : `Continuar → +${STEP_XP[step] || 20} XP`
                  : '✓ Enviar Briefing →'}
              </button>
            </div>

            {step === STEPS_CE.length - 1 && !user && (
              <p style={{ textAlign: 'center', marginTop: 10, fontSize: 12, color: 'var(--text-3)' }}>
                Já tens conta? <span style={{ color: 'var(--purple-soft)', cursor: 'pointer' }} onClick={() => onNav('entrar')}>Entrar →</span>
              </p>
            )}
          </div>

          {/* ── RIGHT: Hexis AI panel (wizard steps only) ── */}
          {!isProductsStep && (
            <HexisStepPanel
              stepId={s.id}
              data={data}
              profile={profile}
              opts={s.opts}
              onSmartFill={handleSmartFill}
              stepXP={STEP_XP[step] || 20}
            />
          )}
        </div>

        {/* Live briefing summary strip */}
        {(data.tipo || data.setor || data.escala || data.objetivo.length > 0) && (
          <div style={{ marginTop: 20, padding: '12px 18px', background: 'rgba(123,97,255,0.05)', border: '1px solid rgba(123,97,255,0.15)', borderRadius: 12, display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', fontSize: 12 }}>
            <span style={{ color: 'var(--purple-soft)', fontWeight: 700, fontSize: 13 }}>⟡ Hexis · Briefing em curso</span>
            {data.tipo     && <span style={{ color: 'var(--text-2)' }}>Tipo: <strong style={{ color: '#fff' }}>{data.tipo}</strong></span>}
            {data.setor    && <span style={{ color: 'var(--text-2)' }}>Setor: <strong style={{ color: '#fff' }}>{data.setor}</strong></span>}
            {data.escala   && <span style={{ color: 'var(--text-2)' }}>Escala: <strong style={{ color: '#fff' }}>{data.escala}</strong></span>}
            {data.objetivo.length > 0 && <span style={{ color: 'var(--text-2)' }}>KPIs: <strong style={{ color: '#fff' }}>{data.objetivo.join(' · ')}</strong></span>}
            {productCart.length > 0 && <span style={{ color: 'var(--gold)', fontFamily: 'var(--font-mono)', fontWeight: 700 }}>{productCart.length} produtos · €{productCart.reduce((s, p) => s + p.price, 0).toLocaleString('pt-PT')}</span>}
          </div>
        )}
      </div>
    </div>
  );
};

window.CriarExperienciaPage = CriarExperienciaPage;
