/**
 * Safely queries a single DOM element
 * @param {string} selector - CSS selector string
 * @returns {Element|null} - DOM element or null if not found
 */
function safeQuerySelector(selector) {
  const element = document.querySelector(selector);
  return element || null;
}

/**
 * Safely adds an event listener to an element
 * @param {Element} element - DOM element to attach listener to
 * @param {string} event - Event name (e.g., 'click', 'submit')
 * @param {Function} handler - Event handler function
 */
function safeAddEventListener(element, event, handler) {
  if (element) {
    element.addEventListener(event, handler);
  }
}

/**
 * Show animated knowledge base building screen
 * @param {Object} options - Animation options
 * @param {boolean} options.hasContent - Whether content was loaded into knowledge base
 */
function showKnowledgeBaseAnimation(options = {}) {
  const strings = window.botamiLocalizedStringsAdmin.animation_strings || {};
  const animationSteps = [
    { emoji: '🤖', text: strings.init || 'Initializing your intelligent assistant...' },
    { emoji: '📚', text: strings.building || 'Building the knowledge base...' },
    { emoji: '🧠', text: strings.learning || 'Learning your data...' },
    { emoji: '⚡', text: strings.optimizing || 'Optimizing performance...' },
    { emoji: '🎨', text: strings.customizing || 'Customizing the interface...' },
    { emoji: '✨', text: strings.finalizing || 'Finalizing the configuration...' },
    { emoji: '🚀', text: strings.ready || 'Your chatbot is ready!' }
  ];

  // Store animation start time to ensure minimum duration
  const animationStartTime = Date.now();
  const minAnimationDuration = 3000; // 3 seconds minimum

  // Create overlay
  const overlay = document.createElement('div');
  overlay.id = 'botami-knowledge-animation';
  overlay.innerHTML = `
    <div class="botami-animation-container">
      <div class="botami-animation-content">
        <div class="botami-emoji-wrapper">
          <div class="botami-emoji" id="botami-emoji">🤖</div>
          <div class="botami-emoji-glow"></div>
        </div>
        <div class="botami-text-wrapper">
          <h2 class="botami-animation-title">${strings.title || 'Configuration in progress'}</h2>
          <p class="botami-animation-text" id="botami-animation-text">${strings.init || 'Initializing your intelligent assistant...'}</p>
        </div>
        <div class="botami-progress-bar">
          <div class="botami-progress-fill" id="botami-progress-fill"></div>
        </div>
        <div class="botami-floating-emojis" id="botami-floating-emojis"></div>
      </div>
    </div>
  `;

  document.body.appendChild(overlay);

  // Animate the emojis floating in background
  const floatingContainer = document.getElementById('botami-floating-emojis');
  const bgEmojis = ['💡', '📖', '🎯', '⭐', '🔮', '💫', '🌟', '✨'];

  for (let i = 0; i < 15; i++) {
    const emoji = document.createElement('div');
    emoji.className = 'botami-floating-emoji';
    emoji.textContent = bgEmojis[Math.floor(Math.random() * bgEmojis.length)];
    emoji.style.left = Math.random() * 100 + '%';
    emoji.style.animationDelay = Math.random() * 3 + 's';
    emoji.style.animationDuration = (Math.random() * 3 + 4) + 's';
    floatingContainer.appendChild(emoji);
  }

  // Animate through steps
  let currentStep = 0;
  const emojiEl = document.getElementById('botami-emoji');
  const textEl = document.getElementById('botami-animation-text');
  const progressEl = document.getElementById('botami-progress-fill');

  const animateStep = () => {
    if (currentStep < animationSteps.length) {
      const step = animationSteps[currentStep];

      // Animate emoji change
      emojiEl.style.transform = 'scale(0) rotate(-180deg)';

      setTimeout(() => {
        emojiEl.textContent = step.emoji;
        emojiEl.style.transform = 'scale(1) rotate(0deg)';
        textEl.textContent = step.text;

        // Update progress bar
        const progress = ((currentStep + 1) / animationSteps.length) * 100;
        progressEl.style.width = progress + '%';
      }, 300);

      currentStep++;

      if (currentStep < animationSteps.length) {
        setTimeout(animateStep, 1500);
      } else {
        // Final step - ensure minimum animation duration, then complete
        const finishAnimation = async () => {
          // Calculate remaining time to meet minimum duration
          const elapsedTime = Date.now() - animationStartTime;
          const remainingTime = Math.max(0, minAnimationDuration - elapsedTime);

          // Wait for remaining time if needed
          await new Promise(resolve => setTimeout(resolve, remainingTime));

          // Show message if no content was loaded
          if (options.hasContent === false) {
            textEl.textContent = strings.no_content || 'Setup complete! You can now add content to your knowledge base.';
            await new Promise(resolve => setTimeout(resolve, 2000));
          }

          overlay.style.opacity = '0';

          // Mark setup as complete in WordPress options
          try {
            await fetch(window.botamiLocalizedStringsAdmin.ajax_url, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
              },
              body: new URLSearchParams({
                action: 'botami_mark_setup_complete',
                nonce: window.botamiLocalizedStringsAdmin.nonce,
              }),
            });
          } catch (error) {
            console.error('Error marking setup as complete:', error);
          }

          setTimeout(() => {
            window.location.reload();
          }, 500);
        };

        setTimeout(finishAnimation, 1500);
      }
    }
  };

  // Start animation after a brief delay
  setTimeout(() => {
    overlay.classList.add('active');
    setTimeout(animateStep, 500);
  }, 100);
}

/**
 * Main initialization function for the admin panel
 * Coordinates all component initializations and provides global configuration
 */
