try {
  $ = jQuery;
} catch (err) { }
let is_load_more_diamonds = KRFStats.currentProductCount != 0;
let total_load_more_diamonds = 0;
let scroll_cooldown = false;
let current_page = 1;

const filters_uri = new URLSearchParams(window.location.search);
let ini_price = getRangeValues_krfs(filters_uri, "minprice", "maxprice");

const CurrencyFormatter = new Intl.NumberFormat(KRFListing.currency_locale, {
  style: "currency",
  currency: KRFListing.currency_code,
  minimumFractionDigits: 0,
});

try {
  numeral.register('locale', KRFListing.currency_locale, NUMERAL_LANGUAGES[KRFListing.currency_locale]);
  numeral.locale(KRFListing.currency_locale);
} catch (e) {
  console.error(e);
}

function formatCurrency(value) {
  let formattedCurrency = CurrencyFormatter.format(value);
  // Remove alphabetic characters before the currency symbol
  formattedCurrency = formattedCurrency.replace(/[A-Za-z]+(?=\p{Sc})/u, '');
  return formattedCurrency;
}


var search_cooldown = false;
$(document).ready(function () {
  // Toggle button functionality
  $("#all_diamond_label").html(
    `${KRFTranslation.results} (<span class="krfs_listing_count">${KRFStats.totalProductsCount}</span>)`
  );

  $("#krfs_bridal_set_tab").html(
    `${KRFTranslation.bridal_set} (<span class="krfs_listing_count_bridal">${KRFStats.bridalSetsCount}</span>)`
  );
  $("#krfs_bridal_set_tab").toggle(KRFStats.bridalSetsCount != 0);
  $("#krfs_bridal_set_tab").click(function () {
    if (!$(this).hasClass("active")) {
      $('#result_set').val($(this).data('type'));
      handlefilter_krfs('result_set');
      $(this).addClass("active");
      $("#all_diamond_label").removeClass("active");
    }
  });

  $(document).on("scroll", function () {
    let list_type = "#griddesign";
    let element = null;

    if (document.body.clientWidth <= 766) {
      element = document.getElementById("listdesign");
    } else {
      element = document.getElementById(list_type.replace("#", ""));
    }

    if (!scroll_cooldown && current_page < KRFStats.max_pages) {
      krfs_load_more_prods();
      scroll_cooldown = true;
    }
  });

  $(".men-button-inner button").on("click", function () {
    // Remove 'active' class from all buttons
    $(".men-button-inner button").removeClass("active");
    // Add 'active' class to the clicked button
    $(this).addClass("active");
    var buttonName = $(this).attr("name");
    KRFListing.current_category = buttonName;
    let queryString = window.location.search;
    handlefilter_krfs();
    var updated_url = replaceLastUrlSegment(window.location.href, buttonName);
    window.history.replaceState(null, null, updated_url + queryString);
    location.reload();
  });
  var currentUrl = window.location.href;

  // Check if the URL contains '/wedding-men-rings/'
  if (currentUrl.indexOf("/wedding-men-rings/") > -1) {
    $('button[name="wedding-men-rings"]').addClass("active");
  }
  // Check if the URL contains '/wedding-women-rings/'
  else if (currentUrl.indexOf("/wedding-women-rings/") > -1) {
    $('button[name="wedding-women-rings"]').addClass("active");
  }
  $("#krfs_prods_sort").change((e) => {
    handlefilter_krfs("sort");
  });

  $(".moreless__btn").click(function () {
    $(".more-filters").toggleClass("more-filters-height");
    $(".more-price-filter").toggleClass("more-price");

    if ($(".more-filters").hasClass("more-filters-height")) {
      $(this).text("MORE FILTERS +");
    } else {
      $(this).text("MORE FILTERS -");
    }
  });

  $(".reset_filters_krfs").click(() => {
    reset_filters_krfs();
  });

  // Initialize price-range slider
  $("#price-range").slider({
    range: true,
    min: parseFloat(KRFListing.krfs_minprice),
    max: parseFloat(KRFListing.krfs_maxprice),
    values: ini_price,
    slide: function (event, ui) {
      $("#min_price").val(formatCurrency(ui.values[0])); // Update min price input field
      $("#max_price").val(formatCurrency(ui.values[1])); // Update max price input field
      handlefilter_krfs("price", ui.values); // Pass the updated values directly
    },
  });

  // Initialize input fields with the current slider values
  $("#min_price").val(formatCurrency($("#price-range").slider("values", 0)));
  $("#max_price").val(formatCurrency($("#price-range").slider("values", 1)));
  $(".shape-box").click(function () {
    if (!$(this).hasClass("active")) {
      $(this).addClass("active");
      $(".krfs-diamond-shapes > .shape_item  > .shape-box").not(this).removeClass("active");
      handlefilter_krfs("shape");
    }
  });
  $(".stone-box").click(function () {
    if (!$(this).hasClass("active")) {
      $(this).addClass("active");
      $(".krfs-diamond-stones> .stone_item  > .stone-box")
        .not(this)
        .removeClass("active");
      handlefilter_krfs("stone");
    }
  });
  $(".metal-name").click(function () {
    if (!$(this).hasClass("active")) {
      $(this).addClass("active");
      $(".metal-name").not(this).removeClass("active");
      handlefilter_krfs("metal");
    }
  });
  $(".ring-style-name").click(function () {
    if (!$(this).hasClass("active")) {
      $(this).addClass("active");
      $(".ring-style-name").not(this).removeClass("active");
      handlefilter_krfs("style");
    }
  });


  $(".price_inp").on("change", function () {
    let minP = numeral($("#min_price").val()).value();
    let maxP = numeral($("#max_price").val()).value();

    // min less than final min then set to final min.
    if (
      minP <= parseFloat(KRFListing.krfs_minprice) ||
      isNaN(minP) ||
      minP > maxP
    ) {
      $("#min_price").val(
        formatCurrency(parseFloat(KRFListing.krfs_minprice))
      );
      minP = parseFloat(KRFListing.krfs_minprice);
    }

    // if max value less than min then set max to min.
    if (maxP < minP) {
      $("#max_price").val(
        formatCurrency(parseFloat(KRFListing.krfs_minprice))
      );
      maxP = parseFloat(KRFListing.krfs_minprice);
    }

    if (maxP >= parseFloat(KRFListing.krfs_maxprice) || isNaN(maxP)) {
      $("#max_price").val(
        formatCurrency(parseFloat(KRFListing.krfs_maxprice))
      );
      maxP = parseFloat(KRFListing.krfs_maxprice);
    }

    if (
      minP >= parseFloat(KRFListing.krfs_minprice) &&
      maxP <= parseFloat(KRFListing.krfs_maxprice)
    ) {
      $("#price-range").slider("option", "values", [minP, maxP]);
      $("#min_price").val(formatCurrency(minP));
      $("#max_price").val(formatCurrency(maxP));
      handlefilter_krfs("price");
    }
  });

  $("#krfs_search_txt").keypress((e) => {
    if (e.which == 13) {
      handlefilter_krfs("search");
    }
  });

  $("#krfs_search_txt").on("input", () => {
    if ($("#krfs_search_txt").val() == "") {
      handlefilter_krfs("search");
    }
  });

  $('#filterContainer').on('click', function (e) {
    // Check if the click happened inside the child
    if ($(e.target).closest('.krfs-new-filter-section').length === 0) {
      $("#filtercloseBtn").trigger("click");
    }
  });

  // Prevent click inside sidebar from closing it
  $('.krfs-new-filter-section, .selected-filter-div').on('click', function (e) {
    e.stopPropagation(); // This prevents sidebar close logic
  });


  $("#krfs_search_btn").click(() => {
    handlefilter_krfs("search");
  });
  SliderMobileTouch("#price-range");
  krfs_init_grid_listeners();
});

