/* ─────────────────────────────────────────────────────────────────────────
   Sign-in / Sign-up modal — Firebase Auth
   ───────────────────────────────────────────────────────────────────────── */

const { useState: usSi } = React;

function mapFirebaseError(code) {
  const m = {
    'auth/user-not-found':              'No existe una cuenta con este correo.',
    'auth/wrong-password':              'Contraseña incorrecta.',
    'auth/invalid-credential':          'Correo o contraseña incorrectos.',
    'auth/invalid-login-credentials':   'Correo o contraseña incorrectos.',
    'auth/email-already-in-use':        'Ya existe una cuenta con este correo. Inicia sesión.',
    'auth/weak-password':               'La contraseña debe tener al menos 6 caracteres.',
    'auth/invalid-email':               'El correo electrónico no es válido.',
    'auth/too-many-requests':           'Demasiados intentos. Espera un momento.',
    'auth/network-request-failed':      'Error de conexión. Verifica tu internet.',
    'auth/popup-closed-by-user':        '',
    'auth/operation-not-allowed':       'Este método de inicio de sesión no está habilitado.',
  };
  return m[code] ?? 'Error al autenticar. Intenta de nuevo.';
}

function buildUser(fu, provider) {
  return {
    name:     fu.displayName || fu.email?.split('@')[0] || 'Usuario',
    email:    fu.email || '',
    uid:      fu.uid,
    avatar:   fu.photoURL || null,
    provider,
  };
}

async function lookupProfile(firebaseUser) {
  if (window.MF?.getProfileByUid) {
    try {
      const fp = await window.MF.getProfileByUid(firebaseUser.uid);
      if (fp) return { ...fp, user: buildUser(firebaseUser, fp.user?.provider || 'email') };
    } catch (e) { console.warn('[signin] Firestore lookup failed:', e.message); }
  }
  try {
    const saved = JSON.parse(localStorage.getItem('factoryProfile') || 'null');
    if (saved?.user?.uid === firebaseUser.uid || saved?.user?.email === firebaseUser.email) {
      return saved;
    }
  } catch {}
  return null;
}

