/**
 * Acoustics Theme Scripts
 *
 * @author CodeGearThemes
 * @category WordPress
 * @package Acoustics
 * @version 1.0.0
 */

(function ($) {
  const initNavMenu = () => {
    const menuItems = $(".menu-item-has-children, .page_item_has_children");
    menuItems.append('<span class="item-toggle"><i class="fa fa-angle-down"></i></span>');

    $(document).on("click", ".item-toggle", function () {
      $(this).siblings(".sub-menu, .children").toggleClass("active");
    });
  };

  const initProductSlider = () => {
    $(".products-grid").each(function () {
      const $this = $(this);
      const data = $this.parents(".section-products").attr("type");

      $this.owlCarousel({
        loop: true,
        margin: 20,
        lazyLoad: true,
        responsiveClass: true,
        dots: false,
        navContainer: `.owl-nav-${data}`,
        navText: [`.owl-next-${data}`, `.owl-prev-${data}`],
        responsive: {
          0: { items: 1, nav: true, autoplay: true, autoplayTimeout: 2000, autoplayHoverPause: true },
          600: { items: 3, nav: true, autoplay: true, autoplayTimeout: 2000, autoplayHoverPause: true },
          1000: { items: 4, nav: true, loop: false },
        },
      });
    });
  };

  $(document).on('click', function(event) {
    const target = $(event.target);
    const quantityButton = target.closest('.quantity button');

    if (quantityButton && quantityButton.closest('.quantity')) {
        const quantityElement = quantityButton.closest('.quantity');
        const qtyInput = quantityElement.find('.qty');

        if (!qtyInput.length) return;

        const val = parseFloat(qtyInput.val());
        const max = parseFloat(qtyInput.attr('max'));
        const min = parseFloat(qtyInput.attr('min'));
        const step = parseFloat(qtyInput.attr('step'));

        if (quantityButton.hasClass('plus')) {
            if (max && max <= val) {
                qtyInput.val(max);
            } else {
                qtyInput.val(val + step);
            }
        } else if (quantityButton.hasClass('minus')) {
            if (min && min >= val) {
                qtyInput.val(min);
            } else if (val > 1) {
                qtyInput.val(val - step);
            }
        }
    }
  });

  const initializeScripts = () => {
    initNavMenu();
    initProductSlider();


    $( document.body ).on( 'added_to_cart', function(){
      $("html, body").animate({ scrollTop: 0 }, "slow");
      $('#site-header-cart').addClass('active');
      setInterval( function(){
        $('#site-header-cart').removeClass('active');
      }, 3000);
    });
  };

  // Ensure the DOM is ready before initializing scripts
  $(document).ready(initializeScripts);
})(window.jQuery);
