# ai-builder/2.1.7/assets/js/account.js

AI Builder – Generate pages, blocks, images &amp; translate with AI, version 2.1.7. 484 lines.

- Page: https://pluginprobe.com/plugins/ai-builder/2.1.7/code/assets/js/account.js
- Raw: https://pluginprobe.com/plugins/ai-builder/2.1.7/raw/assets/js/account.js
- Modified: 2025-11-20T09:32:54+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/ai-builder/2.1.7/code/assets/js/account.js#L10-L20`.

```javascript
let currentForm = "";

function showMessage(message, type = "info") {
  let container = document.getElementById("message-container");

  // Si le container n'existe pas, le créer
  if (!container) {
    container = document.createElement("div");
    container.id = "message-container";
    const authContainer = document.querySelector(".ai-auth-container");
    if (authContainer) {
      authContainer.appendChild(container);
    }
  }

  container.innerHTML = `<div class="ai-message ${type}">${message}</div>`;
  container.scrollIntoView({ behavior: "smooth" });
}

function setLoading(buttonId, isLoading) {
  const button = document.getElementById(buttonId);

  if (!button) {
    console.error(`Button with id '${buttonId}' not found`);
    return;
  }

  let loading = button.querySelector(".ai-loading");

  // Si l'élément loading n'existe pas, le créer
  if (!loading) {
    loading = document.createElement("span");
    loading.className = "ai-loading";
    loading.style.display = "none";
    button.appendChild(loading);
  }

  // Stocker le texte original dans un attribut data si pas déjà fait
  if (!button.dataset.originalText) {
    button.dataset.originalText = button.textContent.trim();
  }

  if (isLoading) {
    loading.style.display = "inline-block";
    button.disabled = true;
    button.textContent = "";
    button.appendChild(loading);
    button.appendChild(document.createTextNode(button.dataset.originalText));
  } else {
    loading.style.display = "none";
    button.disabled = false;
    button.textContent = button.dataset.originalText;
  }
}

function toggleForm(formType) {
  const container = document.querySelector(".ai-auth-container");
  const hiddenSignup = document.getElementById("hidden-signup-form");
  const hiddenSignin = document.getElementById("hidden-signin-form");

  if (formType === "signup") {
    container.innerHTML = hiddenSignup.innerHTML;
    currentForm = "signup";
    setupFormListeners();
  } else {
    container.innerHTML = hiddenSignin.innerHTML;
    currentForm = "signin";
    setupFormListeners();
  }

  // Ajouter l'animation
  container.classList.remove("ai-fade-in");
  void container.offsetWidth; // Trigger reflow
  container.classList.add("ai-fade-in");
}

function setupFormListeners() {
  const signupForm =
    document.getElementById("signup-form") ||
    document.getElementById("hidden-signup-form-element");
  const signinForm =
    document.getElementById("signin-form") ||
    document.getElementById("hidden-signin-form-element");

  if (signupForm) {
    signupForm.addEventListener("submit", handleSignup);

    // Ajouter un listener pour la checkbox des conditions d'utilisation
    const termsCheckbox = signupForm.querySelector("#terms-checkbox");
    if (termsCheckbox) {
      termsCheckbox.addEventListener("change", function () {
        const checkboxLabel = this.closest(".ai-checkbox-label");
        if (checkboxLabel) {
          if (this.checked) {
            checkboxLabel.classList.remove("error");
          }
        }
      });
    }
  }

  if (signinForm) {
    signinForm.addEventListener("submit", handleSignin);
  }
}

async function handleSignup(e) {
  e.preventDefault();
  const form = e.target;
  const email = form.email.value;
  const password = form.password.value;
  const confirmPassword = form.confirm_password.value;
  const termsAccepted = form.terms_accepted && form.terms_accepted.checked;

  // Récupérer le token Turnstile selon le formulaire
  let captcha_token = "";
  // if (currentForm === 'signup') {
  //     captcha_token = window.turnstile && turnstile.getResponse('cf-turnstile-signup');
  // } else {
  //     captcha_token = window.turnstile && turnstile.getResponse('cf-turnstile-hidden-signup');
  // }
  // if (!captcha_token) {
  //     showMessage('Please complete the captcha.', 'error');
  //     return;
  // }

  if (password !== confirmPassword) {
    showMessage("Passwords do not match", "error");
    return;
  }

  if (password.length < 8) {
    showMessage("Password must be at least 8 characters long", "error");
    return;
  }

  if (!termsAccepted) {
    showMessage(
      "You must accept the Terms of Service and Privacy Policy to create an account",
      "error"
    );
    // Ajouter une classe d'erreur visuelle à la checkbox
    const checkboxLabel = document.querySelector(".ai-checkbox-label");
    if (checkboxLabel) {
      checkboxLabel.classList.add("error");
      // Retirer la classe d'erreur après 3 secondes
      setTimeout(() => {
        checkboxLabel.classList.remove("error");
      }, 3000);
    }
    return;
  }

  // Déterminer l'ID du bouton selon le formulaire actuel
  const buttonId =
    currentForm === "signup" ? "signup-btn" : "hidden-signup-btn";
  setLoading(buttonId, true);

  // Récupérer le nom de domaine du site
  const siteDomain = (typeof aiBuilderVars !== 'undefined' && aiBuilderVars.siteDomain)
    ? aiBuilderVars.siteDomain
    : window.location.hostname;

  try {
    const response = await fetch(`${window.config.apiUrl}/auth/signup`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password, captcha_token, domain: siteDomain }),
    });

    console.log(response);
    const data = await response.json();

    if (response.ok) {
      // Marquer l'inscription comme réussie
      await fetch(ajaxurl, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body:
          "action=aibui_set_signup_success&nonce=" + aiBuilderVars.nonce,
      });

      showMessage(
        "Account created successfully! Please check your email to verify your account.",
        "success"
      );

      // Basculer vers le formulaire de connexion après 3 secondes
      setTimeout(() => {
        toggleForm("signin");
        showMessage(
          "Before signing in, please check your email and click the verification link to activate your account.",
          "info"
        );
      }, 3000);
    } else {
      showMessage(data.message || "Signup failed. Please try again.", "error");
    }
  } catch (error) {
    console.log(error);
    showMessage("Network error. Please check your connection.", "error");
  } finally {
    setLoading(buttonId, false);
    // Réinitialiser le widget Turnstile
    // if (currentForm === 'signup') {
    //     window.turnstile && turnstile.reset('cf-turnstile-signup');
    // } else {
    //     window.turnstile && turnstile.reset('cf-turnstile-hidden-signup');
    // }
  }
}

async function handleSignin(e) {
  e.preventDefault();
  const form = e.target;
  const email = form.email.value;
  const password = form.password.value;

  // Récupérer le token Turnstile selon le formulaire
  let captcha_token = "";
  // if (currentForm === 'signin') {
  //     captcha_token = window.turnstile && turnstile.getResponse('cf-turnstile-signin');
  // } else {
  //     captcha_token = window.turnstile && turnstile.getResponse('cf-turnstile-hidden-signin');
  // }
  // if (!captcha_token) {
  //     showMessage('Please complete the captcha.', 'error');
  //     return;
  // }

  // Déterminer l'ID du bouton selon le formulaire actuel
  const buttonId =
    currentForm === "signin" ? "signin-btn" : "hidden-signin-btn";
  setLoading(buttonId, true);

  console.log("🔐 Attempting signin for:", email);

  try {
    const response = await fetch(`${window.config.apiUrl}/auth/signin`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password, captcha_token }),
    });

    const data = await response.json();
    console.log("🔐 Signin response:", { status: response.status, data });

    if (response.ok && data.token) {
      console.log("✅ Token received:", data.token.substring(0, 20) + "...");
      console.log("✅ Token length:", data.token.length);
      console.log(
        "✅ Token format check:",
        data.token.split(".").length === 3
          ? "Valid JWT format"
          : "Invalid JWT format"
      );

      // Vérifier le format du token reçu
      if (data.token.split(".").length !== 3) {
        console.error("❌ Invalid JWT format received from signin API");
        showMessage("Invalid token received from server", "error");
        return;
      }

      // Sauvegarder le token JWT
      const saveResponse = await fetch(ajaxurl, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: `action=aibui_save_token&token=${encodeURIComponent(
          data.token
        )}&nonce=${aiBuilderVars.nonce}`,
      });

      const saveData = await saveResponse.json();
      console.log("💾 Token save response:", saveData);

      showMessage("Sign in successful! Redirecting...", "success");

      // Recharger la page pour afficher le dashboard
      location.reload();
    } else {
      console.error("❌ Signin failed:", data);
      showMessage(
        data.message || "Sign in failed. Please check your credentials.",
        "error"
      );
    }
  } catch (error) {
    console.error("❌ Signin network error:", error);
    showMessage("Network error. Please check your connection.", "error");
  } finally {
    setLoading(buttonId, false);
    // Réinitialiser le widget Turnstile
    // if (currentForm === 'signin') {
    //     window.turnstile && turnstile.reset('cf-turnstile-signin');
    // } else {
    //     window.turnstile && turnstile.reset('cf-turnstile-hidden-signin');
    // }
  }
}

async function signOut() {
  try {
    await fetch(ajaxurl, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: "action=aibui_signout&nonce=" + aiBuilderVars.nonce,
    });

    showMessage("Signed out successfully", "success");

    setTimeout(() => {
      location.reload();
    }, 1500);
  } catch (error) {
    showMessage("Error signing out", "error");
  }
}

// Initialiser les listeners
document.addEventListener("DOMContentLoaded", function () {
  // Déterminer le formulaire actuel basé sur le contenu de la page
  const signupForm = document.getElementById("signup-form");
  const signinForm = document.getElementById("signin-form");
  const dashboardContent = document.querySelector(".ai-dashboard-content");

  if (signupForm) {
    currentForm = "signup";
  } else if (signinForm) {
    currentForm = "signin";
  } else if (dashboardContent) {
    currentForm = "dashboard";
  }

  setupFormListeners();

  // Si on est sur le dashboard, charger les informations du compte
  if (currentForm === "dashboard") {
    loadUserAccountInfo();
  }
});

// Fonction pour charger les informations du compte utilisateur
async function loadUserAccountInfo() {
  // Éviter les appels multiples
  if (window.isLoadingUserInfo) {
    return;
  }
  window.isLoadingUserInfo = true;

  console.log("🔍 Loading user account info...");

  // Récupérer le token depuis les options WordPress via AJAX
  try {
    const tokenResponse = await fetch(ajaxurl, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: "action=aibui_get_token&nonce=" + aiBuilderVars.nonce,
    });

    const tokenData = await tokenResponse.json();
    console.log("📡 Token response:", tokenData);

    if (!tokenData.success || !tokenData.data.token) {
      console.error("❌ No token found:", tokenData);
      showMessage("No authentication token found", "error");
      // Supprimer le token invalide et rediriger vers la connexion
      await fetch(ajaxurl, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: "action=aibui_signout&nonce=" + aiBuilderVars.nonce,
      });
      setTimeout(() => {
        location.reload();
      }, 2000);
      return;
    }

    const jwtToken = tokenData.data.token;
    // Vérifier le format du token
    if (jwtToken.split(".").length !== 3) {
      console.error(
        "❌ Invalid JWT format - token should have 3 parts separated by dots"
      );
      showMessage("Invalid token format", "error");
      return;
    }
    const response = await fetch(`${window.config.apiUrl}/user/profile`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${jwtToken}`,
        "Content-Type": "application/json",
      },
    });

    console.log("🌐 API Response status:", response.status);
    console.log(
      "🌐 API Response headers:",
      Object.fromEntries(response.headers.entries())
    );

    if (response.ok) {
      const userData = await response.json();
      console.log("✅ User data received:", userData);
      displayUserInfo(userData?.user);
    } else if (response.status === 401) {
      console.error("❌ 401 Unauthorized - Token might be invalid");

      // Essayer de récupérer plus d'informations sur l'erreur
      try {
        const errorData = await response.text();
        console.error("❌ Error response body:", errorData);
      } catch (e) {
        console.error("❌ Could not read error response");
      }

      showMessage("Authentication failed. Please sign in again.", "error");
      // Supprimer le token invalide
      await fetch(ajaxurl, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: "action=aibui_signout&nonce=" + aiBuilderVars.nonce,
      });
      // Rediriger vers la connexion sans recharger en boucle
      setTimeout(() => {
        window.location.href = aiBuilderVars.accountUrl;
      }, 2000);
    } else {
      console.error("❌ API Error:", response.status, response.statusText);
      showMessage("Failed to load account information", "error");
    }
  } catch (error) {
    console.error("❌ Network error:", error);
    showMessage("Network error while loading account information", "error");
  } finally {
    window.isLoadingUserInfo = false;
  }
}

