jQuery(document).ready(function ($) {



var ksiteurl = kavehShopData.ksiteurl || kavehShopData;
var ajaxnoinsingle = kavehShopData.ajaxnoinsingle;
var opencartonaddtocart = kavehShopData.opencartonaddtocart;
var woocommerce_cart_redirect_after_add = kavehShopData.woocommerce_cart_redirect_after_add;
var cart_url = kavehShopData.cart_url;


// Save this as product-search.js in your theme's js directory
var debounceTimer;
jQuery('.fetchinpu').on('input', function () {
  var searchTerm = jQuery(this).val();
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(function () {
    if (searchTerm.length >= 2) {
      performSearch(searchTerm);
    } else {
      jQuery('.datafetch3, .row.srows').hide();
    }
  }, 500);
});

function performSearch(searchQuery) {
  jQuery.ajax({
    type: 'post',
    url: ksiteurl,
    data: {
      action: 'kaveh_product_search',
      search: searchQuery
    },
    beforeSend: function () {
      Notiflix.Block.dots('.seabox');
    },
    success: function (response) {
      if (response.success) {
        if (response.data.length === 0) {
          handleNoResults();
        } else {
          displayResults(response.data, searchQuery);
        }
      } else {
        handleNoResults();
      }
    },
    error: function (xhr, status, error) {
      console.error("Error occurred: " + error);
      Notiflix.Notify.failure(kavehShopData.search_error, {
        timeout: 3000,
        rtl: true,
        position: 'center-center',
        fontFamily: kfont[0],
        zindex: 99999999,
      });
      Notiflix.Block.remove('.seabox');
    }
  });
}

function handleNoResults() {
  jQuery('.datafetch3, .row.srows').hide();
  Notiflix.Notify.failure(kavehShopData.nothing_found, {
    timeout: 3000,
    rtl: true,
    position: 'center-center',
    fontFamily: kfont[0],
    zindex: 99999999,
  });
  Notiflix.Block.remove('.seabox');
}

function displayResults(data, searchQuery) {
  jQuery('.row.srows').show();

  var resultsHtml = '';
  var resultsHtml2 = '';
  var resultsHtml3 = '';
  var count = 0;
  var addedCategories = [];

  // Main product results
  data.forEach(function (item) {
    if (count < 8) {
      resultsHtml += `
                <div class="swiper-slide">
                    <a href="${item.permalink}">
                        <div class="prseabox rounded-4 p-2">
                            <div class="row align-items-center justify-content-center">
                                <div class="col-4">
                                    <img class="p-2 d-inline boxim rounded-3" src="${item.thumbnail}" alt="${item.name}">
                                </div>
                                <div class="col">
                                    <p class="d-inline mx-2">${item.name.substring(0, 22)}...</p>
                                    ${item.category.name ? `<span class="rizs ms-2"> ${item.category.name}</span>` : ''}
                                    <div class="price-wrapper">${item.price_html}</div>
                                </div>
                            </div>
                        </div>
                    </a>
                </div>
            `;
      count++;
    }
  });

  jQuery('.datafetch3').show().html(resultsHtml);

  // Popular searches section
  count = 0;
  data.forEach(function (item) {
    if (count < 3) {
      resultsHtml2 += `
                <a href="${item.permalink}">
                    <div class="lisea mt-2 py-2 pe-2 ps-2">
                        <div class="d-inline seer mx-2">
                            <i class="far fa-circle"></i>
                        </div>
                        <span class="f-sea">${item.name.substring(0, 30)}...</span>
                        ${item.on_sale ? '<span class="sale-badge">Sale!</span>' : ''}
                        <i class="isax isax-arrow-left-1"></i>
                    </div>
                </a>
            `;
      count++;
    }
  });

  resultsHtml2 += `
        <a href="/shop?s=${encodeURIComponent(searchQuery)}" class="d-block wrbut"> ${kavehShopData.view_all}
            <i class="isax isax-arrow-left5"></i>
        </a>
    `;

  jQuery('.datafetch').html(resultsHtml2);

  // Categories section
  count = 0;
  data.forEach(function (item) {
    if (count < 3 && item.category.name) {
      if (addedCategories.indexOf(item.category.name) === -1) {
        resultsHtml3 += `
                    <a href="${item.category.link}">
                        <div class="lisea mt-2 py-2 pe-2 ps-2">
                            <div class="d-inline seer mx-2">
                                <i class="far fa-circle"></i>
                            </div>
                            <span class="f-sea">${item.category.name}</span>
                            <span class="rizs ms-2"> ${kavehShopData.view_category}</span>
                            <i class="isax isax-arrow-left-1"></i>
                        </div>
                    </a>
                `;
        addedCategories.push(item.category.name);
        count++;
      }
    }
  });

  jQuery('.datafetch2').html(resultsHtml3);
  Notiflix.Block.remove('.seabox');
}


jQuery(document).on('click', '.single_add_to_cart_button', function (e) {

  // Check if the button has the disabled attribute
  if (jQuery(this).is(':disabled')) {
    // If it has the disabled attribute, do nothing
    return;
  }
  if (jQuery(this).hasClass('disabled')) {
    // If it has the disabled class, do nothing
    return;
  }

  if (ajaxnoinsingle == '1') {
    // Check if the button is inside .insingle_pr
    if (jQuery(this).closest('.insingle_pr').length > 0) {
      // If it is, do nothing
      return;
    }
  }
  e.preventDefault();
  var jQuerythisbutton = jQuery(this),
    jQueryform = jQuerythisbutton.closest('form.cart'),
    id = jQuerythisbutton.attr('value'),
    product_qty = jQueryform.find('input[name=quantity]').val() || 1,
    product_id = jQueryform.find('input[name=product_id]').val() || id,
    variation_id = jQueryform.find('input[name=variation_id]').val() || 0;
  var data = {

  };
  jQuery(document.body).trigger('adding_to_cart', [jQuerythisbutton, data]);
  jQuery.ajax({
    type: 'post',
    url: ksiteurl,
    data: {
      action: 'kaveh_ajax_add_to_cart',
      product_id: product_id,
      product_sku: '',
      quantity: product_qty,
      variation_id: variation_id,
    },
    beforeSend: function () {
      Notiflix.Block.dots('body');
    },
    complete: function () {
      Notiflix.Block.remove('body');
    },
    success: function (response) {
      if (response.error && response.product_url) {
        window.location = response.product_url;
        return;
      } else {
        if (opencartonaddtocart == '1') {
          var cartSliding = document.querySelector("body .cart-sliding");
          if (cartSliding) {
            cartSliding.classList.add("opened");
          }
        }
        jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, jQuerythisbutton]);
        Notiflix.Notify.success(kavehShopData.product_added_to_cart, {
          timeout: 3000,
          rtl: true,
          position: 'left-bottom',
          fontFamily: kfont[0],
        });
        if (woocommerce_cart_redirect_after_add === 'yes') {
          window.location.href = cart_url;
        }
      }
    },
  });
  return false;
});


