// Utility function to add and remove classes
function addClass(element, className) {
    if (element && !element.classList.contains(className)) {
        element.classList.add(className);
    }
}

function removeClass(element, className) {
    if (element && element.classList.contains(className)) {
        element.classList.remove(className);
    }
}

// Utility function to set cookie
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    var expires = "expires=" + d.toUTCString();
    d
	ocument.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// Helper function to find the closest ancestor with a given class
function findClosest(element, selector) {
    while (element && !element.matches(selector)) {
        element = element.parentElement;
    }
    return element;
}

jQuery( document.body ).on(
	'added_to_cart',
	function() {
		addClass(document.querySelector('.header-min-cart'), 'loading');
		var headerMinCart = document.querySelector('.header-min-cart');
		if (headerMinCart) {
			setTimeout(function () {
				removeClass(headerMinCart, 'loading');
			}, 1500);
		}
	}
)
// Add loading class to offcanvas-cart
/* document.body.addEventListener('adding_to_cart', function () {
    addClass(document.querySelector('.header-min-cart'), 'loading');
});

document.body.addEventListener('added_to_cart', function () {
    var headerMinCart = document.querySelector('.header-min-cart');
    if (headerMinCart) {
        setTimeout(function () {
            removeClass(headerMinCart, 'loading');
        }, 1500);
    }
}); */

// Update label when select value changes
document.querySelectorAll('.variations_form td.value select').forEach(function (selectElement) {
    selectElement.addEventListener('change', function () {
        var value = this.options[this.selectedIndex].text;
        var labelContainer = this.closest('tr').querySelector('td.label .mf-attr-value');
        if (labelContainer) {
            labelContainer.innerHTML = value;
        }
    });
    //selectElement.dispatchEvent(new Event('change'));
	jQuery(selectElement).trigger('change');
});

// Switch View mod
document.body.addEventListener("click", function(e) {
    var target = e.target;
    var productViewButton = findClosest(target, ".product-view-button");

    if (productViewButton) {
        e.preventDefault();
        var mod = productViewButton.getAttribute("data-mod") || "grid";

        document.querySelectorAll(".product-view-switcher .product-view-button").forEach(function(button) {
            button.classList.remove("active");
        });

        productViewButton.classList.add("active");

        // Update for "ul.products"
        var productsList = document.querySelector("ul.products");
        productsList.classList.remove("product-grid-view", "product-list-view");
        productsList.classList.add("product-" + mod + "-view");

        // Update for ".archive-product"
        var archiveProducts = document.querySelectorAll(".archive-product");
        archiveProducts.forEach(function (archiveProduct) {
            archiveProduct.classList.remove("product-grid-view", "product-list-view");
            archiveProduct.classList.add("product-" + mod + "-view");
        });

        setCookie("nevo_wc_pl_view_mod", mod, 360);
    }
});

(function() {
	'use strict';

	var handleWooCommerceQuantityIncrementButtons = function( e ) {
		// Only handle "product-qty" button.
		if ( e.target.classList.contains( 'nevo-product-qty' ) ) {
			// Prevent default handlers on click and touch event.
			if ( 'click' === e.type || 'touchend' === e.type ) {
				e.preventDefault();
			}

			// Abort if keydown is not enter or space key.
			else if ( 'keydown' === e.type && 13 !== e.which && 32 !== e.which ) {
				return;
			}

			var $button = e.target,
				$input = $button.parentElement.querySelector( '.qty' ),
				step = parseInt( $input.getAttribute( 'step' ) ),
				min = parseInt( $input.getAttribute( 'min' ) ),
				max = parseInt( $input.getAttribute( 'max' ) ),
				sign = $button.classList.contains( 'nevo-qty-minus' ) ? '-' : '+';

			// Adjust the input value according to the clicked button.
			if ( '-' === sign ) {
				var newValue = parseInt( $input.value ) - step;

				if ( min && min > newValue ) {
					$input.value = parseInt( min );
				} else {
					$input.value = parseInt( newValue );
				}
			} else {
				var newValue = parseInt( $input.value ) + step;

				if ( max && max < newValue ) {
					$input.value = parseInt( max );
				} else {
					$input.value = parseInt( newValue );
				}
			}

			// Trigger "change" event on the input field (use old fashioned way for IE compatibility).
			var event = document.createEvent( 'HTMLEvents' );
			event.initEvent( 'change', true, false);
			$input.dispatchEvent( event );
		}
	};

	document.body.addEventListener( 'click', handleWooCommerceQuantityIncrementButtons );
	document.body.addEventListener( 'touchend', handleWooCommerceQuantityIncrementButtons );
	document.body.addEventListener( 'keydown', handleWooCommerceQuantityIncrementButtons );
})();

document.addEventListener("DOMContentLoaded", function() {
    function setEqualHeight() {
        const viewport = document.querySelector('.product-gallery-vertical .flex-viewport');
        const thumbs = document.querySelector('.product-gallery-vertical .flex-control-thumbs');

        if (viewport && thumbs) {
            setTimeout(() => {
                const viewportHeight = viewport.offsetHeight;
                thumbs.style.height = viewportHeight + 'px';
                console.log('Set thumbs height to: ' + viewportHeight + 'px');
            }, 100); // Adjust the delay as needed
        } else {
            //console.error('Elements .flex-viewport or .flex-control-thumbs not found');
        }
    }

    // Initial check and set height
    function initialCheck() {
        const viewport = document.querySelector('.product-gallery-vertical .flex-viewport');
        const thumbs = document.querySelector('.product-gallery-vertical .flex-control-thumbs');

        if (viewport && thumbs) {
            setEqualHeight();
            return true;
        }
        return false;
    }

    // Initial check
    if (!initialCheck()) {
        // Using MutationObserver to wait for elements to be added
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) { // Ensure the node is an element
                        if (node.classList.contains('flex-viewport') || node.classList.contains('flex-control-thumbs')) {
                            if (initialCheck()) {
                                observer.disconnect(); // Stop observing once elements are found and height is set
                            }
                        }
                    }
                });
            });
        });

        // Start observing the document
        observer.observe(document.body, { childList: true, subtree: true });
    }

    // Set equal height on window resize
    window.addEventListener('resize', setEqualHeight);
});