function initializeAdminPanel() {
  /**
   * Configuration object containing user plan and feature flags
   * @type {Object}
   * @property {boolean} hasApi - Whether user has configured API
   * @property {boolean} isPro - Whether user has pro plan or higher
   * @property {boolean} isPremium - Whether user has premium plan
   * @property {number} charLimit - Character limit based on plan
   */
  const config = {
    hasApi: window.botamiLocalizedStringsAdmin?.has_api || false,
    isPro: window.botamiLocalizedStringsAdmin?.is_pro_or_higher || false,
    isPremium: window.botamiLocalizedStringsAdmin?.is_premium || false,
    charLimit: window.botamiLocalizedStringsAdmin?.char_limit || 10000,
  };

  /**
   * Initializes tab functionality and handles tab switching
   * Disables tabs if API is not configured
   */
  function initializeTabs() {
    const tabs = document.querySelectorAll(".tab-link");
    const tabContents = document.querySelectorAll(".tab-content");
    const apiValidationMessage = safeQuerySelector("#api-validation-message");

    if (!tabs.length || !tabContents.length) {
      console.warn("Tab elements not found");
      return;
    }

    // Disable tabs if no API
    if (!config.hasApi) {
      tabs.forEach((tab) => {
        if (tab.getAttribute("data-tab") !== "dashboard") {
          tab.classList.add("btm-opacity-50", "btm-cursor-not-allowed");
          tab.disabled = true;
        }
      });
    }

    // Tab switching function
    function showTab(tabId) {
      tabs.forEach((tab) => {
        const isActive = tab.getAttribute("data-tab") === tabId;
        tab.classList.toggle("btm-active", isActive);
        tab.classList.toggle("btm-text-active-link", isActive);
      });

      tabContents.forEach((content) => {
        if (content.id === tabId) {
          content.classList.remove("btm-hidden");
          setTimeout(
            () => content.classList.replace("btm-opacity-0", "btm-opacity-100"),
            10
          );
        } else {
          content.classList.add("btm-hidden", "btm-opacity-0");
          content.classList.remove("btm-opacity-100");
        }
      });

      const currentTabInput = document.getElementById("current_tab");
      if (currentTabInput) {
        currentTabInput.value = tabId;
      }
      // Mettre à jour l'URL sans recharger la page
      const newUrl = new URL(window.location.href);
      newUrl.searchParams.set("tab", tabId);
      window.history.pushState({}, "", newUrl);
    }

    // Add tab click handlers
    tabs.forEach((tab) => {
      safeAddEventListener(tab, "click", function () {
        if (!this.disabled && !this.classList.contains("disabled")) {
          showTab(this.getAttribute("data-tab"));
        }
      });
    });

    // Vérifier si un onglet est spécifié dans l'URL
    const urlParams = new URLSearchParams(window.location.search);
    const tabParam = urlParams.get("tab");

    // Déterminer quel onglet afficher initialement
    let initialTab = "dashboard"; // Onglet par défaut

    if (tabParam) {
      // Vérifier si l'onglet demandé existe
      const tabExists = Array.from(tabContents).some(
        (content) => content.id === tabParam
      );

      if (tabExists) {
        // Vérifier si l'onglet est désactivé en raison de l'absence d'API
        const tabElement = Array.from(tabs).find(
          (tab) => tab.getAttribute("data-tab") === tabParam
        );

        if (config.hasApi || !tabElement.disabled) {
          initialTab = tabParam;
        }
      }
    }

    // Initialiser avec l'onglet approprié
    showTab(initialTab);
    const currentTabInput = document.getElementById("current_tab");
    if (currentTabInput) {
      currentTabInput.value = initialTab;
    }
  }

  /**
   * Initializes API key verification functionality
   * Handles API key validation and displays feedback messages
   */
  function initializeApiVerification() {
    const verifyButton = safeQuerySelector("#verify-api-key");
    const apiKeyInput = safeQuerySelector('input[name="botami_api_key"]');
    const apiValidationMessage = safeQuerySelector("#api-validation-message");
  
    if (!verifyButton || !apiKeyInput || !apiValidationMessage) {
      return;
    }
  
    safeAddEventListener(verifyButton, "click", async function () {
      const apiKey = apiKeyInput.value.trim();
      if (!apiKey) {
        showMessage("Please enter an API key", "error");
        return;
      }
  
      // Store original button content
      const originalButtonContent = verifyButton.innerHTML;
      
      // Set loading state
      setLoadingState(true);
  
      try {
        const response = await fetch(window.botamiLocalizedStringsAdmin.ajax_url, {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: new URLSearchParams({
            action: "botami_verify_chatbot_api",
            nonce: window.botamiLocalizedStringsAdmin.nonce,
            api_key: apiKey,
          }),
        });
  
        const data = await response.json();
        showMessage(
          data.success
            ? "API key verified successfully!"
            : data.data?.message || "Verification failed",
          data.success ? "success" : "error"
        );
        if (data.success) {
          // Check if this is the first time setting up the API key (from server response)
          const isFirstSetup = data.data?.is_first_setup || false;

          if (isFirstSetup) {
            // Show loading animation before reload
            // has_content indicates whether knowledge base content was automatically loaded
            showKnowledgeBaseAnimation({
              hasContent: data.data?.has_content
            });
          } else {
            window.location.reload();
          }
        }
      } catch (error) {
        console.error("API verification error:", error);
        showMessage("An error occurred during verification", "error");
      } finally {
        // Reset loading state
        setLoadingState(false);
      }
  
      function setLoadingState(isLoading) {
        if (isLoading) {
          // Disable button and show loading spinner
          verifyButton.disabled = true;
          verifyButton.innerHTML = `
            <svg class="btm-animate-spin btm--ml-1 btm-mr-2 btm-h-4 btm-w-4 btm-text-white  btm-inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="btm-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="btm-opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>

          `;
          verifyButton.classList.add('btm-opacity-75', 'btm-cursor-not-allowed');
        } else {
          // Re-enable button and restore original content
          verifyButton.disabled = false;
          verifyButton.innerHTML = originalButtonContent;
          verifyButton.classList.remove('btm-opacity-75', 'btm-cursor-not-allowed');
        }
      }
    });
  
    function showMessage(message, type) {
      apiValidationMessage.textContent = message;
      apiValidationMessage.className = `btm-mb-4 btm-p-4 btm-rounded ${
        type === "success"
          ? "btm-bg-green-100 btm-text-green-700"
          : "btm-bg-red-100 btm-text-red-700"
      }`;
      apiValidationMessage.classList.remove("btm-hidden");
    }
  }

  /**
   * Initializes character counter for text inputs
   * Updates counter in real-time and handles max length restrictions
   */
  function initializeCharCounter() {
    const textarea = safeQuerySelector("#message");
    const charLimitFeedback = safeQuerySelector("#char-limit-feedback");

    if (!textarea || !charLimitFeedback) {
      return;
    }

    // Ensure charLimit is a valid number
    const charLimit = Number(config.charLimit) || 10000;
    textarea.setAttribute("maxlength", charLimit);

    function updateCharCount() {
      // Safety check: ensure textarea.value exists
      if (!textarea || !textarea.value) {
        return;
      }

      const remainingChars = charLimit - textarea.value.length;
      charLimitFeedback.textContent = `${remainingChars.toLocaleString()} characters remaining`;

      const warningThreshold = charLimit * 0.1;
      charLimitFeedback.classList.toggle(
        "btm-text-red-500",
        remainingChars <= warningThreshold
      );
      charLimitFeedback.classList.toggle(
        "btm-text-gray-500",
        remainingChars > warningThreshold
      );
    }

    safeAddEventListener(textarea, "input", updateCharCount);
    // Try to update, but don't fail if textarea.value is not ready yet
    try {
      updateCharCount();
    } catch (error) {
      console.warn('Could not initialize character count:', error);
    }
  }

  /**
   * Initializes chat export functionality
   * Handles date range selection and CSV export
   * Only available for premium users
   */
  function initializeExport() {
    const exportButton = safeQuerySelector("#exportButton");
    const pickerAlert = safeQuerySelector("#picker-alert");

    if (!exportButton || !pickerAlert || !config.isPro) {
      return;
    }

    safeAddEventListener(exportButton, "click", async function (e) {
      e.preventDefault();

      const startDate = safeQuerySelector("#datepicker-range-start")?.value;
      const endDate = safeQuerySelector("#datepicker-range-end")?.value;

      if (!startDate || !endDate) {
        pickerAlert.classList.remove("btm-hidden");
        pickerAlert.innerText = "Please select both start and end dates";
        return;
      }

      exportButton.disabled = true;
      exportButton.textContent = "Exporting...";

      try {
        const formData = new FormData();
        formData.append("action", "botami_export_chat_messages");
        formData.append("nonce", window.botamiLocalizedStringsAdmin.export_nonce);
        formData.append("start_date", startDate);
        formData.append("end_date", endDate);

        const response = await fetch(window.botamiLocalizedStringsAdmin.ajax_url, {
          method: "POST",
          body: formData,
        });

        const data = await response.json();

        if (data.success) {
          const csvContent = atob(data.data.content);
          const blob = new Blob([csvContent], {
            type: "text/csv;charset=utf-8;",
          });
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = data.data.filename;
          link.click();
        } else {
          throw new Error(data.data || "Export failed");
        }
      } catch (error) {
        console.error("Export error:", error);
        pickerAlert.classList.remove("btm-hidden");
        pickerAlert.innerText =
          error.message || "Export failed. Please try again.";
      } finally {
        exportButton.disabled = false;
        exportButton.textContent = "Export & Download";
      }
    });
  }

  
  /**
   * Initializes PDF file upload functionality
   * Handles drag-and-drop and manual file selection
   * Validates file type and size before upload
   * @returns {void}
   */
  function initializeFileUpload() {
    const fileInput = safeQuerySelector(".filePdf");
    const dropZone = safeQuerySelector('[x-ref="dnd"]');
    const fileComponentDiv = safeQuerySelector("#file_component_div");

    if (!fileInput || !config.isPro) {
      return;
    }

    fileInput.setAttribute("accept", ".pdf,.docx,.csv,.xlsx,.xls");

    async function handleFile(file) {
      const allowedTypes = [
        "application/pdf",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
        "text/csv", // .csv
        "application/vnd.ms-excel", // .xls
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
      ];
      if (!allowedTypes.includes(file.type)) {
        showFileMessage(
          window.botamiLocalizedStringsAdmin.file_upload_strings.invalid_file_format || "Please upload a valid file format (PDF, DOCX, CSV, XLS, XLSX)",
          "error"
        );
        resetFileUpload();
        return;
      }

      const loadingIndicator = createLoadingIndicator();
      if (fileComponentDiv) {
        fileComponentDiv.insertBefore(
          loadingIndicator,
          fileComponentDiv.firstChild
        );
      }

      const formData = new FormData();
      formData.append("file", file);
      formData.append("action", "botami_handle_chatbot_file_upload");
      formData.append("nonce", window.botamiLocalizedStringsAdmin.file_upload_nonce);

      try {
        const response = await fetch(window.botamiLocalizedStringsAdmin.ajax_url, {
          method: "POST",
          body: formData,
          credentials: "same-origin",
        });

        const data = await response.json();
        loadingIndicator.remove();

        if (data.success) {
          // Show success message
          const successMessage = window.botamiLocalizedStringsAdmin.file_upload_strings.file_uploaded?.replace('{filename}', data.data.filename) || 
                                `File "${data.data.filename}" uploaded successfully!`;
          showFileMessage(successMessage, "success");
          
          // Check if there's a warning (content truncation)
          if (data.data.warning) {
            showFileMessage(window.botamiLocalizedStringsAdmin.file_upload_strings.content_truncated_warning || "Content was truncated due to plan limits", "warning");
          }
        } else {
          const errorMessage = data.data.message || 
                              window.botamiLocalizedStringsAdmin.file_upload_strings.upload_failed || 
                              "Upload failed";
          showFileMessage(errorMessage, "error");
        }
      } catch (error) {
        loadingIndicator.remove();
        const errorMessage = window.botamiLocalizedStringsAdmin.file_upload_strings.error_uploading || "An error occurred during upload";
        showFileMessage(errorMessage, "error");
        console.error("Upload error:", error);
      } finally {
        resetFileUpload();
      }
    }

    function resetFileUpload() {
      // Clear the file input value
      if (fileInput) {
        fileInput.value = "";
      }

      // Reset the Alpine.js files array
      const event = new Event("change");
      fileInput.dispatchEvent(event);
    }
    
    // File input change handler
    safeAddEventListener(fileInput, "change", function (e) {
      if (e.target.files.length > 0) {
        handleFile(e.target.files[0]);
      }
    });

    // Drop zone handlers
    if (dropZone) {
      safeAddEventListener(dropZone, "drop", function (e) {
        e.preventDefault();
        if (e.dataTransfer.files.length > 0) {
          handleFile(e.dataTransfer.files[0]);
        }
      });

      safeAddEventListener(dropZone, "dragover", function (e) {
        e.preventDefault();
      });
    }

    /**
     * Creates a loading indicator element
     * @returns {HTMLElement} Loading indicator div
     */
    function createLoadingIndicator() {
      const div = document.createElement("div");
      div.className =
        "btm-mb-4 btm-p-4 btm-rounded btm-bg-blue-100 btm-text-blue-700 btm-flex btm-items-center btm-justify-center";

      const loadingText = window.botamiLocalizedStringsAdmin.file_upload_strings.uploading_file || "Uploading File...";

      div.innerHTML = `
                <svg class="btm-animate-spin btm--ml-1 btm-mr-3 btm-h-5 btm-w-5  btm-text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="btm-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="btm-opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span>${loadingText}</span>
            `;
      return div;
    }

    /**
     * Displays file operation messages to the user
     * @param {string} message - Message to display
     * @param {('success'|'error'|'warning')} type - Message type
     */
    function showFileMessage(message, type) {
      if (!fileComponentDiv) return;

      const messageDiv = document.createElement("div");

      // Set classes based on message type
      let cssClasses = "btm-mb-4 btm-p-4 btm-rounded ";
      switch (type) {
        case "success":
          cssClasses += "btm-bg-green-100 btm-text-green-700 btm-border btm-border-green-200";
          break;
        case "warning":
          cssClasses += "btm-bg-yellow-100 btm-text-yellow-700 btm-border btm-border-yellow-200";
          break;
        case "error":
        default:
          cssClasses += "btm-bg-red-100 btm-text-red-700 btm-border btm-border-red-200";
          break;
      }

      messageDiv.className = cssClasses;
      messageDiv.textContent = message;

      fileComponentDiv.insertBefore(messageDiv, fileComponentDiv.firstChild);

      // Auto-remove success and error messages after 5 seconds
      // Keep warning messages longer (8 seconds) as they're important
      const timeout = type === "warning" ? 8000 : 5000;
      setTimeout(() => messageDiv.remove(), timeout);
    }
  }

  /**
   * Initializes URL management functionality
   * Sets up both knowledge and excluded URL lists
   */
  function initializeUrlManagement() {
    // Knowledge URLs
    initializeUrlList({
      inputContainerId: "form_add_url",
      inputId: "knowledge_url_input",
      submitButtonId: "add_url_submit",
      containerId: "knowledge_urls_container",
      listId: "knowledge_urls_list",
      inputFieldId: "botami_knowledge_urls_input",
      deleteClass: "delete-url",
      maxItems: 10,
    });

    // Excluded URLs
    initializeUrlList({
      inputContainerId: "form_add_excluded_url",
      inputId: "excluded_url_input",
      submitButtonId: "add_excluded_url_submit",
      containerId: "excluded_urls_container",
      listId: "excluded_urls_list",
      inputFieldId: "botami_excluded_urls_input",
      deleteClass: "delete-excluded-url",
    });
  }

  /**
   * Initializes URL list functionality for a specific list type
   * @param {Object} config - Configuration object for the URL list
   */
  function initializeUrlList(config) {
    const inputContainer = safeQuerySelector(`#${config.inputContainerId}`);
    const urlInput = safeQuerySelector(`#${config.inputId}`);
    const addUrlSubmit = safeQuerySelector(`#${config.submitButtonId}`);
    const urlsContainer = safeQuerySelector(`#${config.containerId}`);
    const urlsList = safeQuerySelector(`#${config.listId}`);
    const urlsInputField = safeQuerySelector(`#${config.inputFieldId}`);
    const errorAlert = safeQuerySelector("#error-alert");

    if (
      !inputContainer ||
      !urlInput ||
      !addUrlSubmit ||
      !urlsContainer ||
      !urlsList ||
      !urlsInputField
    ) {
      return;
    }

    safeAddEventListener(addUrlSubmit, "click", function (e) {
      e.preventDefault();
      const url = urlInput.value.trim();

      if (!url) {
        if (errorAlert) {
          errorAlert.classList.remove("btm-hidden");
          errorAlert.innerText = "Please enter a valid URL";
          setTimeout(() => {
            errorAlert.classList.add("btm-hidden");
          }, 3000);
        }
        return;
      }

      const existingUrls = urlsInputField.value
        ? urlsInputField.value.split("||").filter((url) => url.trim())
        : [];

      if (config.maxItems && existingUrls.length >= config.maxItems) {
        if (errorAlert) {
          errorAlert.classList.remove("btm-hidden");
          errorAlert.innerText = `Maximum of ${config.maxItems} URLs allowed`;
          setTimeout(() => {
            errorAlert.classList.add("btm-hidden");
          }, 3000);
        }
        return;
      }

      if (existingUrls.includes(url)) {
        if (errorAlert) {
          errorAlert.classList.remove("btm-hidden");
          errorAlert.innerText = "This URL is already in the list";
          setTimeout(() => {
            errorAlert.classList.add("btm-hidden");
          }, 3000);
        }
        return;
      }

      addUrlToList(url);
      urlInput.value = "";
    });

    function addUrlToList(url) {
      const newRow = document.createElement("tr");
      newRow.className =
        "btm-bg-white btm-border-b btm-dark:bg-gray-800 btm-dark:border-gray-700 btm-hover:bg-gray-50 btm-dark:hover:bg-gray-600";
      newRow.innerHTML = `
                <th scope="row" class="btm-px-6 btm-py-4 btm-font-medium btm-text-gray-900 btm-whitespace-nowrap  btm-dark:text-white">
                    ${url}
                </th>
                <td class="btm-px-6 btm-py-4  btm-text-right">
                    <svg xmlns="http://www.w3.org/2000/svg" class="btm-h-8 btm-w-8  btm-text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                    </svg>
                </td>
                <td class="btm-px-6 btm-py-4 btm-text-right btm-cursor-pointer  btm-${config.deleteClass}" data-url="${url}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="btm-h-6 btm-w-6 btm-text-gray-600 btm-hover:text-red-500 btm-transition  btm-duration-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M10 4h4m-4 0a1 1 0 00-1 1v1h6V5a1 1 0 00-1-1m-4 0h4" />
                    </svg>
                </td>
            `;

      const deleteButton = newRow.querySelector(`.${config.deleteClass}`);
      if (deleteButton) {
        safeAddEventListener(deleteButton, "click", handleUrlDelete);
      }

      urlsList.appendChild(newRow);
      urlsContainer.classList.remove("btm-hidden");

      const currentUrls = urlsInputField.value
        ? urlsInputField.value.split("||").filter((url) => url.trim())
        : [];
      currentUrls.push(url);
      urlsInputField.value = currentUrls.join("||");
    }

    function handleUrlDelete(event) {
      const urlToDelete = event.currentTarget.getAttribute("data-url");
      const row = event.currentTarget.closest("tr");

      if (!urlToDelete || !row) return;

      const currentUrls = urlsInputField.value
        .split("||")
        .filter((url) => url !== urlToDelete);
      urlsInputField.value = currentUrls.join("||");

      row.remove();

      if (currentUrls.length === 0) {
        urlsContainer.classList.add("btm-hidden");
      }
    }

    // Add delete handlers to existing URLs
    document
      .querySelectorAll(`.${config.deleteClass}`)
      .forEach((deleteButton) => {
        safeAddEventListener(deleteButton, "click", handleUrlDelete);
      });
  }

  /**
   * Initializes bot image upload functionality
   * Handles image upload with preview and validation
   * Supports drag-and-drop and file selection
   * Only available for pro users and above
   */
  function initializeBotImageUpload() {
    const dropzone = safeQuerySelector("#dropzone");
    const input = safeQuerySelector("#file-input");
    const errorMessage = safeQuerySelector("#error-message");
    const preview = safeQuerySelector("#preview");
    const logoUrlInput = safeQuerySelector("#botami_bot_image_url");

    if (!dropzone || !input || !config.isPro) {
      return;
    }

    const dragOverHandler = (e) => {
      e.preventDefault();
      dropzone.classList.add("btm-border-indigo-600");
    };

    const dragLeaveHandler = (e) => {
      e.preventDefault();
      dropzone.classList.remove("btm-border-indigo-600");
    };

    const dropHandler = (e) => {
      e.preventDefault();
      dropzone.classList.remove("btm-border-indigo-600");
      if (e.dataTransfer.files.length > 0) {
        handleFileSelect(e.dataTransfer.files[0]);

        // Create a new DataTransfer object and add the file
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(e.dataTransfer.files[0]);

        // Assign the files to the input element
        input.files = dataTransfer.files;

        // Trigger change event to update any other listeners
        const changeEvent = new Event("change", { bubbles: true });
        input.dispatchEvent(changeEvent);
      }
    };

    safeAddEventListener(dropzone, "dragover", dragOverHandler);
    safeAddEventListener(dropzone, "dragleave", dragLeaveHandler);
    safeAddEventListener(dropzone, "drop", dropHandler);
    safeAddEventListener(input, "change", (e) => {
      if (e.target.files.length > 0) {
        handleFileSelect(e.target.files[0]);
      }
    });

    /**
     * Handles file selection and validation
     * @param {File} file - Selected file object
     */
    function handleFileSelect(file) {
      if (!errorMessage || !preview) return;

      errorMessage.classList.add("btm-hidden");
      preview.classList.add("btm-hidden");
      preview.src = "";

      // Deselect any logo templates that might be selected
      const logoTemplates = document.querySelectorAll(".logo-template");
      logoTemplates.forEach((template) => {
        template.classList.remove("btm-border-blue-500", "btm-bg-blue-50");
      });

      // Clear the logo URL input to ensure the form knows we're using a file upload
      if (logoUrlInput) {
        logoUrlInput.value = "";
      }

      const maxSize = 10 * 1024 * 1024; // 10 MB
      const allowedTypes = ["image/jpeg", "image/png", "image/gif"];

      if (!file) {
        showError("No file selected.");
        return;
      }

      if (!allowedTypes.includes(file.type)) {
        showError("Please upload an image file (PNG, JPG, GIF).");
        return;
      }

      if (file.size > maxSize) {
        showError("The file exceeds the maximum size of 10 MB.");
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        preview.src = e.target.result;
        preview.classList.remove("btm-hidden");
        errorMessage.classList.add("btm-hidden");
      };

      reader.onerror = () => {
        showError("An error occurred while reading the file.");
      };

      reader.readAsDataURL(file);
    }

    function showError(message) {
      if (errorMessage) {
        errorMessage.textContent = message;
        errorMessage.classList.remove("btm-hidden");
      }
    }
  }

  /**
   * Initialise le sélecteur de logo de manière cohérente
   * Cette fonction est conçue pour remplacer les différentes implémentations existantes
   */
  function initializeLogoSelector() {
    // Sélectionner les éléments du logo
    const logoTemplates = document.querySelectorAll(".logo-template");
    const logoUrlInput = document.querySelector("#botami_bot_image_url");
    const previewImage = document.querySelector("#preview");

    // Vérifier si les éléments existent
    if (!logoTemplates.length || !logoUrlInput) {
      console.warn("Éléments du sélecteur de logo introuvables");
      return;
    }

    // Fonction pour mettre en évidence le logo actif
    function highlightActiveLogo() {
      if (!logoUrlInput) return;

      const currentLogo = logoUrlInput.value;

      logoTemplates.forEach((template) => {
        const templateLogo = template.getAttribute("data-logo");

        if (templateLogo === currentLogo) {
          template.classList.add("btm-border-blue-500", "btm-bg-blue-50");
        } else {
          template.classList.remove("btm-border-blue-500", "btm-bg-blue-50");
        }
      });
    }

    // Mettre en évidence le logo actif au chargement
    highlightActiveLogo();

    // Ajouter des gestionnaires d'événements pour chaque template de logo
    logoTemplates.forEach((template) => {
      template.addEventListener("click", function (e) {
        // Empêcher la propagation de l'événement
        e.preventDefault();
        e.stopPropagation();

        // Ne pas réagir si l'élément est désactivé (pour les utilisateurs non premium)
        if (
          this.classList.contains("btm-premium-component") &&
          typeof window.botamiLocalizedStringsAdmin !== "undefined" &&
          !window.botamiLocalizedStringsAdmin.is_pro_or_higher
        ) {
          return;
        }

        const logoUrl = this.getAttribute("data-logo");

        // Mettre à jour la valeur de l'input
        logoUrlInput.value = logoUrl;

        // Déclencher l'événement change pour s'assurer que les listeners externes sont notifiés
        const changeEvent = new Event("change", { bubbles: true });
        logoUrlInput.dispatchEvent(changeEvent);

        // Réinitialiser l'aperçu de l'image uploadée si présent
        if (previewImage) {
          previewImage.src = "";
          previewImage.classList.add("btm-hidden");
        }

        // Mettre à jour la visualisation du logo actif
        highlightActiveLogo();
      });
    });

    // Ajouter un événement pour déselectionner les templates lors de l'upload
    const fileInput = document.querySelector("#file-input");
    if (fileInput) {
      fileInput.addEventListener("change", function (e) {
        if (e.target.files.length > 0) {
          // Déselectionner tous les templates de logo lorsqu'un fichier est sélectionné
          logoTemplates.forEach((template) => {
            template.classList.remove("btm-border-blue-500", "btm-bg-blue-50");
          });
        }
      });
    }
  }

  /**
   * Initializes the Enhanced Quick Replies functionality
   * Handles adding, removing, and reordering quick reply items with branching logic
   */
  function initializeQuickReplies() {
    const addButton = document.getElementById('add_quick_reply_btn');
    const input = document.getElementById('quick_reply_input');
    const container = document.querySelector('.quick-replies-container');
    const orderInput = document.getElementById('quick_replies_order');
    const errorAlert = document.getElementById('error-alert');
    const itemsCount = document.getElementById('items-count');
    const emptyState = document.getElementById('empty-state');
    const clearAllButton = document.getElementById('clear-all');
    
    if (!config.isPremium) {
        // Désactiver tous les contrôles si pas Premium
        if (addButton) addButton.disabled = true;
        if (input) input.disabled = true;
        if (container) container.classList.add('btm-premium-component', 'btm-opacity-50');
        
        // Empêcher toute interaction
        if (container) {
            container.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
            });
        }
        
        return; // Sortir de la fonction si pas Premium
    }
    // Get localized strings from the global botamiLocalizedStringsAdmin object
    const strings = window.botamiLocalizedStringsAdmin?.strings || {
        questionNumber: 'Question #',
        interactiveQuestionnaire: 'Interactive questionnaire',
        deleteQuestion: 'Delete this question',
        mainQuestion: 'Main Question',
        enterQuestion: 'Enter your question here...',
        responseOptions: 'Response Options',
        addOption: 'Add Option',
        enterOption: 'Enter option {letter} here...',
        previousQuestion: 'Previous Question',
        optional: 'Optional',
        noPreviousQuestion: 'No previous question',
        previousAnswerOption: 'Previous Answer Option',
        noSpecificAnswer: 'No specific previous answer required',
        onlyAfterAnswer: 'This question will only appear if the user selected the specific answer option above.',
        autoSaveEnabled: 'Auto-save enabled',
        edit: 'Edit',
        deleteQuestionConfirm: 'Are you sure you want to delete this question?',
        enterQuestionMessage: 'Please enter a question message',
        removeAllConfirm: 'Are you sure you want to remove all quick replies?'
    };
    
    // Exit if required elements don't exist
    if (!addButton || !input || !container || !orderInput) {
        console.warn('Quick replies elements not found');
        return;
    }
    
    // Add new quick reply
    addButton.addEventListener('click', function(e) {
        e.preventDefault();
        addQuickReply();
    });
    
    // Allow pressing Enter to add a quick reply
    input.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            addQuickReply();
        }
    });

    // Clear all quick replies
    if (clearAllButton) {
        clearAllButton.addEventListener('click', function(e) {
            e.preventDefault();
            
            if (confirm(strings.removeAllConfirm)) {
                container.innerHTML = '';
                orderInput.value = '[]';
                updateItemsCount();
            }
        });
    }
    
    /**
     * Adds a new questionnaire item to the container with enhanced design
     * @param {Object} data - Optional data to initialize the item with
     */
    function addQuickReply(data = null) {
        // If data is provided, use its text, otherwise use input value
        const replyText = data ? data.text : input.value.trim();
        
        if (!replyText) {
            showError(strings.enterQuestionMessage);
            return null;
        }
        
        // Use provided ID or generate a new one
        const uniqueId = data && data.id ? data.id : 'item-' + Date.now();
        
        // Initialize options data if provided
        const optionsData = data && data.options ? data.options : [''];
        
        // Create new item
        const newItem = document.createElement('div');
        newItem.className = 'sortable-item btm-bg-gradient-to-br btm-from-white btm-to-gray-50 btm-rounded-xl btm-shadow-lg btm-hover:shadow-xl btm-border btm-border-gray-200 btm-hover:border-gray-300 btm-p-6 btm-mb-4 btm-relative btm-transition-all btm-duration-300 btm-group';
        newItem.setAttribute('data-reply-text', replyText);
        newItem.setAttribute('id', uniqueId);
        
        newItem.innerHTML = `
            <!-- Header Section -->
            <div class="btm-flex btm-justify-between btm-items-center btm-mb-4 btm-pb-3 btm-border-b  btm-border-gray-100">
                <div class="btm-flex btm-items-center  btm-gap-3">
                    <div class="btm-w-10 btm-h-10 btm-bg-gradient-to-r btm-from-blue-500 btm-to-purple-600 btm-rounded-lg btm-flex btm-items-center  btm-justify-center">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
                            <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
                        </svg>
                    </div>
                    <div>
                        <span class="btm-font-semibold btm-text-gray-800  btm-text-sm">${strings.questionNumber}${uniqueId.slice(-4)}</span>
                        <p class="btm-text-xs btm-text-gray-500  btm-mt-1">${strings.interactiveQuestionnaire}</p>
                    </div>
                </div>

                <div class="btm-flex btm-items-center  btm-gap-2">
                    <button class="close-btn btm-p-2 btm-rounded-lg btm-bg-red-50 btm-hover:bg-red-100 btm-text-red-400 btm-hover:text-red-600 btm-transition-all btm-duration-200 btm-opacity-0  btm-group-hover:opacity-100" title="${strings.deleteQuestion}">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M18 6L6 18M6 6l12 12"/>
                        </svg>
                    </button>
                </div>
            </div>
            
            <!-- Content Section -->
            <div class="reply-text content-bloc  btm-space-y-6">
                <!-- Question Input -->
                <div class="btm-space-y-2">
                    <label class="btm-flex btm-items-center btm-gap-2 btm-text-sm btm-font-semibold  btm-text-gray-700" for="${uniqueId}-question">
                        <div class="btm-w-2 btm-h-2 btm-bg-blue-500  btm-rounded-full"></div>
                        ${strings.mainQuestion}
                    </label>
                    <div class="btm-relative">
                        <input id="${uniqueId}-question"
                              class="btm-w-full btm-p-4 btm-border-2 btm-border-gray-200 btm-rounded-xl btm-focus:outline-none btm-focus:border-blue-500 btm-focus:ring-4 btm-focus:ring-blue-100 btm-transition-all btm-duration-200 btm-bg-white btm-placeholder-gray-400 btm-text-gray-800  btm-font-medium"
                              value="${replyText.replace(/"/g, '&quot;')}"
                              type="text"
                              placeholder="${strings.enterQuestion}">
                        <div class="btm-absolute btm-right-4 btm-top-1/2 btm-transform btm--translate-y-1/2  btm-text-gray-400">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>
                            </svg>
                        </div>
                    </div>
                </div>
                
                <!-- Response Options Section -->
                <div class="btm-space-y-3">
                    <div class="btm-flex btm-items-center  btm-justify-between">
                        <label class="btm-flex btm-items-center btm-gap-2 btm-text-sm btm-font-semibold  btm-text-gray-700">
                            <div class="btm-w-2 btm-h-2 btm-bg-green-500  btm-rounded-full"></div>
                            ${strings.responseOptions}
                        </label>
                        <button type="button" class="add-option-btn btm-flex btn-botami btm-items-center btm-gap-2 btm-text-sm btm-px-4 btm-py-2 btm-text-black btm-rounded-lg btm-hover:from-green-600 btm-hover:to-emerald-600 btm-transition-all btm-duration-200 btm-shadow-md btm-hover:shadow-lg btm-transform  btm-hover:-translate-y-0.5">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M12 5v14M5 12h14"/>
                            </svg>
                            ${strings.addOption}
                        </button>
                    </div>
                    
                    <div class="options-container btm-bg-gray-50 btm-rounded-xl btm-p-4 btm-space-y-3 btm-border-2 btm-border-dashed  btm-border-gray-200" id="${uniqueId}-options">
                        ${optionsData.map((option, index) => {
                            const letter = String.fromCharCode(65 + index);
                            return `
                                <div class="option-item btm-group/option btm-bg-white btm-rounded-lg btm-p-3 btm-border btm-border-gray-200 btm-hover:border-gray-300 btm-transition-all btm-duration-200  btm-hover:shadow-md">
                                    <div class="btm-flex btm-items-center  btm-gap-3">
                                        <div class="btm-flex btm-items-center btm-justify-center btm-w-8 btm-h-8 btm-bg-gradient-to-r btm-from-blue-400 btm-to-purple-500 btm-text-white btm-rounded-lg btm-font-bold  btm-text-sm">
                                            ${letter}
                                        </div>
                                        <input type="text"
                                              class="option-input btm-flex-1 btm-p-3 btm-border btm-border-gray-200 btm-rounded-lg btm-focus:outline-none btm-focus:border-blue-500 btm-focus:ring-3 btm-focus:ring-blue-100 btm-transition-all btm-duration-200 btm-bg-white btm-placeholder-gray-400  btm-text-gray-700"
                                              value="${option.replace(/"/g, '&quot;')}"
                                              placeholder="${strings.enterOption.replace('{letter}', letter)}">
                                        <button type="button" class="remove-option-btn btm-opacity-0 btm-group-hover/option:opacity-100 btm-transition-opacity btm-duration-200 btm-w-8 btm-h-8 btm-flex btm-items-center btm-justify-center btm-rounded-lg btm-bg-red-50 btm-hover:bg-red-100 btm-text-red-400 btm-hover:text-red-600  btm-transition-colors">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                <path d="M18 6L6 18M6 6l12 12"/>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
                
                <!-- Previous Question Section -->
                <div class="btm-space-y-2">
                    <label class="btm-flex btm-items-center btm-gap-2 btm-text-sm btm-font-semibold  btm-text-gray-700" for="${uniqueId}-previous">
                        <div class="btm-w-2 btm-h-2 btm-bg-purple-500  btm-rounded-full"></div>
                        ${strings.previousQuestion}
                        <span class="btm-text-xs btm-bg-purple-100 btm-text-purple-700 btm-px-2 btm-py-1 btm-rounded-full  btm-font-medium">
                            ${strings.optional}
                        </span>
                    </label>
                    <div class="btm-relative">
                        <select id="${uniqueId}-previous"
                                class="previous-question-select btm-w-full btm-p-4 btm-border-2 btm-border-gray-200 btm-rounded-xl btm-appearance-none btm-focus:outline-none btm-focus:border-purple-500 btm-focus:ring-4 btm-focus:ring-purple-100 btm-bg-white btm-pr-12 btm-transition-all btm-duration-200  btm-text-gray-700">
                            <option value="">${strings.noPreviousQuestion}</option>
                        </select>
                    </div>
                </div>

                <!-- Previous Option Section - NEW! -->
                <div class="btm-space-y-2">
                    <label class="btm-flex btm-items-center btm-gap-2 btm-text-sm btm-font-semibold  btm-text-gray-700" for="${uniqueId}-previous-option">
                        <div class="btm-w-2 btm-h-2 btm-bg-orange-500  btm-rounded-full"></div>
                        ${strings.previousAnswerOption}
                        <span class="btm-text-xs btm-bg-orange-100 btm-text-orange-700 btm-px-2 btm-py-1 btm-rounded-full  btm-font-medium">
                            ${strings.optional}
                        </span>
                    </label>
                    <div class="btm-relative">
                        <select id="${uniqueId}-previous-option"
                                class="previous-option-select btm-w-full btm-p-4 btm-border-2 btm-border-gray-200 btm-rounded-xl btm-appearance-none btm-focus:outline-none btm-focus:border-orange-500 btm-focus:ring-4 btm-focus:ring-orange-100 btm-bg-white btm-pr-12 btm-transition-all btm-duration-200  btm-text-gray-700">
                            <option value="">${strings.noSpecificAnswer}</option>
                        </select>
                    </div>
                    <p class="btm-text-xs btm-text-gray-500  btm-mt-1">${strings.onlyAfterAnswer}</p>
                </div>
                
                <!-- Action Buttons -->
                <div class="btm-flex btm-justify-between btm-items-center btm-pt-4 btm-border-t  btm-border-gray-100">
                    <div class="btm-flex btm-items-center btm-gap-2 btm-text-sm  btm-text-gray-500">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                        </svg>
                        ${strings.autoSaveEnabled}
                    </div>
                    <div class="btm-flex  btm-gap-2">
                        <button type="button" class="edit-btn btm-flex btm-items-center btm-gap-2 btm-text-sm btm-px-4 btm-py-2 btm-bg-gradient-to-r btm-from-blue-500 btm-to-indigo-500 btm-text-white btm-rounded-lg btm-hover:from-blue-600 btm-hover:to-indigo-600 btm-transition-all btm-duration-200 btm-shadow-md btm-hover:shadow-lg btm-transform  btm-hover:-translate-y-0.5">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                                <path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                            </svg>
                            ${strings.edit}
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // Add delete functionality
        const closeBtn = newItem.querySelector('.close-btn');
        if (closeBtn) {
            closeBtn.addEventListener('click', function(e) {
                e.preventDefault();
                if (confirm(strings.deleteQuestionConfirm)) {
                    newItem.classList.add('btm-opacity-0', 'btm-scale-95', 'btm-transform');
                    newItem.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
                    
                    setTimeout(() => {
                        newItem.remove();
                        saveOrder();
                        updateItemsCount();
                        updateSelectOptions();
                    }, 300);
                }
            });
        }
        
        // Add edit functionality
        const editBtn = newItem.querySelector('.edit-btn');
        if (editBtn) {
            editBtn.addEventListener('click', function() {
                const questionInput = newItem.querySelector(`#${uniqueId}-question`);
                questionInput.focus();
                questionInput.select();
                questionInput.style.transform = 'scale(1.02)';
                setTimeout(() => {
                    questionInput.style.transform = 'scale(1)';
                }, 200);
            });
        }

        // Add input change event for question
        const questionInput = newItem.querySelector(`#${uniqueId}-question`);
        if (questionInput) {
            questionInput.addEventListener('input', function() {
                newItem.setAttribute('data-reply-text', this.value);
                this.style.borderColor = '#10b981';
                setTimeout(() => {
                    this.style.borderColor = '';
                }, 1000);
            });
            
            questionInput.addEventListener('change', function() {
                saveOrder();
                updateSelectOptions();
            });
        }
        
        // Add select change events for both previous question and previous option
        const previousQuestionSelect = newItem.querySelector('.previous-question-select');
        const previousOptionSelect = newItem.querySelector('.previous-option-select');
        
        if (previousQuestionSelect) {
            previousQuestionSelect.addEventListener('change', function() {
                saveOrder();
                updatePreviousOptionDropdown(uniqueId, this.value);
                this.style.borderColor = '#8b5cf6';
                setTimeout(() => {
                    this.style.borderColor = '';
                }, 1000);
            });
        }
        
        if (previousOptionSelect) {
            previousOptionSelect.addEventListener('change', function() {
                saveOrder();
                this.style.borderColor = '#f97316';
                setTimeout(() => {
                    this.style.borderColor = '';
                }, 1000);
            });
        }
        
        // Add functionality for adding new options
        const addOptionBtn = newItem.querySelector('.add-option-btn');
        if (addOptionBtn) {
            addOptionBtn.addEventListener('click', function() {
                addNewOption(uniqueId);
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = 'scale(1)';
                }, 150);
            });
        }
        
        // Add functionality for existing option inputs and remove buttons
        initializeOptionEvents(newItem, uniqueId);
        
        // Add to container with enhanced animation
        newItem.style.opacity = '0';
        newItem.style.transform = 'translateY(20px) scale(0.95)';
        container.appendChild(newItem);
        
        // Trigger entrance animation
        setTimeout(() => {
            newItem.style.transition = 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)';
            newItem.style.opacity = '1';
            newItem.style.transform = 'translateY(0) scale(1)';
        }, 10);
        
        // Clear input if this is a new item
        if (!data) {
            input.value = '';
            input.focus();
        }
        
        saveOrder();
        updateItemsCount();
        updateSelectOptions();
        return newItem;
    }

    /**
     * Update the previous option dropdown based on selected previous question
     * @param {string} currentItemId - ID of the current item
     * @param {string} selectedQuestionId - ID of the selected previous question
     */
    function updatePreviousOptionDropdown(currentItemId, selectedQuestionId) {
        const currentItem = document.getElementById(currentItemId);
        const previousOptionSelect = currentItem.querySelector('.previous-option-select');
        
        if (!previousOptionSelect) return;
        
        // Save current selection
        const currentSelection = previousOptionSelect.value;
        
        // Clear current options
        previousOptionSelect.innerHTML = '<option value="">No specific previous answer required</option>';
        
        if (!selectedQuestionId) {
            return;
        }
        
        // Find the selected previous question
        const previousQuestion = document.getElementById(selectedQuestionId);
        if (!previousQuestion) return;
        
        // Get all options from the previous question
        const optionInputs = previousQuestion.querySelectorAll('.option-input');
        
        optionInputs.forEach((optionInput, index) => {
            const optionText = optionInput.value.trim();
            if (optionText) {
                const option = document.createElement('option');
                option.value = index; // Use index as value
                option.textContent = `${String.fromCharCode(65 + index)}: ${optionText.substring(0, 30)}${optionText.length > 30 ? '...' : ''}`;
                previousOptionSelect.appendChild(option);
            }
        });
        
        // Restore selection if it still exists
        if (currentSelection !== '') {
            const optionExists = Array.from(previousOptionSelect.options).some(opt => opt.value === currentSelection);
            if (optionExists) {
                previousOptionSelect.value = currentSelection;
            }
        }
    }

    /**
     * Add a new option input to an existing question
     * @param {string} itemId - The ID of the item to add the option to
     */
    function addNewOption(itemId) {
        const optionsContainer = document.querySelector(`#${itemId}-options`);
        if (!optionsContainer) return;
        
        const optionCount = optionsContainer.children.length;
        const optionLetter = String.fromCharCode(65 + optionCount);
        
        const optionDiv = document.createElement('div');
        optionDiv.className = 'option-item btm-group/option btm-bg-white btm-rounded-lg btm-p-3 btm-border btm-border-gray-200 btm-hover:border-gray-300 btm-transition-all btm-duration-200 btm-hover:shadow-md';
        
        optionDiv.innerHTML = `
            <div class="btm-flex btm-items-center  btm-gap-3">
                <div class="btm-flex btm-items-center btm-justify-center btm-w-8 btm-h-8 btm-bg-gradient-to-r btm-from-blue-400 btm-to-purple-500 btm-text-white btm-rounded-lg btm-font-bold  btm-text-sm">
                    ${optionLetter}
                </div>
                <input type="text"
                      class="option-input btm-flex-1 btm-p-3 btm-border btm-border-gray-200 btm-rounded-lg btm-focus:outline-none btm-focus:border-blue-500 btm-focus:ring-3 btm-focus:ring-blue-100 btm-transition-all btm-duration-200 btm-bg-white btm-placeholder-gray-400  btm-text-gray-700"
                      value=""
                      placeholder="${strings.enterOption.replace('{letter}', optionLetter)}">
                <button type="button" class="remove-option-btn btm-opacity-0 btm-group-hover/option:opacity-100 btm-transition-opacity btm-duration-200 btm-w-8 btm-h-8 btm-flex btm-items-center btm-justify-center btm-rounded-lg btm-bg-red-50 btm-hover:bg-red-100 btm-text-red-400 btm-hover:text-red-600  btm-transition-colors">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M18 6L6 18M6 6l12 12"/>
                    </svg>
                </button>
            </div>
        `;
        
        // Add with enhanced animation
        optionDiv.style.opacity = '0';
        optionDiv.style.transform = 'translateX(-20px) scale(0.95)';
        optionsContainer.appendChild(optionDiv);
        
        setTimeout(() => {
            optionDiv.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
            optionDiv.style.opacity = '1';
            optionDiv.style.transform = 'translateX(0) scale(1)';
        }, 10);
        
        // Initialize events for the new option
        const newItem = document.getElementById(itemId);
        initializeOptionEvents(newItem, itemId);
        
        // Update any dependent previous option dropdowns
        updateAllPreviousOptionDropdowns();
        
        // Focus on the new input with animation
        const newInput = optionDiv.querySelector('.option-input');
        if (newInput) {
            setTimeout(() => {
                newInput.focus();
                newInput.style.transform = 'scale(1.02)';
                setTimeout(() => {
                    newInput.style.transform = 'scale(1)';
                }, 200);
            }, 100);
        }
    }

    /**
     * Update all previous option dropdowns when options change
     */
    function updateAllPreviousOptionDropdowns() {
        const items = container.querySelectorAll('.sortable-item');
        
        items.forEach(item => {
            const itemId = item.id;
            const previousQuestionSelect = item.querySelector('.previous-question-select');
            
            if (previousQuestionSelect && previousQuestionSelect.value) {
                updatePreviousOptionDropdown(itemId, previousQuestionSelect.value);
            }
        });
    }

    /**
     * Initialize events for option inputs and remove buttons
     * @param {HTMLElement} item - The item element
     * @param {string} itemId - The ID of the item
     */
    function initializeOptionEvents(item, itemId) {
        // Option input change events
        const optionInputs = item.querySelectorAll('.option-input');
        optionInputs.forEach(input => {
            input.removeEventListener('input', handleOptionInput);
            input.removeEventListener('change', handleOptionChange);
            
            input.addEventListener('input', handleOptionInput);
            input.addEventListener('change', handleOptionChange);
        });
        
        // Remove option button events
        const removeButtons = item.querySelectorAll('.remove-option-btn');
        removeButtons.forEach(btn => {
            btn.removeEventListener('click', handleRemoveOption);
            btn.addEventListener('click', handleRemoveOption);
        });
    }

    /**
     * Handle option input changes with visual feedback
     */
    function handleOptionInput(e) {
        e.target.style.borderColor = '#10b981';
        setTimeout(() => {
            e.target.style.borderColor = '';
        }, 1000);
    }

    /**
     * Handle option input changes
     */
    function handleOptionChange() {
        saveOrder();
        updateAllPreviousOptionDropdowns();
    }

    /**
     * Handle remove option button clicks
     * @param {Event} e - The click event
     */
    function handleRemoveOption(e) {
        e.preventDefault();
        const optionItem = e.target.closest('.option-item');
        const optionsContainer = e.target.closest('.options-container');
        
        if (optionItem && optionsContainer && optionsContainer.children.length > 1) {
            optionItem.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
            optionItem.style.opacity = '0';
            optionItem.style.transform = 'translateX(20px) scale(0.95)';
            
            setTimeout(() => {
                optionItem.remove();
                saveOrder();
                updateOptionLabels(optionsContainer);
                updateAllPreviousOptionDropdowns();
            }, 300);
        } else if (optionsContainer && optionsContainer.children.length === 1) {
            // Show feedback when trying to remove the last option
            const button = e.target.closest('.remove-option-btn');
            button.style.backgroundColor = '#fecaca';
            button.style.transform = 'scale(1.1)';
            setTimeout(() => {
                button.style.backgroundColor = '';
                button.style.transform = 'scale(1)';
            }, 200);
        }
    }

    /**
     * Update option labels (A, B, C, etc.) after removal
     * @param {HTMLElement} container - The options container
     */
    function updateOptionLabels(container) {
        const options = container.querySelectorAll('.option-item');
        options.forEach((option, index) => {
            const letter = String.fromCharCode(65 + index);
            const label = option.querySelector('.w-8.h-8');
            const input = option.querySelector('.option-input');
            
            if (label) label.textContent = letter;
            if (input) input.placeholder = strings.enterOption.replace('{letter}', letter);
        });
    }
    
    /**
     * Updates all select dropdown options with current items
     */
    function updateSelectOptions() {
        const items = container.querySelectorAll('.sortable-item');
        
        // First, gather all questions for the options
        const options = [];
        items.forEach(item => {
            const id = item.id;
            const input = item.querySelector('input[type="text"]');
            const text = input ? input.value : '';
            
            options.push({
                id: id,
                text: text
            });
        });
        
        // Then update each select
        items.forEach(item => {
            const select = item.querySelector('.previous-question-select');
            const currentId = item.id;
            const currentValue = select ? select.value : '';
            
            if (select) {
                // Clear current options
                select.innerHTML = '<option value="">No previous question</option>';
                
                // Add options for all other items
                options.forEach(option => {
                    if (option.id !== currentId) {
                        const opt = document.createElement('option');
                        opt.value = option.id;
                        opt.textContent = `#${option.id.slice(-4)} - ${option.text.substring(0, 30)}${option.text.length > 30 ? '...' : ''}`;
                        select.appendChild(opt);
                    }
                });
                
                // Restore selection if it exists
                if (currentValue) {
                    const optionExists = Array.from(select.options).some(opt => opt.value === currentValue);
                    if (optionExists) {
                        select.value = currentValue;
                        // Update the corresponding previous option dropdown
                        updatePreviousOptionDropdown(currentId, currentValue);
                    }
                }
            }
        });
    }
    
    /**
     * Shows an error notification
     * @param {string} message - Error message to display
     */
    function showError(message) {
        const errorNotification = document.createElement('div');
        errorNotification.className = 'btm-fixed btm-bottom-4 btm-right-4 btm-bg-red-50 btm-text-red-800 btm-rounded-lg btm-shadow-lg btm-p-4 btm-flex btm-items-center btm-z-50';
        errorNotification.innerHTML = `
            <svg class="btm-w-5 btm-h-5  btm-mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
            ${message}
        `;
        
        document.body.appendChild(errorNotification);
        
        setTimeout(() => {
            errorNotification.style.opacity = '0';
            errorNotification.style.transform = 'translateY(10px)';
            errorNotification.style.transition = 'all 0.3s ease-out';
            
            setTimeout(() => {
                errorNotification.remove();
            }, 300);
        }, 3000);
    }
    
    /**
     * Saves the current order to the hidden input
     */
    function saveOrder() {
        const items = container.querySelectorAll('.sortable-item');
        const data = Array.from(items).map((item, index) => {
            const questionInput = item.querySelector('input[type="text"]');
            const previousQuestionSelect = item.querySelector('.previous-question-select');
            const previousOptionSelect = item.querySelector('.previous-option-select');
            
            // Get all options for this question
            const optionInputs = item.querySelectorAll('.option-input');
            const options = Array.from(optionInputs).map(input => input.value.trim()).filter(value => value !== '');
            
            return {
                id: item.id,
                text: questionInput.value,
                options: options,
                previousQuestion: previousQuestionSelect ? previousQuestionSelect.value : '',
                previousOption: previousOptionSelect ? previousOptionSelect.value : '',
                position: index
            };
        });
        
        // Update hidden input with current order as JSON
        orderInput.value = JSON.stringify(data);
    }
    
    /**
     * Updates the items counter
     */
    function updateItemsCount() {
        const count = container.querySelectorAll('.sortable-item').length;
        
        if (itemsCount) {
            itemsCount.textContent = count;
        }
        
        // Show or hide empty state
        if (emptyState) {
            if (count === 0) {
                emptyState.style.display = 'block';
            } else {
                emptyState.style.display = 'none';
            }
        }
    }
    
    /**
     * Loads saved replies from the hidden input 
     */
    function loadSavedReplies() {
        try {
            // Clear existing items first
            container.innerHTML = '';
            
            // Try to parse the JSON string from the hidden input
            let savedReplies = [];
            const savedValue = orderInput.value.trim();
            
            if (savedValue) {
                try {
                    savedReplies = JSON.parse(savedValue);
                    
                    // Check if it's valid array format
                    if (!Array.isArray(savedReplies)) {
                        throw new Error('Not an array');
                    }
                } catch (e) {
                    console.warn('Invalid JSON in quick replies, trying to fix', e);
                    
                    // Try to handle legacy format (string array)
                    if (savedValue.startsWith('[') && savedValue.endsWith(']')) {
                        try {
                            // Handle legacy array of strings
                            const legacyItems = JSON.parse(savedValue);
                            if (Array.isArray(legacyItems)) {
                                savedReplies = legacyItems.map(item => {
                                    if (typeof item === 'string') {
                                        return { 
                                            id: 'item-' + Date.now() + Math.random().toString(36).substr(2, 5), 
                                            text: item,
                                            options: [''], // Default single option
                                            previousQuestion: '',
                                            previousOption: ''
                                        };
                                    }
                                    return item;
                                });
                            }
                        } catch (e2) {
                            console.error('Failed to parse legacy format', e2);
                            savedReplies = [];
                        }
                    }
                }
            }
            
            // Create items for each saved reply
            if (savedReplies.length > 0) {
                // First, create all items
                const createdItems = [];
                
                savedReplies.forEach(reply => {
                    if (typeof reply === 'object' && reply.text) {
                        // Ensure options exist, default to single empty option
                        if (!reply.options || !Array.isArray(reply.options)) {
                            reply.options = [''];
                        }
                        // Ensure previousOption exists
                        if (!reply.hasOwnProperty('previousOption')) {
                            reply.previousOption = '';
                        }
                        const item = addQuickReply(reply);
                        if (item) {
                            createdItems.push(item);
                        }
                    } else if (typeof reply === 'string' && reply.trim()) {
                        // Legacy string format
                        const item = addQuickReply({ 
                            text: reply,
                            options: [''], // Default single option
                            previousQuestion: '',
                            previousOption: ''
                        });
                        if (item) {
                            createdItems.push(item);
                        }
                    }
                });
                
                // Update select options now that all items exist
                updateSelectOptions();
                
                // Now set all previousQuestion and previousOption values
                savedReplies.forEach((reply, index) => {
                    if (reply.previousQuestion && index < createdItems.length) {
                        const previousQuestionSelect = createdItems[index].querySelector('.previous-question-select');
                        if (previousQuestionSelect) {
                            previousQuestionSelect.value = reply.previousQuestion;
                            // Update the previous option dropdown for this question
                            updatePreviousOptionDropdown(createdItems[index].id, reply.previousQuestion);
                        }
                    }
                    if (reply.previousOption && index < createdItems.length) {
                        const previousOptionSelect = createdItems[index].querySelector('.previous-option-select');
                        if (previousOptionSelect) {
                            // Small delay to ensure the options are populated first
                            setTimeout(() => {
                                previousOptionSelect.value = reply.previousOption;
                            }, 100);
                        }
                    }
                });
            }
            
            // Update UI states
            updateItemsCount();
            
            // Save order to ensure format is correct
            saveOrder();
            
        } catch (error) {
            console.error('Error loading quick replies:', error);
            // Reset to empty array in case of error
            orderInput.value = '[]';
        }
    }
    
    // Initialize with existing items
    loadSavedReplies();
    
    // Set up global event listener for dynamically added selects
    container.addEventListener('change', function(e) {
        if (e.target.classList.contains('previous-question-select')) {
            const itemId = e.target.closest('.sortable-item').id;
            updatePreviousOptionDropdown(itemId, e.target.value);
            saveOrder();
        } else if (e.target.classList.contains('previous-option-select')) {
            saveOrder();
        }
    });
  }

  /**
   * Initializes lead export functionality
   * Handles CSV export of leads
   * Only available for premium users
   */
  function initializeLeadExport() {
    const leadExportButton = safeQuerySelector("#leadExportButton");
    const leadExportAlert = safeQuerySelector("#lead-export-alert");

    if (!leadExportButton || !config.isPremium) {
      return;
    }

    safeAddEventListener(leadExportButton, "click", async function (e) {
      e.preventDefault();

      leadExportButton.disabled = true;
      leadExportButton.textContent = "Exporting...";

      try {
        const formData = new FormData();
        formData.append("action", "botami_export_lead_data");
        formData.append("nonce", window.botamiLocalizedStringsAdmin.lead_export_nonce);

        const response = await fetch(window.botamiLocalizedStringsAdmin.ajax_url, {
          method: "POST",
          body: formData,
        });

        const data = await response.json();

        if (data.success) {
          const csvContent = atob(data.data.content);
          const blob = new Blob([csvContent], {
            type: "text/csv;charset=utf-8;",
          });
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = data.data.filename;
          link.click();
        } else {
          throw new Error(data.data || "Export failed");
        }
      } catch (error) {
        console.error("Lead export error:", error);
        if (leadExportAlert) {
          leadExportAlert.classList.remove("btm-hidden");
          leadExportAlert.innerText =
            error.message || "Export failed. Please try again.";

          setTimeout(() => {
            leadExportAlert.classList.add("btm-hidden");
          }, 5000);
        }
      } finally {
        leadExportButton.disabled = false;
        leadExportButton.textContent = "Export Leads (CSV)";
      }
    });
  }

  /**
   * Enhances the Quick Replies lead form selector by:
   * 1. Filtering the dropdown to only show end-node quick replies
   * 2. Completely hiding non-end node options
   */
  function initializeLeadFormSelector() {

    if (!config.isPremium) {
        const selector = document.getElementById("botami_lead_gen_quick_reply");
        if (selector) {
            selector.disabled = true;
            selector.classList.add('btm-premium-component');
        }
        return;
    }
    // Get the selector element
    const selector = document.getElementById("botami_lead_gen_quick_reply");
    if (!selector) return;

    // Get the current quick replies configuration
    let quickReplies = [];
    const quickRepliesInput = document.getElementById("quick_replies_order");

    if (quickRepliesInput && quickRepliesInput.value) {
        try {
            quickReplies = JSON.parse(quickRepliesInput.value);
            // Track changes to quick reply ordering
            quickRepliesInput.addEventListener("change", filterEndNodeOptions);
        } catch (e) {
            console.error("Failed to parse quick replies JSON", e);
        }
    }

    /**
     * Filters the options to only show end-node quick replies
     * An end-node is a question that either:
     * 1. Has no questions that reference it as a previous question, OR
     * 2. Has questions that reference it, but those questions specify particular answer options
     */
    function filterEndNodeOptions() {
        // Parse current quick replies data
        let currentReplies = [];
        try {
            if (quickRepliesInput.value) {
                currentReplies = JSON.parse(quickRepliesInput.value);
            }
        } catch (e) {
            console.error("Failed to parse updated quick replies JSON", e);
            currentReplies = [];
        }

        // Get current selected value
        const currentValue = selector.value;

        // Create a map of question ID to its answer options
        const questionOptionsMap = new Map();
        currentReplies.forEach(reply => {
            if (reply.options && Array.isArray(reply.options)) {
                questionOptionsMap.set(reply.id, reply.options.length);
            }
        });

        // Find all questions that are referenced as previous questions
        const referencedQuestions = new Map(); // questionId -> Set of option indices
        currentReplies.forEach(reply => {
            if (reply.previousQuestion) {
                if (!referencedQuestions.has(reply.previousQuestion)) {
                    referencedQuestions.set(reply.previousQuestion, new Set());
                }
                
                // If this question specifies a previous option, add it to the set
                if (reply.previousOption !== undefined && reply.previousOption !== '') {
                    referencedQuestions.get(reply.previousQuestion).add(parseInt(reply.previousOption));
                }
            }
        });

        // Determine end nodes
        const endNodes = currentReplies.filter(reply => {
            // If this question is not referenced at all, it's an end node
            if (!referencedQuestions.has(reply.id)) {
                return true;
            }
            
            // If this question is referenced, check if all its options are covered
            const referencedOptions = referencedQuestions.get(reply.id);
            const totalOptions = questionOptionsMap.get(reply.id) || 0;
            
            // If no specific options are referenced (empty set), this question leads to a generic next question
            // In this case, it's not an end node
            if (referencedOptions.size === 0) {
                return false;
            }
            
            // If some but not all options are referenced, this question has some paths that end
            // We'll consider it an end node if there are unreferenced options
            const hasUnreferencedOptions = referencedOptions.size < totalOptions;
            return hasUnreferencedOptions;
        });

        // Store the current selection
        let currentSelection = selector.value;

        // Clear all options except the first one (which is "None")
        while (selector.options.length > 1) {
            selector.remove(1);
        }

        // Add only end node options
        endNodes.forEach((node) => {
            const option = document.createElement("option");
            option.value = node.id;
            option.textContent = node.text;
            selector.appendChild(option);
        });

        // Add warning if no end nodes are available
        if (endNodes.length === 0 && currentReplies.length > 0) {
            const option = document.createElement("option");
            option.disabled = true;
            option.textContent = "-- No end nodes available --";
            selector.appendChild(option);
        }

        // Create a set of end node IDs for easier lookups
        const endNodeIds = new Set(endNodes.map((node) => node.id));

        // Restore selection if it was an end node
        if (endNodeIds.has(currentSelection)) {
            selector.value = currentSelection;
        }

        // If current selection is not an end node but we had a value, add it with a warning
        if (
            currentSelection &&
            !endNodeIds.has(currentSelection) &&
            currentSelection !== ""
        ) {
            // Find the text for this option
            const currentReply = currentReplies.find(
                (reply) => reply.id === currentSelection
            );
            if (currentReply) {
                const option = document.createElement("option");
                option.value = currentSelection;
                option.textContent = `${currentReply.text} (Warning: not an end node)`;
                option.className = "btm-text-red-600 btm-font-bold";
                selector.appendChild(option);
                selector.value = currentSelection;
            }
        }
    }

    // Initialize
    filterEndNodeOptions();

    // Add listener to quick reply container to detect changes
    const quickRepliesContainer = document.querySelector(
        ".quick-replies-container"
    );
    if (quickRepliesContainer) {
        // Use MutationObserver to detect when quick replies are added or removed
        const observer = new MutationObserver(filterEndNodeOptions);
        observer.observe(quickRepliesContainer, {
            childList: true,
            subtree: true,
        });
    }

    // Listen for changes to previous-question selects
    document.addEventListener("change", function (e) {
        if (e.target.classList.contains("previous-question-select") || 
            e.target.classList.contains("previous-option-select")) {
            setTimeout(filterEndNodeOptions, 100); // Small delay to let the data update
        }
    });
  }
  
  function disableRestrictedElements() {
      // Désactiver les éléments premium-component pour les non-Premium
      if (!config.isPremium) {
          const premiumElements = document.querySelectorAll('.premium-component');
          premiumElements.forEach(element => {
              if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
                  element.disabled = true;
              } else if (element.tagName === 'BUTTON') {
                  element.disabled = true;
              }
              
              // Empêcher les clics sur tous les éléments premium
              element.addEventListener('click', function(e) {
                  e.preventDefault();
                  e.stopPropagation();
              });
          });
      }
      
      // Désactiver les éléments pro-component pour les non-Pro
      if (!config.isPro) {
          const proElements = document.querySelectorAll('.pro-component');
          proElements.forEach(element => {
              if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
                  element.disabled = true;
              } else if (element.tagName === 'BUTTON') {
                  element.disabled = true;
              }
              
              // Empêcher les clics sur tous les éléments pro
              element.addEventListener('click', function(e) {
                  e.preventDefault();
                  e.stopPropagation();
              });
          });
      }
  }

  // Initialize all components with individual error handling
  // This ensures one failing component doesn't break the rest
  const initFunctions = [
    { name: 'Tabs', fn: initializeTabs },
    { name: 'API Verification', fn: initializeApiVerification },
    { name: 'Char Counter', fn: initializeCharCounter },
    { name: 'Export', fn: initializeExport },
    { name: 'File Upload', fn: initializeFileUpload },
    { name: 'URL Management', fn: initializeUrlManagement },
    { name: 'Bot Image Upload', fn: initializeBotImageUpload },
    { name: 'Quick Replies', fn: initializeQuickReplies },
    { name: 'Lead Export', fn: initializeLeadExport },
    { name: 'Logo Selector', fn: initializeLogoSelector },
    { name: 'Lead Form Selector', fn: initializeLeadFormSelector },
    { name: 'Restricted Elements', fn: disableRestrictedElements }
  ];

  initFunctions.forEach(({ name, fn }) => {
    try {
      fn();
    } catch (error) {
      console.warn(`Failed to initialize ${name}:`, error);
    }
  });
}
// Wait for DOM content to load
document.addEventListener("DOMContentLoaded", initializeAdminPanel);