jQuery(document).ready(function ($) {
  jQuery(document).on('click', '.nav-header-cart-dropdown-two .changeinp', function () {
    var quantityInput = jQuery(this).siblings('.quantity').find('input[type=number]');
    var newQuantity = parseInt(quantityInput.val());
    var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
    // Send AJAX request to update the cart
    jQuery.ajax({
      url: ksiteurl,
      type: 'POST',
      data: {
        action: 'kaveh_ajax_update_cart_kk',
        cart_item_key: cartItemKey,
        quantity: newQuantity
      },
      beforeSend: function () {
        jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
      },
      success: function (response) {
        // Update the cart UI with the updated fragments
        if (response && response.fragments) {
          jQuery.each(response.fragments, function (key, value) {
            jQuery(key).replaceWith(value);
          });
        }
      },
      error: function (xhr, status, error) {
        // Handle any error that occurred during the AJAX request
      }
    });
  });
});


jQuery(document).ready(function ($) {
  jQuery(document).on('click', '.nav-header-cart-dropdown-two .delete', function (e) {
    e.preventDefault();
    var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
    // Send AJAX request to update the cart
    jQuery.ajax({
      url: ksiteurl,
      type: 'POST',
      data: {
        action: 'kaveh_ajax_update_cart_kk_remove',
        cart_item_key: cartItemKey,
        quantity: 0
      },
      beforeSend: function () {
        jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
      },
      success: function (response) {
        // Update the cart UI with the updated fragments
        if (response && response.fragments) {
          jQuery.each(response.fragments, function (key, value) {
            jQuery(key).replaceWith(value);
          });
        }
      },
      error: function (xhr, status, error) {
        // Handle any error that occurred during the AJAX request
      }
    });
  });
});