// Fonction pour afficher les informations utilisateur
function displayUserInfo(userData) {
  console.log("🔍 User data:", userData);
  // Afficher le plan
  const planBadge = document.getElementById("plan-badge");
  if (planBadge) {
    const plan = userData.plan || "basic";
    planBadge.textContent = plan.charAt(0).toUpperCase() + plan.slice(1);
    console.log("🔍 Plan:", planBadge.textContent);
    planBadge.className = `ai-plan-badge ${plan}`;
  }

  // Afficher les crédits
  const creditsDisplay = document.getElementById("credits-display");
  const creditsBreakdown = userData.aiCredits || {
    onAccountCreation: 0,
    monthlySubscription: 0,
    paid: 0,
  };

  // Calculer le total des crédits
  const totalCredits =
    creditsBreakdown.onAccountCreation +
    creditsBreakdown.monthlySubscription +
    creditsBreakdown.paid;

  if (creditsDisplay) {
    creditsDisplay.innerHTML = `
            <span>${totalCredits}</span>
            <span style="font-size: 14px; color: #666;">credits</span>
        `;
  }

  // Afficher le détail des crédits
  const creationCredits = document.getElementById("creation-credits");
  const monthlyCredits = document.getElementById("monthly-credits");
  const paidCredits = document.getElementById("paid-credits");

  if (creationCredits)
    creationCredits.textContent = creditsBreakdown.onAccountCreation;
  if (monthlyCredits)
    monthlyCredits.textContent = creditsBreakdown.monthlySubscription;
  if (paidCredits) paidCredits.textContent = creditsBreakdown.paid;
}

```