document.addEventListener("DOMContentLoaded", function () {
  // Récupération des éléments d'entrée de couleur
  const primaryColorInput = document.getElementById(
    "botami_primary_color_text"
  );
  const primaryColorPicker = document.getElementById("botami_primary_color");
  const secondaryColorInput = document.getElementById(
    "botami_secondary_color_text"
  );
  const secondaryColorPicker = document.getElementById(
    "botami_secondary_color"
  );

  // Récupération des éléments de prévisualisation dans l'interface d'administration
  const chatbotHeader = document.getElementById("chatbot-header");
  const botMessageGradient = document.getElementById("bot-message-gradient");
  const previewReloadButton = document.getElementById("preview-reload-button");
  const sendButton = document.getElementById("send-button");

  // Vérification des éléments d'en-tête
  const headerElements = document.querySelectorAll(
    "#chatbot-header h4, #chatbot-header p, #chatbot-header .text-smal, #chatbot-header a"
  );

  // Fonction pour générer le gradient exactement comme demandé
  function getGradient(primaryColor, secondaryColor) {
    return `linear-gradient(90deg, ${primaryColor} 0%, ${secondaryColor} 100%)`;
  }

  // Fonction pour mettre à jour le texte de l'en-tête et du statut
  function updateHeaderText() {
    // Mettre à jour la couleur du texte dans l'en-tête
    if (headerElements && headerElements.length > 0) {
      headerElements.forEach((element) => {
        element.style.color = "white";
      });
    }
  }

  // Fonction pour mettre à jour tous les éléments avec le gradient
  function updateAllElements(primaryColor, secondaryColor) {
    const gradient = getGradient(primaryColor, secondaryColor);

    // Mise à jour de la prévisualisation dans l'interface d'administration
    if (chatbotHeader) {
      chatbotHeader.style.background = gradient;
    }

    if (botMessageGradient) {
      botMessageGradient.style.background = gradient;
      botMessageGradient.style.color = "white";
    }

    if (previewReloadButton) {
      previewReloadButton.style.background = gradient;
      previewReloadButton.style.color = "white";
    }

    if (sendButton) {
      sendButton.style.background = gradient;
    }

    // Mise à jour des éléments qui pourraient être générés dynamiquement
    const style = document.createElement("style");
    style.textContent = `
            .message.user-message {
                background: ${gradient} !important;
                color: white;
            }
            .btn-refresh {
                background: ${gradient} !important;
                color: white;
            }
            #chatbot-send {
                background: ${gradient} !important;
                color: white;
            }
            .btn_submit_lead {
                background: ${gradient} !important;
                color: white;
            }
            #refreshbtn {
                background: ${gradient} !important;
                color: white;
            }
        `;

    // Supprimer l'ancienne feuille de style si elle existe
    const oldStyle = document.getElementById("dynamic-gradient-styles");
    if (oldStyle) {
      oldStyle.remove();
    }

    // Ajouter la nouvelle feuille de style
    style.id = "dynamic-gradient-styles";
    document.head.appendChild(style);

    // S'assurer que le texte reste lisible
    updateHeaderText();
  }

  // Mise à jour en temps réel des couleurs lors de la modification de la couleur primaire
  if (primaryColorInput && primaryColorPicker) {
    primaryColorInput.addEventListener("input", function () {
      const primaryColor = primaryColorInput.value;
      const secondaryColor = secondaryColorPicker.value;

      primaryColorPicker.value = primaryColor;
      updateAllElements(primaryColor, secondaryColor);
    });

    primaryColorPicker.addEventListener("input", function () {
      const primaryColor = primaryColorPicker.value;
      const secondaryColor = secondaryColorPicker.value;

      primaryColorInput.value = primaryColor;
      updateAllElements(primaryColor, secondaryColor);
    });
  }

  // Mise à jour en temps réel des couleurs lors de la modification de la couleur secondaire
  if (secondaryColorInput && secondaryColorPicker) {
    secondaryColorInput.addEventListener("input", function () {
      const primaryColor = primaryColorPicker.value;
      const secondaryColor = secondaryColorInput.value;

      secondaryColorPicker.value = secondaryColor;
      updateAllElements(primaryColor, secondaryColor);
    });

    secondaryColorPicker.addEventListener("input", function () {
      const primaryColor = primaryColorPicker.value;
      const secondaryColor = secondaryColorPicker.value;

      secondaryColorInput.value = secondaryColor;
      updateAllElements(primaryColor, secondaryColor);
    });
  }

  // Mise à jour des champs texte du formulaire et de la prévisualisation
  const headingTextInput = document.getElementById("heading-text-input");
  const previewHeadingText = document.getElementById("preview-heading-text");

  if (headingTextInput && previewHeadingText) {
    headingTextInput.addEventListener("input", function () {
      previewHeadingText.textContent = this.value;
    });
  }

  const onlineStatusInput = document.getElementById("online-status-input");
  const previewOnlineStatus = document.getElementById("preview-online-status");

  if (onlineStatusInput && previewOnlineStatus) {
    onlineStatusInput.addEventListener("input", function () {
      previewOnlineStatus.textContent = this.value;
    });
  }

  const reloadTextInput = document.getElementById("reload-text-input");

  if (reloadTextInput && previewReloadButton) {
    reloadTextInput.addEventListener("input", function () {
      previewReloadButton.textContent = this.value;
    });
  }

  const placeholderInput = document.getElementById("placeholder-input");
  const previewPlaceholder = document.getElementById("preview-placeholder");

  if (placeholderInput && previewPlaceholder) {
    placeholderInput.addEventListener("input", function () {
      previewPlaceholder.placeholder = this.value;
    });
  }

  const defaultMessageInput = document.getElementById("default-message-input");
  const previewDefaultMessage = document.getElementById(
    "preview-default-message"
  );

  if (defaultMessageInput && previewDefaultMessage) {
    defaultMessageInput.addEventListener("input", function () {
      previewDefaultMessage.textContent = this.value;
    });
  }

  // Écouteurs pour l'image du bot
  const botImageUrlInput = document.getElementById("botami_bot_image_url");
  const previewBotImage = document.getElementById("preview-bot-image");

  if (botImageUrlInput && previewBotImage) {
    botImageUrlInput.addEventListener("input", function () {
      previewBotImage.src = this.value;
    });
  }

  // Écouteurs pour les templates de logo
  const logoTemplates = document.querySelectorAll(".logo-template");

  if (logoTemplates.length > 0 && botImageUrlInput && previewBotImage) {
    logoTemplates.forEach(function (template) {
      template.addEventListener("click", function () {
        const logoUrl = this.getAttribute("data-logo");
        if (logoUrl) {
          botImageUrlInput.value = logoUrl;
          previewBotImage.src = logoUrl;
        }
      });
    });
  }

  // Prévisualisation de l'upload de fichier
  const fileInput = document.getElementById("file-input");
  const preview = document.getElementById("preview");
  const errorMessage = document.getElementById("error-message");

  if (fileInput && preview) {
    fileInput.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        const file = this.files[0];

        // Vérifier si c'est une image
        if (!file.type.match("image.*")) {
          if (errorMessage) {
            errorMessage.classList.remove("btm-hidden");
          }
          return;
        }

        if (errorMessage) {
          errorMessage.classList.add("btm-hidden");
        }

        const reader = new FileReader();

        reader.onload = function (e) {
          preview.src = e.target.result;
          preview.classList.remove("btm-hidden");

          // Mettre à jour également l'image de prévisualisation du bot
          if (previewBotImage) {
            previewBotImage.src = e.target.result;
          }
        };

        reader.readAsDataURL(file);
      }
    });
  }

  // Initialisation des couleurs au chargement de la page
  if (primaryColorPicker && secondaryColorPicker) {
    const primaryColor = primaryColorPicker.value;
    const secondaryColor = secondaryColorPicker.value;

    updateAllElements(primaryColor, secondaryColor);
  }
});

