jQuery(document).ready(function ($) {
  // Variables globales
  let hasWelcomed = false;
  let conversationHistory = [];
  const MAX_HISTORY_MESSAGES = 20;

  const shouldAutoReload = botami_site_data.should_reload === '1';
  let questionnaireAlreadyStarted = false;

  // Variable globale pour suivre si l'utilisateur est en bas du chat
  let userIsAtBottom = true;

  // Initialiser l'interface
  if (typeof botami_site_data !== 'undefined') {
      if (botami_site_data.placeholder_text) {
          $('#chatbot-input').attr('placeholder', botami_site_data.placeholder_text);
      }
      if (botami_site_data.reload_text) {
          $('#refreshbtn').text(botami_site_data.reload_text);
      }
      if (botami_site_data.welcome_message) {
          $('#welcome-message-text').text(botami_site_data.welcome_message);
      }
  }
  function initializeInterface() {
    // If auto-reload is enabled, load messages automatically
    if (shouldAutoReload) {
      loadMessages();
      // Hide refresh button when auto-reload is enabled
      $("#refreshbtn").hide();
    } else {
      // Only show refresh button if there are messages and auto-reload is disabled
      updateRefreshButtonVisibility();
    }
  }

  // Call initialize function
  initializeInterface();

  // Vérifier si l'utilisateur est en bas du chat (comme WhatsApp/Telegram)
  function checkIfUserIsAtBottom() {
    const messagesContainer = $("#chatbot-messages")[0];
    if (!messagesContainer) return true;

    const scrollTop = messagesContainer.scrollTop;
    const scrollHeight = messagesContainer.scrollHeight;
    const clientHeight = messagesContainer.clientHeight;

    // Considérer l'utilisateur "en bas" s'il est à moins de 100px du bas
    return (scrollHeight - scrollTop - clientHeight) < 100;
  }

  // Scroller vers le bas seulement si l'utilisateur est déjà en bas
  function autoScrollIfAtBottom() {
    if (userIsAtBottom) {
      $("#chatbot-messages").scrollTop($("#chatbot-messages")[0].scrollHeight);
    }
  }

  // Gérer le scroll utilisateur une seule fois pour toute l'application
  const messagesContainer = $("#chatbot-messages")[0];
  if (messagesContainer) {
    messagesContainer.addEventListener('scroll', function() {
      userIsAtBottom = checkIfUserIsAtBottom();
    }, { passive: true });
  }
  
  // Gestion de l'historique de conversation
  function addToHistory(message, role) {
    conversationHistory.push({
      role: role,
      content: message,
    });

    // Conserver uniquement les derniers messages
    if (conversationHistory.length > MAX_HISTORY_MESSAGES) {
      conversationHistory = conversationHistory.slice(-MAX_HISTORY_MESSAGES);
    }
  }



  function hasShownQuestionnaire() {
  return localStorage.getItem('questionnaireShown') === 'true';
}

function markQuestionnaireAsShown() {
  localStorage.setItem('questionnaireShown', 'true');
}



  // Fonction de formatage améliorée pour les messages Markdown
function formatMessage(message) {
  if (!message) return "";

  // Si le message contient déjà des balises HTML (strong, em, br, etc.),
  // on le retourne tel quel sans transformation
  const hasHtmlTags = /<(strong|em|b|i|br|ul|ol|li|p|div|span|h[1-6]|a|code|pre)/i.test(message);
  if (hasHtmlTags) {
    return message;
  }

  // Détection des éléments Markdown spéciaux qu'il faut préserver avant de traiter les retours à la ligne
  let formattedMessage = message;

  // Traiter les titres Markdown (### Titre) avec des span au lieu de h1-h6
  // Seulement si le titre est complet (pas à la fin du texte sans contenu)
  formattedMessage = formattedMessage.replace(
    /^(#{1,6})\s+(.+?)$/gm,
    function (match, hashes, title) {
      const level = hashes.length;
      return `<span class="md-heading md-h${level}">${title}</span><br>`;
    }
  );

  // 1. Convertir les retours à la ligne (\n) en balises <br> si le backend ne l'a pas déjà fait
  formattedMessage = formattedMessage.replace(/\n/g, "<br>");

  // 2. Gérer le formatage markdown de base AVANT de traiter les listes
  // Gras: **texte** ou __texte__ - seulement si les balises sont fermées
  formattedMessage = formattedMessage.replace(
    /\*\*([^*]+?)\*\*/g,
    "<strong>$1</strong>"
  );
  formattedMessage = formattedMessage.replace(
    /__([^_]+?)__/g,
    "<strong>$1</strong>"
  );

  // Italique: *texte* ou _texte_
  // Modification du regex pour éviter les conflits avec les listes et s'assurer que c'est fermé
  formattedMessage = formattedMessage.replace(
    /\*([^*\n<]+?)\*(?=\s|$|<|[,.])/g,
    "<em>$1</em>"
  );
  formattedMessage = formattedMessage.replace(
    /_([^_\n<]+?)_(?=\s|$|<|[,.])/g,
    "<em>$1</em>"
  );

  // 2.5. Maintenant séparer les items de liste collés ensemble
  // Chercher du texte (y compris des balises HTML) suivi directement par un tiret/puce sans <br>
  // Éviter de casser si c'est un * dans une balise ou un marqueur markdown
  formattedMessage = formattedMessage.replace(/([a-zA-Z0-9.,!?>\)])(\s*[-•]\s+)/g, '$1<br>$2');

  // Pour les listes numérotées
  formattedMessage = formattedMessage.replace(/([a-zA-Z0-9.,!?>\)])(\s*\d+\.\s+)/g, '$1<br>$2');

  // 2.6. Nettoyer les multiples <br> consécutifs
  formattedMessage = formattedMessage.replace(/(<br>\s*){3,}/g, '<br>');

  // 3. Gérer les listes
  // Listes à puces - amélioration pour capturer tous les items
  formattedMessage = formattedMessage.replace(
    /<br>([-*•])\s+(.+?)(?=<br>|$)/g,
    function (match, bullet, content) {
      return '<br><span class="bullet-item">• ' + content.trim() + "</span>";
    }
  );

  // Listes numérotées
  formattedMessage = formattedMessage.replace(
    /<br>(\d+)\.\s+(.+?)(?=<br>|$)/g,
    function (match, number, content) {
      return (
        '<br><span class="numbered-item">' +
        number +
        ". " +
        content.trim() +
        "</span>"
      );
    }
  );

  // Nettoyer les <br> multiples créés par les listes (après le formatage des listes)
  formattedMessage = formattedMessage.replace(/(<br>\s*){3,}/g, '<br>');

  // 4. Gérer les liens
  formattedMessage = formattedMessage.replace(
    /\[([^\]]+)\]\(([^)]+)\)/g,
    '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'
  );

  // 5. Gérer les séparateurs horizontaux
  formattedMessage = formattedMessage.replace(
    /(?:<br>|^)---(?:<br>|$)/g,
    '<div class="md-hr"></div>'
  );

  // 6. Gérer les blocs de code
  formattedMessage = formattedMessage.replace(
    /`{3}(.*?)<br>([\s\S]*?)<br>`{3}/g,
    function (match, language, code) {
      return `<div class="md-code-block"><code class="language-${language || "text"}">${code}</code></div>`;
    }
  );

  // Code inline
  formattedMessage = formattedMessage.replace(
    /`([^`]+)`/g,
    '<code class="md-code-inline">$1</code>'
  );

  // 7. Gérer les citations
  formattedMessage = formattedMessage.replace(
    /(?:<br>|^)>\s+(.*?)(?=<br>>|<br><br>|$)/g,
    function (match, content) {
      return '<div class="md-blockquote">' + content + "</div>";
    }
  );

  // 8. Supprimer les balises <userStyle> si présentes
  formattedMessage = formattedMessage.replace(
    /<userStyle>.*?<\/userStyle>/g,
    ""
  );

  return formattedMessage;
}


  // Fonctions pour créer le HTML des messages
  function createBotMessageHtml(message, shouldAnimate = false) {
    const messageId = 'bot-msg-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);

    if (shouldAnimate) {
      return `
        <div style="display: flex; align-items: flex-start; margin-bottom: 12px;">
          <div style="display: grid;">
            <div class="message bot-message-botami">
              <p class="small_text typing-text" id="${messageId}" data-full-text="${message.replace(/"/g, '&quot;')}" style="padding: 0px; margin: 0px;"></p>
            </div>
          </div>
        </div>
      `;
    }

    return `
        <div style="display: flex; align-items: flex-start; margin-bottom: 12px;">
          <div style="display: grid;">
            <div class="message bot-message-botami">
              <p class="small_text" style="padding: 0px; margin: 0px;">${formatMessage(
                message
              )}</p>
            </div>
          </div>
        </div>
      `;
  }

  // Fonction pour calculer la durée totale de l'animation de typing
  function calculateTypingDuration(text, speed = 30) {
    let totalDuration = 0;
    for (let i = 0; i < text.length; i++) {
      let charDelay = speed;
      if (text[i] === '.' || text[i] === '!' || text[i] === '?') {
        charDelay = speed * 8;
      } else if (text[i] === ',') {
        charDelay = speed * 4;
      }
      totalDuration += charDelay;
    }
    return totalDuration;
  }

  // Fonction pour animer le texte avec effet typing
  function animateTyping(elementId, fullText, speed = 30, onComplete = null) {
    const element = document.getElementById(elementId);
    if (!element) return;

    let index = 0;
    const text = fullText;
    let lastTime = performance.now();
    let accumulatedTime = 0;
    let animationId = null;

    // Pour les longs textes, afficher plusieurs caractères à la fois
    const charsPerFrame = text.length > 500 ? 2 : 1;

    function type(currentTime) {
      const deltaTime = currentTime - lastTime;
      lastTime = currentTime;
      accumulatedTime += deltaTime;

      // Vitesse variable selon le caractère
      let nextDelay = speed;
      if (index > 0) {
        const prevChar = text[index - 1];
        if (prevChar === '.' || prevChar === '!' || prevChar === '?') {
          nextDelay = speed * 8;
        } else if (prevChar === ',') {
          nextDelay = speed * 4;
        }
      }

      if (accumulatedTime >= nextDelay) {
        accumulatedTime = 0;

        if (index < text.length) {
          // Ajouter caractère(s) par caractère(s)
          index = Math.min(index + charsPerFrame, text.length);
          const currentText = text.substring(0, index);

          // Formater le texte progressivement
          element.innerHTML = formatMessage(currentText);

          // Scroll automatique seulement si l'utilisateur est en bas
          autoScrollIfAtBottom();
        }
      }

      if (index < text.length) {
        animationId = requestAnimationFrame(type);
      } else {
        // Animation terminée - s'assurer que le formatage complet est appliqué
        element.classList.remove('typing-text');
        element.innerHTML = formatMessage(text);

        // Appeler le callback si fourni
        if (onComplete && typeof onComplete === 'function') {
          onComplete();
        }
      }
    }

    animationId = requestAnimationFrame(type);

    // Sauvegarder l'ID d'animation pour pouvoir l'annuler si nécessaire
    element.dataset.animationId = animationId;
  }
  
  
  function createBotMessageEvaluationHtml() {
    const uniqueIdLike = "btn-like-" + Date.now();
    const uniqueIdUnlike = "btn-unlike-" + Date.now();

    return `
        <div class="margin-left-9">
          <div style="margin-left: 0rem; margin-top: 0.5rem; margin-bottom: 0.5rem; background-color: #fff; border-top-left-radius: 0px !important; color: black; padding: 12px; border-radius: 8px; max-width: 270px; animation: animtext 0.7s; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);">
            <p class="small_text" style="padding: 0px; margin: 0px">${botami_site_data.translations.was_helpful}</p>
          </div>
          <div style="display: flex; justify-content: space-between; max-width: 130px;">
            <div style="margin-left: 0rem; margin-top: 0.5rem; background-color: ${botami_site_data.secondary_color}; color: white; padding: 7px; border-radius: 8px; max-width: 320px; animation: animtext 0.7s; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15); cursor: pointer; transition: all 0.2s ease;" class="feedback-btn" id="btn-like">
              <p class="small_text" style="padding: 0px; margin: 0px">👍 ${botami_site_data.translations.yes}</p>
            </div>
            <div style="margin-left: 0rem; margin-top: 0.5rem; background-color: ${botami_site_data.secondary_color}; color: white; padding: 7px; border-radius: 8px; max-width: 320px; animation: animtext 0.7s; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15); cursor: pointer; transition: all 0.2s ease;" class="feedback-btn" id="btn-unlike">
              <p class="small_text" style="padding: 0px; margin: 0px">👎 ${botami_site_data.translations.no}</p>
            </div>
          </div>
        </div>
      `;
  }

  function createUserMessageHtml(message) {
    return `
        <div style="display: flex; justify-content: flex-end;">
          <div style="margin-right: 1rem;" class="text-dark uersmessage message user-message">
            <p style="color: white; padding: 0px; margin: 0px;" class="small_text text-white">${formatMessage(
              message
            )}</p>
          </div>
        </div>
      `;
}

  function createTypingIndicator() {
    return `
        <div id="typing-indicator" style="display: flex; align-items: flex-start;">
          <div style="background-color: #fff; color: black; border-top-left-radius: 0px !important; padding: 12px; border-radius: 8px; max-width: 400px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);">
            <div class="small_text typing-indicator" style="padding: 0px; margin: 0px">${botami_site_data.translations.typing_message}<div class="typing-dots"><div class="dot"></div><div class="dot"></div><div class="dot"></div></div></div>
          </div>
        </div>
      `;
  }

  // Fonction pour afficher le message de bienvenue
  function showWelcomeMessage() {
    if (!hasWelcomed) {
      var welcomeMessageHtml = `
          <div style="display: flex; align-items: flex-start;">
            <div class="message bot-message-botami">
              <p class="small_text" style="padding: 0px; margin: 0px">${botami_site_data.message_bienvenue}</p>
            </div>
          </div>
        `;
      $("#chatbot-messages").append(welcomeMessageHtml);
      hasWelcomed = true;
    }
  }

  // Fonction pour sauvegarder les messages dans la base de données
  function saveMessage(content, source) {
    return $.ajax({
      type: "POST",
      url: botamiChatbot.ajax_url,
      data: {
        nonce: botamiChatbot.nonce,
        action: "botami_save_message",
        message: content,
        source: source,
      },
      success: function (response) {
        // Succès silencieux
      },
      error: function (xhr, status, error) {
        console.error("Error: Failed to save the message.", error);
      },
    });
  }

  // Fonction pour charger l'historique des messages
  function loadMessages() {
    $.ajax({
      type: "POST",
      url: botamiChatbot.ajax_url,
      data: { 
        action: "botami_get_messages",
        nonce: botamiChatbot.nonce,
      },
      success: function (response) {
        if (response.success) {
          $("#chatbot-messages").empty();
          const messages = response.data.messages;

          messages.forEach((msg) => {
            const messageHtml =
              msg.source === "assistant"
                ? createBotMessageHtml(msg.message)
                : createUserMessageHtml(msg.message);
            $("#chatbot-messages").append(messageHtml);
          });

          // Recréer l'historique de conversation
          conversationHistory = [];
          const recentMessages = messages.slice(-MAX_HISTORY_MESSAGES);
          recentMessages.forEach((msg) => {
            addToHistory(
              msg.message,
              msg.source === "assistant" ? "assistant" : "user"
            );
          });
        }
        // Forcer le scroll vers le bas après le chargement des messages
        setTimeout(() => {
          const messagesContainer = $("#chatbot-messages")[0];
          if (messagesContainer) {
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            userIsAtBottom = true;
          }
        }, 100);
      },
      error: function () {
        console.error("Error: Failed to load messages.");
      },
    });
  }

  // Fonction pour vérifier s'il existe des messages et mettre à jour le bouton de rafraîchissement
  function updateRefreshButtonVisibility() {
    $.ajax({
      type: "POST",
      url: botamiChatbot.ajax_url,
      data: {
        action: "botami_check_has_messages",
        nonce: botamiChatbot.nonce,
      },
      success: function (response) {
        if (response.success) {
          const hasMessages = response.data.hasMessages;
          if (hasMessages) {
            $("#refreshbtn").css('display', 'block');
          } else {
            $("#refreshbtn").css('display', 'none');
          }
        }
      },
    });
  }

  // Fonction pour afficher le message d'évaluation
  function showEvaluationMessage() {
    // Afficher l'indicateur de typing
    $("#chatbot-messages").append(createTypingIndicator());
    autoScrollIfAtBottom();

    setTimeout(() => {
      $("#typing-indicator").remove();
      var lastMessageId = "msg-" + Date.now();
      var botMessageEvaluationHtml = createBotMessageEvaluationHtml();
      $("#chatbot-messages").append(botMessageEvaluationHtml);

      // Ajouter un ID unique à ce groupe de boutons d'évaluation
      $("#chatbot-messages .margin-left-9")
        .last()
        .attr("id", lastMessageId);
      autoScrollIfAtBottom();
    }, 2000);
  }

  // Gestion de l'envoi des messages
  function sendMessage() {
    var message = $("#chatbot-input").val();
    message = message.replace(/</g, "&lt;").replace(/>/g, "&gt;");

    if (message.trim() === "") {
      return;
    }

    // Ajouter à l'historique et afficher le message de l'utilisateur
    addToHistory(message, "user");
    $("#chatbot-input").val("");

    var userMessageHtml = createUserMessageHtml(message);
    $("#chatbot-messages").append(userMessageHtml);
    autoScrollIfAtBottom();

    saveMessage(message, "user");

    // Afficher l'indicateur de frappe
    $("#chatbot-messages").append(createTypingIndicator());
    autoScrollIfAtBottom();

    // Envoyer le message via AJAX
    $.ajax({
      type: "POST",
      url: botamiChatbot.ajax_url,
      data: {
        action: "botami_chatbot_send_message",
        message: message,
        history: conversationHistory,
        nonce: botamiChatbot.nonce,
      },
      success: function (response) {
        // Retirer l'indicateur de frappe
        $("#typing-indicator").remove();

        if (response.success) {
          const botResponse = response.data;
          let messageText = '';

          // Check if the response is an object with a request_feedback flag
          if (
            typeof botResponse === "object" &&
            botResponse.hasOwnProperty("response")
          ) {
            messageText = botResponse.response;
            addToHistory(messageText, "assistant");

            // Afficher la réponse du bot avec animation
            var botMessageHtml = createBotMessageHtml(messageText, true);
            const $message = $(botMessageHtml);
            $("#chatbot-messages").append($message);

            // Extraire l'ID du message et démarrer l'animation
            const messageId = $message.find('.typing-text').attr('id');
            if (messageId) {
              // Si feedback est demandé, utiliser un callback
              const showFeedback = botResponse.request_feedback === true;
              if (showFeedback) {
                animateTyping(messageId, messageText, 30, function() {
                  // Animation terminée, maintenant afficher l'évaluation
                  setTimeout(() => {
                    showEvaluationMessage();
                  }, 1000);
                });
              } else {
                animateTyping(messageId, messageText);
              }
            }

            saveMessage(messageText, "assistant");
          } else {
            // Handle legacy response format (simple string)
            messageText = botResponse;
            addToHistory(messageText, "assistant");

            // Afficher la réponse du bot avec animation
            var botMessageHtml = createBotMessageHtml(messageText, true);
            const $message = $(botMessageHtml);
            $("#chatbot-messages").append($message);

            // Extraire l'ID du message et démarrer l'animation
            const messageId = $message.find('.typing-text').attr('id');
            if (messageId) {
              animateTyping(messageId, messageText);
            }

            saveMessage(messageText, "assistant");
          }

          // Note: L'évaluation est maintenant gérée par le callback dans animateTyping()
        } else {
          // Afficher le message d'erreur
          var botMessageHtml = createBotMessageHtml(response.data);
          $("#chatbot-messages").append(botMessageHtml);
        }

        autoScrollIfAtBottom();
      },
      error: function () {
        $("#typing-indicator").remove();
        $("#chatbot-messages").append(
          createBotMessageHtml(botami_site_data.translations.error_message)
        );
        autoScrollIfAtBottom();
      },
    });
  }

  // Gestion des boutons d'évaluation
  $(document).on("click", ".feedback-btn", function () {
    // Trouver le parent .margin-left-9 contenant ce bouton spécifique
    const parentContainer = $(this).closest(".margin-left-9");
    // Déterminer quel bouton a été cliqué
    const isLike = $(this).attr("id") === "btn-like";
    const feedbackText = isLike
      ? botami_site_data.translations.feedback_positive
      : botami_site_data.translations.feedback_negative;
    const feedbackType = isLike ? "positive" : "negative";

    // Changer la couleur du bouton cliqué (plus foncé) et désactiver les deux boutons
    $(this).css({
      "background-color": isLike ? "#4CAF50" : "#F44336", // Vert pour like, rouge pour unlike
      "box-shadow": "0 1px 3px rgba(0, 0, 0, 0.2)",
      transform: "translateY(1px)",
    });

    // Désactiver les deux boutons pour éviter des clics multiples
    parentContainer.find(".feedback-btn").not($(this)).css({
      opacity: "0.5",
      "pointer-events": "none",
    });

    // Désactiver aussi le bouton cliqué après avoir changé son apparence
    $(this).css("pointer-events", "none");

    // Envoyer le feedback comme si c'était un message de l'utilisateur
    var userMessageHtml = createUserMessageHtml(feedbackText);
    $("#chatbot-messages").append(userMessageHtml);
    autoScrollIfAtBottom();

    addToHistory(feedbackText, "user");
    saveMessage(feedbackText, "user");

    $("#chatbot-messages").append(createTypingIndicator());
    autoScrollIfAtBottom();

    $.ajax({
      type: "POST",
      url: botamiChatbot.ajax_url,
      data: {
        action: "botami_save_feedback",
        feedback: feedbackType,
        nonce: botamiChatbot.nonce,
      },
      success: function (response) {
        $("#typing-indicator").remove();

        // Generate appropriate response based on feedback type
        let botResponse = isLike
          ? botami_site_data.translations.feedback_response_positive
          : botami_site_data.translations.feedback_response_negative;

        // Add bot's response to the history
        addToHistory(botResponse, "assistant");

        // Display the bot's response
        var botMessageHtml = createBotMessageHtml(botResponse);
        $("#chatbot-messages").append(botMessageHtml);
        saveMessage(botResponse, "assistant");

        // Scroll to the latest message
        autoScrollIfAtBottom();
      },
      error: function () {
        $("#typing-indicator").remove();
        var errorMessage =
          botami_site_data.translations.error_message ||
          "Sorry, got a temporary delay.";
        var botMessageHtml = createBotMessageHtml(errorMessage);
        $("#chatbot-messages").append(botMessageHtml);
        autoScrollIfAtBottom();
      },
    });
  });

  // Événements de l'interface

  // Touche Entrée pour envoyer un message
  $("#chatbot-input").keydown(function (event) {
    if (event.keyCode === 13 && event.shiftKey) {
      return true; // Permettre les sauts de ligne avec Shift+Entrée
    } else if (event.keyCode === 13) {
      event.preventDefault();
      messageCount++;

      sendMessage();
      setTimeout(checkLeadFormDisplay, 3000);

    }
  });

// Bouton d'ouverture du chatbot
$("#chatbot-open-botami").click(function () {
  // Ajouter la classe d'animation d'ouverture style macOS
  $("#chatbot-widget-botami").removeClass("chatbot-mac-closing").addClass("chatbot-mac-opening");

  // Cacher le message de démarrage
  $("#champ_start_mesage").hide();

  // Garder le conteneur visible
  $("#chatbot-container-botami").css("display", "block");

  // Cacher le bouton d'ouverture
  $("#chatbot-open-botami").hide();

  // Afficher le message de bienvenue
  showWelcomeMessage();

  // Scroll automatique vers le bas après l'ouverture
  setTimeout(function () {
    const messagesContainer = $("#chatbot-messages")[0];
    if (messagesContainer) {
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
      userIsAtBottom = true;
    }
  }, 300);

  // Supprimer l'animation pulse du bouton
  $("#chatbot-open-botami").removeClass("chatbot-pulse");
  setTimeout(function () {
    // Vérification supplémentaire avant de démarrer
    if (currentQuestionnaireState.questionnaireData.length > 0 &&
        !questionnaireAlreadyStarted) {
      startQuestionnaire();
    }
  }, 1500);
});

// Bouton de fermeture du chatbot
$("#chatbot-close").click(function () {
  // Ajouter la classe d'animation de fermeture style macOS
  $("#chatbot-widget-botami").removeClass("chatbot-mac-opening").addClass("chatbot-mac-closing");

  // Only reset isActive state, but keep questionnaireAlreadyStarted
  // to prevent re-showing questionnaire in same session
  currentQuestionnaireState.isActive = false;

  // Attendre la fin de l'animation avant de cacher
  setTimeout(function() {
    // After animation finishes, hide the widget and remove the animation class
    $("#chatbot-container-botami").css("display", "none");
    $("#chatbot-open-botami").show();
    // Important: Only remove the class after the widget is hidden
    $("#chatbot-widget-botami").css("display", "none");
    $("#chatbot-widget-botami").removeClass("chatbot-mac-closing");
  }, 600);
});

// Ajouter à la section ready pour l'animation de pulse initiale
$(document).ready(function() {
  // S'assurer que le widget a les propriétés 3D correctes
  $("#chatbot-widget-botami").css({
    "backface-visibility": "hidden",
    "-webkit-backface-visibility": "hidden",
    "transform-style": "preserve-3d"
  });
  
  // Ajouter l'animation de pulse au bouton après un délai
  setTimeout(function() {
    $("#chatbot-open-botami").addClass("chatbot-pulse");
  }, 3000);

  // Keep track of completion status but don't prevent questionnaire from starting
  // Quick replies should show on every visit
  if (sessionStorage.getItem('questionnaire_completed_session') === 'true') {
    currentQuestionnaireState.hasCompletedQuestionnaire = true;
  }

  // Vérifier localStorage aussi
  if (localStorage.getItem('chatbot_questionnaire_completed') === 'true') {
    currentQuestionnaireState.hasCompletedQuestionnaire = true;
  }
});

  // Bouton d'envoi de message
  const originalSendButtonClick = $("#chatbot-send").click;
  $("#chatbot-send").off('click').on('click', function() {
    // Increment message count before sending
    messageCount++;
    
    // Call the original sendMessage function
    sendMessage();
    
    // Check if we should show the lead form after sending
    setTimeout(checkLeadFormDisplay, 3000);
  });

  // Bouton de rafraîchissement
  $("#refreshbtn").click(function () {
    var dots = `<span class="dot">.</span><span class="dot">.</span><span class="dot">.</span>`;
    $("#refreshbtn").html(dots);

    setTimeout(() => {
      $(this).css('display', 'none');
      loadMessages();
    }, 1600);
  });

  // Gestion du message de démarrage
  var btn_close_message_start = document.querySelector(
    "#champ_start_mesage_btn_close"
  );
  var champ_start_mesage = document.querySelector("#champ_start_mesage");

  if (champ_start_mesage) {
    // Fermeture du message de démarrage
    btn_close_message_start.addEventListener("click", () => {
      champ_start_mesage.style.display = "none";
    });

    // Affichage automatique du message de démarrage après 4 secondes
    setTimeout(() => {
      if (
        window.getComputedStyle(document.querySelector("#chatbot-widget-botami"))
          .display === "none"
      ) {
        champ_start_mesage.style.display = "block";
      } else {
        champ_start_mesage.style.display = "none";
      }
    }, 4000);
  }

  window.messageCount = 0;
  window.leadFormSubmitted = false;
  window.leadFormShown = false;

  // Function to create lead form HTML
  function createLeadForm() {
  // Get custom field labels from the localized data
  const namePlaceholder = botami_site_data.lead_gen_name_placeholder || 'Votre nom';
  const emailPlaceholder = botami_site_data.lead_gen_email_placeholder || 'Votre email';

  // Get custom field label and placeholder
  const customFieldPlaceholder = botami_site_data.lead_gen_field_placeholder || '';

  // Get the button text
  const buttonText = botami_site_data.lead_gen_button_text || 'Envoyer';

  // Check if custom field should be displayed
  const showCustomField = customFieldPlaceholder && customFieldPlaceholder.trim() !== '';

  return `
  <div style="display: flex; align-items: flex-start;" class="lead-form-container">
    <div style="display: grid;">
      <div class="chatbot-lead-form" style="margin-left: 0rem;">
        <div class="chatbot-lead-title">📝 Vos informations</div>
        <form id="lead-capture-form">
          <input type="text" name="lead_name" class="chatbot-lead-input" placeholder="${namePlaceholder}" required />
          <input type="email" name="lead_email" placeholder="${emailPlaceholder}" class="chatbot-lead-input" required />
          ${showCustomField ?
            `<input type="text" name="lead_custom_field" placeholder="${customFieldPlaceholder}" class="chatbot-lead-input" />`
            : ''}
          ${botami_site_data.consent_is_active ?
           `<div class="chatbot-lead-consent">
              <input type="checkbox" id="lead_consent" name="lead_consent" required>
              <span class="concentement">${botami_site_data.lead_gen_consentment || "J'accepte d'être contacté concernant ma demande."}</span>
            </div>`
          : ''}
          <button type="button" class="chatbot-lead-button btn_submit_lead">
            ${buttonText}
          </button>
        </form>
      </div>
    </div>
  </div>`;
}

// Ajoutez ces styles CSS améliorés à la section des styles
const enhancedLeadFormStyles = `
  .chatbot-lead-form {
    margin: 10px 0;
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    border: 2px solid ${botami_site_data.secondary_color || '#673de6'};
    animation: slideIn 0.3s ease forwards;
    max-width: 280px;
  }
  
  .chatbot-lead-title {
    font-weight: bold;
    margin-bottom: 15px;
    color: ${botami_site_data.primary_color || '#31377b'};
    font-size: 16px;
    text-align: center;
  }
  
  .chatbot-lead-input {
    width: 100%;
    padding: 10px 12px;
    margin: 8px 0 !important;
    border: 2px solid #e9ecef;
    border-radius: 8px !important;
    font-size: 14px !important;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif !important;
    transition: border-color 0.2s !important;
    box-sizing: border-box !important;
  }
  
  .chatbot-lead-input:focus {
    outline: none;
    border-color: ${botami_site_data.primary_color || '#31377b'};
    box-shadow: 0 0 0 3px rgba(103, 61, 230, 0.1);
  }
  
  .chatbot-lead-button {
    width: 100%;
    padding: 12px;
    margin-top: 15px;
    background: linear-gradient(90deg, ${botami_site_data.primary_color || '#31377b'} 0%, ${botami_site_data.secondary_color || '#673de6'} 100%);
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    font-weight: bold;
    transition: opacity 0.2s;
    text-transform: none !important;
  }
  
  .chatbot-lead-button:hover {
    opacity: 0.9;
  }
  
  .chatbot-lead-button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
  
  .chatbot-lead-consent {
    display: flex;
    align-items: flex-start;
    margin: 12px 0;
    font-size: 12px;
    color: #666;
    line-height: 1.4;
  }
  
  .chatbot-lead-consent input {
    margin-right: 8px;
    margin-top: 2px;
    flex-shrink: 0;
  }
  
  @keyframes slideIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  /* Styles pour les messages de validation et de chargement */
  .lead-validation-message {
    color: #e53935;
    font-size: 12px;
    margin-top: 5px;
    margin-bottom: 5px;
    padding: 8px;
    background-color: #ffebee;
    border-radius: 4px;
    border-left: 3px solid #e53935;
  }
  
  .lead-loading {
    font-size: 12px;
    margin-top: 5px;
    margin-bottom: 5px;
    color: #2196f3;
    padding: 8px;
    background-color: #e3f2fd;
    border-radius: 4px;
    border-left: 3px solid #2196f3;
    display: flex;
    align-items: center;
  }
  
  .lead-loading::before {
    content: '';
    width: 16px;
    height: 16px;
    border: 2px solid #2196f3;
    border-top: 2px solid transparent;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 8px;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  /* Responsive design pour mobile */
  @media (max-width: 768px) {
    .chatbot-lead-form {
      max-width: 100%;
      margin: 5px 0;
      padding: 15px;
    }
    
    .chatbot-lead-input {
      font-size: 16px; /* Évite le zoom sur iOS */
    }
  }
`;
  // Function to check if we should show the lead form
  function checkLeadFormDisplay() {
    // Skip if lead generation is disabled, already submitted, or already shown
    if (!botami_site_data.lead_gen_enabled || leadFormSubmitted || leadFormShown) {
      return;
    }
    
    // Check if logged-in user or current session has already submitted
    if (botami_site_data.lead_already_submitted) {
      leadFormSubmitted = true;
      return;
    }
    
    // If we're using a specific quick reply trigger, don't show based on message count
    if (botami_site_data.lead_gen_quick_reply) {
      return;
    }
    
    // Show form after user has sent 2 messages (default behavior)
    if (messageCount >= 2) {
      showLeadForm();
      leadFormShown = true;
    }
  }

  window.showLeadForm = function() {
    // Get the intro message
    const introMessage = botami_site_data.lead_gen_intro_message || "Nous serions ravis de vous aider ! Veuillez partager vos coordonnées.";

    // Function to check if bot is currently "talking"
    function isBotCurrentlyTalking() {
      const hasTypingIndicator = $('#typing-indicator').length > 0;
      const hasTypingAnimation = $('.typing-text').length > 0;
      return hasTypingIndicator || hasTypingAnimation;
    }

    // Wait for any ongoing bot activity to complete before showing lead form
    function waitAndShowLeadForm() {
      if (isBotCurrentlyTalking()) {
        // Bot is still talking, wait and check again
        const checkInterval = setInterval(function() {
          if (!isBotCurrentlyTalking()) {
            // Bot finished talking, clear interval and show lead form
            clearInterval(checkInterval);
            // Add a small delay before showing the lead form intro
            setTimeout(function() {
              displayLeadFormIntro();
            }, 1000);
          }
        }, 100); // Check every 100ms
      } else {
        // Bot not talking, show immediately
        displayLeadFormIntro();
      }
    }

    // Function to show the lead form intro and form
    function displayLeadFormIntro() {
      // Show typing indicator first
      $("#chatbot-messages").append(createTypingIndicator());
      autoScrollIfAtBottom();

      setTimeout(function() {
        $("#typing-indicator").remove();

        // Display intro message with typing animation
        const botMessageHtml = createBotMessageHtml(introMessage, true);
        const $message = $(botMessageHtml);
        $("#chatbot-messages").append($message);

        // Get the message ID and start typing animation
        const messageId = $message.find('.typing-text').attr('id');

        if (messageId) {
          // Start the typing animation with a callback to show the form after
          animateTyping(messageId, introMessage, 30, function() {
            // Typing animation completed, now show the form after a brief delay
            setTimeout(function() {
              const formHtml = createLeadForm();
              $("#chatbot-messages").append(formHtml);
              autoScrollIfAtBottom();

              // Save the intro message
              saveMessage(introMessage, "assistant");

              $(".btn_submit_lead").on("click", function() {
                submitLeadForm();
              });
            }, 500);
          });
        } else {
          // Fallback if animation doesn't work
          setTimeout(function() {
            const formHtml = createLeadForm();
            $("#chatbot-messages").append(formHtml);
            autoScrollIfAtBottom();

            saveMessage(introMessage, "assistant");

            $(".btn_submit_lead").on("click", function() {
              submitLeadForm();
            });
          }, 2000);
        }

        autoScrollIfAtBottom();
      }, 2000);
    }

    // Start the waiting and checking process
    waitAndShowLeadForm();
  }

  // Submit the lead form
  function submitLeadForm() {
  const form = $("#lead-capture-form");
  const name = form.find("input[name='lead_name']").val();
  const email = form.find("input[name='lead_email']").val();
  const customField = form.find("input[name='lead_custom_field']").val();
  const consent = form.find("input[name='lead_consent']").is(":checked");
  
  // Validate form
  if (!name || !email) {
    showValidationMessage(form, 'Veuillez remplir tous les champs obligatoires.');
    return;
  }
  
  if (botami_site_data.consent_is_active && !consent) {
    showValidationMessage(form, 'Veuillez accepter le consentement pour continuer.');
    return;
  }
  
  // Validate email format
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    showValidationMessage(form, 'Veuillez entrer une adresse email valide.');
    return;
  }
  
  // Remove any validation messages
  $(".lead-validation-message").remove();
  
  // Show loading indicator with animation
  showLoadingMessage(form, 'Envoi en cours...');
  
  // Disable the button
  const submitBtn = form.find('.btn_submit_lead');
  submitBtn.prop('disabled', true);
  
  // Submit via AJAX
  $.ajax({
    type: "POST",
    url: botamiChatbot.ajax_url,
    data: {
      action: "botami_save_chatbot_lead",
      name: name,
      email: email,
      custom_field_label: botami_site_data.lead_gen_field_placeholder || '',
      custom_field_value: customField || '',
      nonce: botamiChatbot.nonce
    },
    success: function(response) {
      $(".lead-loading").remove();
      
      if (response.success) {
        // Mark as submitted
        leadFormSubmitted = true;
        
        // Replace form with thank you message with animation
        $(".lead-form-container").fadeOut(300, function() {
          $(this).replaceWith(createBotMessageHtml(
            botami_site_data.lead_gen_thank_you || "Merci ! Vos informations ont été enregistrées."
          ));
          
          // Scroll to the bottom
          autoScrollIfAtBottom();
        });
      } else {
        showValidationMessage(form, 'Une erreur s\'est produite lors de l\'envoi. Veuillez réessayer.');
        submitBtn.prop('disabled', false);
      }
    },
    error: function() {
      $(".lead-loading").remove();
      showValidationMessage(form, 'Une erreur s\'est produite lors de l\'envoi. Veuillez réessayer.');
      submitBtn.prop('disabled', false);
    }
  });
}


// Fonction pour afficher les messages de validation avec style
function showValidationMessage(form, message) {
  // Remove existing validation messages
  $(".lead-validation-message").remove();
  
  // Add new validation message with animation
  const validationHtml = `<div class="lead-validation-message" style="opacity: 0;">${message}</div>`;
  form.append(validationHtml);
  
  // Animate the message appearance
  $(".lead-validation-message").animate({ opacity: 1 }, 300);
  
  // Auto-hide after 5 seconds
  setTimeout(() => {
    $(".lead-validation-message").fadeOut(300, function() {
      $(this).remove();
    });
  }, 5000);
}

// Fonction pour afficher le message de chargement avec animation
function showLoadingMessage(form, message) {
  // Remove existing messages
  $(".lead-loading, .lead-validation-message").remove();
  
  // Add loading message
  const loadingHtml = `<div class="lead-loading" style="opacity: 0;">${message}</div>`;
  form.append(loadingHtml);
  
  // Animate the message appearance
  $(".lead-loading").animate({ opacity: 1 }, 300);
}

  // Check for previous lead submissions
  function checkPreviousLeadSubmission() {
    if (!botami_site_data.lead_gen_enabled) {
      return;
    }
    
    $.ajax({
      type: "POST",
      url: botamiChatbot.ajax_url,
      data: {
        action: "botami_check_lead_submission",
        nonce: botamiChatbot.nonce
      },
      success: function(response) {
        if (response.success && response.data.has_submitted) {
          leadFormSubmitted = true;
        }
      }
    });
  }


  // Store the original AJAX function
  const originalAjaxFn = $.ajax;

  // Override AJAX to check for lead form after bot responses
  $.ajax = function(options) {
    if (options && options.data && typeof options.data === 'object' && options.data.action === "botami_chatbot_send_message") {
      const originalSuccess = options.success;
      options.success = function(response) {
        if (originalSuccess) {
          originalSuccess.apply(this, arguments);
        }
        
        // After receiving the response, check if we should show the lead form
        setTimeout(checkLeadFormDisplay, 2000);
      };
    }
    return originalAjaxFn.apply(this, arguments);
  };

  // Initialize by checking for previous submissions
  checkPreviousLeadSubmission();

  // Add styles for lead form
  const leadFormStyles = `
    .input-width-227 {
      width: 227px;
      padding: 8px;
      margin-bottom: 8px;
      border: 1px solid #e0e0e0;
      border-radius: 5px;
      font-size: 14px;
    }
    
    .btn_submit_lead {
      transition: all 0.2s ease;
      cursor: pointer;
    }
    
    .btn_submit_lead:hover {
      opacity: 0.9;
      transform: translateY(-1px);
    }
    
    .btn_submit_lead:active {
      transform: translateY(0);
    }
    
    .lead-validation-message {
      color: #e53935;
      font-size: 12px;
      margin-top: 5px;
      margin-bottom: 5px;
    }
    
    .lead-loading {
      font-size: 12px;
      margin-top: 5px;
      margin-bottom: 5px;
      color: #2196f3;
    }
  `;

  // Add styles to head
$("head").append(`<style>${enhancedLeadFormStyles}</style>`);


  // Track the current questionnaire state
  let currentQuestionnaireState = {
    currentQuestionId: null,
    isActive: false,
    answers: [],
    questionnaireData: [],
    hasCompletedQuestionnaire: false,
    currentPath: [] // Track the path taken through the questionnaire
  };

  /**
   * Check if user has already completed the questionnaire
   * @returns {boolean} True if questionnaire was completed before
   */
function hasUserCompletedQuestionnaire() {
  // Vérifier localStorage
  const completionKey = 'chatbot_questionnaire_completed';
  const completed = localStorage.getItem(completionKey);
  
  // Vérifier l'état de session
  const sessionCompleted = sessionStorage.getItem('questionnaire_completed_session');
  
  // Vérifier l'état interne
  return completed === 'true' || 
         sessionCompleted === 'true' || 
         currentQuestionnaireState.hasCompletedQuestionnaire;
}

  /**
   * Mark questionnaire as completed
   */
function markQuestionnaireAsCompleted() {
  const completionKey = 'chatbot_questionnaire_completed';
  localStorage.setItem(completionKey, 'true');
  sessionStorage.setItem('questionnaire_completed_session', 'true');
  currentQuestionnaireState.hasCompletedQuestionnaire = true;
  
  // Marquer aussi dans une variable globale pour cette session
  window.questionnaireCompleted = true;
}

  /**
   * Initialize the questionnaire system
   */
  function initializeQuestionnaire() {
    // Parse questionnaire data from botami_site_data
    if (typeof botami_site_data !== "undefined" && botami_site_data.quick_replies) {
      try {
        currentQuestionnaireState.questionnaireData = JSON.parse(botami_site_data.quick_replies);
      } catch (e) {
        console.error('Failed to parse questionnaire data:', e);
        currentQuestionnaireState.questionnaireData = [];
      }
    }
  }

  /**
   * Find the first question (question with no previousQuestion)
   * @returns {Object|null} First question object or null
   */
  function findFirstQuestion() {
    return currentQuestionnaireState.questionnaireData.find(q => 
      !q.previousQuestion || q.previousQuestion === ""
    ) || null;
  }

  /**
   * Find the next question based on the current question ID and selected option
   * @param {string} currentQuestionId - ID of the current question
   * @param {number} selectedOptionIndex - Index of the selected option
   * @returns {Object|null} Next question object or null
   */
  function findNextQuestion(currentQuestionId, selectedOptionIndex = null) {
    
    // Find questions that have this question as their previous question
    const candidateQuestions = currentQuestionnaireState.questionnaireData.filter(q => 
      q.previousQuestion === currentQuestionId
    );
    
    
    if (candidateQuestions.length === 0) {
      return null; // No next question
    }
    
    // If we have a selected option index, look for a question that matches it
    if (selectedOptionIndex !== null) {
      const specificQuestion = candidateQuestions.find(q => 
        q.previousOption === selectedOptionIndex.toString()
      );
      
      if (specificQuestion) {
        return specificQuestion;
      }
    }
    
    // Fallback: return the first question that doesn't specify a previous option
    const fallbackQuestion = candidateQuestions.find(q => 
      !q.previousOption || q.previousOption === ''
    );
    
    if (fallbackQuestion) {
      return fallbackQuestion;
    }
    
    return null;
  }

  /**
   * Check if a question is the last in the sequence for a given path
   * @param {string} questionId - ID of the question to check
   * @param {number} selectedOptionIndex - Index of the selected option
   * @returns {boolean} True if this is the last question for this path
   */
  function isLastQuestion(questionId, selectedOptionIndex = null) {
    const nextQuestion = findNextQuestion(questionId, selectedOptionIndex);
    const isLast = nextQuestion === null;
    return isLast;
  }

  /**
   * Display a question as a bot message with its options as quick reply buttons
   * @param {Object} questionData - Question object with text and options
   */
  function displayQuestion(questionData) {
    if (!questionData || !questionData.text) {
      return;
    }


    // Create bot message with the question WITH ANIMATION
    const questionMessageHtml = createBotMessageHtml(questionData.text, true);
    const $message = $(questionMessageHtml);
    $("#chatbot-messages").append($message);

    // Extract message ID and start animation
    const messageId = $message.find('.typing-text').attr('id');
    if (messageId) {
      animateTyping(messageId, questionData.text);

      // Calculate animation duration based on text length
      const animationDuration = questionData.text.length * 30; // 30ms per character

      // Display the options AFTER typing animation is complete
      if (questionData.options && questionData.options.length > 0) {
        setTimeout(() => {
          displayQuestionOptions(questionData);
        }, animationDuration + 200); // Add small delay after text is complete
      }
    } else {
      // Fallback if no animation
      if (questionData.options && questionData.options.length > 0) {
        displayQuestionOptions(questionData);
      }
    }

    // Scroll to show the question
    autoScrollIfAtBottom();
  }

  /**
   * Display question options as quick reply buttons
   * @param {Object} questionData - Question object with options
   */
  function displayQuestionOptions(questionData) {
    // Filter out empty options
    const validOptions = questionData.options.filter(option => option && option.trim() !== "");
    
    if (validOptions.length === 0) {
      return;
    }


    // Create quick replies container
    const quickRepliesHtml = `
      <div id="question-options-container" class="question-options-wrapper" data-question-id="${questionData.id}">
        ${validOptions.map((option, index) => `
          <button class="question-option-btn" data-option-index="${index}" data-option-text="${option.replace(/"/g, "&quot;")}">
            ${option}
          </button>
        `).join("")}
      </div>
    `;

    // Append the options after the messages
    $("#chatbot-messages").append(quickRepliesHtml);
    
    // Scroll to show the options
    autoScrollIfAtBottom();

    // Add click event handlers
    $(".question-option-btn").on("click", function () {
      const optionText = $(this).data("option-text");
      const optionIndex = $(this).data("option-index");
      const questionId = $(this).closest(".question-options-wrapper").data("question-id");
      const questionText = questionData.text;
      handleOptionSelection(questionId, optionText, optionIndex, questionText);
    });
  }

  /**
   * Handle when a user selects an option
   * @param {string} questionId - ID of the question that was answered
   * @param {string} optionText - Text of the selected option
   * @param {number} optionIndex - Index of the selected option
   * @param {string} questionText - Text of the question that was answered
   */
  function handleOptionSelection(questionId, optionText, optionIndex, questionText) {

    // Hide the current options
    hideQuestionOptions();

    // Record the answer with full context
    const answerRecord = {
      questionId: questionId,
      answer: optionText,
      answerIndex: optionIndex,
      timestamp: new Date().toISOString()
    };

    currentQuestionnaireState.answers.push(answerRecord);
    currentQuestionnaireState.currentPath.push({
      questionId: questionId,
      selectedOption: optionIndex
    });

    // Display user's selection as a message
    const userMessageHtml = createUserMessageHtml(optionText);
    $("#chatbot-messages").append(userMessageHtml);
    autoScrollIfAtBottom();

    // IMPORTANT: Save messages in the correct order using promises
    // First save the question (bot message), then save user's answer
    saveMessage(questionText, "assistant").then(function() {
      // Wait for question to be saved, then save user's answer
      saveMessage(optionText, "user");
    });

    // Check if this is the last question for this path
    if (isLastQuestion(questionId, optionIndex)) {
      // End of questionnaire - check if we should show lead form
      handleQuestionnaireEnd();
    } else {
      // Find and display the next question based on the selected option
      const nextQuestion = findNextQuestion(questionId, optionIndex);
      if (nextQuestion) {
        // Small delay before showing next question
        setTimeout(() => {
          displayQuestion(nextQuestion);
          currentQuestionnaireState.currentQuestionId = nextQuestion.id;
        }, 500);
      } else {
        // No next question found, end questionnaire
        handleQuestionnaireEnd();
      }
    }
  }

  /**
   * Handle the end of the questionnaire
   */
  function handleQuestionnaireEnd() {
    currentQuestionnaireState.isActive = false;

    // Mark questionnaire as completed
    markQuestionnaireAsCompleted();

    generatePersonalizedResponse();
  }

  /**
   * Generate a personalized response based on questionnaire answers
   */
  function generatePersonalizedResponse() {
      
      // Show typing indicator
      $("#chatbot-messages").append(createTypingIndicator());
      autoScrollIfAtBottom();
      
      // Prepare the questionnaire summary for the AI
      const questionnaireSummary = prepareQuestionnaireSummary();
      
      // Add the questionnaire summary to conversation history
      addToHistory(questionnaireSummary, "user");
      
      // Send to AI for personalized response
      $.ajax({
          type: "POST",
          url: botamiChatbot.ajax_url,
          data: {
              nonce: botamiChatbot.nonce,
              action: "botami_chatbot_send_message",
              message: questionnaireSummary,
              history: conversationHistory,
              is_questionnaire_summary: true // Flag to indicate this is questionnaire data
          },
          success: function (response) {
              // Remove typing indicator
              $("#typing-indicator").remove();

              if (response.success) {
                  const botResponse = response.data;
                  let personalizedMessage = '';
                  
                  // Handle response format
                  if (typeof botResponse === "object" && botResponse.hasOwnProperty("response")) {
                      personalizedMessage = botResponse.response;
                  } else {
                      personalizedMessage = botResponse;
                  }
                  
                  // Add personalized response to history
                  addToHistory(personalizedMessage, "assistant");

                  // Display the personalized response with animation
                  var botMessageHtml = createBotMessageHtml(personalizedMessage, true);
                  const $message = $(botMessageHtml);
                  $("#chatbot-messages").append($message);

                  // Extract message ID and start animation
                  const messageId = $message.find('.typing-text').attr('id');
                  if (messageId) {
                    animateTyping(messageId, personalizedMessage);
                  }

                  saveMessage(personalizedMessage, "assistant");

                  // Scroll to show the response
                  autoScrollIfAtBottom();
                  
                  // After showing personalized response, check if we should show lead form
                  setTimeout(() => {
                      checkAndShowLeadForm();
                  }, 2000); // Give user time to read the personalized response
                  
              } else {
                  // Fallback if AI response fails
                  showFallbackResponse();
              }
          },
          error: function (xhr, status, error) {
              $("#typing-indicator").remove();
              showFallbackResponse();
          }
      });
  }

  /**
   * Prepare a summary of questionnaire answers for the AI
   * @returns {string} Formatted summary of user's questionnaire responses
   */
  function prepareQuestionnaireSummary() {
      const answers = currentQuestionnaireState.answers;
      const questionnaireData = currentQuestionnaireState.questionnaireData;
      
      // Create a map of question IDs to question text for easy lookup
      const questionMap = new Map();
      questionnaireData.forEach(q => {
          questionMap.set(q.id, q.text);
      });
      
      // Build the summary
      let summary = "Based on my questionnaire responses:\n\n";
      
      answers.forEach((answer, index) => {
          const questionText = questionMap.get(answer.questionId) || `Question ${index + 1}`;
          summary += `${questionText}\nMy answer: ${answer.answer}\n\n`;
      });
      
      summary += "Please provide me with personalized recommendations and information based on these responses.";
      
      return summary;
  }

  /**
   * Check if we should show the lead form after the personalized response
   */
  function checkAndShowLeadForm() {
      const leadFormQuestionId = botami_site_data.lead_gen_quick_reply || '';
      const shouldShowLeadForm = leadFormQuestionId && 
                                leadFormQuestionId === currentQuestionnaireState.currentQuestionId &&
                                botami_site_data.lead_gen_enabled &&
                                !window.leadFormSubmitted &&
                                !window.leadFormShown;

      if (shouldShowLeadForm) {
          // Show lead form after personalized response
          setTimeout(() => {
              
              // Show typing indicator briefly
              $("#chatbot-messages").append(createTypingIndicator());
              autoScrollIfAtBottom();
              
              setTimeout(() => {
                  $("#typing-indicator").remove();
                  
                  // Then show the lead form
                  setTimeout(() => {
                      window.showLeadForm();
                      window.leadFormShown = true;
                  }, 1500);
              }, 1000);
          }, 1000);
      }
  }

  /**
   * Show fallback response if AI personalization fails
   */
  function showFallbackResponse() {
      const fallbackMessage = botami_site_data.translations?.questionnaire_fallback;
      
      const botMessageHtml = createBotMessageHtml(fallbackMessage);
      $("#chatbot-messages").append(botMessageHtml);
      saveMessage(fallbackMessage, "assistant");
      autoScrollIfAtBottom();
      
      // Still check for lead form after fallback
      setTimeout(() => {
          checkAndShowLeadForm();
      }, 2000);
  }

  /**
   * Hide question options
   */
  function hideQuestionOptions() {
    $("#question-options-container").remove();
  }

  /**
   * Start the questionnaire when the chatbot is opened
   */
  function startQuestionnaire() {
  if (questionnaireAlreadyStarted) {
    return;
  }

  if (currentQuestionnaireState.isActive) {
    return;
  }

  if (currentQuestionnaireState.questionnaireData.length === 0) {
    return;
  }

  const firstQuestion = findFirstQuestion();
  if (firstQuestion) {
    // Marquer comme démarré
    questionnaireAlreadyStarted = true;
    currentQuestionnaireState.isActive = true;
    currentQuestionnaireState.currentQuestionId = firstQuestion.id;

    // Reset des données
    currentQuestionnaireState.currentPath = [];
    currentQuestionnaireState.answers = [];


    // Délai avant d'afficher la première question
    setTimeout(() => {
      displayQuestion(firstQuestion);
    }, 1000);
  }
}

  /**
   * Check if questionnaire is currently active
   * @returns {boolean} True if questionnaire is active
   */
  function isQuestionnaireActive() {
    return currentQuestionnaireState.isActive;
  }

  /**
   * Override the normal message sending when questionnaire is active
   */
  function interceptMessageSending() {
    // Store the original send function
    const originalSendMessage = window.sendMessage;
    
    // Override sendMessage to check questionnaire state
    window.sendMessage = function() {
      if (isQuestionnaireActive()) {
        // User chose to chat directly instead of using questionnaire
        // Exit questionnaire mode and proceed with normal chat
        exitQuestionnaire();
        hideQuestionOptions();
      }
      
      // Proceed with normal sending (either questionnaire was not active, or we just exited it)
      if (originalSendMessage) {
        originalSendMessage.apply(this, arguments);
      }
    };
  }

  /**
   * Exit questionnaire mode and return to normal chat
   */
  function exitQuestionnaire() {
    currentQuestionnaireState.isActive = false;
    currentQuestionnaireState.currentQuestionId = null;
    
    // Remove any visual indicators
    $("#chatbot-container-botami").removeClass("questionnaire-active");
  }

  // Initialize questionnaire system
  initializeQuestionnaire();

  // Start questionnaire when chat is opened
  $("#chatbot-open-botami").on("click", function () {
    // Wait for chat to be fully opened and welcome message to be shown
    setTimeout(function () {
      if (currentQuestionnaireState.questionnaireData.length > 0) {
        startQuestionnaire();
      }
    }, 1500); // Delay to allow welcome message to be displayed first
  });

  // Hide question options when user starts typing (if any are visible)
  $("#chatbot-input").on("focus", function () {
    hideQuestionOptions();
  });


  // Initialize message sending interception
  interceptMessageSending();

  // Add CSS for question options (enhanced version)
  const questionOptionsStyles = `
    <style>
      .question-options-wrapper {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin: -12px 0 15px;
        padding: 5px 0;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: thin;
        justify-content: flex-start;
        animation: fadeInUp 0.4s ease-out;
      }
      
      
      
      .question-option-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(103, 61, 230, 0.1), transparent);
        transition: left 0.5s;
      }
      
      .question-option-btn:hover {
        background: linear-gradient(135deg, rgba(103, 61, 230, 0.05) 0%, rgba(103, 61, 230, 0.1) 100%);
        border-color: rgba(103, 61, 230, 0.4);
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(103, 61, 230, 0.2);
      }
      
      .question-option-btn:hover::before {
        left: 100%;
      }
      
      .question-option-btn:active {
        transform: translateY(0);
        box-shadow: 0 2px 4px rgba(103, 61, 230, 0.2);
      }
      
      .question-option-btn:focus {
        outline: none;
        border-color: rgba(103, 61, 230, 0.6);
        box-shadow: 0 0 0 3px rgba(103, 61, 230, 0.1);
      }
      
      @keyframes fadeInUp {
        from {
          opacity: 0;
          transform: translateY(15px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }
      
      @keyframes pulse {
        0%, 100% {
          box-shadow: 0 3px 6px rgba(103, 61, 230, 0.1);
        }
        50% {
          box-shadow: 0 6px 12px rgba(103, 61, 230, 0.2);
        }
      }
      
      .question-option-btn:nth-child(odd) {
        animation-delay: 0.1s;
      }
      
      .question-option-btn:nth-child(even) {
        animation-delay: 0.2s;
      }
      
      @media (max-width: 768px) {
        .question-options-wrapper {
          padding: 5px 10px;
          margin-bottom: 15px;
          gap: 6px;
        }
        
        .question-option-btn {
          font-size: 12px !important;
          padding: 8px 14px;
          border-radius: 1.5rem;
          white-space: normal;
          max-width: calc(50% - 3px);
          word-break: break-word;
        }
      }
      
      /* Style input when questionnaire is active but still allow interaction */

      
      .questionnaire-active #chatbot-send {
        background: linear-gradient(90deg, rgba(103, 61, 230, 0.8) 0%, rgba(103, 61, 230, 0.6) 100%);
      }
      

      

    </style>
  `;

  // Append styles to head
  $("head").append(questionOptionsStyles);

  // Add/remove questionnaire-active class based on state
  function updateQuestionnaireUI() {
    if (isQuestionnaireActive()) {
      $("#chatbot-container-botami").addClass("questionnaire-active");
    } else {
      $("#chatbot-container-botami").removeClass("questionnaire-active");
    }
  }

  // Monitor questionnaire state changes
  setInterval(updateQuestionnaireUI, 300);

});