$("#krfs_single_set_tab").click(function () {
  $('#result_set').val($(this).data('type'));
  handlefilter_krfs('result_set');
});
$("#all_diamond_label").click(function () {
  if (!$(this).hasClass("active")) {
    $('#result_set').val($(this).data('type'));
    handlefilter_krfs('result_set');
    $(this).addClass("active");
    $("#krfs_bridal_set_tab").removeClass("active");
  }
});
function replaceLastUrlSegment(url, newSegment) {
  // Split the URL by the '/' character
  let baseUrl = url.split("?")[0];
  let urlParts = baseUrl.split("/");

  // Replace the last non-empty segment with the new segment
  if (urlParts[urlParts.length - 1] === "") {
    urlParts[urlParts.length - 2] = newSegment; // If the URL ends with '/'
  } else {
    urlParts[urlParts.length - 1] = newSegment; // If it doesn't end with '/'
  }

  // Rebuild and return the updated URL
  return urlParts.join("/");
}

function getRangeValues_krfs(filters_uri, paramMin, paramMax) {
  let min = filters_uri.get(paramMin);
  let max = filters_uri.get(paramMax);
  return min && max
    ? [parseFloat(min), parseFloat(max)]
    : [
      parseFloat(KRFListing.krfs_minprice),
      parseFloat(KRFListing.krfs_maxprice),
    ];
}

const getAllFilters_krfs = (reset) => {
  if (reset == "reset") {
    return null;
  }
  let filters = {
    price: $("#price-range")
      .slider("values")
      .map((val) => parseInt(val)),
  };

  let curr_shape = $(
    ".krfs-diamond-shapes > .shape_item  > .shape-box.active"
  ).data("shape");

  // Add shape filter if selected
  if (curr_shape != undefined) {
    filters["shape"] = curr_shape;
  }

  let curr_stone = $(
    ".krfs-diamond-stones > .stone_item  > .stone-box.active"
  ).data("stone");

  // Add stone filter if selected
  if (curr_stone != undefined) {
    filters["stone"] = curr_stone;
  }

  let current_ring_style = $(".ring-style-name.active").data("style");
  if (current_ring_style != undefined) {
    filters["style"] = current_ring_style;
  }
  let current_metal = $(".metal-box .metal-name.active").data("metal");
  if (current_metal != undefined) {
    filters["metal"] = current_metal;
  }

  let result_set = $("#result_set").val();
  if (result_set != undefined) {
    filters["result_set"] = result_set;
  }

  let home_preview = $(".homepreviewfield").val();
  if (result_set != undefined && home_preview == 'on') {
    filters["home_preview"] = 'true';
  }

  return filters;
};