document.addEventListener("DOMContentLoaded", function () {
  const deleteButton = document.getElementById("delete-knowledge-file");
  const filesContainer = document.getElementById("knowledge-files-container");

  if (deleteButton && filesContainer) {
    deleteButton.addEventListener("click", function (e) {
      e.preventDefault();
      deleteKnowledgeFile();
    });
  }

  /**
   * Send AJAX request to delete the knowledge file
   */
  function deleteKnowledgeFile() {
    // Show loading state
    deleteButton.innerHTML =
      '<svg class="btm-animate-spin btm-h-5  btm-w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="btm-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="btm-opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>';
    deleteButton.disabled = true;

    // Send AJAX request to delete the file
    fetch(botamiLocalizedStringsAdmin.ajax_url, {
      method: "POST",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({
        action: "botami_delete_knowledge_file",
        nonce: botamiLocalizedStringsAdmin.file_upload_nonce,
      }),
    })
      .then((response) => response.json())
      .then((data) => {
        if (data.success) {
          // Show success message
          showMessage("File deleted successfully!", "success");

          // Hide the file container
          filesContainer.classList.add("btm-hidden");
        } else {
          // Show error message
          showMessage(data.data.message || "Error deleting file", "error");

          // Reset delete button
          deleteButton.innerHTML =
            '<svg xmlns="http://www.w3.org/2000/svg" class="btm-h-5  btm-w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" /></svg>';
          deleteButton.disabled = false;
        }
      })
      .catch((error) => {
        // Show error message
        showMessage("Error communicating with server", "error");
        console.error("Error:", error);

        // Reset delete button
        deleteButton.innerHTML =
          '<svg xmlns="http://www.w3.org/2000/svg" class="btm-h-5  btm-w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" /></svg>';
        deleteButton.disabled = false;
      });
  }

  /**
   * Show a message to the user
   * @param {string} message - The message to display
   * @param {string} type - The type of message (success or error)
   */
  function showMessage(message, type) {
    const fileComponentDiv = document.getElementById("file_component_div");
    if (!fileComponentDiv) return;

    const messageDiv = document.createElement("div");
    messageDiv.className = `btm-mb-4 btm-p-4 btm-rounded ${
      type === "success"
        ? "btm-bg-green-100 btm-text-green-700"
        : "btm-bg-red-100 btm-text-red-700"
    }`;
    messageDiv.textContent = message;

    fileComponentDiv.insertBefore(messageDiv, fileComponentDiv.firstChild);

    // Remove the message after 5 seconds
    setTimeout(() => {
      messageDiv.remove();
    }, 5000);
  }
});


