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

try {
  numeral.register('locale', DListing.currency_locale, NUMERAL_LANGUAGES[DListing.currency_locale]);
  numeral.locale(DListing.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;
}


// Catg Constants
const KIRB_CATG = {
  NATURAL: "NATURAL",
  GEMSTONE: "GEMSTONE",
  LAB_CREATED: "LAB CREATED",
  COLORED_DIAMONDS: "COLORED DIAMONDS",
};

let current_page = 1;
let current_prods = 0;

let scroll_cooldown = true;
let is_load_more_diamonds = DStat.diamond_listing_global.total_count != 0;
let total_load_more_diamonds = 0;
let compare_list_login = [];

const PRICE_FILTER_MAPPINGS = {
  'inMax': 0,
  'outMax': 1000,
};

let slider_memory = null;


// ======================== Initialize the filter values start ========================
function getFilterValues(filters_uri, param, filter, transformFunc = (x) => x) {
  let values = filters_uri.get(param);
  if (values) {
    values = transformFunc(values).split(",");
    if(values.length == 1) {
      let itemIdx = filter.findIndex(item => item.toLowerCase() === values[0].toLowerCase());
      return itemIdx == -1 ? [0, filter.length] : [itemIdx, itemIdx + 1];
    }else if(values.length > 1) {
      let range = [
        filter.findIndex(item => item.toLowerCase().trim() === values[0].trim().toLowerCase()),
        filter.findIndex(item => item.toLowerCase().trim() === values[values.length - 1].toLowerCase().trim())
      ];
      range[0] = range[0] == -1 ? 0 : range[0];
      range[1] = range[1] == -1 ? filter.length : range[1] + 1;
      return range;
    }
  }
  return [0, filter.length];
}

function getRangeValues(
  filters_uri,
  paramMin,
  paramMax,
  filter,
  minParam,
  maxParam
) {
  let min = filters_uri.get(paramMin);
  let max = filters_uri.get(paramMax);
  if(min && max) {
    min = parseFloat(min);
    max = parseFloat(max);
    let filterMin = parseFloat(filter[minParam]);
    let filterMax = parseFloat(filter[maxParam]);
    return [Math.max(min, filterMin), Math.min(max, filterMax)];
  }else{
    return [parseFloat(filter[minParam]), parseFloat(filter[maxParam])];
  }
}

const filters_uri = new URLSearchParams(window.location.search);
let ini_carat = getRangeValues(
  filters_uri,
  "mincarat",
  "maxcarat",
  DFilters.filter_carat_range,
  "minCarat",
  "maxCarat"
);
let ini_color = getFilterValues(filters_uri, "color", DFilters.filter_colors);
let ini_cut = getFilterValues(filters_uri, "cut", DFilters.filter_cuts);

let ini_clarity = getFilterValues(
  filters_uri,
  "clarity",
  DFilters.filter_clarity,
  (val) => val.replaceAll("FL,IF", "FL/IF")
);

let ini_price = getRangeValues(
  filters_uri,
  "minprice",
  "maxprice",
  DFilters.filter_price_range,
  "minSaleAmt",
  "maxSaleAmt"
);

let ini_polish = getFilterValues(filters_uri, "polish", DFilters.filter_polish);
let ini_symmetry = getFilterValues(filters_uri, "symmetry", DFilters.filter_symmetry);
let ini_fluor = getFilterValues(filters_uri, "fluor", DFilters.filter_fluor);
let ini_table = getRangeValues(
  filters_uri,
  "mintable",
  "maxtable",
  DFilters.filter_table_range,
  "minTa",
  "maxTa"
);
let ini_depth = getRangeValues(
  filters_uri,
  "mindepth",
  "maxdepth",
  DFilters.filter_depth_range,
  "minTd",
  "maxTd"
);
let ini_lw_ratio = getRangeValues(
  filters_uri,
  "minratio",
  "maxratio",
  DFilters.filter_lw_ratio_range,
  "min",
  "max"
);
// ======================== Initialize the filter values end ========================
function elementInViewport(el) {
  const rect = el.getBoundingClientRect();  
  const windowHeight = window.innerHeight || document.documentElement.clientHeight;
  return rect.bottom <= windowHeight;
}

function elementScrollEnd(el) {
  return Math.ceil(el.scrollTop) + Math.ceil(el.clientHeight) >= Math.round(el.scrollHeight);
}

const handleScrollEvent = (element, isScrollable) => {
  let active_tab = $("#main_tabs").find("div.active").data("bs-target");
  if (active_tab === "#all_diamond" && !scroll_cooldown && is_load_more_diamonds) {  
    let condition = isScrollable ? elementScrollEnd(element) : elementInViewport(element, null);
    if (condition) {
      kirb_load_more_prods();
      scroll_cooldown = true;
    }
  }
};

const kirb_list_scroll_listeners = () => {
  $(document).off('scroll');
  $("#kirb_product_list_wrapper").off('scroll');

  if ($("#kirb_product_list_wrapper").css("overflow") === 'scroll') {
    console.log("Scrollable list detected");
    if($("#diamond_content #griddesign").hasClass("active")) {
      console.log("Grid design active");
      $(document).on('scroll', function() {
        let list_type = $(".grid-list-tab").find("div.active").data("bs-target");
        handleScrollEvent(document.getElementById(list_type.replace("#", "")), false);
      });
    }else{
      console.log("List design active");
      $("#kirb_product_list_wrapper").on('scroll', function() {
        handleScrollEvent(document.getElementById('kirb_product_list_wrapper'), true);
      });
    }
  } else {
    $(document).on('scroll', function() {
      let list_type = $(".grid-list-tab").find("div.active").data("bs-target");
      handleScrollEvent(document.getElementById(list_type.replace("#", "")), false);
    });
  }
};

$(document).ready(async function () {
  $(".moreless__btn").click(function () {
    $(".more-filters").toggleClass("more-filters-height");
    $(".moreless__btn").text($(this).text().trim() === `${DTranslations['more_filters']}`+' +' ? `${DTranslations['more_filters']}`+' -' : `${DTranslations['more_filters']}`+' +');

    if(DListing.current_catg == KIRB_CATG.COLORED_DIAMONDS) {
      $(".kirb-filter-advance-block").toggle();
    }
  });

  if ($("#kirb_product_list_wrapper").css("overflow") === 'scroll') {
    if($("#diamond_content #griddesign").hasClass("active")) {
      $("#diamond_content #griddesign").removeClass("active");
      $("#diamond_content #listdesign").addClass("active");
    }
  }

  kirb_list_scroll_listeners();
  
  // Handle shapes selection
  $(".kirb-diamond-shapes > .shape_item >.shape-box").click(function () {
    if (!$(this).hasClass("active")) {
      $(".kirb-diamond-shapes> .shape_item  > .shape-box").removeClass("active");
      $(this).addClass("active");
      handleFilterChange("shape");

      // Disable/Enable cut range slider
    }
  });

  $(document).on('click', '.shape-box', function () {
  const subtitle = $(this).find('.shape-img').data('subtitle');
    if (subtitle) {
        $('#kirb_shape_subtitle').text(subtitle);
    }
  });
  
  // Get the value of category
  if(DListing.current_catg == KIRB_CATG.GEMSTONE || DListing.current_catg == KIRB_CATG.COLORED_DIAMONDS) {
    $(".kirb_gem_color").click((e)=>{
      if(!$(e.currentTarget).hasClass("active")) {
        $(".kirb_gem_color").removeClass("active");
        $(e.currentTarget).addClass("active");
        handleFilterChange("color");
      }
    });
  }
  if(DListing.current_catg == KIRB_CATG.GEMSTONE) {
    $(".kirb_gem_type").click((e)=>{
      if($(e.currentTarget).hasClass("active")) {
        $(e.currentTarget).removeClass("active");
        handleFilterChange('gemType');
        return;
      }
      $(".kirb_gem_type").removeClass("active");
      $(e.currentTarget).addClass("active");
      handleFilterChange("gemType");
    });
  }

  if(DListing.current_catg == KIRB_CATG.COLORED_DIAMONDS) {
    $(".kirb_diamond_intensity").click((e)=>{
      if($(e.currentTarget).hasClass("active")) {
        $(e.currentTarget).removeClass("active");
        handleFilterChange('intensity');
        return;
      }
      $(".kirb_diamond_intensity").removeClass("active");
      $(e.currentTarget).addClass("active");
      handleFilterChange('intensity');
    });
  }

  // Prepare Modal for 360 view
  setTimeout(() => {
    $("body").append(DViewModals.popup_360_code);
    
    // Flushes the modals from the memory
    DViewModals = null;
  }, 1000);


  //////////////////////////////////////////////////////////////////////////////
  /* 
    The below JavaScript code is setting up event listeners for input fields with specific classes
  (carat_inp, price_inp, table_inp, depth_inp, lw_ratio_inp). When the input in these fields
  changes, the code retrieves the minimum and maximum values entered, performs some validation
  checks against predefined ranges (carat_range, price_range, table_range, depth_range,
  lw_ratio_range), and updates corresponding slider values if the input values are within the
  allowed ranges. 
  */


  $(".carat_inp").on("change", function () {
    let min = parseFloat($("#min_carat").val());
    let max = parseFloat($("#max_carat").val());

    // do not chagne filter value less than and max value.
    if(min <= DFilters.filter_carat_range.minCarat  || isNaN(min) || min>max) {
      $("#min_carat").val(DFilters.filter_carat_range.minCarat);
      min = DFilters.filter_carat_range.minCarat;
    }


    // if max value less than min then set max to min.
    if(max < min) {
      $("#max_carat").val(DFilters.filter_carat_range.minCarat);
      max =  DFilters.filter_carat_range.minCarat;
    }

    // if max value is greater than final max then set to final max
    if(max >= DFilters.filter_carat_range.maxCarat || isNaN(max)) {
      $("#max_carat").val(DFilters.filter_carat_range.maxCarat);
      max = DFilters.filter_carat_range.maxCarat;
    }

    // if value is less than and max vlaue then set max value on key press.
    if(max >= DFilters.filter_carat_range.maxCarat) {
      max  = DFilters.filter_carat_range.maxCarat;
    }

    if (
      min >= DFilters.filter_carat_range.minCarat &&
      max <= DFilters.filter_carat_range.maxCarat
    ) {
      $("#carat-range").slider("option", "values", [min, max]);
      handleFilterChange("carat");
    }
    
    $("#min_carat").val(parseFloat($("#min_carat").val()).toFixed(2));
    $("#max_carat").val(parseFloat($("#max_carat").val()).toFixed(2));
  });

  $(".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 <= DFilters.filter_price_range.minSaleAmt ||  isNaN(minP) || minP>maxP) {
          $("#min_price").val(formatCurrency(DFilters.filter_price_range.minSaleAmt));
          minP = DFilters.filter_price_range.minSaleAmt;
      }

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

    if(maxP >= DFilters.filter_price_range.maxSaleAmt || isNaN(maxP)) {
      $("#max_price").val(formatCurrency(DFilters.filter_price_range.maxSaleAmt));
      maxP = DFilters.filter_price_range.maxSaleAmt;
    }

    if (
      minP >= DFilters.filter_price_range.minSaleAmt &&
      maxP <= DFilters.filter_price_range.maxSaleAmt
    ) {
      $("#price-range").slider("option", "values", [map_values_for_slider(minP), map_values_for_slider(maxP)]);
      $("#min_price").val(formatCurrency(minP));
      $("#max_price").val(formatCurrency(maxP));
      handleFilterChange("price");
    }
  });

  $(".table_inp").on("change", function () {
    let min = parseFloat($("#min_table").val());
    let max = parseFloat($("#max_table").val());

    // is data blank or less than min value then update to min value.
    if(min <= DFilters.filter_table_range.minTa || isNaN(min) || min>max) {
      $("#min_table").val(DFilters.filter_table_range.minTa.toFixed(1));
      min = DFilters.filter_table_range.minTa;
    }


    // if max value less than min then set max to min.
    if(max < min) {
       $("#max_table").val(DFilters.filter_table_range.minTa.toFixed(1));
       max =  DFilters.filter_table_range.minTa;
    }

    // is data blank or less than min value then update to min value.
    if(min <= DFilters.filter_table_range.minTa || isNaN(min)) {
      $("#min_table").val(DFilters.filter_table_range.minTa.toFixed(1));
      min = DFilters.filter_table_range.minTa;
    }

    // if max vlaue is greater then max value then upate to max.
    if(max >= DFilters.filter_table_range.maxTa || isNaN(max)) {
      $("#max_table").val(DFilters.filter_table_range.maxTa.toFixed(1));
      max = DFilters.filter_table_range.maxTa;
    }

    if (min >= DFilters.filter_table_range.minTa && max <= DFilters.filter_table_range.maxTa) {
      $("#table-range").slider("option", "values", [min, max]);
      handleFilterChange("table");
    }

    $("#min_table").val(parseFloat($("#min_table").val()).toFixed(1));
    $("#max_table").val(parseFloat($("#max_table").val()).toFixed(1));
  });

  $(".depth_inp").on("change", function () {
    let min = parseFloat($("#min_depth").val());
    let max = parseFloat($("#max_depth").val());

    // is data blank or less than min value then update to min value.
    if(min <= DFilters.filter_depth_range.minTd  || isNaN(min) || min>max) {
      $("#min_depth").val(DFilters.filter_depth_range.minTd.toFixed(1));
      min = DFilters.filter_depth_range.minTd;
    }

    // if max value less than min then set max to min.
    if(max < min) {
       $("#max_depth").val(DFilters.filter_depth_range.minTd.toFixed(1));
       max =  DFilters.filter_depth_range.minTd;
    }

    // if max vlaue is greater then max value then upate to max.
    if(max >= DFilters.filter_depth_range.maxTd || isNaN(max)) {
      $("#max_depth").val(DFilters.filter_depth_range.maxTd.toFixed(1));
      max = DFilters.filter_depth_range.maxTd;
    }

    if (min >= DFilters.filter_depth_range.minTd && max <= DFilters.filter_depth_range.maxTd) {
      $("#depth-range").slider("option", "values", [min, max]);
      handleFilterChange("depth");
    }

    $("#min_depth").val(parseFloat($("#min_depth").val()).toFixed(1));
    $("#max_depth").val(parseFloat($("#max_depth").val()).toFixed(1));
  });

  $(".lw_ratio_inp").on("change", function () {
    let min = parseFloat($("#min_lw-ratio").val());
    let max = parseFloat($("#max_lw-ratio").val());

     // is data blank or less than min value then update to min value.
     if(min <= DFilters.filter_lw_ratio_range.min || isNaN(min)  || min>max) {
      $("#min_lw-ratio").val(DFilters.filter_lw_ratio_range.min.toFixed(2));
      min = DFilters.filter_lw_ratio_range.min;
    }

    // if max value less than min then set max to min.
    if(max < min) {
      $("#max_lw-ratio").val(DFilters.filter_lw_ratio_range.min.toFixed(2));
      max =  DFilters.filter_lw_ratio_range.min;
    }

    // if max vlaue is greater then max value then upate to max.
    if(max >= DFilters.filter_lw_ratio_range.max || isNaN(max)) {
      $("#max_lw-ratio").val(DFilters.filter_lw_ratio_range.max.toFixed(2));
        max = DFilters.filter_lw_ratio_range.max;
    }

    if (min >= DFilters.filter_lw_ratio_range.min && max <= DFilters.filter_lw_ratio_range.max) {
      $("#lw-ratio-range").slider("option", "values", [min, max]);
      handleFilterChange("lw_ratio");
    }

    $("#min_lw-ratio").val(parseFloat($("#min_lw-ratio").val()).toFixed(2));
    $("#max_lw-ratio").val(parseFloat($("#max_lw-ratio").val()).toFixed(2));
  });

  //////////////////////////////////////////////////////////////////////////////

  // Fill the diamond listing count
  $(".kirb_diam_count").html(
    `${DTranslations['showing']} ${DStat.diamond_listing_global.total_count} ${DTranslations['result']}${DStat.diamond_listing_global.total_count > 1 ? 's' : ''}`
  );

  $("#all_diamond_label").html(`${DTranslations['all_results']} (${DStat.diamond_listing_global.total_count})`);


  // Enable/Disable load more products
  if (DStat.diamond_listing_global.total_pages == current_page) {
    is_load_more_diamonds = false;
  }

  // Fix global objects
  Object.keys(DStat.diamond_listing_global).forEach((key) => {
    DStat.diamond_listing_global[key] = parseFloat(DStat.diamond_listing_global[key]);
  });

  current_prods = DStat.diamond_listing_global.count;

  /////////////////////// Initialize Sliders Start ///////////////////////

  // carat-range
  $("#carat-range").slider({
    range: true,
    min: DFilters.filter_carat_range.minCarat,
    max: DFilters.filter_carat_range.maxCarat,
    step: 0.01,
    values: ini_carat,
    slide: function (event, ui) {
      $("#min_carat").val(parseFloat(ui.values[0]).toFixed(2));
      $("#max_carat").val(parseFloat(ui.values[1]).toFixed(2));
    },
    start: function (event, ui) {
      slider_memory = ui.values;
    },
    stop: function (event, ui) {
      if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
        handleFilterChange("carat");
      }
    },
  });
  $("#min_carat").val(
    parseFloat($("#carat-range").slider("values", 0)).toFixed(2)
  );
  $("#max_carat").val(
    parseFloat($("#carat-range").slider("values", 1)).toFixed(2)
  );

  // price-range
  // $("#price-range").slider({
  //   range: true,
  //   min: DFilters.filter_price_range.minSaleAmt,
  //   max: DFilters.filter_price_range.maxSaleAmt,
  //   values: ini_price,
  //   slide: function (event, ui) {
  //     $("#min_price").val(formatCurrency(ui.values[0]));
  //     $("#max_price").val(formatCurrency(ui.values[1]));
  //     handleFilterChange("price");
  //   },
  // });
  $("#price-range").slider({
    range: true,
    min: 0,
    max: 1000,
    values: [map_values_for_slider(ini_price[0]), map_values_for_slider(ini_price[1])],
    slide: function (event, ui) {
      const map1 = map_values_of_slider(parseInt(ui.values[0]));
      const map2 = map_values_of_slider(parseInt(ui.values[1]));
      // Map the slider's values to the custom ranges
      $("#min_price").val(formatCurrency(map1));
      $("#max_price").val(formatCurrency(map2));
    },
    start: function (event, ui) {
      slider_memory = ui.values;
    },
    stop: function (event, ui) {
      if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
        handleFilterChange("price");
      }
    }
  });

  $("#min_price").val(formatCurrency(ini_price[0]));
  $("#max_price").val(formatCurrency(ini_price[1]));
 
  if (DListing.current_catg != KIRB_CATG.GEMSTONE) {
    // color range filter
    $("#colors-range").prev(".slider-dots").append(DFilters.filter_colors.map((elem, index) => `<span class="slider-dot" style="left: ${index * 100 / DFilters.filter_colors.length}%;"></span>`).join(''));
    $("#colors-range").slider({
      range: true,
      min: 0,
      max: DFilters.filter_colors.length,
      values: ini_color,
      slide: function (event, ui) {
        // Check if the values are overlapping
        if (ui.values[0] >= ui.values[1]) {
          return false;
        }
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("color");
        }
      }
    });

    // cut range filter
    $("#cut-range").prev(".slider-dots").append(DFilters.filter_cuts.map((elem, index) => `<span class="slider-dot" style="left: ${index * 100 / DFilters.filter_cuts.length}%;"></span>`).join(''));
    $("#cut-range").slider({
      step: 1,
      range: true,
      min: 0,
      max: DFilters.filter_cuts.length,
      values: ini_cut,
      slide: function (event, ui) {
        // Check if the values are overlapping
        if (ui.values[0] >= ui.values[1]) {
          // Adjust the overlapping handle to prevent overlap
          return false;
        }
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("cut");
        }
      }
    });

    // Disable cut on page load and shape not round

    $("#cut__filterss").val(0, 1);

    // Clarity range filter
    $("#clarity-range").prev(".slider-dots").append(DFilters.filter_clarity.map((elem, index) => `<span class="slider-dot" style="left: ${index * 100 / DFilters.filter_clarity.length}%;"></span>`).join(''));
    $("#clarity-range").slider({
      step: 1,
      range: true,
      min: 0,
      max: DFilters.filter_clarity.length,
      values: ini_clarity,
      slide: function (event, ui) {
        // Check if the values are overlapping
        if (ui.values[0] >= ui.values[1]) {
          // Adjust the overlapping handle to prevent overlap
          return false;
        }
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("clarity");
        }
      }
    });
    $("#clarity__filterss").val(0, 1);

    // polish range filter
    $("#polish-range").prev(".slider-dots").append(DFilters.filter_polish.map((elem, index) => `<span class="slider-dot" style="left: ${index * 100 / DFilters.filter_polish.length}%;"></span>`).join(''));
    $("#polish-range").slider({
      step: 1,
      range: true,
      min: 0,
      max: DFilters.filter_polish.length,
      values: ini_polish,
      slide: function (event, ui) {
        // Check if the values are overlapping
        if (ui.values[0] >= ui.values[1]) {
          // Adjust the overlapping handle to prevent overlap
          return false;
        }
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("polish");
        }
      }
    });
    $("#polish__filterss").val(0, 1);

    // symmetry range filter
    $("#symmetry-range").prev(".slider-dots").append(DFilters.filter_symmetry.map((elem, index) => `<span class="slider-dot" style="left: ${index * 100 / DFilters.filter_symmetry.length}%;"></span>`).join(''));
    $("#symmetry-range").slider({
      step: 1,
      range: true,
      min: 0,
      max: DFilters.filter_symmetry.length,
      values: ini_symmetry,
      slide: function (event, ui) {
        // Check if the values are overlapping
        if (ui.values[0] >= ui.values[1]) {
          // Adjust the overlapping handle to prevent overlap
          return false;
        }
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("symmetry");
        }
      }
    });
    $("#symmetry__filterss").val(0, 1);

    // fluor range filter
    $("#fluor-range").prev(".slider-dots").append(DFilters.filter_fluor.map((elem, index) => `<span class="slider-dot" style="left: ${index * 100 / DFilters.filter_fluor.length}%;"></span>`).join(''));
    $("#fluor-range").slider({
      step: 1,
      range: true,
      min: 0,
      max: DFilters.filter_fluor.length,
      values: ini_fluor,
      slide: function (event, ui) {
        // Check if the values are overlapping
        if (ui.values[0] >= ui.values[1]) {
          // Adjust the overlapping handle to prevent overlap
          return false;
        }
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("fluor");
        }
      }
    });
    $("#fluor__filterss").val(0, 1);

    // table-range
    $("#table-range").slider({
      range: true,
      min: DFilters.filter_table_range.minTa,
      max: DFilters.filter_table_range.maxTa,
      values: ini_table,
      step: 0.1,
      slide: function (event, ui) {
        $("#min_table").val(parseFloat(ui.values[0]).toFixed(1));
        $("#max_table").val(parseFloat(ui.values[1]).toFixed(1));
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("table");
        }
      }
    });
    $("#min_table").val(parseFloat($("#table-range").slider("values", 0)).toFixed(1));
    $("#max_table").val(parseFloat($("#table-range").slider("values", 1)).toFixed(1));

    // depth-range
    $("#depth-range").slider({
      range: true,
      min: DFilters.filter_depth_range.minTd,
      max: DFilters.filter_depth_range.maxTd,
      values: ini_depth,
      step: 0.1,
      slide: function (event, ui) {
        $("#min_depth").val(parseFloat(ui.values[0]).toFixed(1));
        $("#max_depth").val(parseFloat(ui.values[1]).toFixed(1));
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("depth");
        }
      }
    });
    $("#min_depth").val(parseFloat($("#depth-range").slider("values", 0)).toFixed(1));
    $("#max_depth").val(parseFloat($("#depth-range").slider("values", 1)).toFixed(1));

    // lw-ratio-range
    $("#lw-ratio-range").slider({
      range: true,
      min: DFilters.filter_lw_ratio_range.min,
      max: DFilters.filter_lw_ratio_range.max,
      step: 0.01,
      values: ini_lw_ratio,
      slide: function (event, ui) {
        $("#min_lw-ratio").val(parseFloat(ui.values[0]).toFixed(2));
        $("#max_lw-ratio").val(parseFloat(ui.values[1]).toFixed(2));
      },
      start: function (event, ui) {
        slider_memory = ui.values;
      },
      stop: function (event, ui) {
        if (slider_memory[0] != ui.values[0] || slider_memory[1] != ui.values[1]) {
          handleFilterChange("lw_ratio");
        }
      }
    });
    $("#min_lw-ratio").val(parseFloat($("#lw-ratio-range").slider("values", 0)).toFixed(2));
    $("#max_lw-ratio").val(parseFloat($("#lw-ratio-range").slider("values", 1)).toFixed(2));
  }

  /////////////////////// Initialize Sliders End ///////////////////////

  // Update filters labels
  kirb_update_filter_labels();

  // Reset all filters
  $(".kirb_reset_filters").click(() => {
    kirb_reset_filters();
    $("#all_diamond_label").click();
  });

  // Handle search button click
  $("#kirb_search_btn").click(() => {
    handleFilterChange("search");
  });

  $("#kirb_search_txt").keypress((e) => {
    if (e.which == 13) {
      handleFilterChange("search");
    }
  });
  $("#kirb_search_txt").on('input', () => {
    if ($("#kirb_search_txt").val() == "") {
      handleFilterChange("search");
    }
  });

  // Handle sort change
  $("#kirb_prods_sort").change((e) => {
    handleFilterChange("sort");
  });

  $(".labclass").change((e) => {
    handleFilterChange("labFilter");
  });

  $(".kirb_extra_filter").change((e) => {
    let filter = $(e.target).data("filter");
    handleFilterChange(filter);
  });

  function handle_tab_change(e) {
    let target = $(e.target).data("bs-target");
    if(target == "#all_diamond") {
      $(".kirb_search_bar_strip").show();
    }else if((target == "#recently-view" || target == "#comparison")){
      $(".kirb_search_bar_strip").attr("style","display: none !important;");
    }
  }

  $("div[data-bs-toggle='tab']").click(handle_tab_change);
  $("div[data-bs-toggle='tab'] span").click((e)=>{
    $(e.target).parent().click();
  });

  $(".kirb-select-filter-show").click((e) => {
    let target = $(e.target).hasClass("kirb-remove-filter");
    if(target) {
      let filter_key = $(e.target).parent().data("key");
      if(filter_key == "labFilter") {
        let filter_val = $(e.target).parent().data("value");
        kirb_remove_single_active_filter(filter_key, filter_val);
        let flg = false;
        $(".lab_checkbox input").each((index, elem) => { 
          if($(elem).is(":checked")) {
            flg = true;
          }
        });
        if(flg) {
          $(e.target).parent().remove();
        }else{
          $(e.target).parent().parent().remove();
        }
      }else{
        kirb_remove_single_active_filter(filter_key);
        $(e.target).parent().parent().remove();
      }
      if($(e.currentTarget).html().trim() == "") {
        $(e.currentTarget).hide();
      }
    }
  });
  

  $(".kirb_scrollable_div").each(function () {
    let $container = $(this);
    let $children = $container.children().not(".kirb-left-btn, .kirb-right-btn");
    const VISIBLE_COUNT = $container.data("maxItems")    || 8;
    const currentPage = $container.data("currentPage") || 1;
    const totalChildren = $children.length;
    let scrollIndex = (currentPage - 1) * VISIBLE_COUNT;
  
    // clamp
    scrollIndex = Math.max(0, Math.min(scrollIndex, totalChildren - VISIBLE_COUNT));
  
    // set container data
    $container.data("scrollIndex", scrollIndex);
  
    // ensure flex-nowrap
    // $container.css("flex-wrap", "nowrap");
  
    // hide all, then show the slice
    $children.hide().slice(scrollIndex, scrollIndex + VISIBLE_COUNT).show();
  
    // only add buttons once
    if (!$container.find(".kirb-left-btn").length) {
      $container.prepend('<div class="kirb-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="kirb-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>');
    }
  
    // toggle initial arrow visibility
    $container.find(".kirb-left-btn").toggle(scrollIndex > 0);
    $container.find(".kirb-right-btn").toggle(scrollIndex + VISIBLE_COUNT < totalChildren);
  });
  
  $(".kirb-left-btn, .kirb-right-btn").click(function () {
    let $container = $(this).closest(".kirb_scrollable_div");
    let $children = $container.children().not(".kirb-left-btn, .kirb-right-btn");
    let scrollIndex = $container.data("scrollIndex") || 0;
    const VISIBLE_COUNT = $container.data("maxItems") || 8;
    const totalChildren = $children.length;
  
    // shift index
    if ($(this).hasClass("kirb-right-btn")) {
      scrollIndex += VISIBLE_COUNT;
    } else {
      scrollIndex -= VISIBLE_COUNT;
    }
  
    // clamp
    scrollIndex = Math.max(0, Math.min(scrollIndex, totalChildren - VISIBLE_COUNT));
    $container.data("scrollIndex", scrollIndex);
  
    // update visible items
    $children.hide().slice(scrollIndex, scrollIndex + VISIBLE_COUNT).show();
  
    // toggle arrows
    $container.find(".kirb-left-btn").toggle(scrollIndex > 0);
    $container.find(".kirb-right-btn").toggle(scrollIndex + VISIBLE_COUNT < totalChildren);
  });

  let slider_arr = ['#cut-range', '#colors-range', '#clarity-range', '#fluor-range', '#polish-range', '#symmetry-range', '#price-range', '#gem-price-range', '#carat-range', '#gem-carat-range', '#lw-ratio-range', '#table-range', '#depth-range'];
  
  slider_arr.forEach((slider) => {
    SliderMobileTouch(slider);
  });


  /////////////////////////////////// Mobile Filters Setup ///////////////////////////////////

  kirb_setupMobileFilterPopup('.kirb_openFilter', '#kirb_filterPopup', '#kirb_closeFilter');

  function kirb_updateFilterButtonText() {
    if (window.innerWidth < 768) {
      $('.kirb_mobile-filter-popup .kirb_reset_filters').text('Reset All');
      $('.list-view-options').addClass('active');
      $('.grid-view-options').removeClass('active');
    } else {
      $('.kirb_mobile-filter-popup .kirb_reset_filters').text(DTranslations['clear_filter']);
    }
  }

  // Run on page load
  kirb_updateFilterButtonText();

  // Optional: Update text on window resize
  $(window).on('resize', function () {
    kirb_updateFilterButtonText();
  });

  $(document).on('click', '.ri-search-line', function () {
    $('#kirb_filterPopup').removeClass('show');
  });

  /////////////////////////////////// Mobile Filters Setup ///////////////////////////////////

  // Initialize compare list
  kirb_toggle_listing_loader_top(true);
  await Promise.all([
    kirb_load_compare_prods(),
    kirb_load_recent_prods(false)
  ]);
  scroll_cooldown = false;
  kirb_toggle_listing_loader_top(false);
  reloadCompareList();
  kirb_auto_clear_cache();
  kirb_update_active_filters();
});

