jQuery(document).ready(function ($) {
  var ksiteurl = kavehShopData.ksiteurl || kavehShopData;
  var originalHighestPrice = parseInt(kavehShopData.highestPrice) || 0;
  var originalLowestPrice = parseInt(kavehShopData.lowestPrice) || 0;
  
  // Fix swapped values if needed
  var highestPrice = Math.max(originalHighestPrice, originalLowestPrice);
  var lowestPrice = Math.min(originalHighestPrice, originalLowestPrice);
  
// Category Price
  const categoryPrice = document.getElementById("category-price");

  if (categoryPrice && lowestPrice !== highestPrice && lowestPrice < highestPrice && !isNaN(lowestPrice) && !isNaN(highestPrice)) {
    try {
      // Check if currency is Iranian Rial or Toman to configure step
      var isIranianCurrency = kavehShopData.currency_code === 'IRT' || kavehShopData.currency_code === 'IRR';
      var sliderConfig = {
        start: [lowestPrice, highestPrice],
        margin: Math.min(1000, (highestPrice - lowestPrice) / 10), // Dynamic margin based on price range
        behaviour: "drag",
        connect: true,
        range: {
          min: lowestPrice,
          max: highestPrice,
        },
      };
      
      // Add step configuration for Iranian currencies to prevent decimals
      if (isIranianCurrency) {
        sliderConfig.step = 1;
      }
      
      noUiSlider.create(categoryPrice, sliderConfig);
    } catch (error) {
      console.error('Error initializing price slider:', error);
    }

    var limitFieldMin = document.getElementById("category-price-min");
    var limitFieldMax = document.getElementById("category-price-max");
    var priceFilterTimeout;

    categoryPrice.noUiSlider.on("update", function (values, handle) {
      // Check if currency is Iranian Rial or Toman to avoid decimals
      var isIranianCurrency = kavehShopData.currency_code === 'IRT' || kavehShopData.currency_code === 'IRR';
      
      if (handle === 0) {
        // First handle (minimum)
        var minValue = isIranianCurrency ? Math.round(Number(values[0])) : Number(values[0]);
        limitFieldMin.value = new Intl.NumberFormat("en").format(minValue);
      } else {
        // Second handle (maximum)
        var maxValue = isIranianCurrency ? Math.round(Number(values[1])) : Number(values[1]);
        limitFieldMax.value = new Intl.NumberFormat("en").format(maxValue);
      }
    });

    // Add filtering functionality when slider changes
    categoryPrice.noUiSlider.on("change", function (values, handle) {
      // Clear existing timeout
      if (priceFilterTimeout) {
        clearTimeout(priceFilterTimeout);
      }
      // Set a new timeout to debounce the filter call
      priceFilterTimeout = setTimeout(function() {
        filterProducts();
      }, 300); // 300ms delay to prevent too many AJAX calls
    });
  }

  // Open Child Category Sidebar
  const itemsSidebar = document.querySelectorAll(
    ".category-sidebar-box-items li.has-child span"
  );
  if (itemsSidebar.length > 0) {
    itemsSidebar.forEach((item) => {
      item.addEventListener("click", (ev) => {
        const el = ev.target,
          content = el.nextElementSibling,
          parent = el.parentElement;

        parent.classList.toggle("opened");

        if (parent.classList.contains("opened")) {
          content.style.height = content.scrollHeight + "px";

          setTimeout(() => {
            content.style.height = "auto";
          }, 300);
        } else {
          content.style.height = content.scrollHeight + "px";

          setTimeout(() => {
            content.style.height = 0;
          }, 10);
        }
      });
    });
  }
  // Sidebar Category
  const btnOpenSidebarCategory = document.querySelector(".category-btn-filter"),
    sidebarCategory = document.querySelector(".category-sidebar"),
    backdropSidebarCategory = document.querySelector(
      ".category-sidebar-backdrop"
    );

  if (btnOpenSidebarCategory) {
    btnOpenSidebarCategory.addEventListener("click", () => {
      sidebarCategory.classList.add("open");
    });

    backdropSidebarCategory.addEventListener("click", () => {
      sidebarCategory.classList.remove("open");
    });
  }


  jQuery('ul.attrhidden li input').on('click', function (e) {
    e.preventDefault();
    jQuery(this).toggleClass('activeFilter');
    // Find the closest ancestor ul.attrhidden
    var closestUlAttrHidden = jQuery(this).closest('ul.attrhidden');
    // Find the .attrhiddeninput within the closest ancestor
    var attrHiddenInput = closestUlAttrHidden.find('.attrhiddeninput');
    editFilterInputs(attrHiddenInput, jQuery(this).attr('myid'));
    filterProducts();
  });


  jQuery('ul.cathidden li input').on('click', function (e) {
    e.preventDefault();
    jQuery(this).toggleClass('activeFilter');
    editFilterInputs(jQuery('.filterhiddeninput'), jQuery(this).attr('myid'));
    filterProducts();
  });


  jQuery('ul.brandhidden li input').on('click', function (e) {
    e.preventDefault();
    jQuery(this).toggleClass('activeFilter');
    editFilterInputs(jQuery('.filterhiddeninputbrand'), jQuery(this).attr('myid'));
    filterProducts();
  });


  function editFilterInputs(inputField, value) {
    if (!inputField || !inputField.length || !value) {
      return;
    }
    
    const currentValue = inputField.val() || '';
    const currentFilters = currentValue.split(',').filter(function(item) { return item.trim() !== ''; });
    const newFilter = value.toString().trim();

    if (currentFilters.includes(newFilter)) {
      const j = currentFilters.indexOf(newFilter);
      currentFilters.splice(j, 1);
      inputField.val(currentFilters.join(','));
    } else {
      if (currentFilters.length === 0) {
        inputField.val(newFilter);
      } else {
        inputField.val(currentFilters.join(',') + ',' + newFilter);
      }
    }
  }


  var checkBoxexit = document.getElementById("onlysale");
  if (checkBoxexit) {
    // Set checkbox to checked by default
    checkBoxexit.checked = false;
    checkBoxexit.addEventListener('click', function (e) {
      filterProducts()
    });
  }

  var checkBoxexit1 = document.getElementById("exists-products");
  if (checkBoxexit1) {
    checkBoxexit1.addEventListener('click', function (e) {
      filterProducts()
    });
  }



  jQuery(document).on('click', '.pg1 a.page-numbers', function (a) {
    a.preventDefault();
    var fired_a = jQuery(this).text();
    var filterData = getFilterData();
    filterData.page = fired_a;
    
    executeFilterRequest(filterData);
    return false;
  });
  
  // Helper function to get current filter data
  function getFilterData() {
    var attrHiddenInputs = document.querySelectorAll('.attrhiddeninput');
    var count = attrHiddenInputs.length;
    var taxIds = [];
    var attrId = [];
    var catIds = [];
    var brandIds = [];

    // Get brand IDs
    if (jQuery('.name-brands').length && jQuery('.name-brands').attr('catid')) {
      var brandCatId = jQuery('.name-brands').attr('catid');
      if (brandCatId && brandCatId.length > 0) {
        if (jQuery('.filterhiddeninputbrand').length && jQuery('.filterhiddeninputbrand').val()) {
          var brandFilterVal = jQuery('.filterhiddeninputbrand').val();
          if (brandFilterVal && brandFilterVal.split(',').length > 1) {
            brandIds = brandFilterVal.split(',').filter(function(item) { return item.trim() !== ''; });
          } else {
            brandIds = [brandCatId];
          }
        } else {
          brandIds = [brandCatId];
        }
      }
    } else if (jQuery('.filterhiddeninputbrand').length && jQuery('.filterhiddeninputbrand').val()) {
      brandIds = jQuery('.filterhiddeninputbrand').val().split(',').filter(function(item) { return item.trim() !== ''; });
    }

    // Get category IDs
    if (jQuery('.name-category').length && jQuery('.name-category').attr('catid')) {
      var catCatId = jQuery('.name-category').attr('catid');
      if (catCatId && catCatId.length > 0) {
        if (jQuery('.filterhiddeninput').length && jQuery('.filterhiddeninput').val()) {
          var catFilterVal = jQuery('.filterhiddeninput').val();
          if (catFilterVal && catFilterVal.split(',').length > 1) {
            catIds = catFilterVal.split(',').filter(function(item) { return item.trim() !== ''; });
          } else {
            catIds = [catCatId];
          }
        } else {
          catIds = [catCatId];
        }
      }
    } else if (jQuery('.filterhiddeninput').length && jQuery('.filterhiddeninput').val()) {
      catIds = jQuery('.filterhiddeninput').val().split(',').filter(function(item) { return item.trim() !== ''; });
    }

    // Get attribute data
    for (let i = 0; i < count; i++) {
      var attrInput = jQuery(attrHiddenInputs[i]);
      var attrVal = attrInput.val();
      taxIds.push(attrVal ? attrVal.split(',').filter(function(item) { return item.trim() !== ''; }) : []);
      attrId.push(attrInput.attr('taxid') || '');
    }

    // Get price range
    var priceMin = 0;
    var priceMax = 999999999;
    if (jQuery('.noUi-handle.noUi-handle-lower').length) {
      priceMin = jQuery('.noUi-handle.noUi-handle-lower').attr('aria-valuenow') || 0;
    }
    if (jQuery('.noUi-handle.noUi-handle-upper').length) {
      priceMax = jQuery('.noUi-handle.noUi-handle-upper').attr('aria-valuenow') || 999999999;
    }

    return {
      action: 'kaveh_shop_filters',
      onsalee: jQuery('#onlysale').length ? jQuery('#onlysale').is(':checked') : false,
      onstock: jQuery('#exists-products').length ? jQuery('#exists-products').is(':checked') : false,
      pricemin: priceMin,
      pricemax: priceMax,
      count: count,
      attrId: JSON.stringify(attrId),
      taxIds: JSON.stringify(taxIds),
      catIds: catIds,
      brandIds: brandIds,
      sortt: jQuery('.category-sort ul li input:checked').attr('id') || 'sort-1',
      nonce: kavehShopData.shop_filter_nonce,
      page: 1
    };
  }
  
  // Helper function to execute filter request
  function executeFilterRequest(data) {
    jQuery.ajax({
      url: ksiteurl,
      type: 'post',
      data: data,
      beforeSend: function () {
        Notiflix.Block.pulse('body');
      },
      success: function (response) {
        if (response.success && response.data && response.data.html) {
          jQuery('#woor').html(response.data.html);
        } else if (typeof response === 'string') {
          // Fallback for old response format
          jQuery('#woor').html(response);
        } else {
          console.error('Invalid response format:', response);
          Notiflix.Notify.failure(ksiteurl.invalid_response || 'Invalid response from server.');
        }
        jQuery('.woocommerce-pagination').remove();
        Notiflix.Block.remove('body');
      },
      error: function(xhr, status, error) {
        console.error('Ajax error:', error);
        Notiflix.Block.remove('body');
        var errorMessage = ksiteurl.filter_error || 'An error occurred while filtering products.';
        if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
          errorMessage = xhr.responseJSON.data.message;
        }
        Notiflix.Notify.failure(errorMessage);
      },
    });
  }

  function filterProducts() {
    var filterData = getFilterData();
    executeFilterRequest(filterData);
    return false;
  }

  jQuery('li > #sort-2').click(function () {
    filterProducts();
  })
  jQuery('li > #sort-3').click(function () {
    filterProducts();
  })
  jQuery('li > #sort-4').click(function () {
    filterProducts();
  })
  jQuery('li > #sort-1').click(function () {
    filterProducts();
  })

})