document.addEventListener('DOMContentLoaded', function () {
  const primaryColorInput = document.getElementById('botami_primary_color_text');
  const primaryColorPicker = document.getElementById('botami_primary_color');
  const secondaryColorInput = document.getElementById('botami_secondary_color_text');
  const secondaryColorPicker = document.getElementById('botami_secondary_color');

  primaryColorInput.addEventListener('input', function () {
    primaryColorPicker.value = primaryColorInput.value;
  });

  secondaryColorInput.addEventListener('input', function () {
    secondaryColorPicker.value = secondaryColorInput.value;
  });

  primaryColorPicker.addEventListener('input', function () {
    primaryColorInput.value = primaryColorPicker.value;
  });

  secondaryColorPicker.addEventListener('input', function () {
    secondaryColorInput.value = secondaryColorPicker.value;
  });
});

// Date range validation for export functionality
document.addEventListener('DOMContentLoaded', function () {
  const startDateInput = document.getElementById('datepicker-range-start');
  const endDateInput = document.getElementById('datepicker-range-end');

  if (startDateInput && endDateInput) {
    // Update end date min value when start date changes
    startDateInput.addEventListener('change', function() {
      endDateInput.min = startDateInput.value;
    });

    // Update start date max value when end date changes
    endDateInput.addEventListener('change', function() {
      startDateInput.max = endDateInput.value;
    });
  }
});

