/* ═══════════════════════════════════════════════════════════
   AUTH CONTEXT + ENTRAR PAGE + ONBOARDING
   Real API auth · JWT localStorage · RGPD compliant
   Fallback gracioso se API offline — utilizador nunca fica bloqueado
═══════════════════════════════════════════════════════════ */
const { useState: useStateAuth, useEffect: useEffectAuth, useContext: useContextAuth, createContext: createContextAuth } = React;

/* ── Auth Context ─────────────────────────────────────────── */
const AuthCtx = createContextAuth(null);
const useAuth = () => useContextAuth(AuthCtx);

/* ── Token helpers (localStorage — sobrevive ao fecho do tab) ── */
const _getToken = () => { try { return localStorage.getItem('mx_token'); } catch { return null; } };
const _setToken = (t) => { try { t ? localStorage.setItem('mx_token', t) : localStorage.removeItem('mx_token'); } catch {} };
const _getUser  = () => { try { return JSON.parse(localStorage.getItem('mx_user') || 'null'); } catch { return null; } };
const _setUser  = (u) => { try { u ? localStorage.setItem('mx_user', JSON.stringify(u)) : localStorage.removeItem('mx_user'); } catch {} };

const AuthProvider = ({ children }) => {
  const [user, setUser] = useStateAuth(() => _getUser());

  const login = (u, token) => {
    _setUser(u); _setToken(token || null); setUser(u);
    if (window.HexisEngine && u) HexisEngine.updateProfile({ userId: u.id || u.email, sector: u.sector, role: u.role });
  };

  const logout = () => { _setUser(null); _setToken(null); setUser(null); };

  useEffectAuth(() => {
    window.getAuthUser  = () => user;
    window.getAuthToken = _getToken;
  }, [user]);

  return React.createElement(AuthCtx.Provider, { value: { user, login, logout } }, children);
};

window.AuthCtx = AuthCtx;
window.AuthProvider = AuthProvider;
window.useAuth = useAuth;