const prepare_filters_uri_krfs = (filter, remove_single = false) => {
  let uri = new URLSearchParams(window.location.search);
  let multi_keys_filters = ['metal', 'style']
  if(remove_single) {
    Object.keys(filter).forEach((key) => {
      if(multi_keys_filters.includes(key)) {
        uri.delete(`${key}[]`);

        // Re-add current values from the filter object
        if (Array.isArray(filter[key])) {
          filter[key].forEach(val => uri.append(`${key}[]`, val));
        }
      } else {
        uri.delete(key);
      }
    });
  }else if (filter != null) {
    Object.keys(filter).forEach((key) => {
      if (Array.isArray(filter[key])) {
        // Remove all existing values for this key
        uri.delete(key);
        uri.delete(`${key}[]`);
        
        // Get existing params with same name to avoid duplicates
        const seen = new Set();

        filter[key].forEach((val) => {
          if (!seen.has(val)) {
            uri.append(`${key}[]`, val);
            seen.add(val);
          }
        });
      } else {
        // If filter is set and matches the current value, remove it
        if (filter[key] == undefined || uri.get(key) === filter[key]) {
          uri.delete(key);
          uri.delete(`${key}[]`);
        } else {
          uri.set(key, filter[key]);
        }
      }
    });
  } else {
    // Remove all filters
    let params = [
      "shape",
      "stone",
      "metal[]",
      "style[]",
      "maxprice",
      "minprice",
      "sort",
      "home_preview",
      "result_set"
    ];
    params.forEach((param) => {
      uri.delete(param);
    });
  }
  const queryString = uri.toString();
  window.history.pushState(
    {},
    "",
    `${window.location.pathname}?${queryString}`
  );
  localStorage.setItem("krfs_query_string", queryString);
  krfs_update_active_filters();
};

let filterDebounce = null;

const reset_filters_krfs_old = () => {
  $("#krfs_search_txt").val("");
  $("#price-range").slider("values", [
    parseFloat(KRFListing.krfs_minprice),
    parseFloat(KRFListing.krfs_maxprice),
  ]);
  search_cooldown = false;
  $("#min_price").val(
    formatCurrency(parseFloat(KRFListing.krfs_minprice))
  );
  $("#max_price").val(
    formatCurrency(parseFloat(KRFListing.krfs_maxprice))
  );
  $(".ring-style-name").removeClass("active");
  $(".metal-name").removeClass("active");
  $(".shape-box").removeClass("active");
  $(".stone-box").removeClass("active");
  handlefilter_krfs("reset");
};

const krfs_toggle_listing_loader = (show, hideSection = true) => {
  if (show) {
    $(".krfs_listing_loader").attr("style", "display: flex !important;");
    if (hideSection) {
      $(".krfs-main-tab-section").hide();
    }
  } else {
    $(".krfs_listing_loader").hide();
    if ($(".krfs-main-tab-section").is(":hidden")) {
      $(".krfs-main-tab-section").show();
    }
  }
};
const krfs_load_more_prods = () => {
  krfs_toggle_listing_loader(true, false);
  let filters = getAllFilters_krfs();
  let sort = $("#krfs_prods_sort").val();
  let search_txt = $("#krfs_search_txt").val();
  let filters_data = {
    action: "krfs_load_more_prods",
    nextpage: current_page + 1,
    catg: KRFListing.current_category,
    search: search_txt,
    minprice: filters.price[0],
    maxprice: filters.price[1],
    sort: sort,
    nonce: KRFListing.krfs_nonce
  };

  if (filters.shape != undefined && !search_cooldown) {
    filters_data.shape = filters.shape;
  }
  if (filters.stone != undefined && !search_cooldown) {
    filters_data.stone = filters.stone;
  }

  if (filters.style != undefined && !search_cooldown) {
    filters_data.style = filters.style;
  }
  if (filters.metal != undefined && !search_cooldown) {
    filters_data.metal = filters.metal;
  }
  $.get(KRFS_GLOBALS.ajax_url, filters_data, (response) => {
    current_page++;

    $("#krfs_product_grid").append(response.html);

    krfs_toggle_listing_loader(false);

    KRFStats.max_pages = response?.pagination?.total_pages;
    if (
      KRFStats.max_pages == current_page ||
      response.count == 0 ||
      KRFStats.max_pages == 0
    ) {
      is_load_more_diamonds = false;
      $("#krfs_product_grid").after(`
        <div style="text-align:center;width:100%;margin-top:20px;" class="finish_message">
        ${KRFTranslation.finishMessage}
        </div>
      `);
    }
    scroll_cooldown = false;
    total_load_more_diamonds++;
  });
};

