try {
  $ = jQuery;
} catch (err) {}
function opensliderLang() {
  document.getElementById("mySidenav").style.width = "50%";
  document
    .getElementById("krfs_activation_form_overlay")
    .classList.add("visible");
}

function closesliderLang() {
  document.getElementById("mySidenav").style.width = "0";
  document
    .getElementById("krfs_activation_form_overlay")
    .classList.remove("visible");
  $("body").removeClass("no-scroll");
}
function toggleIcon(checkbox) {
  const iconDiv = checkbox
    .closest(".input-section")
    .querySelector(".send-link-icon");
  if (iconDiv) {
    iconDiv.style.display = checkbox.checked ? "flex" : "none";
  }
}
$(document).ready(() => {
  $("#advance_filter_form").submit(function (event) {
    $(".alert-section-none")
      .removeClass("alert-section-none")
      .addClass("alert-section");
  });
  $(".krfs-addon-toggle-switch").each(function () {
    $(this).on("click", function () {
        let $button = $(this);
        let currentState = $button.attr("data-state");
        let $statusLabel = $button.next(); // Select the status label next to the button
        let buttonType = $button.data("type");
        let targetSection = $button.data("target"); // Get the target section from the button

        let $hiddenField;

        // Determine the heading to update based on the target section
        let heading;
        if (targetSection === "krfs-engraving-info-section") {
            heading = $(".engraving-heading"); // Engraving heading
        } else if (targetSection === "krfs-ringsize-info-section") {
            heading = $(".ring-size-heading"); // Ring Size heading
        }

        // Select the appropriate hidden field based on button type
        if (buttonType === "shape") {
            $hiddenField = $(".shapefield");
        } else if (buttonType === "metal") {
            $hiddenField = $(".metalfield");
        } else if (buttonType === "style") {
            $hiddenField = $(".stylefield");
        } else if (buttonType === "wedmen") {
            $hiddenField = $(".wedmenfield");
        } else if (buttonType === "wedwomen") {
            $hiddenField = $(".wedwomenfield");
        } else if (buttonType === "sidestone") {
            $hiddenField = $(".sidestonefield");
        } else if (buttonType === "bridalset") {
            $hiddenField = $(".bridalSetsfield");
        } else if (buttonType === "homepreview") {
            $hiddenField = $(".homepreviewfield");
        }

        // Toggle switch state
        if (currentState === "checked") {
            $button.attr("data-state", "unchecked");
            $button.attr("aria-checked", "false");
            $button.val("off");
            $statusLabel.text("Inactive"); // Change label to "Inactive"
            $statusLabel.removeClass("active");

            if ($hiddenField) {
                $hiddenField.val("off"); // Set hidden field value to 'off'
            } else {
                $button.closest(".inner-section").find("input[type='hidden']").val("off");
            }

            // Update the heading text based on which button was clicked
            if (heading) {
                if (targetSection === "krfs-engraving-info-section") {
                    heading.text("A. Add Engraving"); // Default text when unchecked
                } else if (targetSection === "krfs-ringsize-info-section") {
                    heading.text("B. Ring Size");
                }
            }

        } else {
            $button.attr("data-state", "checked");
            $button.attr("aria-checked", "true");
            $button.val("on");
            $statusLabel.addClass("active");
            $statusLabel.text("Active"); // Change label to "Active"

            if ($hiddenField) {
                $hiddenField.val("on"); // Set hidden field value to 'on'
            } else {
                $button.closest(".inner-section").find("input[type='hidden']").val("on");
            }

            // Update the heading text when toggled on
            if (heading) {
                if (targetSection === "krfs-engraving-info-section") {
                    heading.text("A. Select Collections to Display Engraving");
                } else if (targetSection === "krfs-ringsize-info-section") {
                    heading.text("B. Select Collections to Display Ring Size");
                }
            }
        }
    });
  });


  $(".img-icon").hover(
    function () {
      // Show the advance-info-text on mouse enter
      $(this).siblings(".advance-info-text").show();
    },
    function () {
      // Hide the advance-info-text on mouse leave
      $(this).siblings(".advance-info-text").hide();
    }
  );
  $(".UparrowIcon").click(function () {
    $(this).toggleClass("rotate-180");
    $(this).toggleClass("margin-top");
    $(this)
      .closest(".input.choose-add-btn-div")
      .siblings(".krfs-card-toggle.iteams")
      .toggle(); // Toggle display none
    $(this)
      .closest(".input.choose-add-btn-div")
      .siblings(".subheading-advance-filter")
      .toggle();
    $(this).closest(".section-iteam.mb-4").find(".add-btn").toggle(); // Toggle display none if the add-btn exists
  });
  $(".settings_action_btn").click(function (e) {
    e.preventDefault();
    $("#settings_action").val($(this).data("val"));
    $("#settings_form").submit();
  });
  $(".advance_filter_btn").click(function (e) {
    e.preventDefault();
    $("#advance_filter_action").val($(this).data("val"));
    $("#advance_filter_form").submit();
  });
  $(".help_action_btn").click(function (e) {
    e.preventDefault();
    $("#help_action").val($(this).data("val"));
    $("#help_form").submit();
  });
  $("#saveCOll").click(function (e) {
    // Add the 'name' attribute only when the button is clicked
    e.preventDefault();
    $(this).attr("name", "delete_action");
    $(".alert-section-none").html("Deleted Successfully");
  });

  $(".krfs-addon-toggle-switch").click(function(){
    let state = $(this).attr("data-state");
    let target = $(this).attr("data-target");
    console.log(state, target);
    if(target) {
        $(`#${target}`).toggle(state === 'checked');
    }
  });

  $(".krfs_multi_select_chkbox").click(function(){
      let name = $(this).attr("name");
      let target = $(this).attr("data-target");
      if(target) {
          let checkedNames = $(`input[name='${name}']:checked`).map(function() {
              return this.value;
          }).get();
          $(`#${target}`).toggle(checkedNames.length > 0);
      }
  });

  $(".krfs-multi-dropdown-btn").click(function(){
      let dropdown = $(this).next();
      let button = $(this);
      let isOpen = dropdown.css("display") === "block";
      dropdown.css("display", isOpen ? "none" : "block");
      if (isOpen) {
          button.removeClass("rotate");
      } else {
          button.addClass("rotate");
      }
  });
  document.addEventListener("click", function (event) {
      if (!event.target.closest(".krfs-select-page-dropdown")) {
          $(".krfs-multi-dropdown-content").hide();
          $(".krfs-multi-dropdown-btn").removeClass("rotate");
      }
  });

   $("#krfsConsentCheck").change(function() {
        if(this.checked) {
            $(".krfsapp-consent-card .krfsapp-consent-accept-btn").prop("disabled", false);
        }else{
            $(".krfsapp-consent-card .krfsapp-consent-accept-btn").prop("disabled", true);
        }
    });

  prepareTermOptions('engagement_ring', 'style', 'engagement_ring_style_terms');  // For engagement rings style mapping
  prepareTermOptions('engagement_ring', 'side_stone', 'engagement_ring_sidestone_terms'); // For engagement rings side stone mapping
  prepareTermOptions('wedding_ring', 'wed_men', 'wedding_ring_terms_wedmen'); // For men wedding rings style
  prepareTermOptions('wedding_ring', 'wed_women', 'wedding_ring_terms_wedwomen'); // For women wedding rings style
  prepareTermOptions('common', 'metal', 'metal_terms'); // For metal type
  prepareTermOptions('common', 'shape' , 'shape_terms'); // For diamond shape
});