function dataFileDnD() {
  return {
    files: [],
    fileDragging: null,
    fileDropping: null,
    humanFileSize(size) {
      const i = Math.floor(Math.log(size) / Math.log(1024));
      return (
        (size / Math.pow(1024, i)).toFixed(2) * 1 +
        " " +
        ["B", "kB", "MB", "GB", "TB"][i]
      );
    },
    remove(index) {
      let files = [...this.files];
      files.splice(index, 1);

      this.files = createFileList(files);
    },
    drop(e) {
      let removed, add;
      let files = [...this.files];

      removed = files.splice(this.fileDragging, 1);
      files.splice(this.fileDropping, 0, ...removed);

      this.files = createFileList(files);

      this.fileDropping = null;
      this.fileDragging = null;
    },
    dragenter(e) {
      let targetElem = e.target.closest("[draggable]");

      this.fileDropping = targetElem.getAttribute("data-index");
    },
    dragstart(e) {
      this.fileDragging = e.target
        .closest("[draggable]")
        .getAttribute("data-index");
      e.dataTransfer.effectAllowed = "move";
    },
    loadFile(file) {
      const preview = document.querySelectorAll(".preview");
      const blobUrl = URL.createObjectURL(file);

      preview.forEach((elem) => {
        elem.onload = () => {
          URL.revokeObjectURL(elem.src); // free memory
        };
      });

      return blobUrl;
    },
    addFiles(e) {
      const files = createFileList([...e.target.files]);
      this.files = files;
    },
  };
}