const kirb_diamond_byor = (e) => {
  toggle_kirb_loader(true);
  const diamondId = $(e).data('id');
  const setting_type = $(e).data('type');
  $.get(KIRB_GLOBALS.ajax_url, {
    action: "kirb_add_to_byor",
    product_id: diamondId,
    diamond_type: DListing.is_gemstone ? 'gemstone' : 'diamond',
    diamond_redirect: setting_type,
    type: 'diamond',
    nonce: KIRB_GLOBALS.nonce
  }, (resp) => {
    if (resp.status === 'success') {
      window.location.href = resp.redirect_url;
    }
  });
}

const kirb_load_more_prods = () => {
  kirb_toggle_listing_loader_below(true, false);
  let filters = getAllFilters();

  let sort = $("#kirb_prods_sort").val();

  let filters_data = {
    action: "kirb_load_more_prods",
    catg: DListing.current_catg,
    page: current_page + 1,
    mincarat: filters.carat[0],
    maxcarat: filters.carat[1],
    minprice: filters.price[0],
    maxprice: filters.price[1],
    sort: sort,
    nonce: KIRB_GLOBALS.nonce,
  };

  let search_txt = $("#kirb_search_txt").val();
  if(search_txt != "") {
    filters_data.search = search_txt;
  }

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


  if (filters.labFilter != undefined) {
    filters_data.labFilter = filters.labFilter;
  }

  filters_data = prepare_filter_obj_by_catg(filters_data, filters);

  if(current_page == 1) {
    total_load_more_diamonds = 0;
  }

  $.get(KIRB_GLOBALS.ajax_url, filters_data, (response) => {
    current_page++;
    $(".kirb_empty_err").remove();
    $("#kirb_product_grid").append(response.grid_html);
    $("#kirb_product_list").append(response.list_html);
    
    DStat.diamond_listing_global.count = DStat.diamond_listing_global.count + response.stats.count;
    count_prods = DStat.diamond_listing_global.count;
    
    kirb_toggle_listing_loader_below(false);

    // Initialize compare list
    reloadCompareList();

    scroll_cooldown = false;

    if (DStat.diamond_listing_global.total_pages == current_page || total_load_more_diamonds == 5) {
      is_load_more_diamonds = false;
      $("#kirb_product_grid").append(`
        <div style="text-align:center;width:100%;margin-top:20px;white-space: nowrap;">
          ${DTranslations['closest_match']}
        </div>
      `);
      $("#kirb_product_list").append(`
        <tr>
          <td colspan="11" style="padding: 20px;">${DTranslations['closest_match']}</td>
        </tr>
      `);
    }    
    total_load_more_diamonds++;
  });
};

