(function ($) {
  'use strict';

  $(window).on('load', function () {
    preloader();
  });
  
  $(function () {
    mainNav();
    stickyHeader();
    dynamicBackground();
    scrollUp();
  });
      
  function preloader() {
    $('.cs_preloader_in').fadeOut();
    $('.cs_preloader').delay(150).fadeOut('slow');
  }

  $(window).on('scroll', function () {
    showScrollUp();
  });

  /*--------------------------------------------------------------
    2. Mobile Menu
  --------------------------------------------------------------*/
  function mainNav() {
    $('.cs_site_header').append(
      '<span class="cs_menu_toggle"><span></span></span>',
    );
    $('.menu-item-has-children,li.cs_mega_menu').append(
      '<span class="cs_munu_dropdown_toggle"><span></span></span>',
    );
    $('.cs_menu_toggle').on('click', function () {
      $(this)
        .toggleClass('cs_toggle_active')
        .parents('.cs_site_header')
        .toggleClass('cs_mobile_active');
    });
    $('.cs_menu_toggle')
      .parents('body')
      .find('.cs_side_header')
      .addClass('cs_has_main_nav');
    $('.cs_menu_toggle')
      .parents('body')
      .find('.cs_toolbox')
      .addClass('cs_has_main_nav');
    $('.cs_header_overlay_mobile, .cs_close_mobile_active').on(
      'click',
      function () {
        $('.cs_site_header').removeClass('cs_mobile_active');
        $('.cs_menu_toggle').removeClass('cs_toggle_active');
      },
    );
    $('.cs_munu_dropdown_toggle').on('click', function () {
      $(this).toggleClass('active').siblings('ul').slideToggle();
      $(this).parent().toggleClass('active');
    });
    $('.cs_mobile_tab_btn').on('click', function () {
      $(this)
        .parent()
        .addClass('cs_mobile_active')
        .siblings()
        .removeClass('cs_mobile_active');
    });
    // Search toggle
    $('.cs_mobile_search_toggle').on('click', function () {
      $('.cs_header_search_form_wrap').toggleClass('active');
    });
    // Side Nav
    $('.cs_hamburger_btn').on('click', function () {
      $('.cs_side_header').addClass('active');
    });
    $('.cs_close, .cs_side_header_overlay').on('click', function () {
      $('.cs_side_header').removeClass('active');
    });
  }
    
    function stickyHeader() {
      var $window = $(window);
      var lastScrollTop = 0;
      var $header = $('.cs_sticky_header');
      var headerHeight = $header.outerHeight() + 30;
  
      $window.scroll(function () {
        var windowTop = $window.scrollTop();
  
        if (windowTop >= headerHeight) {
          $header.addClass('cs_sticky_active');
        } else {
          $header.removeClass('cs_sticky_active');
        }
  
        lastScrollTop = windowTop;
      });
    }
  
    /*--------------------------------------------------------------
      4. Dynamic Background
    --------------------------------------------------------------*/
    function dynamicBackground() {
      $('[data-src]').each(function () {
        var src = $(this).attr('data-src');
        $(this).css({
          'background-image': 'url(' + src + ')',
        });
      });
    }

  /*--------------------------------------------------------------
   Scroll Up
  --------------------------------------------------------------*/
  function scrollUp() {
    $('.cs_scrollup').on('click', function (e) {
      e.preventDefault();
      $('html,body').animate(
        {
          scrollTop: 0,
        },
        0,
      );
    });
  }
  /* For Scroll Up */
  function showScrollUp() {
    let scroll = $(window).scrollTop();
    if (scroll >= 350) {
      $('.cs_scrollup').addClass('cs_scrollup_show');
    } else {
      $('.cs_scrollup').removeClass('cs_scrollup_show');
    }
  }

  // Define the exists function
  $.fn.exists = function () {
    return this.length !== 0;
  };

  jQuery(window).on('load', function() {
    function initMasonry() {
        var $grid = $('.sp-wp-masonry,.row.grid,ul.products').masonry({
            // options
            itemSelector: '.sp-wp-masonry-item,.row.grid .grid-item, ul.products #single-products',
        });
        
        // layout Masonry after each image loads
        $grid.imagesLoaded().progress(function() {
            $grid.masonry('layout');
        });
    }
    
    function destroyMasonry() {
        var $grid = $('.sp-wp-masonry,.row.grid,ul.products').masonry();
        $grid.masonry('destroy');
    }

    var isMasonryInitialized = false;

    function checkMasonry() {
        if (jQuery(window).width() > 992) {
            if (!isMasonryInitialized) {
                initMasonry();
                isMasonryInitialized = true;
            }
        } else {
            if (isMasonryInitialized) {
                destroyMasonry();
                isMasonryInitialized = false;
            }
        }
    }

    // Check on load
    checkMasonry();

    // Check on resize
    jQuery(window).on('resize', function() {
        checkMasonry();
    });
});
	
})(jQuery); // End of use strict

jQuery(function($) {
  // Show updated cart sidebar after item is added
  $('body').on('added_to_cart', function(event, fragments, cart_hash, $button) {
      updateMiniCart();
  });

  // Handle item removal from sidebar cart
  $(document).on('click', '.cs_cart_card_item_remove', function(e) {
      e.preventDefault();
      
      var $btn = $(this);
      var cartItemKey = $btn.data('cart-item-key');

      if (!cartItemKey) {
          console.error('Cart item key not found.');
          return;
      }

      $.ajax({
          url: wc_add_to_cart_params.ajax_url,
          type: 'POST',
          data: {
              action: 'remove_cart_item',
              cart_item_key: cartItemKey
          },
          success: function(response) {
              if (response.success) {
                  // Update cart fragments (this updates header cart count and total)
                  if (response.data.fragments) {
                      $.each(response.data.fragments, function(key, value) {
                          $(key).replaceWith(value);
                      });
                  }
                  
                  // Refresh the mini cart
                  updateMiniCart();

                  // Trigger WooCommerce events
                  $(document.body).trigger('wc_fragments_refreshed');
                  $(document.body).trigger('wc_fragment_refresh');
              } else {
                  console.error('Failed to remove cart item:', response.data);
                  alert('Failed to remove item from cart.');
              }
          },
          error: function(xhr, status, error) {
              console.error("Remove cart item error:", error);
              alert('An error occurred while removing the item.');
          }
      });
  });

  // Reusable function to refresh the mini cart content
  function updateMiniCart() {
      $.ajax({
          url: wc_add_to_cart_params.ajax_url,
          type: 'POST',
          data: {
              action: 'get_mini_cart_html'
          },
          success: function(response) {
              if (response.success) {
                  $('.cs_cart_card_wrap .cs_cart_card').replaceWith(response.data.html);
                  $('.cs_cart_card_wrap').addClass('active');
              } else {
                  console.error('Mini cart fetch failed:', response.data);
              }
          },
          error: function(xhr, status, error) {
              console.error("Mini cart fetch error:", error);
          }
      });
  }

});