// ResetPasswordPage — page de réinitialisation de mot de passe Vestora
// Route : #/reset-password (Supabase redirige ici après clic sur le lien email)
// Le SDK Supabase consomme automatiquement le token de recovery via detectSessionInUrl: true.

const { useState: useRPP, useEffect: useRPE } = React;

function ResetPasswordPage({ lang }) {
  const FR = lang !== 'en';

  const [password, setPassword] = useRPP('');
  const [confirm, setConfirm] = useRPP('');
  const [loading, setLoading] = useRPP(false);
  const [error, setError] = useRPP('');
  const [success, setSuccess] = useRPP(false);
  const [hasSession, setHasSession] = useRPP(null); // null = en cours de vérification

  // Vérifier qu'une session recovery est bien active
  useRPE(() => {
    const auth = window.vestora && window.vestora.auth;
    if (!auth) {
      setHasSession(false);
      return;
    }
    // Petit délai pour laisser detectSessionInUrl consommer le token du fragment URL
    const timer = setTimeout(async () => {
      const client = auth.getClient();
      if (!client) { setHasSession(false); return; }
      const { data } = await client.auth.getSession();
      setHasSession(!!(data && data.session));
    }, 300);
    return () => clearTimeout(timer);
  }, []);

  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',
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (password.length < 8) {
      setError(FR
        ? 'Le mot de passe doit faire au moins 8 caractères.'
        : 'Password must be at least 8 characters.');
      return;
    }
    if (password !== confirm) {
      setError(FR
        ? 'Les mots de passe ne correspondent pas.'
        : 'Passwords do not match.');
      return;
    }

    const auth = window.vestora && window.vestora.auth;
    if (!auth) {
      setError(FR ? 'Auth non disponible.' : 'Auth unavailable.');
      return;
    }

    setLoading(true);
    const { error: updateError } = await auth.updatePassword(password);
    setLoading(false);

    if (updateError) {
      // Détecter les erreurs de session invalide/expirée
      const msg = updateError.message || '';
      if (
        msg.toLowerCase().includes('session') ||
        msg.toLowerCase().includes('expired') ||
        msg.toLowerCase().includes('invalid') ||
        msg.toLowerCase().includes('not authenticated')
      ) {
        setError(FR
          ? "Le lien est invalide ou expiré. Demande un nouveau lien depuis l'écran de connexion."
          : 'The link is invalid or expired. Request a new link from the sign-in screen.');
      } else {
        setError(msg || (FR ? 'Erreur lors de la mise à jour.' : 'Error updating password.'));
      }
    } else {
      setSuccess(true);
    }
  };

  // Affichage pendant la vérification de session
  if (hasSession === null) {
    return (
      <div className="legal-page" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <p style={{ color: 'var(--ink-1, #666)', fontSize: 14 }}>
          {FR ? 'Vérification du lien…' : 'Verifying link…'}
        </p>
      </div>
    );
  }

  return (
    <div className="legal-page" style={{ minHeight: '100vh' }}>
      <div className="legal-header">
        <button
          className="btn btn-ghost"
          onClick={() => window.navigateTo('#/')}
        >
          {FR ? '← Retour' : '← Back'}
        </button>
      </div>

      <div className="legal-body" style={{ maxWidth: 460, margin: '0 auto', padding: '40px 20px' }}>
        <h1 style={{
          fontFamily: 'var(--font-display)',
          fontSize: 26,
          fontWeight: 600,
          color: 'var(--color-text, #1a1a1a)',
          marginBottom: 8,
        }}>
          {FR ? 'Nouveau mot de passe' : 'New password'}
        </h1>
        <p style={{ fontSize: 14, color: 'var(--ink-1, #666)', marginBottom: 28, lineHeight: 1.5 }}>
          {FR
            ? 'Choisis un nouveau mot de passe pour ton compte Vestora.'
            : 'Choose a new password for your Vestora account.'}
        </p>

        {/* Session invalide / lien expiré */}
        {!hasSession && !success && (
          <div style={{
            background: 'var(--color-warning-soft, #fff8e1)',
            border: '1px solid var(--color-warning, #f59e0b)',
            borderRadius: 8,
            padding: '14px 16px',
            marginBottom: 24,
          }}>
            <p style={{ fontSize: 14, color: 'var(--color-text, #1a1a1a)', margin: 0 }}>
              {FR
                ? "Le lien est invalide ou expiré. Demande un nouveau lien depuis l'écran de connexion."
                : 'The link is invalid or expired. Request a new link from the sign-in screen.'}
            </p>
            <button
              type="button"
              className="btn btn-ghost"
              style={{ marginTop: 12 }}
              onClick={() => window.navigateTo('#/')}
            >
              {FR ? 'Retour à la connexion' : 'Back to sign in'}
            </button>
          </div>
        )}

        {/* Succès */}
        {success && (
          <div style={{
            background: 'var(--accent-soft, #f0fdf4)',
            border: '1px solid var(--accent, #16a34a)',
            borderRadius: 8,
            padding: '14px 16px',
            marginBottom: 24,
          }}>
            <p style={{ fontSize: 14, color: 'var(--color-text, #1a1a1a)', margin: 0, fontWeight: 600 }}>
              {FR ? 'Mot de passe mis à jour ✓' : 'Password updated ✓'}
            </p>
            <p style={{ fontSize: 13, color: 'var(--ink-1, #555)', marginTop: 6, marginBottom: 0 }}>
              {FR
                ? 'Tu peux maintenant te connecter avec ton nouveau mot de passe.'
                : 'You can now sign in with your new password.'}
            </p>
            <button
              type="button"
              className="btn upm-btn-save"
              style={{ marginTop: 14 }}
              onClick={() => window.navigateTo('#/')}
            >
              {FR ? "Retour à l'app" : 'Back to app'}
            </button>
          </div>
        )}

        {/* Formulaire — visible uniquement si session valide et pas encore soumis */}
        {hasSession && !success && (
          <form onSubmit={handleSubmit} noValidate>
            <div className="upm-row">
              <label className="upm-label" htmlFor="rp-password">
                {FR ? 'Nouveau mot de passe' : 'New password'}
              </label>
              <input
                id="rp-password"
                type="password"
                autoComplete="new-password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={FR ? '8 caractères minimum' : 'At least 8 characters'}
                disabled={loading}
                style={inputStyle}
              />
            </div>

            <div className="upm-row" style={{ marginTop: 14 }}>
              <label className="upm-label" htmlFor="rp-confirm">
                {FR ? 'Confirmer le mot de passe' : 'Confirm password'}
              </label>
              <input
                id="rp-confirm"
                type="password"
                autoComplete="new-password"
                required
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                placeholder={FR ? 'Répète ton nouveau mot de passe' : 'Repeat your new password'}
                disabled={loading}
                style={inputStyle}
              />
            </div>

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

            <button
              type="submit"
              className="btn upm-btn-save"
              disabled={loading}
              style={{ width: '100%', marginTop: 20 }}
            >
              {loading
                ? (FR ? 'Mise à jour…' : 'Updating…')
                : (FR ? 'Mettre à jour le mot de passe' : 'Update password')}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ResetPasswordPage });