// Reset filters function
const kirb_reset_filters = () => {
  $("#kirb_search_txt").val("");
  $("#carat-range").slider("values", [
    DFilters.filter_carat_range.minCarat,
    DFilters.filter_carat_range.maxCarat,
  ]);
  
  $("#price-range").slider("values", [    
    map_values_for_slider(DFilters.filter_price_range.minSaleAmt), 
    map_values_for_slider(DFilters.filter_price_range.maxSaleAmt),
  ]);

  $("#min_carat").val(parseFloat(DFilters.filter_carat_range.minCarat).toFixed(2));
  $("#max_carat").val(parseFloat(DFilters.filter_carat_range.maxCarat).toFixed(2));
  $("#min_price").val(formatCurrency(DFilters.filter_price_range.minSaleAmt));
  $("#max_price").val(formatCurrency(DFilters.filter_price_range.maxSaleAmt));
  $(".kirb-diamond-shapes > .shape_item > .shape-box").removeClass("active");
  $("#cut-range").slider("enable");

  if (DListing.current_catg != KIRB_CATG.GEMSTONE) {
    $("#table-range").slider("values", [
      DFilters.filter_table_range.minTa,
      DFilters.filter_table_range.maxTa,
    ]);
    $("#depth-range").slider("values", [
      DFilters.filter_depth_range.minTd,
      DFilters.filter_depth_range.maxTd,
    ]);
    $("#lw-ratio-range").slider("values", [
      DFilters.filter_lw_ratio_range.min,
      DFilters.filter_lw_ratio_range.max,
    ]);
    $("#colors-range").slider("values", [0, DFilters.filter_colors.length]);
    $("#cut-range").slider("values", [0, DFilters.filter_cuts.length]);
    $("#clarity-range").slider("values", [0, DFilters.filter_clarity.length]);
    $("#polish-range").slider("values", [0, DFilters.filter_polish.length]);
    $("#symmetry-range").slider("values", [0, DFilters.filter_symmetry.length]);
    $("#fluor-range").slider("values", [0, DFilters.filter_fluor.length]);
    $("#min_table").val(parseFloat(DFilters.filter_table_range.minTa).toFixed(1));
    $("#max_table").val(parseFloat(DFilters.filter_table_range.maxTa).toFixed(1));
    $("#min_depth").val(parseFloat(DFilters.filter_depth_range.minTd).toFixed(1));
    $("#max_depth").val(parseFloat(DFilters.filter_depth_range.maxTd).toFixed(1));
    $("#min_lw-ratio").val(parseFloat(DFilters.filter_lw_ratio_range.min).toFixed(2));
    $("#max_lw-ratio").val(parseFloat(DFilters.filter_lw_ratio_range.max).toFixed(2));
  }

  $(".kirb_gem_color").removeClass("active");
  $(".kirb_diamond_intensity").removeClass("active")
  $(".kirb_gem_type").removeClass("active")
  $(".kirb_extra_filter").prop("checked", false);
  $(".labclass").prop("checked", false);
  handleFilterChange('reset');
};