// Engagement rings style mapping
$('#krfs_engagement_ring_style').change(function() {
  prepareTermOptions('engagement_ring', 'style', 'engagement_ring_style_terms');
});

// Engagement rings side stone mapping
$('#krfs_engagement_ring_side_stone').change(function() {
  prepareTermOptions('engagement_ring', 'side_stone', 'engagement_ring_sidestone_terms');
});

// Mens wedding rings mapping
$('#krfs_wedding_ring_wed_men').change(function() {
  prepareTermOptions('wedding_ring', 'wed_men', 'wedding_ring_terms_wedmen');
});

// Women wedding rings mapping
$('#krfs_wedding_ring_wed_women').change(function() {
  prepareTermOptions('wedding_ring', 'wed_women', 'wedding_ring_terms_wedwomen');
});

// Metal type mapping
$('#krfs_metal').change(function() {
  prepareTermOptions('common', 'metal', 'metal_terms');
});

// Diamond type mapping
$('#krfs_shape').change(function() {
  prepareTermOptions('common', 'shape' , 'shape_terms');
});

function prepareTermOptions(ring_type, attr, terms_key) {
  // Setting indentifier for the attribute
  var identifier = "";
  if(ring_type === 'common') {
    identifier = 'krfs_'+attr;
  } else {
    identifier = 'krfs_'+ring_type+'_'+attr;
  }
  
  var attribute = $('#'+identifier).val();

  var loader = $('#krfs_'+attr+'_loader'); // Loader element
  loader.show();
  
  if(attribute) { 
    $.post(ajaxurl, {
      action: 'krfs_get_attribute_terms',
      attribute: attribute,
      term_selector: attr+'_attr_advance_filters',
      ring_type: ring_type,
      terms_key: terms_key
    }, function(response) {
      $('.'+identifier+'_terms').html(response.data.options);
      autoSelectTerm(response.data.selected_terms);
      loader.hide();
    }).fail(function(jqXHR, textStatus) {
      alert('AJAX Error: ' + textStatus);
      loader.hide();
    });
  } else {
    $('.'+identifier+'_terms').html('<option value="">Select Term</option>');
    loader.hide();
  }
}