function SliderMobileTouch(divId) {
  $(document).on("touchstart", `${divId} .ui-slider-handle`, function (e) {
    let t = e.touches[0] || e;
    $(this)
      .addClass("ui-state-hover")
      .addClass("ui-state-active")
      .addClass("ui-state-focus");
    var newEvent = new MouseEvent("mousedown", {
      screenX: t.screenX,
      screenY: t.screenY,
      clientX: t.clientX,
      clientY: t.clientY,
      relatedTarget: t.target,
    });
    Object.defineProperty(newEvent, "target", {
      value: t.target,
      enumerable: true,
    });
    Object.defineProperty(newEvent, "currentTarget", {
      value: t.target,
      enumerable: true,
    });
    $(this).parent().slider("instance")._mouseDown(newEvent);
  });

  $(document).on("touchend", `${divId} .ui-slider-handle`, function (e) {
    let t = e.touches[0] || e;
    $(this)
      .removeClass("ui-state-hover")
      .removeClass("ui-state-active")
      .removeClass("ui-state-focus");
    var newEvent = new MouseEvent("mouseup", {
      screenX: t.screenX,
      screenY: t.screenY,
      clientX: t.clientX,
      clientY: t.clientY,
      relatedTarget: t.target,
    });
    Object.defineProperty(newEvent, "target", {
      value: t.target,
      enumerable: true,
    });
    Object.defineProperty(newEvent, "currentTarget", {
      value: t.target,
      enumerable: true,
    });
    $(this).parent().slider("instance")._mouseUp(newEvent);
  });

  $(document).on("touchmove", `${divId} .ui-slider-handle`, function (e) {
    let t = e.touches[0] || e;
    var newEvent = new MouseEvent("mousemove", {
      screenX: t.screenX,
      screenY: t.screenY,
      clientX: t.clientX,
      clientY: t.clientY,
      relatedTarget: t.target,
      bubbles: true,
      cancelable: true,
    });

    Object.defineProperty(newEvent, "target", {
      value: t.target,
      enumerable: true,
    });
    Object.defineProperty(newEvent, "currentTarget", {
      value: t.target,
      enumerable: true,
    });
    $(this).parent().slider("instance")._mouseMove(newEvent);
  });
}
// SideStone slider
$(document).ready(function () {
  let items = $(".sidestone_item");
  let itemsPerPage = 8;
  let currentStartIndex = 0;

  // Function to update visibility of items and buttons
  function updateItems() {
    let totalItems = items.length;
    let isLastPage = currentStartIndex + itemsPerPage >= totalItems;

    items.each(function (index) {
      // Show items for the current page, hide the rest
      $(this).toggle(
        index >= currentStartIndex && index < currentStartIndex + itemsPerPage
      );
    });

    // Update button visibility
    $("#back-arrow").toggle(currentStartIndex > 0);
    $("#next-arrow").toggle(currentStartIndex + itemsPerPage < totalItems);
  }

  // Check if there are any items, and hide the demo_txt if none are found
  if (items.length === 0) {
    $("#krfs-stoneVisibility").hide();
    $(".shape-filter-mobile").addClass("shape-filter-mobile-hidden");
  } else {
    $("#krfs-stoneVisibility").show();
  }

  // Next button click event
  $("#next-arrow").click(function () {
    let totalItems = items.length;
    if (currentStartIndex + itemsPerPage < totalItems) {
      currentStartIndex += itemsPerPage;
      updateItems();
    }
  });

  // Back button click event
  $("#back-arrow").click(function () {
    if (currentStartIndex > 0) {
      currentStartIndex -= itemsPerPage;
      updateItems();
    }
  });

  // Initialize visibility on load
  updateItems();
});


function krfs_toggle_switch_btn($button, flg) {
  
  let $statusLabel = $button.next(); // Select the status label next to the button

  // Get the type of the button to determine which hidden field to update
  let buttonType = $button.data("type");
  let $hiddenField;

  // Select the appropriate hidden field based on button type
  if (buttonType === "homepreview") {
    $hiddenField = $(".homepreviewfield");
  }

  if (flg) {
    $button.attr("data-state", "unchecked");
    $button.attr("aria-checked", "false");
    $button.val("off");
    $statusLabel.text("Inactive"); // Change label to "Inactive"
    $statusLabel.removeClass("active");
    $hiddenField.val("off"); // Set hidden field value to 'off'
  } else {
    $button.attr("data-state", "checked");
    $button.attr("aria-checked", "true");
    $button.val("on");
    $statusLabel.addClass("active");
    $statusLabel.text("Active"); // Change label back to "Active"
    $hiddenField.val("on"); // Set hidden field value to 'on'
  }
}

$(".krfs-addon-toggle-switch").on("click", function () {
  let $button = $(this);
  let currentState = $button.attr("data-state");

  krfs_toggle_switch_btn($button, currentState === "checked");
  handlefilter_krfs('home_preview');
});