const handle_empty_rc_msg = (type, isEmpty) => {
  $(`#kirb_${type}_table`).toggle(!isEmpty);
  $(`#kirb_${type}_empty_msg`).toggle(isEmpty);
}


const highlight_compare_items = (compare_list) => {
    $(`.kirb_compare_btn`).children("img").removeClass("kirb_highlight_img_btn");
    if(compare_list == null) {
      compare_list = {};
    }
    let current_catg_compare_list = [];

    if(Array.isArray(compare_list)) {
      current_catg_compare_list = compare_list;
    }else{
      if(compare_list.hasOwnProperty(DListing.current_catg)) {
        current_catg_compare_list = compare_list[DListing.current_catg];
      }    
    }
    current_catg_compare_list.forEach((diamond_id) => {
      $(`.kirb_compare_btn[data-id="${diamond_id}"]`)
        .children("img")
        .addClass("kirb_highlight_img_btn");
    });
};

// Handle compare list reload for compare button highlight
const reloadCompareList = () => {
  if (!DListing.logged_in) {
    let compare_list = JSON.parse(localStorage.getItem("kirb_compare_list"));
    if (compare_list == null) {
      compare_list = {};
    }
    highlight_compare_items(compare_list);
  }
};

// Handle compare button click
const kirb_compare_prod = async (e, remove) => {
  let diamond_id = $(e).data("id");
  let add_item = !($(e).find("img").hasClass("kirb_highlight_img_btn"));
  if(add_item) {
    $(e).children("img").not('.kirb_highlight_img_btn').addClass("kirb_highlight_img_btn");
  }else{
    $(e).children("img").removeClass("kirb_highlight_img_btn");
  }
  if(remove) {
    // find parent tr
    $(e).closest("tr").remove();
  }
  if (!DListing.logged_in) {
    let compare_list = JSON.parse(localStorage.getItem("kirb_compare_list"));
    if (compare_list == null) {
      compare_list = {};
    }
    let current_catg_compare_list = [];
    if(compare_list.hasOwnProperty(DListing.current_catg)) {
      current_catg_compare_list = compare_list[DListing.current_catg];
    }

    if (current_catg_compare_list.includes(diamond_id)) {
      current_catg_compare_list = current_catg_compare_list.filter((val) => val != diamond_id);
    } else {
      current_catg_compare_list.push(diamond_id);
    }
    compare_list[DListing.current_catg] = current_catg_compare_list;
    localStorage.setItem("kirb_compare_list", JSON.stringify(compare_list));
    reloadCompareList();
    kirb_load_compare_prods();
  } else {
    $.get(
      KIRB_GLOBALS.ajax_url,
      { 
        action: "kirb_handle_rc_prods", 
        prod_id: diamond_id, 
        type: "compare", 
        catg: DListing.current_catg,
        nonce: KIRB_GLOBALS.nonce,
      },
      (response) => {
        let count = response.result.stats.count;
        let diamond_id = $(e).data("id");
        if(add_item) {
          $(`.kirb_compare_btn[data-id="${diamond_id}"]`).children("img").not('.kirb_highlight_img_btn').addClass("kirb_highlight_img_btn");
        }else{
          $(`.kirb_compare_btn[data-id="${diamond_id}"]`).children("img").removeClass("kirb_highlight_img_btn");
        }
        $("#kirb_compare_count").html(
          `${DTranslations['showing']} ${count} ${DTranslations['result']}${count > 1 ? 's' : ''}`
        );
        $("#comparison_label").html(
          `${DTranslations['compare']} (${count})`
        );
        handle_empty_rc_msg('compare', count == 0);
        if(count > 0) {
          $("#kirb_compare_prods").html(response.result.html);
          $("#kirb_compare_prods_section").show();
          $("#kirb_compare_prods_empty").hide();
          $("#kirb_comparison_tab").prop("disabled", false);
          $("#kirb_comparison_tab").removeClass("disabled");
        }else{
          $("#kirb_compare_prods_section").hide();
          $("#kirb_compare_prods_empty").show();
          $("#kirb_comparison_tab").prop("disabled", true);
          $("#kirb_comparison_tab").addClass("disabled");
        }
      }
    );
  }
};

