/* auth.jsx — Login + Registro (correo, Google, magic link) */
const { useState: useAuthState } = React;

function GoogleG({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.6l6.7-6.7C35.6 2.7 30.1 0 24 0 14.6 0 6.5 5.4 2.6 13.2l7.8 6.1C12.3 13.2 17.6 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.5 3-2.2 5.5-4.7 7.2l7.3 5.7c4.3-4 6.8-9.9 6.8-17.4z"/><path fill="#FBBC05" d="M10.4 28.7c-.5-1.5-.8-3-.8-4.7s.3-3.2.8-4.7l-7.8-6.1C1 16.3 0 20 0 24s1 7.7 2.6 10.8l7.8-6.1z"/><path fill="#34A853" d="M24 48c6.5 0 11.9-2.1 15.9-5.8l-7.3-5.7c-2 1.4-4.7 2.3-8.6 2.3-6.4 0-11.7-3.7-13.6-9.1l-7.8 6.1C6.5 42.6 14.6 48 24 48z"/></svg>
  );
}

function AuthAside() {
  return (
    <div className="pf-auth-aside">
      <div className="glow" />
      <div style={{ position: 'relative', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <Logo size={28} ink="#fff" />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', maxWidth: 420 }}>
          <div className="pf-eyebrow" style={{ color: 'var(--yb-yellow)' }}>Cumplimiento con certeza</div>
          <h1 style={{ fontSize: 34, lineHeight: 1.12, color: '#fff', marginTop: 14 }}>
            Sabe si tu inmueble puede operar — y deja de adivinar.
          </h1>
          <p style={{ fontSize: 15.5, color: 'rgba(255,255,255,.66)', lineHeight: 1.6, marginTop: 16 }}>
            Analiza tu propiedad, arma el expediente y mantén tu evidencia sellada bajo NOM-151. Un dictamen claro por cada inmueble.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 30 }}>
            {[['shieldcheck', 'Dictamen claro de qué exige tu zona'], ['doc', 'Expediente digital con sello NOM-151'], ['pen', 'Firma electrónica avanzada (JAAK)']].map(([ic, t]) => (
              <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,200,61,.16)', color: 'var(--yb-yellow)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}><Icon name={ic} size={18} /></div>
                <span style={{ fontSize: 14.5, color: 'rgba(255,255,255,.88)', fontWeight: 500 }}>{t}</span>
              </div>
            ))}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, color: 'rgba(255,255,255,.5)', fontSize: 13 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="shield" size={15} /> Datos cifrados</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="pin" size={15} /> Hecho en CDMX</span>
        </div>
      </div>
    </div>
  );
}

function AuthScreen({ store }) {
  const [mode, setMode] = useAuthState('signup'); // signup | login
  const [step, setStep] = useAuthState('form'); // form | magic
  const [email, setEmail] = useAuthState('');
  const [name, setName] = useAuthState('');
  const [pw, setPw] = useAuthState('');

  const enter = (provider) => {
    const u = provider === 'google'
      ? { name: 'Mariana Robles', email: 'mariana.robles@gmail.com', provider: 'google' }
      : { name: name || 'Mariana Robles', email: email || 'mariana@correo.com', provider: 'email' };
    store.setUser(u);
    store.setAuthed(true);
    store.nav('dashboard');
  };

  const valid = mode === 'signup' ? (email.includes('@') && name.length > 1 && pw.length >= 4) : (email.includes('@') && pw.length >= 4);

  return (
    <div className="pf-auth">
      <AuthAside />
      <div className="pf-auth-main">
        <div className="pf-auth-form">
          <div style={{ display: 'none' }}><Logo size={26} /></div>
          {step === 'magic' ? (
            <div>
              <div style={{ width: 56, height: 56, borderRadius: 16, background: '#FFFCF3', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--yb-yellow-deep)', marginBottom: 20 }}><Icon name="bell" size={26} /></div>
              <h2 style={{ fontSize: 24 }}>Revisa tu correo</h2>
              <p className="pf-muted" style={{ fontSize: 15, marginTop: 10, lineHeight: 1.55 }}>Enviamos un enlace de acceso a <strong style={{ color: 'var(--ink)' }}>{email || 'tu correo'}</strong>. Ábrelo para entrar sin contraseña.</p>
              <button className="pf-btn pf-btn-yellow pf-btn-lg" style={{ width: '100%', marginTop: 24 }} onClick={() => enter('email')}>Simular clic en el enlace <Icon name="chevright" size={16} /></button>
              <button className="pf-btn pf-btn-soft" style={{ width: '100%', marginTop: 10 }} onClick={() => setStep('form')}>Volver</button>
            </div>
          ) : (
            <div>
              <div style={{ marginBottom: 22 }}><Logo size={26} /></div>
              <h2 style={{ fontSize: 26 }}>{mode === 'signup' ? 'Crea tu cuenta' : 'Bienvenido de vuelta'}</h2>
              <p className="pf-muted" style={{ fontSize: 14.5, marginTop: 8 }}>
                {mode === 'signup' ? 'Empieza analizando tu primer inmueble.' : 'Entra para ver tus inmuebles y trámites.'}
              </p>

              <button className="pf-oauth" style={{ marginTop: 24 }} onClick={() => enter('google')}><GoogleG /> Continuar con Google</button>
              <button className="pf-oauth" style={{ marginTop: 10 }} onClick={() => enter('email')}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="2" y="4" width="20" height="16" rx="3"/><path d="m3 6 9 7 9-7"/></svg>
                Continuar con Apple
              </button>

              <div className="pf-or">o con tu correo</div>

              {mode === 'signup' && (
                <div className="pf-field">
                  <label>Nombre completo</label>
                  <input className="pf-input" value={name} onChange={e => setName(e.target.value)} placeholder="Mariana Robles" />
                </div>
              )}
              <div className="pf-field">
                <label>Correo electrónico</label>
                <input className="pf-input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="tu@correo.com" />
              </div>
              <div className="pf-field">
                <label>Contraseña</label>
                <input className="pf-input" type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••" />
              </div>

              <button className="pf-btn pf-btn-yellow pf-btn-lg" style={{ width: '100%', marginTop: 8, opacity: valid ? 1 : .55 }} disabled={!valid} onClick={() => enter('email')}>
                {mode === 'signup' ? 'Crear cuenta' : 'Iniciar sesión'} <Icon name="chevright" size={16} />
              </button>
              <button className="pf-btn pf-btn-soft" style={{ width: '100%', marginTop: 10 }} onClick={() => { if (email.includes('@')) setStep('magic'); }}>
                Enviarme un enlace de acceso
              </button>

              <p style={{ textAlign: 'center', fontSize: 13.5, color: 'var(--muted)', marginTop: 22 }}>
                {mode === 'signup' ? '¿Ya tienes cuenta? ' : '¿Aún no tienes cuenta? '}
                <span style={{ color: 'var(--yb-yellow-deep)', fontWeight: 700, cursor: 'pointer' }} onClick={() => setMode(mode === 'signup' ? 'login' : 'signup')}>
                  {mode === 'signup' ? 'Inicia sesión' : 'Regístrate'}
                </span>
              </p>
              {mode === 'signup' && <p style={{ textAlign: 'center', fontSize: 11.5, color: 'var(--faint)', marginTop: 14, lineHeight: 1.5 }}>Al crear tu cuenta aceptas los Términos y el Aviso de Privacidad de YellowBlock.</p>}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen, GoogleG });