$(document).ready(function () {
  $(".krfs_scrollable_div").each(function () {
    let $container = $(this);
    let $children = $container.children();
    const VISIBLE_COUNT = $(this).data("maxItems") || 8;


    if ($children.length > VISIBLE_COUNT) {
      $children.hide();
      $children.slice(0, VISIBLE_COUNT).show(); // Show first batch

      $container.data("scrollIndex", 0); // Save starting point in data attribute

      $container.prepend('<div class="krfs-left-btn" style="display:none;"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l192 192c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L77.3 256 246.6 86.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-192 192z"/></svg></div>');
      $container.append('<div class="krfs-right-btn"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M310.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-192 192c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L242.7 256 73.4 86.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l192 192z"/></svg></div>');
    }
  });

  $(".krfs-left-btn, .krfs-right-btn").click(function () {
    let $container = $(this).closest(".krfs_scrollable_div");
    let $children = $container.children().not(".krfs-left-btn, .krfs-right-btn");
    let scrollIndex = $container.data("scrollIndex") || 0;
    let totalChildren = $children.length;
    const VISIBLE_COUNT = $container.data("maxItems") || 8;


    if ($(this).hasClass("krfs-right-btn")) {
      scrollIndex += VISIBLE_COUNT;
    } else {
      scrollIndex -= VISIBLE_COUNT;
    }

    // Clamp the index
    if (scrollIndex < 0) scrollIndex = 0;
    if (scrollIndex > totalChildren - VISIBLE_COUNT) {
      scrollIndex = totalChildren - VISIBLE_COUNT;
    }

    $children.hide();
    $children.slice(scrollIndex, scrollIndex + VISIBLE_COUNT).show();
    $container.data("scrollIndex", scrollIndex);

    // Toggle button visibility
    $container.find(".krfs-left-btn").toggle(scrollIndex > 0);
    $container.find(".krfs-right-btn").toggle(scrollIndex + VISIBLE_COUNT < totalChildren);
  });
});

/* ================================================================================================= */
/* =======================================START: new updates======================================== */
/* ================================================================================================= */
$(document).ready(function () {
  krfs_update_active_filters();
});

function capitalizeWords(str) {
  return str.split(' ').map((v) => v.charAt(0).toUpperCase() + v.slice(1)).join(' ');
}

$(".krfs-select-filter-show").click((e) => {
  const $target = $(e.target);

  // Handle individual filter remove
  if ($target.hasClass("krfs-remove-filter")) {
    const $parent = $target.parent();
    let filter_key = $parent.data("key"); // like "metal[]"
    let filter_value = $parent.data("value"); // like "metal_gold"

    // Clean key (remove brackets)
    filter_key = filter_key.replace("[]", "");

    if (filter_value) {
      // Remove only the clicked value from filter array
      krfs_remove_single_active_filter(filter_key, filter_value);
    } else {
      // Remove entire filter (single-select fallback)
      krfs_remove_single_active_filter(filter_key);
    }

    $parent.remove();

    // Hide if all filters are removed
    if ($(".krfs-select-filter-show").html().trim() === "") {
      $(".krfs-select-filter-show").hide();
    }

  } else if ($target.hasClass("krfs-reset-filters")) {
    reset_filters_krfs();
  }
});

function krfs_extract_values(vals) {
  return vals
  .map(s => s.trim().replace(/^[^_]+_/, ''))
  .filter(Boolean); // remove any undefined/null just in case
}

const krfs_update_active_filters = () => {
  let labels_arr = {};

  labels_arr['Style'] = ['style[]'];
  labels_arr['Diamond Shape'] = ['shape'];
  labels_arr['Price'] = ['minprice', 'maxprice'];
  labels_arr['Metal'] = ['metal[]'];
  labels_arr['Stone'] = ['stone'];
  labels_arr['Home Preview'] = ['home_preview'];

  const keys_mapping = {
    'minprice,maxprice': 'price',
  };

  const comma_sep_range_keys = [];

  const boolean_keys = ['home_preview'];

  const multi_keys = ['style[]','metal[]']

  let uri = new URLSearchParams(window.location.search);

  // if(!uri.has('shape') && DListing.shape_slug_config && DListing.url_shape_preset) {
  //   uri.set('shape', DListing.url_shape_preset);
  // }

  if (uri.has('sort')) {
    uri.delete('sort');
  }

  if (uri.size == 0) {
    $(".krfs-select-filter-show").html('');
    $(".krfs-select-filter-show").hide();
    $(".filter-main-reset").hide();
  } else {
    $(".krfs-select-filter-show").attr('style', 'display: block;');
    $(".filter-main-reset").attr('style', 'display: block;');
    let active_filters = [];
    Object.keys(labels_arr).forEach((key) => {
      let filter = labels_arr[key];
      if (filter.length == 1) {
        let k = filter[0];
        if (uri.has(k)) {
          active_filters.push(key);
        }
      } else {
        if (uri.has(filter[0]) || uri.has(filter[1])) {
          active_filters.push(key);
        }
      }
    });

    let active_filters_html = active_filters.map((filter) => {
      let filter_key = labels_arr[filter];

      let mapped_filter_key = Object.keys(keys_mapping).includes(filter_key.join(','))
        ? keys_mapping[filter_key.join(',')]
        : filter_key[0];

      $(`.krfs_filter-button-mobile button[data-key="${mapped_filter_key}"]`).addClass('active-filter');

      // Handle multi-select filters (metal[], style[])
      if (multi_keys.includes(filter_key[0])) {
        let all_vals = uri.getAll(filter_key[0]);
        let values_html = all_vals.map((val) => {
          let display_val = capitalizeWords(krfs_extract_values([val])[0].replaceAll("_", " "));
          return `
            <span class="light-text" data-key="${filter_key[0]}" data-value="${val}">
              ${display_val}
              <span class="cross-line krfs-remove-filter">×</span>
            </span>
          `;
        }).join('');

        return `
          <div>
            <span class="krfs-select-filter-heading dark-text">${filter}:</span>
            ${values_html}
          </div>
        `;
      }

      // Handle single filters
      let filter_val = uri.get(filter_key[0]);

      if (filter_val && filter_val.indexOf("_") !== -1) {
        filter_val = filter_val.split("_");
        filter_val.shift();
        filter_val = filter_val.join(" ");
      }

      // filter_val = filter_val.replaceAll("style","").trim();

      if (filter_key.length == 2) {
        if (filter_key[0] == 'minprice') {
          filter_val = `${formatCurrency(filter_val)} - ${formatCurrency(uri.get(filter_key[1]))}`;
        } else {
          filter_val = `${uri.get(filter_key[0])} - ${uri.get(filter_key[1])}`;
        }
      } else if (comma_sep_range_keys.includes(filter_key[0]) && filter_val.includes(',')) {
        let vals = filter_val.split(',');
        const v1 = capitalizeWords(vals[0]);
        const v2 = capitalizeWords(vals[vals.length - 1]);
        filter_val = v1 + ' - ' + v2;
      } else {
        filter_val = capitalizeWords(filter_val);
      }

      if (boolean_keys.includes(filter_key[0])) {
        return `
          <div data-key="${mapped_filter_key}">
            <span class="krfs-select-filter-heading dark-text"></span>
            <span class="light-text">${filter}</span>
            <span class="cross-line krfs-remove-filter">×</span>
          </div>
        `;
      } else {
        return `
          <div data-key="${mapped_filter_key}">
            <span class="krfs-select-filter-heading dark-text">${filter}:</span>
            <span class="light-text">${filter_val}</span>
            <span class="cross-line krfs-remove-filter">×</span>
          </div>
        `;
      }
    }).flat(); // ensures multi-select maps are flattened


    if (uri.size > 0) {
      let reset_filter = `<div style="cursor: pointer;">
          <span class="light-text krfs-reset-filters">Reset All</span>
          <span class="cross-line krfs-reset-filters">×</span>
        </div>`;
      active_filters_html.push(reset_filter);

      $(".krfs-select-filter-show").html(active_filters_html.join(''));
    }

  }
};