function autoSelectTerm(selected_terms) {
  for (let key in selected_terms) {
    $(`#${key} option[value="${selected_terms[key]}"]`).attr('selected','selected');
  }
}

// Handle image slider on admin panel
$(".krfs-nav-arrow").click(function () {
  let current_target = $(this).attr("data-target");
  let action = $(this).attr("data-action");
  let target_elem = $(`.krfs_img_slides[data-id="${current_target}"]`);
  let slides_count = $(target_elem).find("img").length;
  let current_idx = $(target_elem).data("activeIndex");
  if (action == "prev") {
    current_idx = (current_idx - 1 + slides_count) % slides_count;
  } else if (action == "next") {
    current_idx = (current_idx + 1) % slides_count;
  }
  $(target_elem).data("activeIndex", current_idx);
  $(target_elem).find("img").hide();
  $(target_elem).find("img").eq(current_idx).show();
});

$('.filter--iteams input[type="checkbox"]').on("change", function () {
  if ($(this).is(":checked")) {
    $(this).closest(".filter--iteams div div").addClass("krfs-checkbox-active");
  } else {
    $(this)
      .closest(".filter--iteams div div")
      .removeClass("krfs-checkbox-active");
  }
});

$(".accordion").each(function () {
  $(this).on("click", function () {
    $(this).toggleClass("active");
    var panel = $(this).next();
    panel.slideToggle(0, function () {
      if (panel.is(":visible")) {
        $(this).prev().find(".sign").text("-");
      } else {
        $(this).prev().find(".sign").text("+");
      }
    });
  });
});

$(".krfs_help_tab").click(function () {
  let data_id = $(this).attr("id") + "-parent";
  $(".krfs-help-support-tab button").removeClass("active");
  $(`.krfs-help-support-tab button#${data_id}`).addClass("active");
});

$(".krfs-help-support-tab").click(function () {
  let data_target_id = $(this).find("button").attr("data-target-id");
  $(`button#${data_target_id}`).click();
});

// Close the popup and overlay when clicking on the overlay
document
  .querySelector(".manage-popup-main .close-popup")
  .addEventListener("click", function () {
    const managePopup = document.querySelector(".manage-popup-main");
    const body = document.body;
    document.querySelector(".body-overlay-bg").style.display = "none";
    managePopup.style.display = "none";
    body.classList.remove("body-no-scroll"); // Enable body scroll
  });

$(".krfs_img_slides img").click(function () {
  let src = $(this).attr("src");
  let current_image_tab = $(this).data("target");
  if (current_image_tab === "setting-tab-image") {
    $("#krfs-setting-images-preview").html(
      `<img class="krfs-image-preview" src="${src}"/>`
    );
  } else if (current_image_tab === "lang-setting-tab-image") {
    $("#krfs-lang-setting-images-preview").html(
      `<img class="krfs-image-preview" src="${src}"/>`
    );
  }
  else if (current_image_tab === "premium-tab-image") {
    $("#krfs-premium-images-preview").html(
      `<img class="krfs-image-preview" src="${src}"/>`
    );
  }
  else if (current_image_tab === "filterBasic-tab-image") {
    $("#krfs-filterBasic-images-preview").html(
      `<img class="krfs-image-preview" src="${src}"/>`
    );
  } else if (current_image_tab === "filterMore-tab-image") {
    $("#krfs-filterMore-images-preview").html(
      `<img class="krfs-image-preview" src="${src}"/>`
    );
  } else if (current_image_tab === "language-tab-image") {
    $("#krfs-language-images-preview").html(
      `<img class="krfs-image-preview" src="${src}"/>`
    );
  }
});