function MFSignIn({ onClose, onSuccess, initialMode = 'signin', initialEmail = '' }) {
  const [mode, setMode]         = usSi(initialMode);
  const isNew                   = mode === 'signup';
  const [tab, setTab]           = usSi(initialEmail ? 'email' : 'google');
  const [email, setEmail]       = usSi(initialEmail);
  const [password, setPassword] = usSi('');
  const [busy, setBusy]         = usSi(false);
  const [error, setError]       = usSi('');
  const [verifySent, setVerifySent] = usSi(false);
  const [resetSent, setResetSent]   = usSi(false);

  // Only Google and email — phone/Apple/Meta/SSO not implemented
  const TABS = [['google','Google'],['email','Email']];

  const switchMode = () => {
    setMode(isNew ? 'signin' : 'signup');
    setError('');
    setVerifySent(false);
    setResetSent(false);
  };

  const handleGoogleAuth = async () => {
    if (typeof firebase === 'undefined') { setError('Firebase no está disponible.'); return; }
    setBusy(true); setError('');
    try {
      const provider = new firebase.auth.GoogleAuthProvider();
      const cred = await firebase.auth().signInWithPopup(provider);
      const fp = await lookupProfile(cred.user);
      onSuccess?.({ user: buildUser(cred.user, 'google.com'), ...(fp || {}) });
    } catch (err) {
      const msg = mapFirebaseError(err.code);
      if (msg) setError(msg);
    } finally { setBusy(false); }
  };

  const handleEmailAuth = async () => {
    if (!email || !password) return;
    if (typeof firebase === 'undefined') { setError('Firebase no está disponible.'); return; }
    setBusy(true); setError('');
    try {
      if (isNew) {
        const cred = await firebase.auth().createUserWithEmailAndPassword(email, password);
        try { await cred.user.sendEmailVerification(); } catch (_) {}
        setVerifySent(true);
      } else {
        const cred = await firebase.auth().signInWithEmailAndPassword(email, password);
        const fp = await lookupProfile(cred.user);
        onSuccess?.({ user: buildUser(cred.user, 'email'), ...(fp || {}) });
      }
    } catch (err) {
      setError(mapFirebaseError(err.code));
    } finally { setBusy(false); }
  };

  const handleForgotPassword = async () => {
    if (!email) { setError('Ingresa tu correo primero.'); return; }
    if (typeof firebase === 'undefined') { setError('Firebase no está disponible.'); return; }
    setBusy(true); setError('');
    try {
      await firebase.auth().sendPasswordResetEmail(email);
      setResetSent(true);
    } catch (err) {
      setError(mapFirebaseError(err.code));
    } finally { setBusy(false); }
  };

  const handleContinueAfterVerification = async () => {
    const fu = firebase.auth().currentUser;
    if (!fu) { setError('Sesión expirada. Por favor inicia sesión de nuevo.'); setVerifySent(false); return; }
    setBusy(true);
    // Reload to get the latest emailVerified flag from the server
    try { await fu.reload(); } catch (_) {}
    const refreshed = firebase.auth().currentUser;
    onSuccess?.({ user: buildUser(refreshed, 'email'), restaurantId: null });
    setBusy(false);
  };

  const handleResendVerification = async () => {
    const fu = firebase.auth().currentUser;
    if (!fu) return;
    setBusy(true); setError('');
    try {
      await fu.sendEmailVerification();
    } catch (err) {
      setError(mapFirebaseError(err.code));
    } finally { setBusy(false); }
  };

  const backdropStyle = {
    width: '100%', height: '100%',
    background: 'rgba(10,9,8,0.45)',
    backdropFilter: 'blur(8px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 24, position: 'relative', overflow: 'hidden',
  };

  const cardStyle = {
    width: 460, maxWidth: '100%', padding: 32, position: 'relative',
  };

  if (verifySent) {
    return (
      <div style={backdropStyle} onClick={() => onClose?.()}>
        <FloatBg style={{ top: -80, right: -80, width: 240, height: 240, background: 'var(--coral)' }} />
        <FloatBg style={{ bottom: -100, left: -60, width: 280, height: 280, background: 'var(--saffron)' }} />
        <div className="card elev fade-up" style={cardStyle} onClick={e => e.stopPropagation()}>
          <div style={{ textAlign: 'center', padding: '8px 0' }}>
            <div style={{ fontSize: 48, marginBottom: 16, lineHeight: 1 }}>✉</div>
            <h2 className="display display-md" style={{ fontSize: 28, marginBottom: 12 }}>
              Revisa tu correo
            </h2>
            <p style={{ fontSize: 14, color: 'var(--mu)', lineHeight: 1.65, marginBottom: 24 }}>
              Enviamos un enlace de confirmación a<br />
              <strong style={{ color: 'var(--ink)' }}>{email}</strong>.<br />
              Confirma tu cuenta para activarla completamente.
            </p>
            {error && (
              <div style={{ padding: '10px 14px', background: 'var(--warn-pale, #fee2e2)', color: 'var(--warn-2, #b91c1c)', borderRadius: 8, fontSize: 13, marginBottom: 16 }}>
                {error}
              </div>
            )}
            <button className="btn coral lg" onClick={handleContinueAfterVerification}
              disabled={busy} style={{ width: '100%', marginBottom: 12 }}>
              {busy ? 'Verificando...' : 'Continuar →'}
            </button>
            <button onClick={handleResendVerification} disabled={busy}
              style={{ width: '100%', marginBottom: 8, padding: '10px', fontSize: 13, color: 'var(--coral)', fontWeight: 600, background: 'transparent' }}>
              {busy ? '...' : '¿No llegó? Reenviar correo'}
            </button>
            <p style={{ fontSize: 12, color: 'var(--mu)' }}>
              Puedes verificar tu correo después y seguir configurando tu menú.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={backdropStyle} onClick={() => onClose?.()}>
      <FloatBg style={{ top: -80, right: -80, width: 240, height: 240, background: 'var(--coral)' }} />
      <FloatBg style={{ bottom: -100, left: -60, width: 280, height: 280, background: 'var(--saffron)' }} />

      <div className="card elev fade-up" style={cardStyle} onClick={e => e.stopPropagation()}>

        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
          <div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: 11, color: 'var(--coral-2)',
              background: 'var(--coral-pale)', padding: '4px 10px', borderRadius: 999,
              fontWeight: 700, letterSpacing: '0.08em',
            }}>● {isNew ? 'NUEVA CUENTA' : 'BIENVENIDO'}</div>
            <h2 className="display display-md" style={{ fontSize: 34, marginTop: 12 }}>
              {isNew ? 'Crear ' : 'Iniciar '}
              <span className="italic">{isNew ? 'cuenta' : 'sesión'}</span>
            </h2>
            <div style={{ fontSize: 13, color: 'var(--mu)', marginTop: 6 }}>
              {isNew ? (
                <>¿Ya tienes cuenta?{' '}
                  <button onClick={switchMode} style={{ color: 'var(--coral)', fontWeight: 600 }}>
                    Inicia sesión →
                  </button>
                </>
              ) : (
                <>¿Sin cuenta?{' '}
                  <button onClick={switchMode} style={{ color: 'var(--coral)', fontWeight: 600 }}>
                    Crea una en 5 min →
                  </button>
                </>
              )}
            </div>
          </div>
          <button onClick={() => onClose?.()} style={{
            width: 34, height: 34, borderRadius: '50%',
            border: '1px solid var(--line)', color: 'var(--mu)', fontSize: 16,
            display: 'grid', placeItems: 'center',
          }}>×</button>
        </div>

        {/* Tabs */}
        <div style={{
          display: 'flex', padding: 4,
          background: 'var(--bg)', borderRadius: 12, marginBottom: 24,
        }}>
          {TABS.map(([id, label]) => (
            <button key={id} onClick={() => { setTab(id); setError(''); setResetSent(false); }} style={{
              flex: 1, padding: '9px 0', borderRadius: 9, fontSize: 13,
              background: tab === id ? 'var(--paper)' : 'transparent',
              color: tab === id ? 'var(--ink)' : 'var(--mu)',
              fontWeight: tab === id ? 600 : 500,
              boxShadow: tab === id ? 'var(--sh-1)' : 'none',
              transition: 'all 200ms',
            }}>{label}</button>
          ))}
        </div>

        {error && (
          <div style={{ padding: '10px 14px', background: 'var(--warn-pale, #fee2e2)', color: 'var(--warn-2, #b91c1c)', borderRadius: 8, fontSize: 13, marginBottom: 16 }}>
            {error}
          </div>
        )}

        {resetSent && (
          <div style={{ padding: '10px 14px', background: '#d1fae5', color: '#065f46', borderRadius: 8, fontSize: 13, marginBottom: 16 }}>
            ✓ Correo de recuperación enviado a {email}. Revisa tu bandeja.
          </div>
        )}

        {tab === 'google' && (
          <>
            <button className="btn ghost lg" onClick={handleGoogleAuth} disabled={busy}
              style={{ width: '100%', justifyContent: 'flex-start', paddingLeft: 22, gap: 14 }}>
              <GoogleG />
              {busy ? 'Conectando...' : isNew ? 'Registrarse con Google' : 'Continuar con Google'}
            </button>
            <div style={{
              marginTop: 14, padding: '12px 14px', background: 'var(--bg)', borderRadius: 12,
              display: 'flex', gap: 12, alignItems: 'center', fontSize: 12, color: 'var(--mu)',
            }}>
              <span style={{
                width: 20, height: 20, borderRadius: '50%', background: 'var(--coral-pale)',
                color: 'var(--coral-2)', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
              }}>✦</span>
              <span>Inicio instantáneo. Sin contraseñas que recordar.</span>
            </div>
          </>
        )}

        {tab === 'email' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <input className="input" type="email" placeholder="correo@restaurante.com"
              value={email} onChange={e => setEmail(e.target.value)} autoFocus />
            <input className="input" type="password"
              placeholder={isNew ? 'Crea una contraseña (mín. 6 caracteres)' : 'Tu contraseña'}
              value={password} onChange={e => setPassword(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleEmailAuth()} />
            {!isNew && (
              <div style={{ display: 'flex', justifyContent: 'flex-end', fontSize: 12 }}>
                <button onClick={handleForgotPassword} disabled={busy}
                  style={{ color: 'var(--coral)', fontWeight: 600 }}>
                  ¿Olvidaste tu contraseña?
                </button>
              </div>
            )}
            <button className="btn coral lg" onClick={handleEmailAuth}
              disabled={busy || !email || !password} style={{ marginTop: 6, width: '100%' }}>
              {busy ? 'Procesando...' : isNew ? 'Crear cuenta →' : 'Entrar →'}
            </button>
          </div>
        )}

        <div style={{
          marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--line)',
          fontSize: 11, color: 'var(--mu)', textAlign: 'center',
        }}>
          Al continuar aceptas los{' '}
          <a style={{ color: 'var(--ink)', textDecoration: 'underline' }}>Términos</a> y la{' '}
          <a style={{ color: 'var(--ink)', textDecoration: 'underline' }}>Privacidad</a>.
        </div>
      </div>
    </div>
  );
}

function GoogleG() {
  return (
    <svg width="20" height="20" viewBox="0 0 48 48">
      <path fill="#FFC107" d="M43.6 20.1H42V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3l5.7-5.7C34.2 6.1 29.4 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.6-.4-3.9z"/>
      <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.6 16 18.9 13 24 13c3.1 0 5.8 1.2 7.9 3l5.7-5.7C34.2 6.1 29.4 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/>
      <path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.5-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.6 39.6 16.2 44 24 44z"/>
      <path fill="#1976D2" d="M43.6 20.1H42V20H24v8h11.3c-.8 2.2-2.1 4.1-3.9 5.6l6.2 5.2C41.2 35.9 44 30.5 44 24c0-1.3-.1-2.6-.4-3.9z"/>
    </svg>
  );
}

function FloatBg({ style }) {
  return <div className="floaty" style={{ position: 'absolute', borderRadius: '50%', opacity: 0.18, filter: 'blur(40px)', ...style }} />;
}

window.MFSignIn = MFSignIn;