// Load compare products
const kirb_load_compare_prods = () => {
  return new Promise((resolve, reject) => {
    if (!DListing.logged_in) {
      let compare_list = localStorage.getItem("kirb_compare_list");
      if (compare_list == null) {
        compare_list = "{}";
      }
      
      compare_list = JSON.parse(compare_list);
      // Version update fix - temp
      if(Array.isArray(compare_list)) {
        compare_list = {};
      }
      let current_catg_compare_list = [];
      if(compare_list.hasOwnProperty(DListing.current_catg)) {
        current_catg_compare_list = compare_list[DListing.current_catg];
      }
      current_catg_compare_list = current_catg_compare_list.join(",");
      $.get(
        KIRB_GLOBALS.ajax_url,
        {
          action: "kirb_load_compare_prods",
          products: current_catg_compare_list,
          type: "compare",
          nonce: KIRB_GLOBALS.nonce,
        },
        (response) => {
          if(response.stats.count > 0) {
            $("#kirb_compare_prods").html(response.html);
            $("#kirb_compare_prods_section").show();
            $("#kirb_compare_prods_empty").hide();
            $("#kirb_comparison_tab").prop("disabled", false);
            $("#kirb_comparison_tab").removeClass("disabled");
          }else{
            $("#kirb_compare_prods").html('');
            $("#kirb_compare_prods_section").hide();
            $("#kirb_compare_prods_empty").show();
            $("#kirb_comparison_tab").prop("disabled", true);
            $("#kirb_comparison_tab").addClass("disabled");
          }
          $("#kirb_compare_count").html(
            `${DTranslations['showing']} ${response.stats.count} ${DTranslations['result']}${response.stats.count > 1 ? 's' : ''}`
          );
          $("#comparison_label").html(
            `${DTranslations['compare']} (${response.stats.count})`
          );
          handle_empty_rc_msg('compare', response.stats.count == 0);
          resolve();
        }
      );
    } else {
      $.get(
        KIRB_GLOBALS.ajax_url,
        { 
          action: "kirb_fetch_rc_items", 
          type: "compare", 
          catg: DListing.current_catg,
          nonce: KIRB_GLOBALS.nonce,
        },
        (response) => {
          let compare_list = response.prod_id_list;
          if(response.result.stats.count > 0) {
            $("#kirb_compare_prods").html(response.result.html);
            $("#kirb_compare_prods_section").show();
            $("#kirb_compare_prods_empty").hide();
            $("#kirb_comparison_tab").prop("disabled", false);
            $("#kirb_comparison_tab").removeClass("disabled");
            highlight_compare_items(compare_list);
            compare_list_login = compare_list;
          }else{
            $("#kirb_compare_prods_section").hide();
            $("#kirb_compare_prods_empty").show();
            $("#kirb_comparison_tab").prop("disabled", true);
            $("#kirb_comparison_tab").addClass("disabled");
          }
          $("#kirb_compare_count").html(
            `${DTranslations['showing']} ${response.result.stats.count} ${DTranslations['result']}${response.result.stats.count > 1 ? 's' : ''}`
          );
          $("#comparison_label").html(
            `${DTranslations['compare']} (${response.result.stats.count})`
          );
          handle_empty_rc_msg('compare', response.result.stats.count == 0);
          resolve();
        }
      );
    }
  });
};
// Added the event lister for the click event as there were no definiton of the click handler and also the inline data-onclick was not getting trigerred because browser doesn't render the data-onclick  
$(document).on("click",".kirb_compare_btn",function(){
    // console.log("the compare is working");
    kirb_compare_prod(this,false);
});
// Load recent products
const kirb_load_recent_prods = (show_loader = true) => {
  return new Promise((resolve, reject) => {
    let blank_msg = `<div style="width: 100%;text-align:center;">${DTranslations['no_product_to_show']}...</div>`;
    if (!DListing.logged_in) {
      let recent_list = localStorage.getItem("kirb_recent_list");
      if (recent_list == null) {
        recent_list = "{}";
      }
      // recent_list = JSON.parse(recent_list).join(",");
      recent_list = JSON.parse(recent_list);

      // Version update fix - temp
      if(Array.isArray(recent_list)) {
        recent_list = {};
      }

      let current_catg_recent_list = "";
      if(recent_list.hasOwnProperty(DListing.current_catg)) {
        current_catg_recent_list = recent_list[DListing.current_catg].join(",");
      }
      
      if(show_loader) {
        kirb_toggle_listing_loader_top(true);
      }
      $.get(
        KIRB_GLOBALS.ajax_url,
        {
          action: "kirb_load_recent_prods",
          products: current_catg_recent_list,
          type: "recent",
          nonce: KIRB_GLOBALS.nonce,
        },
        (response) => {
          let resp_html = "";
          if(response.stats.count != 0) {
            resp_html = response.html;
            $("#kirb_recently_view_tab").prop("disabled", false);
            $("#kirb_recently_view_tab").removeClass("disabled");
          }else{
            resp_html = blank_msg;
            $("#kirb_recently_view_tab").prop("disabled", true);
            $("#kirb_recently_view_tab").addClass("disabled");
          }
          $("#kirb_recent_prods").html(resp_html);
          $("#kirb_recent_count").html(`${DTranslations['showing']} ${response.stats.count} ${DTranslations['result']}${response.stats.count > 1 ? 's' : ''}`);
          $("#recently_view_label").html(`${DTranslations['recently_viewed']} (${response.stats.count})`);
          handle_empty_rc_msg('recent', response.stats.count == 0);
          if(show_loader) {
            kirb_toggle_listing_loader_top(false);
          }
          resolve();
        }
      );
    } else {
      if(show_loader) {
        kirb_toggle_listing_loader_top(true);
      }
      $.get(
        KIRB_GLOBALS.ajax_url,
        { 
          action: "kirb_fetch_rc_items", 
          type: "recent" , 
          catg: DListing.current_catg,
          nonce: KIRB_GLOBALS.nonce
        },
        (response) => {
          if(response=="success"){
            kirb_toggle_listing_loader_top(false);
          }
          let resp_html = "";
          if(response.result.stats.count != 0) {       
            resp_html = response.result.html;
            $("#kirb_recently_view_tab").prop("disabled", false);
            $("#kirb_recently_view_tab").removeClass("disabled");
          }else{
            resp_html = blank_msg;
            $("#kirb_recently_view_tab").prop("disabled", true);
            $("#kirb_recently_view_tab").addClass("disabled");
          }
          $("#kirb_recent_prods").html(resp_html);
          $("#kirb_recent_count").html(
            `${DTranslations['showing']} ${response.result.stats.count} ${DTranslations['result']}${response.result.stats.count > 1 ? 's' : ''}`
          );
          $("#recently_view_label").html(`${DTranslations['recently_viewed']} (${response.result.stats.count})`);
          handle_empty_rc_msg('recent', response.result.stats.count == 0);
          highlight_compare_items(compare_list_login);
          if(show_loader) {
            kirb_toggle_listing_loader_top(false);
          }
          resolve();
        } 
      );
    }
  });
};

function kirbUpdateLink(selector, queryString) {
  const linkElement = $(selector);
  if(linkElement.length > 0) {
    let originalHref = linkElement.attr("data-base-url");
    originalHref = originalHref.endsWith("/") ? originalHref : originalHref + "/";
    queryString = queryString.length > 0 ? `?${queryString}` : "";
    let newHref = "";
    if(DListing.url_shape_preset != "") {
      newHref = `${originalHref}${DListing.url_shape_preset}/${queryString}`;
    }else{
      newHref = `${originalHref}${queryString}`;
    }
    linkElement.attr("href", newHref);
  }
}

// Change the url based on the filter selection
const prepare_filters_uri = (filter, singleRemove = false) => {
  let uri = new URLSearchParams(window.location.search);
  if (filter != null) {
    Object.keys(filter).forEach((key) => {
      if (filter[key] == undefined || singleRemove) {
        uri.delete(key);
        if(key == "shape" && DListing.shape_slug_config) {
          let shape_key = Object.keys(DListing.shape_slug_config);
          let path = window.location.pathname;
          for(let i=0; i<shape_key.length; i++) {
            path = path.replace(`/${shape_key[i]}`, "");
          }
          window.history.pushState({}, "", path);
          DListing.url_shape_preset = "";
        }
      } else {
        if(key == "shape" && DListing.shape_slug_config) {
          if(DListing.url_shape_preset.length == 0) {
            if(uri.get('shape') == undefined || uri.get('shape').length == 0) {
              let path = window.location.pathname;
              let shape_key = Object.keys(DListing.shape_slug_config).find(k => DListing.shape_slug_config[k] === filter[key]);
              path = path.endsWith("/") ? path + `${shape_key}/` : path + `/${shape_key}/`;
              window.history.pushState({}, "", path);
              DListing.url_shape_preset = shape_key;
            }else{
              uri.set(key, filter[key]);
            }
          }else{
            let shape_key = Object.keys(DListing.shape_slug_config).find(k => DListing.shape_slug_config[k] === filter[key]);
            let path = window.location.pathname;
            path = path.replace(`/${DListing.url_shape_preset}`, `/${shape_key}`);
            window.history.pushState({}, "", path);
            DListing.url_shape_preset = shape_key;
          }
        }else{
          uri.set(key, filter[key]);
        }
      }
    });
  } else {
    // Remove all filters
    let params = ['shape', 'color', 'cut', 'clarity', 'polish', 'symmetry', 'fluor', 'mincarat', 'maxcarat', 'minprice', 'maxprice', 'mintable', 'maxtable', 'mindepth', 'maxdepth', 'minratio', 'maxratio', 'gemType', 'intensity', 'sort', 'labFilter', 'videoAvailable', 'includeShippingDaysFilter'];
    params.forEach(param => {
      uri.delete(param);
    });

    if(DListing.url_shape_preset != "") {
      let path = window.location.pathname;
      path = path.replace(`/${DListing.url_shape_preset}`, "");
      window.history.pushState({}, "", path);
      DListing.url_shape_preset = "";
    }
  }

  const queryString = uri.toString();
  kirbUpdateLink("#tab_data_natural", queryString);
  kirbUpdateLink("#tab_data_lab_created", queryString);
  
  let new_url = `${window.location.pathname}?${queryString}`;
  if(queryString == "") {
    new_url = window.location.pathname;
  }

  window.history.pushState({},"",new_url);
  localStorage.setItem("kirb_query_string", queryString);
  kirb_update_active_filters();
};

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

