  //Function to setup terms of service modal
  function setupTermsOfServiceModal() {
    var termsCheckbox       = document.getElementById("terms_conditions");
    var acceptButton        = document.getElementById("accept_ai_app_terms_of_service");
    var oldTermsCheckbox    = document.getElementById("terms_of_service-old");
   
    var savePluginSetting   = document.getElementById("save_ai_app_plugin_settings_data");
    var termsOfServiceError = document.getElementById('terms_of_service-error');

    // Event listener for checkbox change
    termsCheckbox.addEventListener("change", function () {
      if (!termsCheckbox.checked) {
        alert(
          "Warning: If you uncheck this box, your app will be disabled."
        );
      }
    });
  
    // Event listener for accept button click
    acceptButton.addEventListener("click", function() {
      if (termsCheckbox.checked) {
        oldTermsCheckbox.checked = true; 
      }else {
        oldTermsCheckbox.checked = false;
      }
      termsOfServiceError.textContent = '';
      uploadTermCondition();
    });

  }

  var modal               = document.getElementById("terms_conditions_modal");
  var closeButton         = modal.querySelector(".btn-close");

  // Function to close the modal
  function closeModal() {
    modal.classList.remove("show"); 
    modal.style.display = "none"; 
    document?.body?.classList?.remove("modal-open"); 
    document.body.style.paddingRight = ""; 
    document?.querySelector(".modal-backdrop")?.remove(); 
  }
  
  // Call the setup function after the DOM is loaded
  setupTermsOfServiceModal();
  //================End terms of service modal js =========================

  
  
  function ai_app_onsite_show_terms_of_service() {
      const termsOfServiceModal = document.getElementById("terms_conditions_modal");
      const termsOfServiceButtons = document.getElementById("terms_conditions_button");
  
      const modalInstance = new bootstrap.Modal(termsOfServiceModal);
      modalInstance.show();

      setTimeout(() => {
        const scrollContainer = document.getElementById('terms_conditions_modal')?.querySelector('.modal-body');
        if (scrollContainer) {
            smoothScrollToBottom(scrollContainer, 1800); 
        }
      }, 500);
  
      termsOfServiceButtons.style.display = "flex";
  }

  function smoothScrollToBottom(element, duration = 1800) {
    const start = element.scrollTop;
    const end = element.scrollHeight - element.clientHeight;
    const distance = end - start;
    const startTime = performance.now();

    function easeInOutCubic(t) {
      return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
    }

    function step(currentTime) {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1); // progress: 0 → 1

      const ease = easeInOutCubic(progress);
      element.scrollTop = start + distance * ease;

      if (progress < 1) {
        requestAnimationFrame(step);
      }
    }

    requestAnimationFrame(step);
  }

  
  let isPluginSaveTriggered = false;
  let isSwitchChecked = false;
  
  //Start save plugin settings JS
  function ai_app_onsite_save_plugin_settings() {
      // Clear all previous error messages
      document.querySelectorAll('.fields-error').forEach(function(error) {
          error.textContent = '';
      });
  
      // Get form fields
      var terms_of_service = document.getElementById("terms_of_service-old").checked;
  
      // Collect error messages
      var errors = [];
      if (!terms_of_service) {
          errors.push('Please Agree to Terms of Service.');
          const modalElement = document.getElementById('terms_conditions_modal');
          const modalInstance = new bootstrap.Modal(modalElement);
          modalInstance.show();

          setTimeout(() => {
            const scrollContainer = document.getElementById('terms_conditions_modal')?.querySelector('.modal-body');
            if (scrollContainer) {
                smoothScrollToBottom(scrollContainer, 1200); 
            }
          }, 500);
  
  
          const termsOfServiceCheckbox = document.getElementById("terms-form-group");
          const divider = document.getElementById("divider");
          const termsOfServiceButtons = document.getElementById("terms_conditions_button");
  
          termsOfServiceCheckbox.style.display = "block";
          divider.style.display = "block";
          termsOfServiceButtons.style.display = "flex";
          isPluginSaveTriggered = true;
      }else {
        isPluginSaveTriggered = false;
      }
      
      // If there are errors, display them and return
      if (errors.length > 0) {
          errors.forEach(function(error) {
              if (error === 'Please Agree to Terms of Service.') {
                  document.getElementById('terms_of_service-error').textContent = error;
              }
          });
          return;
      }
    // Show loader
    var loader = document.getElementById('loader');
    loader.style.display = 'flex';
  
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            // Show success message
            var messageContainer = document.getElementById('Plugin-settings-msg-container');
            setTimeout(function() {
                loader.style.display = 'none';
  
                if (xhr.status === 200) {
                    // Handle the response from the server
                    var response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        messageContainer.innerHTML = '<span style="color: green;"> ' + response.data + '</span>';
                        ai_app_onsite_get_plugin_settings();
                    }else{
                        messageContainer.innerHTML = '<span style="color: red;">Error: ' + response.error + '</span>';
                    }
                } else {
                    messageContainer.innerHTML = '<span style="color: red;">Error: Failed to save data</span>';
                }
                // Hide message after 3 seconds
                setTimeout(function() {
                    messageContainer.innerHTML = '';
                }, 3000);
            }, 2000);
        }
    };
  
    xhr.open('POST', myPluginAjax.ajaxurl, true);
  
    var formData = new FormData();
      formData.append('action', 'ai_app_onsite_save_plugin_settings');
      formData.append('terms_of_service', document.getElementById("terms_of_service-old") ? document.getElementById("terms_of_service-old").checked : false);
      formData.append('app_selector', document.getElementById("app_selector") ? document.getElementById("app_selector").value : "");
      formData.append('app_email', document.getElementById("app_email") ? document.getElementById("app_email").value : "");
  
      // Gather selected banned words
      var bannedWordsSelect = document.querySelector('[data-multi-select-plugin]');
      var selectedOptions = bannedWordsSelect.selectedOptions;
      var banned_words = [];
      let selectedLabels = document.querySelectorAll('.selected-wrapper .selected-label');
  
        // Loop through each of the selected labels
      selectedLabels.forEach(function(label) {
          banned_words.push(label.textContent);
      });
      // Append each banned word to the formData object
      for (var j = 0; j < banned_words.length; j++) {
          formData.append('banned_words[]', banned_words[j]);
      }
  
  
      // Append the CSV file
      const fileInput = document.getElementById('csv-upload');
      if (fileInput.files.length > 0) {
          const file = fileInput.files[0];
          formData.append('csv-file', file);
      }
  
      // Append nonce field value
      formData.append('ai_app_onsite_plugin_settings_nonce_field', document.getElementById("ai_app_onsite_plugin_settings_nonce_field").value);
  
         
    xhr.send(formData);
  }
  
  //=======================End save plugin settings js===========================
  
  //Start get plugin setting from db js
  function ai_app_onsite_get_plugin_settings() {
      var xhr = new XMLHttpRequest();
  
      xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
              if (xhr.status === 200) {
                // Handle success response
                var response = JSON.parse(xhr.responseText);
                if (response.status === "404") {
                    return;
                };

                $accepted_version = response.tos_accepted_version;
                if ($accepted_version !== response.tos_current_version) {
                  ai_app_onsite_show_terms_of_service();
                }
  
                // Accessing the first object in the array
                var firstObject = response.result[0];
                  
                // Accessing properties of the first object
                var id = firstObject.id;
                var agreeTerms = firstObject.agree_terms;
                var appSelector = firstObject.app_selector;
                var userStats = firstObject.user_stats;
                var bannedWords = firstObject.banned_words;
                var bannedWordsCSV = firstObject.banned_words_csv;
                var appName = firstObject.appName;
                const selectElement = document.getElementById("bannedWords");
                
                var app_email = firstObject.app_email;
  
                // Assume selectElement is already defined as your target select element
                bannedWordsCSV.forEach((item) => {
                  // Check if an option with the same value already exists
                  const exists = Array.from(selectElement.options).some(
                    (option) => option.value === item[0]
                  );
  
                  if (!exists) {
                    // Create a new option element
                    const option = document.createElement("option");
  
                    // Set the value and text of the option element
                    option.value = item[0];
                    option.text = item[0];
  
                    // Append the option element to the select element
                    selectElement.appendChild(option);
                  }
  
                  const optionToSelect = Array.from(selectElement.options).find(
                    (option) => option.value === item[0]
                  );
                  if (optionToSelect) {
                    optionToSelect.selected = true;
                  }
                });
  
                if (
                  appName != null &&
                  appName !== "" &&
                  appName !== "undefined"
                ) {
                  var selectElements = document.getElementById("app_selector");
                  selectElements.value = appName;
                }
                var app_emails = document.getElementById("app_email");
                app_emails.value = app_email;
  
                // Set checkbox checked if agreeTerms is "1"
                if (agreeTerms === "1") {
                  document.getElementById("terms_of_service-old").checked = true;
                  document.getElementById("terms_conditions").checked = true;
                  // Ensure the modal is not triggered
                }else {
                    document.getElementById("terms_of_service-old").checked = false;
                    document.getElementById("terms_conditions").checked = false;
                }
  
                var searchContainer = document.querySelector(".search-container");
  
                var searchContainer = document.querySelector(".search-container"); // Ensure the selector is correct
                if (!searchContainer) {
                  console.error("searchContainer element not found!");
                  return; // Exit if the container is missing
                }
                bannedWords.forEach(function (value) {
                  if (value) {
                    // Ensure value is not empty or falsy
                    var exists = document.querySelector(
                      '.selected-wrapper span.selected-label[data-value="' +
                        value +
                        '"]'
                    );
                    if (!exists) {
                      // Create new elements only if the value is not empty and doesn't already exist
                      var newDiv = document.createElement("div");
                      newDiv.className = "selected-wrapper";
  
                      var labelSpan = document.createElement("span");
                      labelSpan.className = "selected-label";
                      labelSpan.textContent = value;
                      labelSpan.setAttribute("data-value", value);
  
                      var closeLink = document.createElement("a");
                      closeLink.className = "selected-close";
                      closeLink.setAttribute("tabindex", "-1");
                      closeLink.setAttribute("data-option", value);
                      closeLink.setAttribute("data-hits", "0");
                      closeLink.href = "#";
                      closeLink.textContent = "x";
  
                      newDiv.appendChild(labelSpan);
                      newDiv.appendChild(closeLink);
                      searchContainer.before(newDiv); // Ensure searchContainer exists before this line
                    }
                  }
                });
  
                document
                  .querySelectorAll(".selected-wrapper")
                  .forEach((wrapper) => {
                    const label = wrapper.querySelector(".selected-label");
                    if (!label.hasAttribute("data-value")) {
                      wrapper.remove();
                    }
                  });
  
                // Event listener for the dropdown icon click
                const dropdownIcon = document.querySelector(".dropdown-icon");
                if (dropdownIcon) {
                  dropdownIcon.addEventListener("click", function () {
                    if (this.classList.contains("active")) {
                      document
                        .querySelectorAll(".selected-wrapper .selected-label")
                        .forEach(function (element) {
                          var valueToRemove = element.textContent.trim();
                          document
                            .querySelectorAll(".autocomplete-list li")
                            .forEach(function (liElement) {
                              if (
                                liElement.textContent.trim() === valueToRemove
                              ) {
                                liElement.parentNode.removeChild(liElement);
                              }
                            });
                        });
                    } else {
                      console.log("Dropdown icon is not active");
                    }
                  });
                } else {
                  console.log("Dropdown icon not found");
                }
              } else {
                  // Handle error response
                  alert('Error occurred: ' + xhr.responseText);
              }
  
              const appSettingsformTracker = trackFormChanges('#app_settings_form');
              window.FormChangeRegistry.register('app_settings', appSettingsformTracker, 'app-settings');
  
              document.getElementById('save_ai_app_plugin_settings_data').addEventListener('click', function () {
                  appSettingsformTracker.reset(); 
              });
  
             
          }
      };
  
      xhr.open('POST', myPluginAjax.ajaxurl, true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
      xhr.send('action=ai_app_onsite_get_plugin_settings');
  
      ai_app_onsite_get_app_license_key();
      ai_app_disable_select_options();

  }

  function ai_app_disable_select_options() {
      const sel = document.getElementById('ai_app_onsite-user-stats');
      // Disable every option with value="#"
      Array.from(sel.options).forEach(opt => {
          if (opt.value === '#') opt.disabled = true;
      });
  }
  
  /*=============End get plugin setting from db js============================== */
  
  
  /*=============Download terms Of service js=================================== */
  
  function ai_app_onsite_download_terms_Of_service() {
      const { jsPDF } = window.jspdf;
      const doc = new jsPDF();
      const termsContent = document.getElementById('terms-conditions-modal-pdf').innerText;
  
      const maxWidth = 180; // Maximum width for text in mm
          const startX = 10; // X-coordinate to start text
          const startY = 10; // Y-coordinate to start text
          const lineHeight = 4.5; // Approximate line height in mm
          const pageHeight = 297; // A4 page height in mm (210x297mm)
          const marginBottom = 10; // Bottom margin
  
          let cursorY = startY; // Track current Y-coordinate
  
          // Set font size
          const fontSize = 12; // Set the font size as desired
          doc.setFontSize(fontSize);
  
          // Split text into lines that fit within the specified max width
          const lines = doc.splitTextToSize(termsContent, maxWidth);
  
          // Add the lines of text to the PDF
          lines.forEach(line => {
              if (cursorY + lineHeight > pageHeight - marginBottom) {
                  // Add new page if the text exceeds the page height
                  doc.addPage();
                  cursorY = startY; // Reset cursorY for new page
              }
              doc.text(line, startX, cursorY);
              cursorY += lineHeight * (fontSize / 10); // Adjust cursorY based on font size
          });
      doc.save('AIappOniste-terms-of-service.pdf');
  }
  
  /*=============End download terms Of service js=================================== */