$(".krfs-ring-style-name").click(function () {
  if (!$(this).hasClass("active")) {
    var selectedStyle = $(this).data("style");
    $('.krfs-ring-style-name[data-style="' + selectedStyle + '"]').addClass("active").next("span").addClass("active");
    handlefilter_krfs("style");
  } else {
    var selectedStyle = $(this).data("style");
    $('.krfs-ring-style-name[data-style="' + selectedStyle + '"]').removeClass("active").next("span").removeClass("active");
    krfs_remove_single_active_filter('style', selectedStyle);

    // $(this).removeClass("active").next("span").removeClass("active");
  }
});

$(".krfs-metal-name").click(function () {
  if (!$(this).hasClass("active")) {
    var selectedMetal = $(this).data("metal");
    $('.krfs-metal-name[data-metal="' + selectedMetal + '"]').addClass("active").next("span").addClass("active");
    handlefilter_krfs("metal");
  } else {
    var selectedMetal = $(this).data("metal");
    $('.krfs-metal-name[data-metal="' + selectedMetal + '"]').removeClass("active").next("span").removeClass("active");
    krfs_remove_single_active_filter('metal', selectedMetal);
  }
});

$(".krfs-filter-shape").click(function () {
  if (!$(this).hasClass("active")) {
    $(this).addClass("active").next("span").addClass("active");
    $(".krfs-filter-shape").not(this).removeClass("active").next("span").removeClass("active");
    handlefilter_krfs("shape");
  }
});

$(".krfs-sidestone-btn").click(function () {
  if (!$(this).hasClass("active")) {
    $(this).addClass("active").next("span").addClass("active");
    $(".krfs-sidestone-btn").not(this).removeClass("active").next("span").removeClass("active");
    handlefilter_krfs("stone");
  }
});

const krfs_getAllFilters = (reset) => {
  if (reset == "reset") {
    return null;
  }
  let filters = {
    price: $("#price-range")
      .slider("values")
      .map((val) => parseInt(val)),
  };

  let curr_shape = $(".krfs-filter-shape.active").data("shape");

  // Add shape filter if selected
  if (curr_shape != undefined) {
    filters["shape"] = curr_shape;
  }

  let curr_stone = $(".krfs-sidestone-btn.active").data("stone");

  // Add stone filter if selected
  if (curr_stone != undefined) {
    filters["stone"] = curr_stone;
  }

  let selected_styles = [];
  $(".krfs-ring-style-name.active").each(function () {
    let style_val = $(this).data("style");
    if (style_val !== undefined) {
      selected_styles.push(style_val);
    }
  });
  selected_styles = [...new Set(selected_styles)];

  if (selected_styles.length > 0) {
    filters["style"] = selected_styles;
  }
  
  // let current_ring_style = $(".krfs-ring-style-name.active").data("style");
  // if (current_ring_style != undefined) {
  //   filters["style"] = current_ring_style;
  // }

  let selected_metals = [];
  $(".krfs-metal-name.active").each(function () {
    let metal_val = $(this).data("metal");
    if (metal_val !== undefined) {
      selected_metals.push(metal_val);
    }
  });
  selected_metals = [...new Set(selected_metals)];

  if (selected_metals.length > 0) {
    filters["metal"] = selected_metals;
  }

  // let current_metal = $(".krfs-metal-name.active").data("metal");
  // if (current_metal != undefined) {
  //   filters["metal"] = current_metal;
  // }

  let result_set = $("#result_set").val();
  if (result_set != undefined) {
    filters["result_set"] = result_set;
  }

  let home_preview = $(".homepreviewfield").val();
  if (result_set != undefined && home_preview == 'on') {
    filters["home_preview"] = 'true';
  }

  return filters;
};