const kirb_update_active_filters = () => {
  let labels_arr = {};
  
  labels_arr[DTranslations.filter_values.shape] = ['shape'];
  labels_arr[DTranslations.filter_values.price] = ['minprice', 'maxprice'];
  labels_arr[DTranslations.filter_values.carat] = ['mincarat', 'maxcarat'];
  labels_arr[DTranslations.filter_values.color] = ['color'];
  labels_arr[DTranslations.filter_values.cut] = ['cut'];
  labels_arr[DTranslations.filter_values.clarity] = ['clarity'];
  labels_arr[DTranslations.filter_values.polish] = ['polish'];
  labels_arr[DTranslations.filter_values.symmetry] = ['symmetry'];
  labels_arr[DTranslations.filter_values.fluorescence] = ['fluor'];
  labels_arr[DTranslations.filter_values.table] = ['mintable', 'maxtable'];
  labels_arr[DTranslations.filter_values.depth] = ['mindepth', 'maxdepth'];
  labels_arr[DTranslations.filter_values.lw_ratio] = ['minratio', 'maxratio'];
  labels_arr[DTranslations.filter_values.lab] = ['labFilter'];
  labels_arr[DTranslations.filter_values.gem_type] = ['gemType'];
  labels_arr[DTranslations.filter_values.intensity] = ['intensity'];
  labels_arr[DTranslations.filter_values.video_available] = ['videoAvailable'];
  labels_arr[DTranslations.filter_values.fast_shipping] = ['includeShippingDaysFilter'];

  const keys_mapping = {
    'mincarat,maxcarat': 'carat',
    'minprice,maxprice': 'price',
    'mintable,maxtable': 'table',
    'mindepth,maxdepth': 'depth',
    'minratio,maxratio': 'lw_ratio',
  };

  const comma_sep_range_keys = ['color', 'cut', 'clarity', 'polish', 'symmetry', 'fluor'];

  const boolean_keys = ['videoAvailable', 'includeShippingDaysFilter'];

  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) {
    $(".kirb-select-filter-show").html('');
    $(".kirb-select-filter-show").hide();
  }else{
    $(".kirb-select-filter-show").attr('style', 'display: flex;');
    let active_filters = [];
    Object.keys(labels_arr).forEach((key) => {
      let filter = labels_arr[key];
      if(filter.length == 1) {
        if(uri.has(filter[0])) {
          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];

      if(filter_key[0] == 'labFilter') {
        let lab_val = uri.get(filter_key[0]);
        let labs = [];
        if(lab_val.includes(',')) {
          labs = lab_val.split(',');
        }else{
          labs = [lab_val];
        }

        let lab_html = labs.map((lab, i) => {
          return `
            <div data-value="${lab}" data-key="${filter_key[0]}" style="${i != labs.length - 1 ? 'margin-right: 10px;' : ''}">
              <span>${lab}</span>
              <button type="button" class="btn-close kirb-remove-filter" aria-label="Close"></button>
            </div>
          `;
        });
        return `
          <div class="kirb-item-filter">
            <span class="kirb-select-filter-heading">${filter}:</span>
            ${lab_html.join('')}
          </div>
        `;
      }else{
        let filter_val = uri.get(filter_key[0]);
        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 = DTranslations['filter_values'][capitalizeWords(vals[0])] ?? capitalizeWords(vals[0]);
          const v2 = DTranslations['filter_values'][capitalizeWords(vals[vals.length - 1])] ?? capitalizeWords(vals[vals.length - 1])

          filter_val = v1 + ' - ' + v2;

        }else{
          filter_val = DTranslations['filter_values'][capitalizeWords(filter_val)] ?? capitalizeWords(filter_val);
        }

        let mapped_filter_key = "";
        if(Object.keys(keys_mapping).includes(filter_key.join(','))) {
          mapped_filter_key = keys_mapping[filter_key.join(',')];
        }else{
          mapped_filter_key = filter_key[0];
        }

        if(boolean_keys.includes(filter_key[0])) {
          return `
            <div class="kirb-item-filter">
              <span class="kirb-select-filter-heading"></span>
              <div data-key="${mapped_filter_key}">
                <span>${filter}</span>
                <button type="button" class="btn-close kirb-remove-filter" aria-label="Close"></button>
              </div>
            </div>
          `;
        }else{
          return `
            <div class="kirb-item-filter">
              <span class="kirb-select-filter-heading">${filter}:</span>
              <div data-key="${mapped_filter_key}">
                <span>${filter_val}</span>
                <button type="button" class="btn-close kirb-remove-filter" aria-label="Close"></button>
              </div>
            </div>
          `;
        }
      }
    });

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

const kirb_remove_single_active_filter = (filter_key, value = "") => {
  if(filter_key == "labFilter") {
    $(`.lab_checkbox input[value="${value}"]`).prop("checked", false);
  }else if(filter_key == "shape"){
    $(".kirb-diamond-shapes > .shape_item > .shape-box").removeClass("active");
    if(DListing.url_shape_preset) {
      DListing.url_shape_preset = "";
    }
  }else if(filter_key == "color") {
    $("#colors-range").slider("values", [0, DFilters.filter_colors.length]);
    $(".kirb_gem_color").removeClass("active");
  }else if(filter_key == "cut") {
    $("#cut-range").slider("values", [0, DFilters.filter_cuts.length]);
  }else if(filter_key == "clarity") {
    $("#clarity-range").slider("values", [0, DFilters.filter_clarity.length]);
  }else if(filter_key == "polish") {
    $("#polish-range").slider("values", [0, DFilters.filter_polish.length]);
  }else if(filter_key == "symmetry") {
    $("#symmetry-range").slider("values", [0, DFilters.filter_symmetry.length]);
  }else if(filter_key == "fluor") {
    $("#fluor-range").slider("values", [0, DFilters.filter_fluor.length]);
  }else if(filter_key == "gemType") {
    $(".kirb_gem_type").removeClass("active");
  }else if(filter_key == "intensity") {
    $(".kirb_diamond_intensity").removeClass("active");
  }else if(filter_key == "price") {
    $("#price-range").slider("values", [    
      map_values_for_slider(DFilters.filter_price_range.minSaleAmt), 
      map_values_for_slider(DFilters.filter_price_range.maxSaleAmt),
    ]);
    $("#min_price").val(formatCurrency(DFilters.filter_price_range.minSaleAmt));
    $("#max_price").val(formatCurrency(DFilters.filter_price_range.maxSaleAmt));
  }else if(filter_key == "carat") {
    $("#carat-range").slider("values", [
      DFilters.filter_carat_range.minCarat,
      DFilters.filter_carat_range.maxCarat,
    ]);
    $("#min_carat").val(parseFloat(DFilters.filter_carat_range.minCarat).toFixed(2));
    $("#max_carat").val(parseFloat(DFilters.filter_carat_range.maxCarat).toFixed(2));
  }else if(filter_key == "table") {
    $("#table-range").slider("values", [
      DFilters.filter_table_range.minTa,
      DFilters.filter_table_range.maxTa,
    ]);
    $("#min_table").val(parseFloat(DFilters.filter_table_range.minTa).toFixed(1));
    $("#max_table").val(parseFloat(DFilters.filter_table_range.maxTa).toFixed(1));
  }else if(filter_key == "depth") {
    $("#depth-range").slider("values", [
      DFilters.filter_depth_range.minTd,
      DFilters.filter_depth_range.maxTd,
    ]);
    $("#min_depth").val(parseFloat(DFilters.filter_depth_range.minTd).toFixed(1));
    $("#max_depth").val(parseFloat(DFilters.filter_depth_range.maxTd).toFixed(1));
  }else if(filter_key == "lw_ratio") {
    $("#lw-ratio-range").slider("values", [
      DFilters.filter_lw_ratio_range.min,
      DFilters.filter_lw_ratio_range.max,
    ]);
    $("#min_lw-ratio").val(parseFloat(DFilters.filter_lw_ratio_range.min).toFixed(2));
    $("#max_lw-ratio").val(parseFloat(DFilters.filter_lw_ratio_range.max).toFixed(2));
  }else if(filter_key == "videoAvailable" || filter_key == "includeShippingDaysFilter") {
    $(`input[data-filter="${filter_key}"]`).prop("checked", false);
  }

  if(filter_key == "labFilter") {
    handleFilterChange(filter_key);
  }else{
    handleFilterChange(filter_key, true);
  }
};

const prepare_filter_obj_by_catg = (filters_data, filters) => {
  if(DListing.current_catg == KIRB_CATG.GEMSTONE || DListing.current_catg == KIRB_CATG.COLORED_DIAMONDS) {
    if('color' in filters) {
      filters_data.color = filters.color;
    }

    if(DListing.current_catg == KIRB_CATG.GEMSTONE) {
      if('gemType' in filters) {
        filters_data.gemType = filters.gemType;
      }
    }else{
      if('intensity' in filters) {
        filters_data.intensity = filters.intensity;
      }
      if('clarity' in filters) {
        filters_data.clarity = filters.clarity.join(",").replaceAll("/", ",");
      }
    }
  } else {
    filters_data.color = filters.color.join(",");
    filters_data.cut = filters.cut.join(",");
    filters_data.clarity = filters.clarity.join(",").replaceAll("/", ",");
    filters_data.polish = filters.polish.join(",");
    filters_data.symmetry = filters.symmetry.join(",");
    filters_data.fluor = filters.fluor.join(",");
    filters_data.mintable = filters.table[0];
    filters_data.maxtable = filters.table[1];
    filters_data.mindepth = filters.depth[0];
    filters_data.maxdepth = filters.depth[1];
    filters_data.minratio = filters.lw_ratio[0];
    filters_data.maxratio = filters.lw_ratio[1];
  }
  return filters_data;
};

// Filter change listener with debounce functionality
let filterDebounce = null;
const handleFilterChange = (filter, singleRemove = false) => {
  scroll_cooldown = true;
  if (filterDebounce) {
    clearTimeout(filterDebounce);
  }
  filterDebounce = setTimeout(() => {
    $('input').blur();
    let filters = getAllFilters();
    current_page = 1;

    let sort = $("#kirb_prods_sort").val();

    let filterData = {
      action: "kirb_filter_products",
      catg: DListing.current_catg,
      page: current_page,
      sort: sort,
      mincarat: filters.carat[0],
      maxcarat: filters.carat[1],
      minprice: filters.price[0],
      maxprice: filters.price[1]
    };

    // Add shape filter if selected
    if (filters.shape != undefined) {
      filterData.shape = filters.shape;
    }

    // Add lab filter if selected
    if (filters.labFilter != undefined) {
      filterData.labFilter = filters.labFilter;
    }

    // Add 360 view available filter if selected
    if (filters.videoAvailable != undefined) {
      filterData.videoAvailable = filters.videoAvailable;
    }

    // Add include shipping days filter if selected
    if (filters.includeShippingDaysFilter != undefined) {
      filterData.includeShippingDaysFilter = filters.includeShippingDaysFilter;
    }

    filterData = prepare_filter_obj_by_catg(filterData, filters);

    kirb_toggle_listing_loader_top(true);

    switch (filter) {
      case "shape":
        prepare_filters_uri({ shape: filterData.shape }, singleRemove);
        break;
      case "color":
        prepare_filters_uri({ color: filterData.color }, singleRemove);
        break;
      case "cut":
        prepare_filters_uri({ cut: filterData.cut }, singleRemove);
        break;
      case "clarity":
        prepare_filters_uri({ clarity: filterData.clarity }, singleRemove);
        break;
      case "polish":
        prepare_filters_uri({ polish: filterData.polish }, singleRemove);
        break;
      case "symmetry":
        prepare_filters_uri({ symmetry: filterData.symmetry }, singleRemove);
        break;
      case "fluor":
        prepare_filters_uri({ fluor: filterData.fluor }, singleRemove);
        break;
      case "carat":
        prepare_filters_uri({
          mincarat: filterData.mincarat,
          maxcarat: filterData.maxcarat,
        }, singleRemove);
        break;
      case "price":
        prepare_filters_uri({
          minprice: filterData.minprice,
          maxprice: filterData.maxprice,
        }, singleRemove);
        break;
      case "table":
        prepare_filters_uri({
          mintable: filterData.mintable,
          maxtable: filterData.maxtable,
        }, singleRemove);
        break;
      case "depth":
        prepare_filters_uri({
          mindepth: filterData.mindepth,
          maxdepth: filterData.maxdepth,
        }, singleRemove);
        break;
      case "lw_ratio":
        prepare_filters_uri({
          minratio: filterData.minratio,
          maxratio: filterData.maxratio,
        }, singleRemove);
        break;
      case "sort":
        prepare_filters_uri({ sort: sort }, singleRemove);
        break;
      case "catg_change":
        prepare_filters_uri({ catg: filterData.catg }, singleRemove);
        break;
      case "gemType":
        prepare_filters_uri({ gemType: filterData.gemType }, singleRemove);
        break;
      case "intensity":
        prepare_filters_uri({intensity: filterData.intensity}, singleRemove);
        break;
      case "labFilter":
        prepare_filters_uri({labFilter: filterData.labFilter}, singleRemove);
        break;
      case "videoAvailable":
        prepare_filters_uri({videoAvailable: filterData.videoAvailable}, singleRemove);
        break;
      case "includeShippingDaysFilter":
        prepare_filters_uri({includeShippingDaysFilter: filterData.includeShippingDaysFilter}, singleRemove);
        break;
    }

    if (filter == null) {
      $("#kirb_prods_sort").prop("selectedIndex", 0);
      prepare_filters_uri(null);
    } else if (filter == "search") {
      let search_txt = $("#kirb_search_txt").val().trim();
      if(search_txt.length > 0) {
        filterData.search = search_txt;
      }
    }else if(filter == "reset") {
      let defaultSort = $('#default_sort_val').val();
      $('#kirb_prods_sort').val(defaultSort);
      prepare_filters_uri(null);
      filterData = {
        action: "kirb_filter_products",
        catg: DListing.current_catg,
        page: current_page,
        sort: defaultSort,
      };
    }

    filterData.nonce = KIRB_GLOBALS.nonce;
    $.get(KIRB_GLOBALS.ajax_url, filterData, (response) => {
      scroll_cooldown = false;
      $("#kirb_product_grid").html(response.grid_html);
      
      $("#kirb_product_list_wrapper").html(response.list_html);

      DStat.diamond_listing_global = response.stats;
      count_prods = DStat.diamond_listing_global.count;
      if (
        DStat.diamond_listing_global.total_pages == current_page ||
        DStat.diamond_listing_global.total_pages == 0
      ) {
        is_load_more_diamonds = false;
      } else {
        is_load_more_diamonds = true;
      }
      kirb_toggle_listing_loader_top(false);

      // Fill the diamond listing count
      $(".kirb_diam_count").html(
        `${DTranslations['showing']} ${DStat.diamond_listing_global.total_count} ${DTranslations['result']}${DStat.diamond_listing_global.total_count > 1 ? 's' : ''}`
      );
      $("#all_diamond_label").html(`${DTranslations['all_results']} (${DStat.diamond_listing_global.total_count})`);

      // Initialize compare list
      reloadCompareList();
    });
  }, 1000);

  setTimeout(() => {
    kirb_update_filter_labels();
  }, 100);
};

/**
 * The function `getAllFilters` retrieves the current values of various filter sliders and returns an
 * object containing the selected filter criteria.
 * @returns The `getAllFilters` function returns an object containing various filter criteria for
 * diamond selection. These criteria include shape, color, cut, clarity, polish, symmetry,
 * fluorescence, carat range, price range, table percentage range, depth percentage range, and
 * length-to-width ratio range.
 */
const getAllFilters = () => {
  let filters = {
    carat: $("#carat-range")
      .slider("values")
      .map((val) => parseFloat(val).toFixed(2)),
  };

  filters["price"] = [parseInt(numeral($("#min_price").val()).value()),parseInt(numeral($("#max_price").val()).value())];

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

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

  let labArray = [];
  $('.labclass:checkbox:checked').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
    labArray.push(sThisVal);
  });

  if(labArray.length > 0) {
    filters["labFilter"] = labArray.toString();
  }

  $(".kirb_extra_filter").each((idx, el) => {
    let filter = $(el).data("filter");
    if($(el).is(":checked")) {
      filters[filter] = 'true';
    }
  });


  if (DListing.current_catg == KIRB_CATG.GEMSTONE) {
    let curr_color = $(".kirb_gem_color.active").data("gemColor");
    let gemType = $(".kirb_gem_type.active").data("gemType");

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

    // Add gemType filter if selected
    if (gemType != undefined) {
      filters["gemType"] = gemType;
    }
  }else if(DListing.current_catg == KIRB_CATG.COLORED_DIAMONDS) {
    let intensity = $(".kirb_diamond_intensity.active").data("intensity");
    let curr_color = $(".kirb_gem_color.active").data("gemColor");
    let curr_clarity_range = $("#clarity-range").slider("values");
    
    filters["clarity"] = DFilters.filter_clarity.slice(
      curr_clarity_range[0],
      curr_clarity_range[1]
    );

    if(intensity != undefined) {
      filters['intensity'] = intensity;
    }
    if(curr_color != undefined) {
      filters['color'] = curr_color;
    }
  } else {
    let curr_polish_range = $("#polish-range").slider("values");
    let curr_symmetry_range = $("#symmetry-range").slider("values");
    let curr_fluor_range = $("#fluor-range").slider("values");
    let curr_color_range = $("#colors-range").slider("values");
    let curr_cut_range = $("#cut-range").slider("values");
    let curr_clarity_range = $("#clarity-range").slider("values");

    filters["color"] = DFilters.filter_colors.slice(
      curr_color_range[0],
      curr_color_range[1]
    );
    
    
    filters["cut"] = DFilters.filter_cuts
      .slice(curr_cut_range[0], curr_cut_range[1])
      .map((val) => val.toLowerCase());
    
    
    filters["clarity"] = DFilters.filter_clarity.slice(
      curr_clarity_range[0],
      curr_clarity_range[1]
    );
    filters["polish"] = DFilters.filter_polish
      .slice(curr_polish_range[0], curr_polish_range[1])
      .map((val) => val.toLowerCase());
    filters["symmetry"] = DFilters.filter_symmetry
      .slice(curr_symmetry_range[0], curr_symmetry_range[1])
      .map((val) => val.toLowerCase());
    filters["fluor"] = DFilters.filter_fluor
      .slice(curr_fluor_range[0], curr_fluor_range[1])
      .map((val) => val.toLowerCase());
    filters["table"] = $("#table-range")
      .slider("values")
      .map((val) => parseFloat(val));
    filters["depth"] = $("#depth-range")
      .slider("values")
      .map((val) => parseFloat(val));
    filters["lw_ratio"] = $("#lw-ratio-range")
      .slider("values")
      .map((val) => parseFloat(val));
  }

  return filters;
};