/* ── API helper ───────────────────────────────────────────── */
const _apiPost = async (path, body) => {
  const base = (typeof API_BASE !== 'undefined') ? API_BASE : 'https://api.marcianusexperience.com/api/v1';
  const r = await fetch(`${base}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(12000),
  });
  const data = await r.json();
  if (!r.ok) throw new Error(data.error || `HTTP ${r.status}`);
  return data;
};

/* ── EntrarPage (Login / Register) ───────────────────────── */
const EntrarPage = ({ onNav }) => {
  const [mode, setMode] = useStateAuth('login');
  const [email, setEmail] = useStateAuth('');
  const [pass, setPass] = useStateAuth('');
  const [passConfirm, setPassConfirm] = useStateAuth('');
  const [showPass, setShowPass] = useStateAuth(false);
  const [name, setName] = useStateAuth('');
  const [company, setCompany] = useStateAuth('');
  const [role, setRole] = useStateAuth('');
  const [terms, setTerms] = useStateAuth(false);
  const [err, setErr] = useStateAuth('');
  const [fieldErrs, setFieldErrs] = useStateAuth({});
  const [loading, setLoading] = useStateAuth(false);
  const [showDemoModal, setShowDemoModal] = useStateAuth(false);
  const { login } = useAuth();

  const validateEmail = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);

  const passStrength = (p) => {
    let s = 0;
    if (p.length >= 8) s++;
    if (/[A-Z]/.test(p)) s++;
    if (/[0-9]/.test(p)) s++;
    if (/[^A-Za-z0-9]/.test(p)) s++;
    return s;
  };
  const strengthLabel = ['Fraca','Fraca','Razoável','Boa','Forte'];
  const strengthColor = ['var(--danger)','var(--danger)','var(--warning)','var(--success)','var(--success)'];
  const pStr = passStrength(pass);

  const validate = () => {
    const fe = {};
    if (!validateEmail(email)) fe.email = 'Email inválido — formato: nome@empresa.com';
    if (mode === 'register') {
      if (!name.trim()) fe.name = 'Nome completo é obrigatório.';
      if (!company.trim()) fe.company = 'Empresa é obrigatória.';
      if (!role) fe.role = 'Seleciona o teu cargo.';
      if (pass.length < 8) fe.pass = 'Mínimo 8 caracteres.';
      else if (pStr < 2) fe.pass = 'Inclui maiúsculas, números ou caracteres especiais.';
      if (pass !== passConfirm) fe.passConfirm = 'As passwords não coincidem.';
      if (!terms) fe.terms = 'Deves aceitar os Termos e Política de Privacidade.';
    } else {
      if (!pass) fe.pass = 'Password é obrigatória.';
    }
    setFieldErrs(fe);
    return Object.keys(fe).length === 0;
  };

  const _buildUser = (apiUser, extra = {}) => ({
    ...apiUser, ...extra,
    name: apiUser.full_name || apiUser.name || apiUser.email,
    initial: (apiUser.full_name || apiUser.name || 'U').split(' ').slice(0,2).map(n=>n[0]).join('').toUpperCase(),
  });

  const handleSubmit = async (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setLoading(true); setErr('');
    try {
      // Registo ou login via upsert (API idempotente)
      const data = await _apiPost('/auth/register', {
        email,
        full_name: name.trim() || email.split('@')[0].replace(/[._-]/g,' ').replace(/\b\w/g,c=>c.toUpperCase()),
        company: company.trim() || email.split('@')[1]?.split('.')[0] || 'Empresa',
        job_title: role || 'Executive',
        sector: 'EventTech',
        password: pass,
      });
      const u = _buildUser(data.user, { intent: 'Networking B2B', isNew: mode === 'register' });
      login(u, data.access_token);
      if (window.ToastBus) ToastBus.push({
        kind: mode === 'register' ? 'success' : 'info',
        icon: 'check-circle',
        title: mode === 'register' ? 'Conta criada! +250 créditos' : 'Sessão iniciada!',
        desc: `Bem-vindo(a), ${u.name.split(' ')[0]}.`,
      });
      onNav('dashboard');
    } catch (apiErr) {
      // Fallback local — utilizador nunca fica bloqueado
      const displayName = name.trim() || email.split('@')[0].replace(/[._-]/g,' ').replace(/\b\w/g,c=>c.toUpperCase());
      const fallback = {
        id: `local_${Date.now()}`, email, name: displayName, full_name: displayName,
        company: company.trim() || 'Empresa', role: role || 'Executive',
        sector: 'EventTech', intent: 'Networking B2B', isNew: mode === 'register',
        initial: displayName.split(' ').slice(0,2).map(n=>n[0]).join('').toUpperCase(),
        tier: 'explorer', xp_total: 0, wallet_balance: 250,
      };
      login(fallback, null);
      if (window.ToastBus) ToastBus.push({ kind:'warning', icon:'wifi-off', title:'Modo offline', desc:'Servidor temporariamente indisponível. A continuar localmente.' });
      onNav('dashboard');
    } finally {
      setLoading(false);
    }
  };

  const confirmDemoLogin = () => {
    setShowDemoModal(false);
    const demo = {
      id:'demo_israel', email:'demo@marcianus.pt', name:'Israel Nzambi', full_name:'Israel Nzambi',
      company:'Marcianus Experience', role:'CEO & Founder', sector:'EventTech',
      intent:'Captação Série A', initial:'IN', isDemo: true,
      xp_total: 4200, wallet_balance: 1500, tier:'operator',
    };
    login(demo, null);
    if (window.ToastBus) ToastBus.push({ kind:'gold', icon:'zap', title:'Modo Demo activo', desc:'Acesso CEO — dados de demonstração.' });
    onNav('dashboard');
  };

  const googleLogin = () => {
    const u = { id:`google_${Date.now()}`, email:'exec@empresa.pt', name:'Carlos Mendes', full_name:'Carlos Mendes', company:'Inovação Global', role:'CEO', sector:'TechB2B', intent:'Networking Executivo', initial:'CM', tier:'explorer', xp_total:150, wallet_balance:500 };
    login(u, null);
    onNav('dashboard');
  };

  const linkedInLogin = () => {
    const u = { id:`li_${Date.now()}`, email:'maria.santos@inovasys.pt', name:'Maria Santos', full_name:'Maria Santos', company:'InovaSys', role:'CTO', sector:'SaaS B2B', intent:'Parceria tecnológica', initial:'MS', tier:'explorer', xp_total:80, wallet_balance:500 };
    login(u, null);
    onNav('dashboard');
  };

  const switchMode = (m) => { setMode(m); setErr(''); setFieldErrs({}); setPass(''); setPassConfirm(''); };

  return (
    <div className="auth-shell">
      {/* Demo Modal */}
      {showDemoModal && (
        <div className="modal-overlay" onClick={() => setShowDemoModal(false)}>
          <div className="modal-box" onClick={e => e.stopPropagation()} style={{maxWidth:420}}>
            <button className="modal-close" onClick={() => setShowDemoModal(false)}>✕</button>
            <div style={{fontSize:'1.5rem', marginBottom:12}}>⚡</div>
            <h3 style={{marginBottom:8, fontWeight:900}}>Modo Demo</h3>
            <p style={{fontSize:14, color:'var(--text-2)', lineHeight:1.65, marginBottom:20}}>
              O acesso Demo é <strong style={{color:'var(--text-1)'}}>apenas para leitura</strong>. Criação de eventos, mensagens e exportações estão desativadas.
            </p>
            <div style={{display:'flex', gap:10}}>
              <button className="btn btn-ghost" style={{flex:1}} onClick={() => setShowDemoModal(false)}>Cancelar</button>
              <button className="btn btn-primary" style={{flex:2}} onClick={confirmDemoLogin}>Entrar em Demo →</button>
            </div>
          </div>
        </div>
      )}

      {/* Left Panel */}
      <div className="auth-left">
        <div className="auth-brand-big" onClick={() => onNav('home')} style={{cursor:'pointer'}}>
          <Brand />
        </div>
        <h1 className="auth-title">Entra no<br/><span className="hl">ecossistema.</span></h1>
        <p className="auth-desc">Hexis AI, D3-BMC, Connect PWA e Marketplace. Auditado por RGPD e ISO 27001. Onboarding em menos de 30 segundos.</p>
        <div className="auth-trust">
          <div className="cell"><div className="v">2,187</div><div className="l">Participants ativos</div></div>
          <div className="cell"><div className="v" style={{color:'var(--purple-soft)'}}>94%</div><div className="l">Match relevante</div></div>
          <div className="cell"><div className="v" style={{color:'var(--gold)'}}>€4.2M</div><div className="l">Pipeline · 90d</div></div>
        </div>
      </div>

      {/* Right Panel */}
      <div className="auth-right">
        <div className="auth-card">
          {/* Mode toggle */}
          <div style={{display:'flex', gap:4, background:'var(--surface-1)', border:'1px solid var(--border-1)', borderRadius:10, padding:4, marginBottom:24}}>
            <button className={`btn btn-sm ${mode==='login'?'btn-primary':'btn-ghost'}`} style={{flex:1}} onClick={() => switchMode('login')}>Entrar</button>
            <button className={`btn btn-sm ${mode==='register'?'btn-primary':'btn-ghost'}`} style={{flex:1}} onClick={() => switchMode('register')}>Criar Conta</button>
          </div>

          <h2 style={{marginBottom:4}}>{mode==='login' ? 'Bem-vindo de volta.' : 'Começa agora.'}</h2>
          <p style={{fontSize:13, color:'var(--text-3)', marginBottom:24}}>{mode==='login' ? 'Acede com o teu email corporativo.' : 'Gratuito · RGPD compliant · Setup em < 30s.'}</p>

          <form onSubmit={handleSubmit} noValidate>
            {mode === 'register' && (
              <>
                <div className="form-group">
                  <label>Nome completo *</label>
                  <input className={`form-input ${fieldErrs.name?'input-err':''}`} type="text" value={name} onChange={e=>{setName(e.target.value);setFieldErrs(fe=>({...fe,name:''}));}} placeholder="João Silva" autoFocus />
                  {fieldErrs.name && <span className="field-err">{fieldErrs.name}</span>}
                </div>
                <div className="form-group">
                  <label>Empresa *</label>
                  <input className={`form-input ${fieldErrs.company?'input-err':''}`} type="text" value={company} onChange={e=>{setCompany(e.target.value);setFieldErrs(fe=>({...fe,company:''}));}} placeholder="NovaEnergy Lda" />
                  {fieldErrs.company && <span className="field-err">{fieldErrs.company}</span>}
                </div>
                <div className="form-group">
                  <label>Cargo *</label>
                  <select className={`form-input ${fieldErrs.role?'input-err':''}`} value={role} onChange={e=>{setRole(e.target.value);setFieldErrs(fe=>({...fe,role:''}));}}>
                    <option value="">Selecionar cargo…</option>
                    {['CEO','CTO','CFO','CMO','COO','Founder','Managing Partner','VP Sales','Director','Head of Product','Investor'].map(r=><option key={r} value={r}>{r}</option>)}
                  </select>
                  {fieldErrs.role && <span className="field-err">{fieldErrs.role}</span>}
                </div>
              </>
            )}

            <div className="form-group">
              <label>Email corporativo *</label>
              <input className={`form-input ${fieldErrs.email?'input-err':''}`} type="email" value={email} onChange={e=>{setEmail(e.target.value);setFieldErrs(fe=>({...fe,email:''}));}} placeholder="nome@empresa.com" autoFocus={mode==='login'} />
              {fieldErrs.email && <span className="field-err">{fieldErrs.email}</span>}
            </div>

            <div className="form-group">
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6}}>
                <label style={{margin:0}}>Password *</label>
                <button type="button" className="auth-show-pass" onClick={()=>setShowPass(v=>!v)}>{showPass?'Ocultar':'Mostrar'}</button>
              </div>
              <input className={`form-input ${fieldErrs.pass?'input-err':''}`} type={showPass?'text':'password'} value={pass} onChange={e=>{setPass(e.target.value);setFieldErrs(fe=>({...fe,pass:''}));}} placeholder={mode==='register'?'Mín. 8 chars · 1 maiúscula · 1 número':'A tua password'} />
              {mode === 'register' && pass.length > 0 && (
                <div style={{display:'flex', gap:4, marginTop:6, alignItems:'center'}}>
                  {[0,1,2,3].map(i => <div key={i} style={{height:3, flex:1, borderRadius:2, background: i < pStr ? strengthColor[pStr] : 'var(--border-1)', transition:'background 0.2s'}} />)}
                  <span style={{fontSize:10, fontFamily:'var(--font-mono)', color:strengthColor[pStr], marginLeft:6, fontWeight:700, minWidth:40}}>{strengthLabel[pStr]}</span>
                </div>
              )}
              {fieldErrs.pass && <span className="field-err">{fieldErrs.pass}</span>}
            </div>

            {mode === 'register' && (
              <div className="form-group">
                <label>Confirmar Password *</label>
                <input className={`form-input ${fieldErrs.passConfirm?'input-err':''}`} type={showPass?'text':'password'} value={passConfirm} onChange={e=>{setPassConfirm(e.target.value);setFieldErrs(fe=>({...fe,passConfirm:''}));}} placeholder="Repetir password" />
                {fieldErrs.passConfirm && <span className="field-err">{fieldErrs.passConfirm}</span>}
              </div>
            )}

            {mode === 'login' && (
              <div style={{display:'flex', justifyContent:'flex-end', marginBottom:16}}>
                <button type="button" style={{background:'none', border:'none', color:'var(--purple-soft)', fontSize:12, cursor:'pointer', padding:0}} onClick={()=>setErr('Link de recuperação enviado para o teu email.')}>Recuperar password</button>
              </div>
            )}

            {mode === 'register' && (
              <div style={{display:'flex', gap:10, alignItems:'flex-start', marginBottom:16}}>
                <div className={`chk-box ${terms?'on':''}`} style={{cursor:'pointer', marginTop:2, flexShrink:0}} onClick={()=>{setTerms(t=>!t);setFieldErrs(fe=>({...fe,terms:''}));}}>{terms&&'✓'}</div>
                <div style={{fontSize:12, color:'var(--text-2)', lineHeight:1.55}}>
                  Aceito os <a href="#" onClick={e=>e.preventDefault()} style={{color:'var(--purple-soft)'}}>Termos de Serviço</a> e a <a href="#" onClick={e=>e.preventDefault()} style={{color:'var(--purple-soft)'}}>Política de Privacidade</a>. Dados tratados conforme RGPD · Art. 6.
                </div>
              </div>
            )}
            {fieldErrs.terms && <span className="field-err" style={{marginBottom:12, display:'block'}}>{fieldErrs.terms}</span>}

            {err && <div className="auth-msg-ok">{err}</div>}

            <button type="submit" className="btn btn-primary" style={{width:'100%', marginTop:4, height:48}} disabled={loading}>
              {loading
                ? <span style={{display:'flex', alignItems:'center', justifyContent:'center', gap:8}}><span className="auth-spinner" />A verificar…</span>
                : mode==='login' ? 'Entrar →' : 'Criar Conta Grátis →'}
            </button>
          </form>

          <div className="auth-alt">ou acesso rápido</div>
          <div className="auth-sso">
            <button className="btn btn-ghost" onClick={() => setShowDemoModal(true)} style={{display:'flex',alignItems:'center',justifyContent:'center',gap:8,height:44}}>
              <span style={{fontSize:14}}>⚡</span> Demo (CEO)
            </button>
            <button className="btn btn-ghost" onClick={linkedInLogin} style={{display:'flex',alignItems:'center',justifyContent:'center',gap:8,height:44}}>
              <span style={{fontFamily:'var(--font-mono)',fontSize:12,fontWeight:700,color:'#0A66C2'}}>in</span> LinkedIn
            </button>
            <button className="btn btn-ghost" onClick={googleLogin} style={{display:'flex',alignItems:'center',justifyContent:'center',gap:8,height:44}}>
              <span style={{fontSize:14,fontWeight:800}}>G</span> Google
            </button>
          </div>

          <div style={{textAlign:'center', marginTop:16, fontSize:13, color:'var(--text-3)'}}>
            {mode==='login'
              ? <><span>Ainda não tens conta? </span><span style={{color:'var(--purple-soft)', cursor:'pointer'}} onClick={()=>switchMode('register')}>Registar →</span></>
              : <><span>Já tens conta? </span><span style={{color:'var(--purple-soft)', cursor:'pointer'}} onClick={()=>switchMode('login')}>Entrar →</span></>}
          </div>

          <div style={{textAlign:'center', marginTop:12}}>
            <button className="btn btn-ghost btn-sm" onClick={() => onNav('home')}>← Voltar ao início</button>
          </div>

          {/* Affiliate CTA */}
          <div style={{ marginTop: 24, background: 'rgba(255,215,0,0.06)', border: '1px solid rgba(255,215,0,0.25)', borderRadius: 12, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <Icon name="gift" size={16} color="var(--gold)" />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--gold)' }}>Programa de Afiliados · 12% comissão</div>
              <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>Cria conta e ganha comissão em cada venda.</div>
            </div>
            <button style={{ background: 'rgba(255,215,0,0.14)', border: '1px solid rgba(255,215,0,0.40)', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontSize: 11, fontWeight: 700, color: 'var(--gold)', fontFamily: 'var(--font-mono)', whiteSpace: 'nowrap' }}
              onClick={() => {
                if (window.SoundFX) SoundFX.tap();
                if (window.ToastBus) ToastBus.push({ kind: 'gold', icon: 'gift', title: 'Programa de Afiliados', desc: 'Regista-te primeiro para candidatares ao programa. Comissão de 12% por venda.' });
              }}>
              Saber mais →
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

window.EntrarPage = EntrarPage;