const krfs_remove_single_active_filter = (filter_key, data_val = null) => {
  if(filter_key == 'style' && data_val == null) {
    $('.krfs-ring-style-name').removeClass("active").next("span").removeClass("active");
  } else if(filter_key == 'style' && data_val != null) {
    $(`.krfs-ring-style-name[data-style="${data_val}"]`).removeClass("active").next("span").removeClass("active");
  }else if(filter_key == 'metal' && data_val == null) {
    $('.krfs-metal-name').removeClass("active").next("span").removeClass("active"); 
  }else if(filter_key == 'metal' && data_val != null) {
    $(`.krfs-metal-name[data-metal="${data_val}"]`).removeClass("active").next("span").removeClass("active");
  }else if(filter_key == 'shape') {
    $(".krfs-filter-shape").removeClass("active").next("span").removeClass("active");
  }else if(filter_key == 'price') {
    $("#price-range").slider("values", [
      parseFloat(KRFListing.krfs_minprice),
      parseFloat(KRFListing.krfs_maxprice),
    ]);
    $("#min_price").val(
      formatCurrency(parseFloat(KRFListing.krfs_minprice))
    );
    $("#max_price").val(
      formatCurrency(parseFloat(KRFListing.krfs_maxprice))
    );
  } else if (filter_key == 'stone') {
    $(".krfs-sidestone-btn").removeClass("active").next("span").removeClass("active");
    // $(".krfs-sidestone-btn div.active").removeClass("active").next("span").removeClass("active");
  }else if(filter_key == 'home_preview') {
    krfs_toggle_switch_btn($(".krfs-home-review"), true);
  }
  handlefilter_krfs(filter_key, null, true);
  $(`.krfs_filter-button-mobile button[data-key="${filter_key}"]`).removeClass('active-filter');
};

const reset_filters_krfs = () => {
  $("#krfs_search_txt").val("");
  $("#price-range").slider("values", [
    parseFloat(KRFListing.krfs_minprice),
    parseFloat(KRFListing.krfs_maxprice),
  ]);
  search_cooldown = false;
  $("#min_price").val(
    formatCurrency(parseFloat(KRFListing.krfs_minprice))
  );
  $("#max_price").val(
    formatCurrency(parseFloat(KRFListing.krfs_maxprice))
  );
  $(".krfs-ring-style-name").removeClass("active").next("span").removeClass("active");
  $(".krfs-metal-name").removeClass("active").next("span").removeClass("active");
  $(".krfs-filter-shape").removeClass("active").next("span").removeClass("active");
  $(".krfs-sidestone-btn").removeClass("active").next("span").removeClass("active");
  $(".stone-box").removeClass("active").next("span").removeClass("active");
  $("#all_diamond_label").addClass("active");
  $("#krfs_bridal_set_tab").removeClass("active");
  krfs_toggle_switch_btn($(".krfs-home-review"), true);
  handlefilter_krfs("reset");
};