// Handle filter labels to look fade when not selected
const kirb_update_filter_labels = () => {
  let curr_polish_range = $("#polish-range").slider("values");
  let curr_symmetry_range = $("#symmetry-range").slider("values");
  let curr_fluor_range = $("#fluor-range").slider("values");
  let curr_color_range = $("#colors-range").slider("values");
  let curr_cut_range = $("#cut-range").slider("values");
  let curr_clarity_range = $("#clarity-range").slider("values");

  $(".kirb-color-labels div").each((idx, el) => {
    if (idx >= curr_color_range[0] && idx < curr_color_range[1]) {
      $(el).removeClass("kirb_label_disable");
    } else {
      $(el).addClass("kirb_label_disable");
    }
  });

  $(".kirb-cut-labels div").each((idx, el) => {
    if (idx >= curr_cut_range[0] && idx < curr_cut_range[1]) {
      $(el).removeClass("kirb_label_disable");
    } else {
      $(el).addClass("kirb_label_disable");
    }
  });

  $(".kirb-clarity-labels div").each((idx, el) => {
    if (idx >= curr_clarity_range[0] && idx < curr_clarity_range[1]) {
      $(el).removeClass("kirb_label_disable");
    } else {
      $(el).addClass("kirb_label_disable");
    }
  });

  $(".kirb-polish-labels div").each((idx, el) => {
    if (idx >= curr_polish_range[0] && idx < curr_polish_range[1]) {
      $(el).removeClass("kirb_label_disable");
    } else {
      $(el).addClass("kirb_label_disable");
    }
  });

  $(".kirb-symm-labels div").each((idx, el) => {
    if (idx >= curr_symmetry_range[0] && idx < curr_symmetry_range[1]) {
      $(el).removeClass("kirb_label_disable");
    } else {
      $(el).addClass("kirb_label_disable");
    }
  });

  $(".kirb-fluor-labels div").each((idx, el) => {
    if (idx >= curr_fluor_range[0] && idx < curr_fluor_range[1]) {
      $(el).removeClass("kirb_label_disable");
    } else {
      $(el).addClass("kirb_label_disable");
    }
  });
};

function kirb_toggle_listing_loader_below(show) {
  if(show) {
    $(".kirb_listing_loader_below").attr("style", "display: flex !important;");
  }else{
    $(".kirb_listing_loader_below").hide();
  }
}

function kirb_toggle_listing_loader_top(show) {
  if(show) {
    $(".kirb_listing_loader_top").attr("style", "display: flex !important;");
  }else{
    $(".kirb_listing_loader_top").hide();
  }
}

// const kirb_toggle_listing_loader = (show, hideSection = true) => {
//   if(show) {
//     $(".kirb_listing_loader").attr("style", "display: flex !important;");
//     if(hideSection) {
//       $(".kirb-main-tab-section").hide();
//     }
//   }else{
//     $(".kirb_listing_loader").hide();
//     if($(".kirb-main-tab-section").is(":hidden")) {
//       $(".kirb-main-tab-section").show();
//     }
//   }
// };

function kirb_showProductDetails(element, section) {
  let target = $(element).data("target");
  if(parseInt($("body").width()) > 765) {
    // Desktop
    $(".kirb-listing-item").show();
    if(section == "list") {
      $(".kirb-details-accord-pc").hide();
      $(`[data-id='diamond-list-${target}']`).css("position", "absolute");
      $(`[data-id='diamond-list-${target}']`).fadeOut(500, ()=>{
        $(`[data-id='diamond-list-${target}']`).css("position","");
      });
      $(`[data-id='details-accord-${target}']`).fadeIn(500);
      $('html,body').animate({scrollTop: $(`[data-id='details-accord-${target}']`).offset().top - 35},'fast');
    }else if(section == "accord") {
      $(`[data-id='details-accord-${target}']`).fadeOut(500);
      $(`[data-id='diamond-list-${target}']`).fadeIn(500);
    }
  }else{
    // Mobile
    $(".diamond-mobile-visible").not(`[data-id='details-accord-mob-${target}']`).hide();
    $(`[data-id='details-accord-mob-${target}']`).toggle();
    $(element).find("img").toggleClass("rotate");
    $(".kirb-product-list-table-dropdown img").not($(element).find("img")).removeClass("rotate");
    scrollToAccord($(element).parent());
  }
}

// Function to scroll to the expanded accordian - mobile view
function scrollToAccord(element) {  
  let container = $('#kirb_product_list_wrapper');
  let elementOffset = $(element).offset().top;
  let containerOffset = container.offset().top;
  let currentScroll = container.scrollTop();
  let scrollValue = elementOffset - containerOffset + currentScroll - 25;  
  container.stop().animate({ scrollTop: scrollValue }, 200);
}


// $('#choose-bttn-modal').on('show.bs.modal', function () {
//   $(this).addClass('modal-static');
// }).on('hide.bs.modal', function () {
//   $(this).removeClass('modal-static');
// });


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);
  });
}

function kirb_auto_clear_cache() {
  $.post(KIRB_GLOBALS.ajax_url, {
    action: "kirb_ajax_auto_clear_cache",
    nonce: KIRB_GLOBALS.nonce,
  }, (resp) => {});
}

function map_values_of_slider(value) {
  value = parseInt(value);
  const inMin = PRICE_FILTER_MAPPINGS.inMax;
  const inMax = PRICE_FILTER_MAPPINGS.outMax;
  const outMin = DFilters.filter_price_range.minSaleAmt;
  const outMax = DFilters.filter_price_range.maxSaleAmt;
  const normalizedValue = (value - inMin) / (inMax - inMin); 
  return Math.round(outMin * Math.pow(outMax / outMin, normalizedValue));
}