jQuery(document).ready(function ($) {
  jQuery(document).on('click', '.nav-header-cart-dropdown-two-products .delete', function (e) {
    e.preventDefault();
    var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
    // Send AJAX request to update the cart
    jQuery.ajax({
      url: ksiteurl,
      type: 'POST',
      data: {
        action: 'kaveh_ajax_update_cart_kk_remove',
        cart_item_key: cartItemKey,
        quantity: 0
      },
      beforeSend: function () {
        jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
      },
      success: function (response) {
        // Update the cart UI with the updated fragments
        if (response && response.fragments) {
          jQuery.each(response.fragments, function (key, value) {
            jQuery(key).replaceWith(value);
          });
        }
      },
      error: function (xhr, status, error) {
        // Handle any error that occurred during the AJAX request
      }
    });
  });
});


jQuery(document).ready(function ($) {
  jQuery(document).on('click', '.cart-sliding-content .changeinp', function () {
    var quantityInput = jQuery(this).siblings('.quantity').find('input[type=number]');
    var newQuantity = parseInt(quantityInput.val());
    var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
    // Send AJAX request to update the cart
    jQuery.ajax({
      url: ksiteurl,
      type: 'POST',
      data: {
        action: 'kaveh_ajax_update_cart_kk',
        cart_item_key: cartItemKey,
        quantity: newQuantity
      },
      beforeSend: function () {
        jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
      },
      success: function (response) {
        // Update the cart UI with the updated fragments
        if (response && response.fragments) {
          jQuery.each(response.fragments, function (key, value) {
            jQuery(key).replaceWith(value);
          });
        }
      },
      error: function (xhr, status, error) {
        // Handle any error that occurred during the AJAX request
      }
    });
  });

  jQuery(document).on('input', '.quantity input[type=number]', function () {
    var quantityInput = jQuery(this);
    var newQuantity = parseInt(quantityInput.val());
    var cartItemKey = jQuery(this).closest('.nav-header-cart-dropdown-two-products-item').find('.delete').data('cart-item-key');
    // Send AJAX request to update the cart
    jQuery.ajax({
      url: ksiteurl,
      type: 'POST',
      data: {
        action: 'kaveh_ajax_update_cart_kk',
        cart_item_key: cartItemKey,
        quantity: newQuantity
      },
      beforeSend: function () {
        jQuery('.nav-header-cart-dropdown-two-products-item').css('opacity', '0.4');
      },
      success: function (response) {
        // Update the cart UI with the updated fragments
        if (response && response.fragments) {
          jQuery.each(response.fragments, function (key, value) {
            jQuery(key).replaceWith(value);
          });
        }
      },
      error: function (xhr, status, error) {
        // Handle any error that occurred during the AJAX request
      }
    });
  });
});


jQuery(document).on('click', '.eyeid', function (emy) {
  var fired_button = jQuery(this).attr('value');
  jQuery.ajax({
    type: 'post',
    url: ksiteurl,
    data: {
      action: 'kaveh_quick_view',
      postid: fired_button,
    },
    beforeSend: function (inud) {
      Notiflix.Block.dots('#ajax_popup');
    },
    success: function (data) {
      jQuery('#ajax_popup').html(data);
    },

  });
  return false;
});
});