const handlefilter_krfs = (filter, priceValues = null, single_remove = false) => {
  scroll_cooldown = true;
  if (filterDebounce) {
    clearTimeout(filterDebounce);
  }
  filterDebounce = setTimeout(() => {
    let filters = krfs_getAllFilters();
    current_page = 1;
    let sort = $("#krfs_prods_sort").val();
    $(".finish_message").remove();
    if (filter != "search") {
      search_cooldown = false;
    }
    let filterData = {
      action: "krfs_filter_products",
      sort: sort,
      style: filters.style,
      metal: filters.metal,
      catg: KRFListing.current_category,
      minprice: priceValues ? priceValues[0] : filters.price[0], // Use passed priceValues if available
      maxprice: priceValues ? priceValues[1] : filters.price[1], // Use passed priceValues if available
      nonce: KRFListing.krfs_nonce
    };

    // Add shape filter if selected
    if (filters.shape != undefined) {
      filterData.shape = filters.shape;
    }
    if (filters.stone != undefined) {
      filterData.stone = filters.stone;
    }
    if (filters.result_set != undefined) {
      filterData.result_set = filters.result_set;
    }
    if (filters.home_preview != undefined) {
      filterData.home_preview = filters.home_preview;
    }
    if (filter == "reset") {
      current_page = 1;
      prepare_filters_uri_krfs(null);
      filterData = {
        action: "krfs_filter_products",
        catg: KRFListing.current_category,
        sort: sort,
        minprice: parseFloat(KRFListing.krfs_minprice),
        maxprice: parseFloat(KRFListing.krfs_maxprice),
        nonce: KRFListing.krfs_nonce
      };
    } else if (filter == "search") {
      prepare_filters_uri_krfs(null, single_remove);
      search_cooldown = true;
      let search_txt = $("#krfs_search_txt").val();
      filterData = {
        action: "krfs_filter_products",
        catg: KRFListing.current_category,
        search: search_txt,
        sort: sort,
        nonce: KRFListing.krfs_nonce
      };
    }

    if (filter != "search") {
      $("#krfs_search_txt").val("");
    }

    krfs_toggle_listing_loader(true);
    switch (filter) {
      case "shape":
        prepare_filters_uri_krfs({ shape: filterData.shape }, single_remove);
        break;
      case "stone":
        prepare_filters_uri_krfs({ stone: filterData.stone }, single_remove);
        break;
      case "style":
        prepare_filters_uri_krfs({ style: filterData.style }, single_remove);
        break;
      case "metal":
        prepare_filters_uri_krfs({ metal: filterData.metal }, single_remove);
        break;
      case "sort":
        prepare_filters_uri_krfs({ sort: sort }, single_remove);
        break;
      case "result_set":
        // prepare_filters_uri_krfs({ result_set: filterData.result_set }, single_remove);
        break;
      case "home_preview":
        prepare_filters_uri_krfs({ home_preview: filterData.home_preview }, single_remove);
        break;
      case "price":
        prepare_filters_uri_krfs({
          minprice: filterData.minprice,
          maxprice: filterData.maxprice,
        }, single_remove);
        break;
    }

    $.ajax({
      url: KRFS_GLOBALS.ajax_url, // URL to send the request to
      type: "GET", // Use 'POST' if your server expects POST requests
      data: filterData, // The data you are sending with the request
      catg: KRFListing.current_category,
      success: function (response) {
        scroll_cooldown = false;
        KRFStats.max_pages = response?.pagination?.total_pages;

        if (KRFStats.max_pages == current_page || response.count == 0) {
          is_load_more_diamonds = false;
        } else {
          is_load_more_diamonds = true;
        }
        if (response.html) {
          krfs_toggle_listing_loader(false);

          const product_count = response?.pagination?.total_products ?? 0;
          const bridal_count = response?.pagination?.bridal_sets_count ?? 0;

          $(".krfs_listing_count").html(`${product_count}`);
          $(".krfs_listing_count_bridal").html(`${bridal_count}`);
          $("#krfs_bridal_set_tab").toggle(bridal_count != 0);

          $("#krfs_product_grid").empty().append(response.html); // Update the grid with the new HTML
          krfs_init_grid_listeners();
        } else {
          console.error("HTML content not found in response");
        }
      },
      error: function (xhr, status, error) {
        console.error("AJAX error:", status, error); // Log any errors that occur
      },
    });
  }, 1000);
};

const krfs_init_grid_listeners = () => {
  $(".image-div").off();
  $(".krfs_prod_item_img").off();

  $(".image-div").on("mouseenter", function () {
    if ($(this).find(".krfs_prod_item_gallery_img").length > 0) {
      $(this).find(".krfs_prod_item_gallery_img").show();
      $(this).find(".krfs_prod_item_img").hide(); 
    }
  });

  $(".image-div").on("mouseleave", function () {
    $(this).find(".krfs_prod_item_gallery_img").hide();
    $(this).find(".krfs_prod_item_img").show();
  });

  $(".krfs-metal-item").on("mouseenter", function () {
    var metalItem = $(this);
    var imageUrl = metalItem.data("img");

    // Get the parent div that has data-id attribute
    var parent = metalItem.closest("[data-id]");
    var targetImgId = "krfs_prod_item_img_" + parent.data("id");

    $("#" + targetImgId).attr("src", imageUrl);
  });

  $(".krfs-metal-item").on("mouseleave", function () {
    var metalItem = $(this);

    // Get the parent div that has data-id attribute
    var parent = metalItem.closest("[data-id]");
    var targetImgId = "krfs_prod_item_img_" + parent.data("id");

    var imageUrl = $("#" + targetImgId).data("default");

    $("#" + targetImgId).attr("src", imageUrl);
  });

}

$(".filter-main-reset").click(function () {
  reset_filters_krfs();
});


document.addEventListener("DOMContentLoaded", function () {
  const openBtn = document.getElementById("openFilterBtn");
  const closeBtn = document.getElementById("filtercloseBtn");
  const filterContainer = document.getElementById("filterContainer");

  openBtn.addEventListener("click", function () {
    filterContainer.classList.add("active");
  });

  closeBtn.addEventListener("click", function () {
    filterContainer.classList.remove("active");
  });
});

document.addEventListener("DOMContentLoaded", function () {
  const toggleButtons = document.querySelectorAll(".krfs-filter-show-button");

  toggleButtons.forEach(function (button) {
    button.addEventListener("click", function () {
      const parent = button.closest(".krfs-inner-metal-filter, .krfs-inner-ring-filter");
      const section = parent.querySelector(".krfs-filter-show-section");

      section.classList.toggle("show");

      // Optional: Rotate arrow
      const arrow = button.querySelector(".arrow-image");
      if (arrow) {
        arrow.classList.toggle("rotated");
      }
    });
  });
});


/* ================================================================================================= */
/* =======================================END: new updates========================================== */
/* ================================================================================================= */