function map_values_for_slider(value) {
  value = parseInt(value);
  const inMin = PRICE_FILTER_MAPPINGS.inMax;
  const inMax = PRICE_FILTER_MAPPINGS.outMax;
  const outMin = DFilters.filter_price_range.minSaleAmt;
  const outMax = DFilters.filter_price_range.maxSaleAmt;
  const normalizedValue = Math.log(value / outMin) / Math.log(outMax / outMin);
  return Math.round(normalizedValue * (inMax - inMin) + inMin);
}

function kirb_notify_admin() {
  toggle_kirb_loader(true);
  $.post(KIRB_GLOBALS.ajax_url, {
    action: "kirb_send_notify_email",
    nonce: KIRB_GLOBALS.nonce,
  }, (resp) => {
    toggle_kirb_loader(false);
    $(".kirb_list_notify").addClass("show_tooltip");
    $(".kirb_list_notify").attr("onclick", "javascript:void(0);");
  });
}

$(document).on("click", ".kirb-copy-btn img",function(e){
    e.preventDefault();
    kirb_copy_info(this);
});

function kirb_copy_info(element) {
  console.log("btn is clicked");
  let $popupContainer = $(element).closest(".kirb-diamond-details-info-popup");
  let viewType = "grid";

  if (!$popupContainer.length) {
    $popupContainer = $(element).closest(".kirb-details-accord-pc");
    viewType = "list-desktop";
  }

  if (!$popupContainer.length) {
    $popupContainer = $(element).closest(".diamond-mobile-card-body-details");
    viewType = "list-mobile";
  }

  if (!$popupContainer.length) return;

  let diamondInfo = "";

  if (viewType === "grid") {
    $popupContainer.find("div").each(function () {
      const $spans = $(this).find("span");
      if ($spans.length === 2) {
        const label = $spans.eq(0).text().trim();
        const value = $spans.eq(1).text().trim();
        if (label && value) {
          diamondInfo += label + " " + value + "\n";
        }
      }
    });
  } else if (viewType === "list-desktop") {
    $popupContainer.find(".item-diamond > div").each(function () {
      const label = $(this).find("p:first").text().trim();
      const values = $(this)
        .find("p:last span")
        .map(function () {
          return $(this).text().trim();
        })
        .get();

      if (label && values.length) {
        diamondInfo += label + " " + values.join(" / ") + "\n";
      }
    });

    const price = $popupContainer
      .find(".price-compare-section p:first")
      .text()
      .trim();

    if (price) {
      diamondInfo += "Price: " + price + "\n";
    }
  } else if (viewType === "list-mobile") {
    $popupContainer.find(".diam-prop-100").each(function () {
      const label = $(this).find("span:first").text().trim();
      const value = $(this).find("span:last").text().trim();

      if (label && value) {
        diamondInfo += label + " " + value + "\n";
      }
    });
  }

  if (diamondInfo) {
    navigator.clipboard
      .writeText(diamondInfo)
      .then(() => {
        kirb_show_custom_tooltip(element, "Copied!");
        setTimeout(() => {
          kirb_hide_custom_tooltip(element);
        }, 3000);
      })
      .catch(() => {
        console.error("Failed to copy diamond information");
      });
  }
}

function kirb_show_custom_tooltip(element, text) {
    $(element).parent().find('.kirb-custom-tooltip').remove();
    const $tooltip = $('<span class="kirb-custom-tooltip">' + text + '</span>');
    
    // Append to body for fixed positioning (avoids clipping)
    $('body').append($tooltip);
    
    // Get element position
    const rect = element.getBoundingClientRect();
    const tooltipWidth = $tooltip.outerWidth();
    const tooltipHeight = $tooltip.outerHeight();
    
    // Position tooltip above the button, centered
    const left = rect.left + rect.width / 2 - tooltipWidth / 2;
    const top = rect.top - tooltipHeight - 12;
    
    $tooltip.css({
        'left': left + 'px',
        'top': top + 'px'
    });
    
    // Trigger animation
    setTimeout(() => {
        $tooltip.addClass('visible');
    }, 10);
}

function kirb_hide_custom_tooltip(element) {
    const $tooltip = $('.kirb-custom-tooltip');
    if ($tooltip.length) {
        $tooltip.removeClass('visible');
        setTimeout(() => {
            $tooltip.remove();
        }, 200);
    }
}


$(document).on('mouseenter', '.kirb-copy-btn img', function() {
    const $existingTooltip = $(this).parent().find('.kirb-custom-tooltip');
    if (!$existingTooltip.length) {
        kirb_show_custom_tooltip(this, 'Copy');
    }
}).on('mouseleave', '.kirb-copy-btn img', function() {
    kirb_hide_custom_tooltip(this);
});

function kirb_toggle_info_popup(e) {
  let target = $(e).data("target");
  $(`[data-popup-id="${target}"]`).fadeToggle(150);
}

function kirb_toggle_360_video(e, flg) {
  let video_url = $(e).data("video");
  if(video_url != "") {
    $(e).find(".kirb_vid_toggle_part").toggle(!flg);
    let iframe = $(e).find("iframe");
    iframe.toggle(flg);

    if(iframe.attr("src") == "") {
      if (!video_url) return;

      iframe.attr("width", 310);
      iframe.attr("height", 310);
      iframe.attr("scrolling", "no");

      video_url = video_url.replace(/\/\d+\/\d+(?=\/|\?|$)/, `/310/310`);
      iframe.attr("src", video_url);
    }
  }
}

function kirb_update_modal(e) {
  let is_incart = $(e).data("incart");
  let diamond_id = $(e).data("id");
  $(".kirb_modal_dynamic_btn_id").attr("data-id", diamond_id);
  if(is_incart) {
    $("#kirb-choose-diamond-modal .kirb_modal_add_cart_btn").hide();
    $("#kirb-choose-diamond-modal .kirb_modal_go_cart_btn").show();
  }else{
    $("#kirb-choose-diamond-modal .kirb_modal_add_cart_btn").show();
    $("#kirb-choose-diamond-modal .kirb_modal_go_cart_btn").hide();
  }
}

function kirb_setupMobileFilterPopup(openBtnSelector, popupBox, closeBtn) {
    const $openBtns = $(openBtnSelector); // Now selects all matching buttons
    const $popupBox = $(popupBox);
    const $closeBtn = $(closeBtn);
    const $popupContent = $popupBox.find('.kirb_popup-content');

    if (window.innerWidth < 768) {
        const $filterSection = $('.filter-div-ab');
        const $shortSearchQuery = $('.diam-listing-search-btn');

        if ($shortSearchQuery.length) {
            const $short = $('<div class="short"></div>').append($shortSearchQuery);
            const $showShort = $('<div class="show__short"></div>').append($short);
            $popupBox.find('.search-sticky').append($showShort);
        }
        if ($filterSection.length) {
            $popupContent.append($filterSection);
        }

        // Open popup on any button click
        $openBtns.on('click', function () {
            $popupBox.addClass('show');
            $('body').addClass('no-scroll');
        });

        // Close popup
        $closeBtn.on('click', function () {
            $popupBox.removeClass('show');
            $('body').removeClass('no-scroll');
            $('body').removeClass('no-scroll');
            window.scrollTo({ top: 200, behavior: 'auto' });
            $('.kirb-diamond-list').scrollTop(0);
        });
    }
}

/**
 * KSES-safe inline handler revival.
 * Looks for data-onclick / data-onmouseenter / data-onmouseleave
 * and calls existing global functions like `kirb_toggle_info_popup(this)`.
 * No eval; supports simple args: this, event, numbers, booleans, quoted strings.
 */
(function () {
  // (Optional) allowlist – helps avoid calling unexpected globals
  const ALLOWED = Object.create(null);
  ['kirb_toggle_info_popup','kirb_toggle_360_video','kirb_load_360','kirb_compare_prod']
    .forEach(n => { if (typeof window[n] === 'function') ALLOWED[n] = window[n]; });

  function splitArgs(s) {
    const out = []; let cur = ''; let q = null; let esc = false; let depth = 0;
    for (const ch of s) {
      if (esc) { cur += ch; esc = false; continue; }
      if (ch === '\\') { esc = true; continue; }
      if (q) { if (ch === q) q = null; cur += ch; continue; }
      if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; }
      if (ch === '(') { depth++; cur += ch; continue; }
      if (ch === ')' && depth) { depth--; cur += ch; continue; }
      if (ch === ',' && depth === 0) { out.push(cur.trim()); cur = ''; continue; }
      cur += ch;
    }
    if (cur.trim()) out.push(cur.trim());
    return out;
  }

  function tokenToVal(tok, el, ev) {
    if (tok === 'this') return el;
    if (tok === 'event') return ev;
    if (/^['"]/.test(tok) && /['"]$/.test(tok)) return tok.slice(1, -1);
    if (/^(true|false)$/i.test(tok)) return tok.toLowerCase() === 'true';
    if (/^-?\d+(\.\d+)?$/.test(tok)) return Number(tok);
    if (el && tok in el.dataset) return el.dataset[tok]; // handy: data-foo => "foo"
    return tok; // fallback: plain string
  }

  function parseCall(str, el, ev) {
    const m = String(str).match(/^([$\w.]+)\s*(?:\((.*)\))?$/);
    if (!m) return null;
    const [, name, raw] = m;
    const fn = ALLOWED[name] || (name.includes('.') ? name.split('.').reduce((o,k)=>o && o[k], window) : window[name]);
    if (typeof fn !== 'function') return null;
    const args = raw ? splitArgs(raw).map(a => tokenToVal(a, el, ev)) : [el, ev];
    return { fn, args };
  }

  function invokeFromAttr(el, attr, ev) {
    // supports either data-onclick="fn(...)" or data-click="fn(...)"
    const val = el.getAttribute(attr) || el.dataset[attr.replace('data-on', '')];
    if (!val) return false;
    const call = parseCall(val, el, ev);
    if (!call) return false;
    call.fn.apply(el, call.args);
    return true;
  }

  // CLICK (bubbles naturally)
  document.addEventListener('click', (ev) => {
    const el = ev.target.closest('[data-onclick]');
    if (el) invokeFromAttr(el, 'data-onclick', ev);
  }, true);

  // MOUSEENTER emulation using mouseover (mouseenter doesn't bubble)
  document.addEventListener('mouseover', (ev) => {
    const el = ev.target.closest('[data-onmouseenter]');
    if (!el) return;
    const rel = ev.relatedTarget;
    if (rel && (rel === el || el.contains(rel))) return; // ignore moves within the same element
    invokeFromAttr(el, 'data-onmouseenter', ev);
  }, true);

  // MOUSELEAVE emulation using mouseout
  document.addEventListener('mouseout', (ev) => {
    const el = ev.target.closest('[data-onmouseleave]');
    if (!el) return;
    const rel = ev.relatedTarget;
    if (rel && (rel === el || el.contains(rel))) return;
    invokeFromAttr(el, 'data-onmouseleave', ev);
  }, true);
})();