/**
 * Download the user stats
 */
function ai_app_onsite_download_user_stats(event) {
    event.preventDefault();

    // DOM Elements
    const loader = document.getElementById("loader");
    const durationSelect = document.getElementById("ai_app_onsite-user-stats");
    const userStatsError = document.getElementById("ai_app_onsite-user-stats-error");
    const messageContainer = document.getElementById("Plugin-settings-msg-container");

    // Show loader
    loader.style.display = "flex";
    userStatsError.textContent = "";
    messageContainer.innerHTML = "";

    const duration = durationSelect.value;
    const nonce = myPluginAjax.downloadUserStatsNonce;

    const available_durations = [
        'today',
        'last_7_days',
        'current_month',
        'last_month'
    ];

    if (!available_durations.includes(duration)) {
        userStatsError.textContent = "Error: Invalid duration selected. Please select a valid duration.";
        loader.style.display = "none";
        setTimeout(() => { messageContainer.innerHTML = ""; }, 3000);
        return;
    }

    // Prepare FormData
    const data = new FormData();
    data.append("action", "ai_app_onsite_download_user_stats");
    data.append("ai_app_onsite_download_user_stats_nonce", nonce);
    data.append("duration", duration);

    fetch(ajaxurl, {
        method: "POST",
        body: data,
    })
        .then(async (response) => {
            const contentType = response.headers.get("content-type");

            // Detect if it's JSON (error from wp_send_json_error)
            if (contentType && contentType.includes("application/json")) {
                const json = await response.json();
                throw new Error(json.data?.message || "No user statistics found.");
            }

            // Otherwise treat as CSV (successful case)
            const blob = await response.blob();

            // Download file
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.style.display = "none";
            a.href = url;
            a.download = "AIappOnsite_User_Stats.csv";
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);

            // Show success message
            messageContainer.innerHTML =
                '<span style="color: green;">User stats downloaded successfully</span>';
        })
        .catch((error) => {
            userStatsError.textContent = "Error: " + error.message;
        })
        .finally(() => {
            // Always hide loader after 2 seconds
            setTimeout(() => {
                loader.style.display = "none";
                setTimeout(() => {
                    messageContainer.innerHTML = "";
                }, 3000);
            }, 2000);
        });
}
  
  //upload file js
  function validateCSVFile(input) {
      var file = document.getElementById('csv-upload').files[0];
      var fileError = document.getElementById('fileError');
      // Check if file is selected
      if (!file) {
          fileError.textContent = 'Please select a file.';
         return;
      }
  
      // Check file type
      var validExtensions = ['text/csv'];
      if (!validExtensions.includes(file.type)) {
          fileError.textContent = 'Please select a valid image file (SVG, PNG, JPG, or GIF).';
          this.value = ''; // Clear the input field
        
          return;
      }
  
      fileError.textContent = ''; // Clear any previous errors
  
         uploadCSVFile(file);
           // Reset input value to allow same file to be selected again
      input.value = '';
  }
  
  
  function uploadCSVFile(file) {
      var formData = new FormData();
      formData.append('csv-file', file);
      formData.append('action', 'ai_app_onsite_handle_csv_upload');
      formData.append('ai_app_onsite_plugin_settings_nonce_csv_upload_field', document.getElementById("ai_app_onsite_plugin_settings_nonce_field").value);
  
      var xhr = new XMLHttpRequest();
      xhr.open('POST', myPluginAjax.ajaxurl, true);
      
      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) { // Ensure the request is complete
              if (xhr.status === 200) {
  
                  if (xhr.responseText) { // Check if the response text is not empty
                      try {
                          var response = JSON.parse(xhr.responseText);
                          var messageContainer = document.getElementById('Plugin-settings-msg-container');
                          if (messageContainer) {
                              if (response.success) {
                                  messageContainer.innerHTML = '<span style="color: green;">' + response.data + '</span>';
                              } else {
                                  messageContainer.innerHTML = '<span style="color: red;">Error: ' + response.error + '</span>';
                              }
                               ai_app_onsite_get_plugin_settings();    
  
                          } else {
                              console.error('messageContainer element not found');
                          }
                      } catch (e) {
                          console.error('Failed to parse response:', e);
                          var messageContainer = document.getElementById('messageContainer');
                          if (messageContainer) {
                              messageContainer.innerHTML = '<span style="color: red;">Error parsing response</span>';
                          } else {
                              console.error('messageContainer element not found');
                          }
                      }
                  } else {
                      console.error('Empty response');
                      var messageContainer = document.getElementById('messageContainer');
                      if (messageContainer) {
                          messageContainer.innerHTML = '<span style="color: red;">Empty response</span>';
                      } else {
                          console.error('messageContainer element not found');
                      }
                  }
              } else {
                  console.error('Request failed with status:', xhr.status);
                  var messageContainer = document.getElementById('messageContainer');
                  if (messageContainer) {
                      messageContainer.innerHTML = '<span style="color: red;">Error: ' + xhr.status + '</span>';
                  } else {
                      console.error('messageContainer element not found');
                  }
              }
              // Hide message after 3 seconds
              setTimeout(function() {
                  messageContainer.innerHTML = '';
              }, 3000);
  
  
          }
      };
  
      xhr.send(formData);
  }
  
  function uploadTermCondition() {
      var terms_of_service = document.getElementById("terms_conditions").checked;
      var terms_of_service_nonce = document.getElementById("ai_app_onsite_plugin_settings_nonce_field").value;

      var xhr = new XMLHttpRequest(); // Initialize the XMLHttpRequest object
      xhr.open('POST', myPluginAjax.ajaxurl, true);

      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Set the request header
  
      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) { // Ensure the request is complete
              var messageContainer = document.getElementById('Plugin-settings-msg-container') || document.getElementById('messageContainer');
              if (xhr.status === 200) {
  
                  if (xhr.responseText) { // Check if the response text is not empty
                      try {
                          var response = JSON.parse(xhr.responseText);
                          if (messageContainer) {
                              if (response.success) {
                                  messageContainer.innerHTML = '<span style="color: green;">' + response.data + '</span>';
                              } else {
                                  messageContainer.innerHTML = '<span style="color: red;">Error: ' + response.error + '</span>';
                              }
                          } else {
                              console.error('messageContainer element not found');
                          }
                      } catch (e) {
                          console.error('Failed to parse response:', e);
                          if (messageContainer) {
                              messageContainer.innerHTML = '<span style="color: red;">Error parsing response</span>';
                          } else {
                              console.error('messageContainer element not found');
                          }
                      }
                  } else {
                      console.error('Empty response');
                      if (messageContainer) {
                          messageContainer.innerHTML = '<span style="color: red;">Empty response</span>';
                      } else {
                          console.error('messageContainer element not found');
                      }
                  }
              } else {
                  console.error('Request failed with status:', xhr.status);
                  if (messageContainer) {
                      messageContainer.innerHTML = '<span style="color: red;">Error: ' + xhr.status + '</span>';
                  } else {
                      console.error('messageContainer element not found');
                  }
              }
  
              // Hide message after 3 seconds
              setTimeout(function() {
                  if (messageContainer) {
                      messageContainer.innerHTML = '';
                  }
                  closeModal(); // Close the modal
              }, 3000);
          }
      };
      
  
      xhr.send('action=ai_app_onsite_get_accept_terms_of_service&terms_of_service=' + terms_of_service+'&ai_app_onsite_plugin_settings_terms_of_service_nonce='+terms_of_service_nonce);
  }
  
  function toggleAppNameSelector() {
    setTimeout(function() {
      const app_selector_input_element = document.getElementById("app_selector");
      const appSelectorLabel           = document.querySelector(".app_selector_input_label");

      if (app_selector_input_element && app_selector_input_element.value != '') {
        appSelectorLabel.innerText         = "Edit App Name";
        app_selector_input_element.classList.remove('border-danger');
      } else {
        appSelectorLabel.innerHTML              = 'App Name <span class="text-danger">*</span>';
        app_selector_input_element.classList.add('border-danger');
        app_selector_input_element.setAttribute('placeholder', 'Please Enter Your App Name');
      }
    }, 2000);
  }
  
  document.addEventListener('DOMContentLoaded', function() {
      const licenseKeyInfoModal = document.getElementById("license_key_info_modal");
      const saveButton          = document.getElementById("active_ai_app_plugin_license_key");
      const disableKeyBtn       = document.getElementById("key-disable-btn");
      const messageContainer    = document.getElementById("app-license-msg-container");
      const keyInput            = document.getElementById('licence_key');
      const appNameInput        = document.getElementById("app_selector");
      const app_selector_error  = document.getElementById("app_selector-error");
  
      document.addEventListener('keydown', function(event) {
          if (event.key === 'Enter') {
              event.preventDefault();
          }
      });

       appNameInput.addEventListener("input", function () {
            const SHORTCODE_MAX = 300;
            const SUFFIX = "_aiao";

            let rawValue = appNameInput.value;
            let trimmedValue = rawValue.trim().replace(/\s+/g, ' ');

            // Generate shortcode as PHP does
            let shortcodePreview = trimmedValue
                .split(' ')
                .map(w => w.toLowerCase())
                .join('_') + SUFFIX;

            // If over limit, trim until valid
            if (shortcodePreview.length > SHORTCODE_MAX) {
                while (trimmedValue.length > 0) {
                    trimmedValue = trimmedValue.slice(0, -1);
                    shortcodePreview = trimmedValue
                        .trim()
                        .replace(/\s+/g, ' ')
                        .split(' ')
                        .map(w => w.toLowerCase())
                        .join('_') + SUFFIX;

                    if (shortcodePreview.length <= SHORTCODE_MAX) break;
                }
                appNameInput.value = trimmedValue;
                app_selector_error.textContent = "Character limit reached (shortcode limit 300)";
                app_selector_error.style.color = "red";
                return;
            }

            // Update remaining count
            if(rawValue != ''){
                const remaining = SHORTCODE_MAX - shortcodePreview.length;
                app_selector_error.textContent = `${remaining} characters left`;
                app_selector_error.style.color = "#555";
            }else {
                app_selector_error.textContent = '';
            }
        });

      const currentStatus = !disableKeyBtn.checked ? 'enabled' : 'disabled';
      disableKeyBtn.setAttribute('data-original-status', currentStatus);
  
      if (licenseKeyInfoModal) {
        let isHidingModal = false;
        let lastClickedElement = null;
        const modalContent = licenseKeyInfoModal.querySelector('.modal-content');
      
        const showUnsavedWarning = () => {
          saveButton?.classList.add("border-danger");
          messageContainer.innerHTML = '<span style="color: red;">You have unsaved changes, consider saving them.</span>';
        };
      
        const resetModalState = () => {
          isSwitchChecked = false;
          messageContainer.innerHTML = "";
          saveButton?.classList.remove("border-danger");
        };
      
        const handleCancelAction = () => {
          isHidingModal = true;
          if (isSwitchChecked) {
            disableKeyBtn.checked = !disableKeyBtn.checked;
            ai_app_onsite_disable_license_key();
          }
          resetModalState();
          jQuery(licenseKeyInfoModal).modal('hide');
          isHidingModal = false;
        };
      
        // Track the last clicked element
        document.addEventListener('mousedown', (event) => {
          lastClickedElement = event.target;
        });
      
      
        // Intercept dismiss logic
        licenseKeyInfoModal.addEventListener('hide.bs.modal', (event) => {
          if (isHidingModal) return;
      
          const isDismissButton = lastClickedElement?.getAttribute("data-bs-dismiss") === "modal";
          const isCancelButton = lastClickedElement?.id === "cancel";

          if (isDismissButton && isCancelButton) {
            handleCancelAction();
          } else if (isSwitchChecked && lastClickedElement?.textContent?.trim() && lastClickedElement?.textContent !== "Save") {
            event.preventDefault();
            showUnsavedWarning();
          }
        });
      }
  
      setTimeout(function() {
          const app_selector_input_element  = document.getElementById("app_selector");
  
          app_selector_input_element.addEventListener("input", function () {
            if (app_selector_input_element.value.trim() !== "") {
              app_selector_input_element.classList.remove("border-danger");
            } else {
              app_selector_input_element.classList.add("border-danger");
            }
          });
      }, 1000); 
  
      keyInput.addEventListener("input", function () {
          if (keyInput.value.trim() !== "") {
              saveButton?.removeAttribute('disabled');
          } else {
              saveButton?.setAttribute('disabled', 'true');
          }
      });
     
  
      // var button = document.getElementById("accept_ai_app_terms_of_service");
      // button.addEventListener("click", function () {
      //   var terms_of_service = document.getElementById("terms_conditions").checked;
      //   var terms_of_service_nonce = document.getElementById("ai_app_onsite_plugin_settings_nonce_field").value;
      //   var xhr = new XMLHttpRequest(); // Initialize the XMLHttpRequest object
      //   xhr.open("POST", myPluginAjax.ajaxurl, true);
      //   xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Set the request header
  
      //   var loader = document.getElementById("loader");
      //   loader.style.display = "flex";
  
      //   xhr.onreadystatechange = function () {
      //     if (xhr.readyState === 4) {
      //       // Ensure the request is complete
      //       var messageContainer =
      //         document.getElementById("Plugin-settings-msg-container") ||
      //         document.getElementById("messageContainer");
      //       if (xhr.status === 200) {
      //         if (xhr.responseText) {
      //           // Check if the response text is not empty
      //           try {
      //             var response = JSON.parse(xhr.responseText);
      //             if (messageContainer) {
      //               if (response.success) {
      //                 if (isPluginSaveTriggered) {
      //                   setTimeout(function () {
      //                     ai_app_onsite_save_plugin_settings();
      //                   }, 1000);
      //                 } else {
      //                   loader.style.display = "none";
      //                   messageContainer.innerHTML =
      //                     '<span style="color: green;">' +
      //                     response.data +
      //                     "</span>";
      //                 }
      //               } else {
      //                 loader.style.display = "none";
      //                 messageContainer.innerHTML =
      //                   '<span style="color: red;">Error: ' +
      //                   response.error +
      //                   "</span>";
      //               }
      //             } else {
      //               loader.style.display = "none";
      //               console.error("messageContainer element not found");
      //             }
      //           } catch (e) {
      //             loader.style.display = "none";
      //             console.error("Failed to parse response:", e);
      //             if (messageContainer) {
      //               messageContainer.innerHTML =
      //                 '<span style="color: red;">Error parsing response</span>';
      //             } else {
      //               console.error("messageContainer element not found");
      //             }
      //           }
      //         } else {
      //           loader.style.display = "none";
      //           console.error("Empty response");
      //           if (messageContainer) {
      //             messageContainer.innerHTML =
      //               '<span style="color: red;">Empty response</span>';
      //           } else {
      //             console.error("messageContainer element not found");
      //           }
      //         }
      //       } else {
      //         loader.style.display = "none";
      //         console.error("Request failed with status:", xhr.status);
      //         if (messageContainer) {
      //           messageContainer.innerHTML =
      //             '<span style="color: red;">Error: ' + xhr.status + "</span>";
      //         } else {
      //           console.error("messageContainer element not found");
      //         }
      //       }
  
      //       // Hide message after 3 seconds
      //       setTimeout(function () {
      //         if (messageContainer) {
      //           messageContainer.innerHTML = "";
      //         }
      //       }, 3000);
      //     }
      //   };
  
      //   xhr.send(
      //     "action=ai_app_onsite_get_accept_terms_of_service&terms_of_service=" +
      //       terms_of_service +
      //       "&ai_app_onsite_plugin_settings_terms_of_service_nonce=" +
      //       terms_of_service_nonce
      //   );
      // });
  
      ai_app_onsite_get_plugin_settings();
  
      var licenseKeychange = document.getElementById('licence_key')
      if (licenseKeychange) {
          licenseKeychange.onchange = handleInputChange;
      }
  });
  /*=============End download user stats js=================================== */
  
  // LICENSE SETTING
  const keyNote              = document.getElementById('key_note');
  const licenseStatus        = document.getElementById('license_status');
  const loader               = document.getElementById('loader');
  const statusElem           = document.getElementById('license_key_status');
  const messageContainer     = document.getElementById('app-license-msg-container');
  const keyInput             = document.getElementById('licence_key');
  const keyInputHd           = document.getElementById('licence_key_hidden');
  const expiryElem           = document.getElementById('license_key_expiry_date');
  const keyDisableStatusElem = document.getElementById('license_key_disabled_status');
  const removeBtn            = document.getElementById('remove_ai_app_plugin_license_key');
  const expiryStatus         = document.getElementById('expiry_status');
  const keyStatus            = document.getElementById('key_status');
  const disableKeyBtn        = document.getElementById("key-disable-btn");
  const licenseTextSwitch    = document.getElementById('license-text-switch');
  
  function handleInputChange() {
    if (keyInput.value) {
      keyInputHd.value = keyInput.value;

      ai_app_onsite_app_verify_license_key();
    }
  }
  
  // Initial state
  setUIState('default');
  
  //====================
  // Helper Functions
  //====================
  
  function formatDate(dateString) {
      return new Date(dateString).toLocaleDateString('en-US', {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
      });
  }
  
  function ai_app_onsite_disable_license_key() {
      // Enable or diabled License key status
      const switch_status = disableKeyBtn.checked;
      if(switch_status){
          licenseTextSwitch.textContent = 'Enabled';
          licenseTextSwitch.style.color = 'green';
          isSwitchChecked = true; // Mark as toggled
      } else {
          licenseTextSwitch.textContent = 'Disabled';
          licenseTextSwitch.style.color = 'red';
          isSwitchChecked = true; // Mark as toggled
      }
  }
  
  function setUIState(state, data = {}) {
      switch (state) {
          case 'active':
          case 'inactive':
              const isActive = state === 'active';
              keyInput.disabled = true;
              licenseStatus.style.display = 'block';
              expiryStatus.style.display = 'block';
              keyStatus.style.display = 'block';
              statusElem.textContent = isActive ? 'ACTIVE' : 'EXPIRED';
              statusElem.style.color = isActive ? 'green' : 'red';
              keyNote.style.display = 'none';
              removeBtn.classList.toggle('d-flex', true);
              removeBtn.disabled = false;
              expiryElem.textContent = formatDate(data.expiry);
              keyDisableStatusElem.textContent = data.key_disable_status == 'false' ? 'Enabled' : 'Disabled';
              keyDisableStatusElem.style.color = data.key_disable_status == 'false' ? 'green' : 'red';
              disableKeyBtn.disabled = false;
              disableKeyBtn.checked = data.key_disable_status == 'false';
              licenseTextSwitch.textContent = data.key_disable_status == 'false' ? 'Enabled' : 'Disabled';
              licenseTextSwitch.style.color = data.key_disable_status == 'false' ? 'green' : 'red';
              break;
  
          case 'default':
          default:
              keyInput.disabled = false;
              keyInput.value = '';
              keyInputHd.value = '';
              licenseStatus.style.display = 'none';
              expiryStatus.style.display = 'none';
              keyStatus.style.display = 'none';
              keyNote.style.display = 'block';
              removeBtn.classList.toggle('d-flex', true);
              removeBtn.disabled = true;
              expiryElem.textContent = '';
              keyDisableStatusElem.textContent = '';
              disableKeyBtn.checked = false;
              disableKeyBtn.disabled = true;
              licenseTextSwitch.textContent = 'Disabled';
              licenseTextSwitch.style.color = 'red';
              break;
      }
  }
  
  function sendAjax(action, onSuccess) {
      const xhr = new XMLHttpRequest();
      xhr.open('POST', myPluginAjax.ajaxurl, true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  
      xhr.onreadystatechange = () => {
          if (xhr.readyState !== 4) return;
          if (xhr.status === 200) {
              try {
                  const response = JSON.parse(xhr.responseText);
                  onSuccess(response);
              } catch (err) {
                  console.error('Invalid JSON response:', err);
                  alert('Unexpected response from server.');
              }
          } else {
              alert(`Error: ${xhr.status} ${xhr.statusText}`);
          }
  
          const licenseFormTracker = trackFormChanges('#license-validation-form');
          window.FormChangeRegistry.register('license_settings', licenseFormTracker, 'app-settings');
  
          document.getElementById('active_ai_app_plugin_license_key').addEventListener('click', function () {
              licenseFormTracker.reset(); 
          });
      };
  
      xhr.send(`action=${encodeURIComponent(action)}`);
  }
  
  //====================
  // Fetch License Key
  //====================
  function ai_app_onsite_get_app_license_key() {
      const saveButton = document.getElementById("active_ai_app_plugin_license_key");
  
      sendAjax('ai_app_onsite_get_app_license_key', (response) => {
          if (response.status === '404') {
              saveButton?.setAttribute('disabled', 'true');
              return;
          }
  
          const { license_key, license_key_hd, key_status, subscription_expiry_date, key_disable_status } = response[0] || {};
   
          keyInput.value = license_key || '';
          keyInputHd.value = license_key_hd || '';
  
          if (key_status === 'ACTIVE') {
              saveButton?.removeAttribute('disabled');
              setUIState('active', { expiry: subscription_expiry_date, key_disable_status: key_disable_status });
          } else if (key_status === 'INACTIVE' && license_key) {
              saveButton?.removeAttribute('disabled');
              setUIState('inactive', { expiry: subscription_expiry_date, key_disable_status: key_disable_status });
          } else {
              saveButton?.setAttribute('disabled', 'true');
              setUIState('default');
          }
          toggleAppNameSelector();
      });
  }
  
  //====================
  // Remove License Key
  //====================
  function ai_app_onsite_app_remove_license_key() {
      if (confirm("Warning: Removing the premium access key may cause your existing app to lose functionality. All PLUS features will be disabled within 24 hours. Are you sure you want to proceed?")) {
          loader.style.display = 'flex';
  
          sendAjax('ai_app_onsite_app_remove_license_key', (response) => {
              loader.style.display = 'none';
              location.reload(true);
              setUIState('default');
          });
      }
  }
  
  //====================
  // Disable/Enable License Key
  //====================
  function ai_app_onsite_app_toggle_license_key_status(status) {
      loader.style.display = 'flex';
  
      const xhr = new XMLHttpRequest();
          xhr.open('POST', myPluginAjax.ajaxurl, true);
  
          xhr.onreadystatechange = () => {
              loader.style.display = 'none';
  
              if (xhr.readyState !== 4) return;
              if (xhr.status === 200) {
                  try {
                      const response = JSON.parse(xhr.responseText);
                  } catch (err) {
                      console.error('Invalid JSON response:', err);
                  }
              } else {
                  alert(`Error: ${xhr.status} ${xhr.statusText}`);
              }
          };
  
          const formData = new FormData();
          formData.append('action', 'ai_app_onsite_app_toggle_license_key_status');
          formData.append('status', status);
      
          xhr.send(formData);
  }
  
  
  //========[ Validate & Save License Key ]========//
function ai_app_onsite_app_verify_license_key(close_modal =  false) {
      const loader = document.getElementById('loader');
      const saveButton                  = document.getElementById("active_ai_app_plugin_license_key");
     
      let licenceKey = document.getElementById('licence_key').value.trim();
      const licenceKeyHidden = document.getElementById('licence_key_hidden').value.trim();
      if (licenceKeyHidden && licenceKeyHidden.trim() !== '') {
          licenceKey = licenceKeyHidden;
      }
      const status = !disableKeyBtn.checked ? 'true' : 'false';
      const nonce = document.getElementById("ai_app_onsite_app_verify_license_key_nonce_field").value;
  
      // Clear error messages
      document.querySelectorAll('.fields-error').forEach(el => el.textContent = '');
      loader.style.display = 'flex';
  
      const xhr = new XMLHttpRequest();
      xhr.open('POST', myPluginAjax.ajaxurl, true);
  
      xhr.onreadystatechange = () => {
          if (xhr.readyState !== 4) return;
  
        setTimeout(function () {
          loader.style.display = 'none';
  
          let response;
          try {
              response = JSON.parse(xhr.responseText);
          } catch (e) {
              messageContainer.innerHTML = `<span style="color: red;">Invalid server response</span>`;
              return;
          }
  
          if (xhr.status === 200) {
              if (response.success) {
                  saveButton?.classList.remove("border-danger");
                  ai_app_onsite_get_app_license_key();
                  messageContainer.innerHTML = `<span style="color: green;">${response.data}</span>`;
                  close_modal = true;
              } else {
                close_modal = false;
                messageContainer.innerHTML = `<span style="color: red;">Error: ${response.data}</span>`;
              }
          } else {
            close_modal = false;
            messageContainer.innerHTML = `<span style="color: red;">Error: Failed to verify data</span>`;
          }
  
          setTimeout(function () {
            if(close_modal){
                var modal = document.getElementById("license_key_info_modal");
                jQuery(modal).modal("hide");
                location.reload(true);
                messageContainer.innerHTML = "";
            }
           
          }, 3000);
        }, 2000);
      };
  
      const formData = new FormData();
      formData.append('action', 'ai_app_onsite_app_verify_license_key');
      formData.append('licence_key', licenceKey);
      formData.append('status', status);
      formData.append('ai_app_onsite_app_verify_license_key_nonce_field', nonce);
  
      xhr.send(formData);
  }
  
  window.FormChangeRegistry = {
      trackers: {},
      tabMap: {},
  
      register: function (key, tracker, tabKey) {
          this.trackers[key] = tracker;
  
          if (tabKey) {
              if (!this.tabMap[tabKey]) this.tabMap[tabKey] = [];
              this.tabMap[tabKey].push(key);
          }
      },
  
      isAnyDirty: function () {
          return Object.values(this.trackers).some(t => t.hasUnsavedChanges());
      },
  
      isTabDirty: function (tabKey) {
          const tabKeys = this.tabMap[tabKey] || [];
          return tabKeys.some(key => this.trackers[key]?.hasUnsavedChanges());
      },
  
      resetTab: function (tabKey) {
          const tabKeys = this.tabMap[tabKey] || [];
          tabKeys.forEach(key => this.trackers[key]?.reset());
      }
  };
  
  let pendingTabSwitch = null;
  let currentTab = null;
  
  document.querySelectorAll('.plugin-tab').forEach(tab => {
      tab.addEventListener('click', function (e) {
          e.preventDefault();
  
          const targetTabId = this.getAttribute('data-tab-id');
          const targetTab = this.getAttribute('data-form-tab');
          const activeTab = document.querySelector('.plugin-tab.nav-tab-active')?.getAttribute('data-form-tab');
          
          if (activeTab && window.FormChangeRegistry.isTabDirty(activeTab)) {
              pendingTabSwitch = targetTab;
              currentTab = activeTab;
  
              // Store targetTabId to proceed later
              window._deferredTabClick = targetTabId;
  
              const modal = new bootstrap.Modal(document.getElementById('unsavedChangesModal'));
              modal.show();
          } else {
              handleTabClick(targetTabId);
          }
      });
  });
  
  document.querySelectorAll('.dismiss-unsaved-modal').forEach(button => {
      button.addEventListener('click', function () {
          const modalElement = document.getElementById('unsavedChangesModal');
          const modalInstance = bootstrap.Modal.getInstance(modalElement);
  
          if (modalInstance) {
              modalInstance.hide();
  
              setTimeout(() => {
                  if (!document.querySelector('.modal.show')) {
                      document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
                      document.body.classList.remove('modal-open');
                      document.body.style.overflow = '';
                  }
  
                  window.FormChangeRegistry.resetTab(currentTab);
  
                  if (window._deferredTabClick) {
                      handleTabClick(window._deferredTabClick);
                      window._deferredTabClick = null;
                      currentTab = null;
                      pendingTabSwitch = null;
                  }
              }, 400);
          }
      });
  });
  
  document.querySelectorAll('.save-changes-modal').forEach(button => {
      button.addEventListener('click', function () {
          const modalElement = document.getElementById('unsavedChangesModal');
          const modalInstance = bootstrap.Modal.getInstance(modalElement);
  
          if (modalInstance) {
            // Wait for the save method to complete (if it returns a Promise), then proceed
            function proceedAfterSave() {
                modalInstance.hide();

                setTimeout(() => {
                    if (!document.querySelector('.modal.show')) {
                        document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
                        document.body.classList.remove('modal-open');
                        document.body.style.overflow = '';
                    }

                    window.FormChangeRegistry.resetTab(currentTab);

                    if (window._deferredTabClick) {
                        handleTabClick(window._deferredTabClick);
                        window._deferredTabClick = null;
                        currentTab = null;
                        pendingTabSwitch = null;
                    }
                }, 400);
            }

            let saveResult;
            switch (currentTab) {
                case 'app-settings':
                    saveResult = ai_app_onsite_save_plugin_settings();
                    break;
                case 'app-details':
                    saveResult = ai_app_onsite_save_app_properties();
                    break;
                case 'model-settings':
                    saveResult = ai_app_onsite_save_model_settings();
                    break;
                case 'field-selector':
                    saveResult = ai_app_onsite_save_ai_app_fieldselector_data();
                    break;
                case 'prompt-editor':
                    saveResult = ai_app_onsite_save_prompt_editor();
                    break;
                case 'app-preview':
                    saveResult = ai_app_onsite_update_style_properties_only();
                    break;
                default:
                    console.warn('No matching save method for the current tab:', currentTab);
                    saveResult = null;
            }

            // If the save method returns a Promise, wait for it to resolve
            if (saveResult && typeof saveResult.then === 'function') {
                saveResult.then(proceedAfterSave).catch(proceedAfterSave);
            } else {
                proceedAfterSave();
            }
          }
      });
  });
  
  function activatePluginTab(tabName) {
      document.querySelectorAll('.plugin-tab-content').forEach(el => el.classList.add('d-none'));
      document.getElementById(`tab-content-${tabName}`)?.classList.remove('d-none');
  
      document.querySelectorAll('.plugin-tab').forEach(el => el.classList.remove('nav-tab-active'));
      document.querySelector(`.plugin-tab[data-form-tab="${tabName}"]`)?.classList.add('nav-tab-active');
  }
  
  // Tracker Utility
  function trackFormChanges(formSelector, options = {}) {
      const form = typeof formSelector === 'string' ? document.querySelector(formSelector) : formSelector;
      if (!form) return;
  
      const config = {
          warnOnLeave: false,
          customWarningMessage: 'You have unsaved changes.',
          onChange: null,
          ...options,
      };
  
      let initialState = {};
      let isDirty = false;
  
      const getFieldValue = (field) => {
          if (field.type === 'color') return;
          if (field.type === 'radio') {
              const selected = document.querySelector(`input[name="${field.name}"]:checked`);
              return selected ? selected.value : '';
          }
          if (field.type === 'checkbox') {
              return field.checked;
          }
          if (field.type === 'file') {
              return Array.from(field.files).map(file => file.name).join(',') || '';
          }
          if (field.tagName === 'TEXTAREA') {
              return field.value.trim(); 
          }
          if (field.tagName === 'SELECT') {
              if (field.multiple) {
                  return Array.from(field.selectedOptions).map(option => option.value).join(',');
              }
              return field.value;
          }
          return field.value.trim();
      };
  
      const getCurrentFormState = () => {
          const state = {};
          form.querySelectorAll('input, textarea, select').forEach(field => {
              if (field.name) {
                  const value = getFieldValue(field);
                  if (value !== undefined) {
                      state[field.name] = value;
                  }
              }
          });
          return state;
      };
  
      const captureInitialState = () => {
          initialState = getCurrentFormState();
      };
  
      const hasChanged = () => {
          const currentState = getCurrentFormState();
      
          for (let key in initialState) {
              if (initialState.hasOwnProperty(key)) {
                  if (initialState[key] !== currentState[key]) {
                      return true; 
                  }
              }
          }
      
          return false;
      };
  
      const markDirty = () => {
          isDirty = hasChanged();
          if (typeof config.onChange === 'function') config.onChange(isDirty);
      };
  
      const bindListeners = () => {
          form.querySelectorAll('input, textarea, select').forEach(field => {
              field.addEventListener('input', markDirty);
              field.addEventListener('change', markDirty);
          });
      };
  
      const observer = new MutationObserver(() => {
          bindListeners();
          markDirty();
      });
  
      observer.observe(form, { childList: true, subtree: true });
  
      captureInitialState();
      bindListeners();
  
      return {
          activate: () => {
              active = true;
              captureInitialState(); 
          },
          deactivate: () => {
              active = false;
          },
          reset: () => {
              captureInitialState();
              isDirty = false;
          },
          hasUnsavedChanges: () => isDirty,
          markDirty: () => markDirty
      };
  }

  const sel = document.getElementById('ai_app_onsite-user-stats');
  sel.addEventListener('change', ai_app_onsite_user_stats_duration_change);

  function ai_app_onsite_user_stats_duration_change(event) {
      const downloadIcon = document.querySelector(".download-icon");
      const duration = event.target.value;
      console.log("Duration changed to:", duration);

      // Treat empty string (placeholder) as invalid
      if (!duration) {
          downloadIcon.classList.add("disabled");
          downloadIcon.setAttribute("title", "Please select a duration");
          return;
      }
      downloadIcon.classList.remove("disabled");
      downloadIcon.removeAttribute("title");
  }
  
  