function krfsOpenImageSidebar(sidebar) {
  document.getElementById(`krfs-${sidebar}-images`).style.width = "50%";
  document.getElementById(`krfs-${sidebar}-preview-image`).classList.add("visible");
  document.body.classList.add("no-scroll");
}

function krfscloseImageSidebar(sidebar) {
  document.getElementById(`krfs-${sidebar}-images`).style.width = "0";
  document.getElementById(`krfs-${sidebar}-preview-image`).classList.remove("visible");
  document.body.classList.remove("no-scroll");
}

$(".krfs-preview-image").click(function () {
  let sidebar = $(this).data("sidebar");
  krfs_activation_sidebar_toggle(false);
  krfscloseImageSidebar(sidebar);
});


setTimeout(function () {
  $(".alert-section").fadeOut();
}, 5000);

$(".krfs_catg_switch").click(function () {
  let catg = $(this).attr("name");
  catg = catg.toLowerCase().replace(/ /g, "");
  $(`#krfs-catg-${catg}`).toggle();
});
$("#help_form")
  .find("textarea[name='message']")
  .on("input", function () {
    if ($(this).val() != "") {
      $(".help_action_btn").prop("disabled", false);
    } else {
      $(".help_action_btn").prop("disabled", true);
    }
  });

$("#advance_form").on("input", function () {
  // Allow only letters, hyphens, and spaces but not space at the start
  this.value = this.value.replace(/[^a-zA-Z-\s]/g, "").replace(/^\s/, "");

  // Check if the input field is empty after the replacement
  if (this.value.trim() === "") {
    $(".error-gap").css("display", "none"); //
  }
});

function eyeMoreOption(eyeImage, changedText) {
  $(eyeImage).click(function () {
    let svgPath = $(this).find("path");
    let currentFill = svgPath.attr("fill");
    let newFill =
      currentFill === "var(--krfs-primary-color)"
        ? "black"
        : "var(--krfs-primary-color)";
    svgPath.attr("fill", newFill);
    $(changedText).toggle();
  });
}

eyeMoreOption("#bridal-sets", "#bridal-sets-new-change");
eyeMoreOption("#home-preview", "#home-preview-new-change");

// Function to toggle all checkboxes except the first and last one
function toggleAllExceptFirstAndLast() {
  let $checkboxes = $(".krfs_catg_switch");
  let $firstCheckbox = $checkboxes.first(); // Get the first checkbox
  let $lastCheckbox = $checkboxes.last(); // Get the last checkbox

  $checkboxes.each(function (index, checkbox) {
    // Toggle all checkboxes except the first and last one
    if (checkbox !== $firstCheckbox[0] && checkbox !== $lastCheckbox[0]) {
      $(checkbox).prop("checked", $lastCheckbox.prop("checked"));
    }
  });
}

// Add event listener to the last checkbox to trigger toggleAllExceptFirstAndLast on change
let $checkboxes = $(".krfs_catg_switch");
let $lastCheckbox = $checkboxes.last(); // Get the last checkbox

// Add change event listener to the last checkbox
$lastCheckbox.on("change", function () {
  toggleAllExceptFirstAndLast();
});

$(".krfs-manage").click(function () {
  const managePopup = document.querySelector(".manage-popup-main");
  const body = document.body;
  const overlay = document.querySelector(".body-overlay-bg");

  // Toggle visibility of the popup and overlay
  if (managePopup.style.display === "block") {
    managePopup.style.display = "none";
    overlay.style.display = "none";
    body.classList.remove("body-no-scroll"); // Enable body scroll
  } else {
    managePopup.style.display = "block";
    overlay.style.display = "block";
    body.classList.add("body-no-scroll"); // Disable body scroll
  }
});

$(".krfs_contact_sales_btn").click(function(e){
  e.preventDefault();
  const customClickEvent = new Event('click', {
      bubbles: true, // Whether the event bubbles up through the DOM or not
      cancelable: true // Whether the event can be canceled
  });
  document.getElementById("support-tab-parent").dispatchEvent(customClickEvent);
});

function krfs_contact_sales() {
  const customClickEvent = new Event('click', {
      bubbles: true, // Whether the event bubbles up through the DOM or not
      cancelable: true // Whether the event can be canceled
  });
  document.getElementById("support-tab-parent").dispatchEvent(customClickEvent);
}