// LoginModal — modal d'authentification Vestora
// Méthodes : Google OAuth (primaire) + Email/Mot de passe (signin + signup)
// Magic link supprimé.

const { useState: useLM, useEffect: useELM } = React;

function LoginModal({ open, onClose, lang }) {
  const FR = lang !== 'en';

  // Mode : 'signin' | 'signup'
  const [mode, setMode] = useLM('signin');

  // Champs formulaire
  const [email, setEmail] = useLM('');
  const [password, setPassword] = useLM('');

  // États de chargement séparés (Google vs email/password)
  const [loadingGoogle, setLoadingGoogle] = useLM(false);
  const [loadingForm, setLoadingForm] = useLM(false);

  // Erreurs
  const [errorGoogle, setErrorGoogle] = useLM('');
  const [errorForm, setErrorForm] = useLM('');

  // Reset au changement d'état modal ou de mode
  useELM(() => {
    if (!open) {
      setMode('signin');
      setEmail('');
      setPassword('');
      setLoadingGoogle(false);
      setLoadingForm(false);
      setErrorGoogle('');
      setErrorForm('');
    }
  }, [open]);

  useELM(() => {
    setErrorForm('');
    setErrorGoogle('');
  }, [mode]);

  // ---- Fermeture sur Échap (DOIT être avant tout return conditionnel) ----
  useELM(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const auth = window.vestora && window.vestora.auth;

  // ---- Validation client ----
  function validate() {
    const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRe.test(email.trim())) {
      setErrorForm(FR ? 'Adresse email invalide.' : 'Invalid email address.');
      return false;
    }
    if (mode === 'signup' && password.length < 8) {
      setErrorForm(FR ? 'Le mot de passe doit faire au moins 8 caractères.' : 'Password must be at least 8 characters.');
      return false;
    }
    if (!password) {
      setErrorForm(FR ? 'Mot de passe requis.' : 'Password required.');
      return false;
    }
    return true;
  }

  // ---- Google OAuth ----
  const handleGoogle = async () => {
    if (!auth) {
      setErrorGoogle(FR ? 'Auth non disponible.' : 'Auth unavailable.');
      return;
    }
    setLoadingGoogle(true);
    setErrorGoogle('');
    const { error } = await auth.signInWithGoogle();
    if (error) {
      setErrorGoogle(error.message || (FR ? 'Erreur inconnue.' : 'Unknown error.'));
      setLoadingGoogle(false);
    }
    // Succès → redirection OAuth, la page recharge — pas besoin de reset
  };

  // ---- Email / Mot de passe ----
  const handleForm = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    if (!auth) {
      setErrorForm(FR ? 'Auth non disponible.' : 'Auth unavailable.');
      return;
    }
    setLoadingForm(true);
    setErrorForm('');

    if (mode === 'signin') {
      const { error } = await auth.signInWithPassword(email.trim(), password);
      if (error) {
        setErrorForm(error.message || (FR ? 'Erreur de connexion.' : 'Sign-in error.'));
        setLoadingForm(false);
      } else {
        // onAuthStateChange dans App.jsx détectera le user → fermer la modal
        onClose();
      }
    } else {
      const { error } = await auth.signUpWithPassword(email.trim(), password);
      if (error) {
        setErrorForm(error.message || (FR ? 'Erreur de création.' : 'Sign-up error.'));
        setLoadingForm(false);
      } else {
        // Supabase envoie un email de confirmation ; informer l'utilisateur
        setErrorForm('');
        // Fermer + laisser onAuthStateChange gérer si auto-confirm activé
        onClose();
      }
    }
  };

  // ---- Labels ----
  const btnLabel = loadingForm
    ? (mode === 'signin'
        ? (FR ? 'Connexion…' : 'Signing in…')
        : (FR ? 'Création…' : 'Creating…'))
    : (mode === 'signin'
        ? (FR ? 'Se connecter' : 'Sign in')
        : (FR ? 'Créer mon compte' : 'Create account'));

  const switchLabel = mode === 'signin'
    ? (FR ? 'Pas encore de compte ?' : "Don't have an account?")
    : (FR ? 'Déjà inscrit ?' : 'Already have an account?');

  const switchAction = mode === 'signin'
    ? (FR ? 'Créer un compte' : 'Create account')
    : (FR ? 'Se connecter' : 'Sign in');

  // ---- Styles locaux réutilisés ----
  const inputStyle = {
    width: '100%',
    boxSizing: 'border-box',
    padding: '9px 12px',
    marginTop: 6,
    border: '1.5px solid var(--color-border, #ddd)',
    borderRadius: 8,
    fontSize: 14,
    fontFamily: 'var(--font-body)',
    background: 'var(--color-surface, #fff)',
    color: 'var(--color-text, #1a1a1a)',
    outline: 'none',
  };

  return (
    <div
      className="upm-backdrop"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="upm-panel" style={{ maxWidth: 420 }}>

        {/* En-tête */}
        <div className="upm-header">
          <h2 className="upm-title">
            {FR ? 'Connexion à Vestora' : 'Sign in to Vestora'}
          </h2>
          <button
            className="upm-close"
            onClick={onClose}
            aria-label={FR ? 'Fermer' : 'Close'}
          >
            <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.5" fill="none">
              <path d="M2 2l10 10M12 2L2 12"/>
            </svg>
          </button>
        </div>

        <div className="upm-body">

          {/* ---- Bouton Google (primaire) ---- */}
          <button
            type="button"
            disabled={loadingGoogle || loadingForm}
            onClick={handleGoogle}
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 10,
              width: '100%',
              padding: '11px 16px',
              borderRadius: 8,
              border: '1.5px solid var(--color-border, #ddd)',
              background: '#fff',
              color: '#1a1a1a',
              fontWeight: 600,
              fontSize: 15,
              cursor: loadingGoogle ? 'wait' : 'pointer',
              fontFamily: 'var(--font-body)',
              boxSizing: 'border-box',
              opacity: (loadingGoogle || loadingForm) ? 0.7 : 1,
              transition: 'box-shadow 0.15s',
            }}
          >
            {/* Logo Google officiel multicolore */}
            <svg width="20" height="20" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
              <path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" fill="#4285F4"/>
              <path d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 009 18z" fill="#34A853"/>
              <path d="M3.964 10.707A5.41 5.41 0 013.682 9c0-.593.102-1.17.282-1.707V4.961H.957A8.996 8.996 0 000 9c0 1.452.348 2.827.957 4.039l3.007-2.332z" fill="#FBBC05"/>
              <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 00.957 4.961L3.964 7.293C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
            </svg>
            {loadingGoogle
              ? (FR ? 'Redirection…' : 'Redirecting…')
              : (FR ? 'Continuer avec Google' : 'Continue with Google')}
          </button>

          {errorGoogle && (
            <p style={{ color: 'var(--color-danger, #c0392b)', fontSize: 13, marginTop: 8, textAlign: 'center' }}>
              {errorGoogle}
            </p>
          )}

          {/* ---- Séparateur ---- */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            margin: '20px 0',
            color: 'var(--ink-1, #888)',
            fontSize: 12,
          }}>
            <div style={{ flex: 1, height: 1, background: 'var(--color-border, #e0e0e0)' }}/>
            {FR ? 'ou avec email' : 'or with email'}
            <div style={{ flex: 1, height: 1, background: 'var(--color-border, #e0e0e0)' }}/>
          </div>

          {/* ---- Formulaire email/password ---- */}
          <form onSubmit={handleForm} noValidate>

            <div className="upm-row">
              <label className="upm-label" htmlFor="lm-email">
                {FR ? 'Email' : 'Email'}
              </label>
              <input
                id="lm-email"
                type="email"
                autoComplete="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={FR ? 'ton@email.com' : 'you@email.com'}
                disabled={loadingForm || loadingGoogle}
                style={inputStyle}
              />
            </div>

            <div className="upm-row" style={{ marginTop: 14 }}>
              <label className="upm-label" htmlFor="lm-password">
                {FR ? 'Mot de passe' : 'Password'}
              </label>
              <input
                id="lm-password"
                type="password"
                autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={mode === 'signup' ? (FR ? '8 caractères minimum' : 'At least 8 characters') : ''}
                disabled={loadingForm || loadingGoogle}
                style={inputStyle}
              />
            </div>

            {errorForm && (
              <p style={{ color: 'var(--color-danger, #c0392b)', fontSize: 13, marginTop: 8 }}>
                {errorForm}
              </p>
            )}

            <button
              type="submit"
              className="btn upm-btn-save"
              disabled={loadingForm || loadingGoogle}
              style={{ width: '100%', marginTop: 18 }}
            >
              {btnLabel}
            </button>
          </form>

          {/* ---- Toggle signin / signup ---- */}
          <p style={{
            marginTop: 16,
            fontSize: 13,
            color: 'var(--ink-1, #666)',
            textAlign: 'center',
          }}>
            {switchLabel}{' '}
            <button
              type="button"
              onClick={() => setMode(mode === 'signin' ? 'signup' : 'signin')}
              style={{
                background: 'none', border: 'none', padding: 0,
                color: 'var(--accent, #2563eb)',
                fontWeight: 600, fontSize: 13,
                cursor: 'pointer', fontFamily: 'var(--font-body)',
                textDecoration: 'underline',
              }}
            >
              {switchAction}
            </button>
          </p>

          {/* Note légale */}
          <p style={{
            marginTop: 14, fontSize: 12,
            color: 'var(--ink-1, #888)',
            textAlign: 'center',
          }}>
            {FR
              ? "En continuant, tu acceptes nos conditions d'utilisation."
              : 'By continuing, you agree to our terms of service.'}
          </p>

        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginModal });
