jQuery(document).ready(function ($) {
    var pluginUrl = team_mxt_data.plugin_url; // Localized data from PHP
  
    // Function to update live preview and stylesheet
    function updateLivePreviewAndStylesheet() {
      var styleInput = $('input[name="team_mxt_member_style"]:checked');
  
      if (styleInput.length > 0) {
        var styleNumber = styleInput.val().replace("style_", "");
  
        var formData = {
          action: "team_mxt_live_preview",
          style: "style_" + styleNumber,
          name: $("#team_mxt_member_name").val(),
          designation: $("#team_mxt_member_designation").val(),
          phone: $("#team_mxt_member_phone").val(),
          email: $("#team_mxt_member_email").val(),
          website: $("#team_mxt_member_website").val(),
          facebook: $('input[name="team_mxt_member_facebook"]').val(),
          twitter: $('input[name="team_mxt_member_twitter"]').val(),
          linkedin: $('input[name="team_mxt_member_linkedin"]').val(),
          whatsapp: $('input[name="team_mxt_member_whatsapp"]').val(),
          instagram: $('input[name="team_mxt_member_instagram"]').val(),
          pinterest: $('input[name="team_mxt_member_pinterest"]').val(),
          discord: $('input[name="team_mxt_member_discord"]').val(),
          "facebook-messenger": $(
            'input[name="team_mxt_member_facebook-messenger"]'
          ).val(),
          youtube: $('input[name="team_mxt_member_youtube"]').val(),
          reddit: $('input[name="team_mxt_member_reddit"]').val(),
          tiktok: $('input[name="team_mxt_member_tiktok"]').val(),
          telegram: $('input[name="team_mxt_member_telegram"]').val(),
          quora: $('input[name="team_mxt_member_quora"]').val(),
          tumblr: $('input[name="team_mxt_member_tumblr"]').val(),
          vimeo: $('input[name="team_mxt_member_vimeo"]').val(),
  
          photo_id: $("#team_mxt_member_photo").val(),
          expertise_area_1: $("#team_mxt_member_expertise_1").val(),
          expertise_percent_1: $("#team_mxt_member_expertise_percent_1").val(),
          expertise_area_2: $("#team_mxt_member_expertise_2").val(),
          expertise_percent_2: $("#team_mxt_member_expertise_percent_2").val(),
          expertise_area_3: $("#team_mxt_member_expertise_3").val(),
          expertise_percent_3: $("#team_mxt_member_expertise_percent_3").val(),
        };
        // console.log(formData);
        $("#live-preview-loader").show();
        $(".carousel-item").hide();
        // Update live preview
        $.post(team_mxt_data.ajax_url, formData, function (response) {
          $("#live-preview").html(response);
        }).always(function () {
          // Hide loader after AJAX response, regardless of success or failure
          $("#live-preview-loader").hide();
          $(".carousel-item").show();
        });
  
        // Update stylesheet
        var newStylesheetUrl = pluginUrl + "css/style-" + styleNumber + ".css";
        var linkElement = document.createElement('link');
        linkElement.rel = 'stylesheet';
        linkElement.type = 'text/css';
        linkElement.href = newStylesheetUrl;
        
        // Remove old stylesheet if exists
        var oldLink = document.querySelector('link[data-team-mxt-style]');
        if (oldLink) {
            oldLink.remove();
        }
        
        // Add new stylesheet
        linkElement.setAttribute('data-team-mxt-style', 'true');
        document.head.appendChild(linkElement);
    }
    }
  
    $('input[name="team_mxt_member_style"]').on("change", function () {
      updateLivePreviewAndStylesheet();
    });
    // Event listeners for form changes
    $(
      'input[type="text"], input[type="email"], input[type="url"], input[type="radio"]'
    ).on("change", function () {
      updateLivePreviewAndStylesheet();
      // Show loader while updating
      $("#live-preview-loader").show();
    });
    // WordPress Media Uploader
    var mediaUploader;
    $("#team_mxt_upload_button").click(function (e) {
      e.preventDefault();
      if (mediaUploader) {
        mediaUploader.open();
        return;
      }
      mediaUploader = wp
        .media({
          title: "Choose Image",
          button: {
            text: "Choose Image",
          },
          multiple: false,
        })
        .on("select", function () {
          var attachment = mediaUploader
            .state()
            .get("selection")
            .first()
            .toJSON();
          $("#team_mxt_member_photo").val(attachment.id);
          $("#team_mxt_image_preview").html(
            '<img src="' + attachment.url + '" style="max-width:100%">'
          );
          updateLivePreviewAndStylesheet();
        });
      mediaUploader.open();
    });
  
    // Toggle style categories
    $(".team-mxt-category-title").click(function () {
      var currentStylesDiv = $(this).next(".team-mxt-styles");
  
      // Check if the current category is already expanded
      if (!currentStylesDiv.is(":visible")) {
        // Collapse other categories
        $(".team-mxt-styles").slideUp();
  
        // Expand the current category
        currentStylesDiv.slideDown();
      }
    });
  
    // Initial update on page load
    updateLivePreviewAndStylesheet();
  });
  
  /////////////////////////////////////////////////////
  
  jQuery(document).ready(function ($) {
    // Assuming you have a similar setup for style selection in the "All Members" section
    $('#all-members-styles input[type="radio"]').change(function () {
      var selectedStyle = $(this).val();
      // AJAX call to update live preview
      $.ajax({
        url: team_mxt_data.ajax_url,
        type: "post",
        data: {
          action: "team_mxt_live_preview",
          style: selectedStyle,
          member_id: $(this).data("member-id"), // Pass the member ID if needed
        },
        success: function (response) {
          // Update the live preview
          $("#live-preview").html(response);
  
          // Update the shortcode display
          $("#team_mxt_shortcode").val(
            '[team_mxt style="' + selectedStyle + '"]'
          );
        },
      });
    });
  
    // Copy shortcode functionality
    $("#copy-shortcode").click(function () {
      var copyText = $("#team_mxt_shortcode");
      copyText.select();
      document.execCommand("copy");
    });
  
    // Initial call to show default style or previously saved style preview
    $('#all-members-styles input[type="radio"]:checked').change();
  });
  //////////////////////
  document.addEventListener("DOMContentLoaded", function () {
    var currentPage = window.location.search; // Gets the query string from the URL
    var navLinks = document.querySelectorAll(".team-mxt-tabs a");
    var navItems = document.querySelectorAll(".team-mxt-tabs li");
  
    // Remove 'active' class from all nav items
    navItems.forEach(function (item) {
      item.classList.remove("active");
    });
  
    // Set 'active' class on the correct nav item
    navLinks.forEach(function (link) {
      var linkPageParam = new URLSearchParams(link.getAttribute("href")).get(
        "page"
      );
      if (currentPage.includes(`page=${linkPageParam}`)) {
        link.parentNode.classList.add("active");
      }
    });
  });
  
  ///////////////////
  jQuery(document).ready(function ($) {
    // Function to update a CSS variable based on input name and value
    function updateCssVariable(input) {
      var cssVarName = "--" + input.name.replace(/_/g, "-");
      var value = input.value;
      document.documentElement.style.setProperty(cssVarName, value);
    }
  
    // Listen for changes on inputs and update CSS variables in real-time
    $(".style-form input").on("input", function () {
      updateCssVariable(this);
    });
  
    // Apply saved settings on page load
    $(".style-form input").each(function () {
      updateCssVariable(this);
    });
    // Listen for changes on dropdowns (font family selection) and update CSS variables
    $(".style-form select").on("change", function () {
      // Find the associated text input using ID manipulation or related input naming convention
      var associatedInputId = this.id.replace("_select", "");
      var associatedInput = document.getElementById(associatedInputId);
      if (associatedInput) {
        // Set the value of the associated input to the selected option's value
        associatedInput.value = this.value;
        // Update the CSS variable
        updateCssVariable(associatedInput);
      }
    });
  
    // Apply saved settings on page load
    $('.style-form input[type="text"]').each(function () {
      updateCssVariable(this);
    });
  });
  
  document.querySelectorAll(".resetSettings").forEach(function (button) {
    button.addEventListener("click", function () {
      var defaults = JSON.parse(this.getAttribute("data-defaults"));
  
      for (var name in defaults) {
        var defaultValue = defaults[name];
        var cssVarName = "--" + name.replace(/_/g, "-");
        var input = document.querySelector('input[name="' + name + '"]');
        if (input) {
          input.value = defaultValue;
          // Update the CSS variable if necessary
          document.documentElement.style.setProperty(cssVarName, defaultValue);
        }
      }
    });
  });
  ////////////////////////////
  //toggle DropDown of Social Media in Add member
  function toggleDropdown() {
    var dropdown = document.getElementById("socialMediaDropdown");
    var icon = document.getElementById("dropdownIcon");
  
    if (dropdown.style.display === "none" || dropdown.style.display === "") {
      dropdown.style.display = "block";
      icon.className = "fas fa-arrow-up";
    } else {
      dropdown.style.display = "none";
      icon.className = "fas fa-arrow-down";
    }
  }
  //  Style Selection Function in Add Member Section
  document.addEventListener("DOMContentLoaded", function () {
    var styleRadios = document.querySelectorAll(
      'input[name="team_mxt_member_style"]'
    );
    var styleForms = document.querySelectorAll(".style-form");
    var select = document.querySelector("#select-style");
  
    // Function to update the form display based on the selected style
    function updateFormDisplay(selectedStyle) {
      styleForms.forEach(function (form, index) {
        if (index + 1 === parseInt(selectedStyle)) {
          form.style.display = "block";
        } else {
          form.style.display = "none";
        }
      });
    }
  
    // Listen for changes in style selection via radio buttons (Section 1)
    styleRadios.forEach(function (radio) {
      radio.addEventListener("change", function () {
        var selectedStyle = this.value.replace("style_", "");
        select.value = selectedStyle; // Update dropdown selection in Section 2
        updateFormDisplay(selectedStyle); // Update form display
      });
    });
  
    // Listen for changes in the dropdown selection (Section 2)
    select.addEventListener("change", function () {
      var selectedStyle = parseInt(this.value);
      updateFormDisplay(selectedStyle);
      // Update radio button selection in Section 1
      var radioToSelect = document.querySelector(
        'input[value="style_' + selectedStyle + '"]'
      );
      if (radioToSelect) {
        radioToSelect.checked = true;
      }
    });
  
    // Initial sync from Section 1 to Section 2 on page load
    var checkedRadio = document.querySelector(
      'input[name="team_mxt_member_style"]:checked'
    );
    if (checkedRadio) {
      var selectedStyle = checkedRadio.value.replace("style_", "");
      select.value = selectedStyle;
      updateFormDisplay(selectedStyle);
    }
  });
  //Loading  spinner code in Add member Section
  jQuery(document).ready(function ($) {
    $(".style-selector").on("change", function () {
      $("#loadingIndicator").show();
      setTimeout(function () {
        $("#loadingIndicator").hide();
      }, 2000);
    });
  });
  
  // Add or Remove Department in Add Member Section
  //Department
  jQuery(document).ready(function ($) {
    var departmentCounter = 2;
  
    $("body").on("click", ".add-more-department", function () {
      var newField = $(
        '<div class="team-mxt-field" id="department-field-' +
          departmentCounter +
          '">' +
          '<label for="team_mxt_member_department_' +
          departmentCounter +
          '" class="info-label">DEPARTMENT:</label>' +
          '<input id="team_mxt_member_department_' +
          departmentCounter +
          '" type="text" name="team_mxt_member_department[]" class="info-value" />' +
          '<button type="button" class="button delete-department">Delete</button>' +
          "</div>"
      );
      $("#additional-departments").append(newField);
      departmentCounter++;
    });
  
    $("body").on("click", ".delete-department", function () {
      $(this).closest(".team-mxt-field").remove();
    });
  });
  
  
  // For Notification
  document.addEventListener("DOMContentLoaded", function() {
    var notificationElement = document.querySelector('.notification');
    var closeButton = document.querySelector('.close-btn');
  
    closeButton.addEventListener('click', function() {
        notificationElement.style.display = 'none'; 
        window.removeEventListener('scroll', handleScroll);
    });
  
    function handleScroll() {
        var scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
        if (scrollPosition > 400) {
            notificationElement.style.bottom = '60px';
        }
    }
  
    window.addEventListener('scroll', handleScroll);
  });
  ///
  document.addEventListener('DOMContentLoaded', function() {
    var submitButton = document.getElementById('submit');
    var modal = document.getElementById('modal');
    var isMouseOverModal = false;
  
    submitButton.addEventListener('mouseenter', function() {
      modal.style.display = 'block';
    });
  
    submitButton.addEventListener('mouseleave', function() {
      hideModalTimeout = setTimeout(function() {
        if (!isMouseOverModal) {
          modal.style.display = 'none';
        }
      }, 2000);
    });
  
    modal.addEventListener('mouseenter', function() {
      modal.style.display = 'block';
      isMouseOverModal = true;
    });
  
    modal.addEventListener('mouseleave', function() {
      modal.style.display = 'none';
      isMouseOverModal = false;
    });
  });