var appStart = function ($) {

    // var screenWidth = $(window).width();
    // handle Preloader OnClick
    function handlePreloaderOnClick() {
        const preloader = document.querySelector(".preloader");
        const closeBtn = document.querySelector(".preloader__close-btn");
        if (preloader) {
            setTimeout(() => {
                preloader.style.opacity = "0";
                preloader.style.visibility = "hidden";
            }, 5000);
            if (closeBtn) {
                closeBtn.addEventListener("click", () => {
                    preloader.style.opacity = "0";
                    preloader.style.visibility = "hidden";
                });
            }
        }
    }

    // handleStickyHeader  =============
    var handleStickyHeader = function () {
        if ($(".sticky-nav").length > 0) {
            var navbar = $(".sticky-nav");
            var navbarOffset = navbar.offset().top;
            $(window).on("scroll", function () {
                var scrollTop = $(window).scrollTop();
                if (scrollTop > navbarOffset) {
                    navbar.addClass("sticky-menu");
                } else {
                    navbar.removeClass("sticky-menu");
                }
            });
        }
    }

    // handle Password Input ===========
    var handlePasswordInput = function () {
        if ($(".show-password-input").length > 0) {
            document.querySelectorAll(".show-password-input").forEach(function (toggle) {
                toggle.addEventListener("click", function () {
                    const input = this.previousElementSibling;
                    this.classList.toggle("display-password");
                    if (input) {
                        input.type = this.classList.contains("display-password") ? "text" : "password";
                    }
                });
            });
        }
    }

    // handle Header Menu ============
    var handleHeaderMenu = function () {
        if ($(window).width() <= 991) {
            jQuery('.menu-wrap li > a, .dropdown-menu li > a')
                .off("click keypress")
                .on("click keypress", function (e) {
                    if (e.type === "keypress" && e.key !== "Enter") return;
                    // handleMenus(e, jQuery(this));
                });
            jQuery('.tabindex').attr("tabindex", "0");

            jQuery('.mobile-toggler button')
                .off('click')
                .on('click', function (e) {
                    e.preventDefault();
                    console.log(11);
                    let parentLi = jQuery(this).closest('li');
                    let dropdown = parentLi.find('.dropdown-menu').first();
                    if (parentLi.hasClass('open')) {
                        dropdown.slideUp('slow', function () {
                            jQuery(this).css('display', 'none');
                        });
                        parentLi.removeClass('open');
                    } else {
                        parentLi.siblings('li').removeClass('open')
                            .children('.dropdown-menu, .mega-menu').slideUp('slow').css('display', 'none');
                        dropdown.css('display', 'block').slideDown();
                        parentLi.addClass('open');
                    }
                });
        } else {
            jQuery('.tabindex').removeAttr("tabindex");
            jQuery('.dropdown-menu, .mega-menu').removeAttr('style');
            jQuery('.menu-wrap li').removeClass('open');
        }
    };

    // handle Mobile Menu =======================
    let topScrolling = 0;
    let topDirection = 0;
    function handleMobileMenu() {
        if (jQuery('.footer-small').length > 0) {
            jQuery(document).ready(function ($) {
                if (window.innerWidth < 991 && document.querySelector('.footer-small')) {
                    let chckScroll = window.scrollY || document.documentElement.scrollTop;
                    let direction = chckScroll > topScrolling ? 2 : (chckScroll < topScrolling ? 1 : topDirection);
                    if (direction !== topDirection) {
                        if (direction === 2 && chckScroll > 52) {
                            document.querySelector('.footer-small').style.bottom = '-105px';
                        } else if (direction === 1) {
                            document.querySelector('.footer-small').style.bottom = '0px';
                        }
                        topDirection = direction;
                    }
                    topScrolling = chckScroll;
                }
            });
        }
    }
    function handleMobileMenuActive() {
        if ($('.footer-small').length > 0) {
            const currentPath = window.location.pathname;
            const menuItems = document.querySelectorAll(".footer-mobile-menu");
            menuItems.forEach(item => {
                const link = item.querySelector("a");
                if (link) {
                    const href = link.getAttribute("href");
                    let linkPath = null;
                    if (href && !href.startsWith("javascript")) {
                        linkPath = new URL(link.href, window.location.origin).pathname;
                    }

                    if (linkPath && currentPath === linkPath) {
                        menuItems.forEach(i => i.classList.remove("active"));
                        item.classList.add("active");
                    }

                    item.addEventListener("click", function () {
                        menuItems.forEach(i => i.classList.remove("active"));
                        this.classList.add("active");
                    });
                }
            });
        }
    }

    // Handle Menu Category Popup ============
    var handleMenuCategoryToggle = function () {
        const switcherButtons = document.querySelectorAll(".switcher-tab > button");
        const productCategories = document.querySelector(".product-category-menu-mobile");
        const menuPrimary = document.querySelector("#AVMenu"); // Corrected ID

        if (switcherButtons.length > 0 && productCategories && menuPrimary) {
            switcherButtons.forEach(button => {
                button.addEventListener("click", function () {
                    let value = button.getAttribute('category');

                    if (value === 'menu') {
                        productCategories.classList.add("d-none");
                        menuPrimary.classList.remove("d-none");
                    } else {
                        productCategories.classList.remove("d-none");
                        menuPrimary.classList.add("d-none");
                    }

                    // Fix the toggle of active class
                    switcherButtons.forEach(btn => btn.classList.remove("active-bg"));
                    this.classList.add("active-bg");
                });
            });
        }

        // Function to handle responsive behavior
        // const handleResponsiveMenu = () => {
            // if (window.innerWidth >= 991) {
                // productCategories.classList.remove("d-none");
                // menuPrimary.classList.add("d-none");
            // }
        // };

        // window.addEventListener("resize", handleResponsiveMenu);
        // handleResponsiveMenu(); // Call once on load to ensure correct display
    };

    // Search Animation
    function initSearchAnimation() {
        document.querySelectorAll('.spinnnn').forEach((ulEl) => {
            const listItems = ulEl.querySelectorAll('li');
            let index_number = 1;
            let activeIndex = 1;
            let newActiveEl = ulEl.querySelector('li:nth-child(1)');
            const rotate = -360 / listItems.length;
            ulEl.style.setProperty("--current_index", '0');
            newActiveEl.classList.add("active");
            function initialize() {
                listItems.forEach((item, idx) => {
                    item.style.setProperty("--item_index", idx);
                });
                ulEl.style.setProperty("--rotateDegrees", rotate);
            }
            function rotateItems() {
                ulEl.style.setProperty("--current_index", index_number);
                const activeEl = ulEl.querySelector("li.active");
                if (activeEl) activeEl.classList.remove("active");
                activeIndex = (index_number + listItems.length) % listItems.length;
                newActiveEl = ulEl.querySelector(`li:nth-child(${activeIndex + 1})`);
                newActiveEl.classList.add("active");
                index_number++;
            }
            initialize();
            setInterval(rotateItems, 5000);
        });
    }
    // Show / Hide Placeholder (For Multiple Inputs)
    function initSearchPlaceholders() {
        document.querySelectorAll('.header-search-input').forEach((searchInput) => {
            const placeholderText = searchInput.parentElement.querySelector('.placeholder');
            if (!placeholderText) return;
            searchInput.addEventListener('focus', function () {
                placeholderText.style.display = 'none';
            });
            searchInput.addEventListener('blur', function () {
                if (searchInput.value.trim() === '') {
                    placeholderText.style.display = 'flex';
                }
            });
            placeholderText.addEventListener('click', function () {
                searchInput.focus();
                placeholderText.style.display = 'none';
            });
        });
    }

    // Handle Popup Toggles ============  
    var handlePopupToggles = function () {
        const body = document.querySelector("body");
        const menuTogglers = document.querySelectorAll(".category-toggle, .category-toggle-mobile, .cart-toggle");
        if (menuTogglers.length > 0) {
            menuTogglers.forEach(menuToggler => {
                const target = menuToggler.getAttribute("data-target");
                const targetElement = document.querySelector(target);
                if (targetElement) {
                    menuToggler.addEventListener("click", function () {
                        body.classList.add("docker-popup-active");
                        targetElement.classList.add("popup-visible");
                    });
                    const closeButton = targetElement.querySelector(".docker-widget-close");
                    if (closeButton) {
                        closeButton.addEventListener("click", function () {
                            body.classList.remove("docker-popup-active");
                            document.querySelectorAll('.docker-widget-popup').forEach(popup => {
                                setTimeout(() => {
                                    popup.classList.remove("popup-visible");
                                }, 1000);
                            });
                        });
                    }
                    const overlay = targetElement.querySelector(".docker-overlay-layer");
                    if (overlay) {
                        overlay.addEventListener("click", function () {
                            body.classList.remove("docker-popup-active");
                            document.querySelectorAll('.docker-widget-popup').forEach(popup => {
                                setTimeout(() => {
                                    popup.classList.remove("popup-visible");
                                }, 1000);
                            });
                        });
                    }
                } else {
                    console.error("Target element not found:", target);
                }
            });
        }

        window.addEventListener("resize", function () {
            setTimeout(() => {
                document.body.classList.remove("docker-popup-active");
                document.querySelectorAll('.docker-widget-popup').forEach(popup => {
                    popup.classList.remove("popup-visible");
                });
            }, 100);
        });
    };

    // handle Popular Product Slider ============
    var handlePopularProductSlider = function () {
        jQuery(document).ready(function ($) {
            $(".popular-product-slider").each(function () {
                var $slider = $(this);
                $slider.owlCarousel({
                    autoWidth: true,
                    loop: true,
                    margin: 15,
                    autoplay: true,
                    autoplayTimeout: 6000,
                    autoplaySpeed: 6000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
                    slideTransition: 'linear',
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        991: {
                            margin: 30
                        }
                    }
                });
            });
        });
    };

    // handle Main Slider Home  ==============
    var handleMainSlider = function () {
        if (jQuery('.main-slider').length > 0) {
            jQuery(document).ready(function ($) {
                var sync1 = $(".main-slider");
                sync1.owlCarousel({
                    items: 1,
                    loop: true,
                    margin: 15,
                    autoplay: true,
                    autoplayTimeout: 5000,
                    autoplayHoverPause: true,
                    smartSpeed: 1500,
                    nav: false,
                    dots: true,
                    autoHeight: false,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    onTranslated: applyAnimations
                }).on('changed.owl.carousel');

                function applyAnimations() {
                    var $activeSlide = sync1.find(".owl-item.active");
                    sync1.find("[data-animation]").each(function () {
                        var animName = $(this).data("animation");
                        $(this).removeClass("animated " + animName).css("opacity", "0");
                    });
                    $activeSlide.find("[data-animation]").each(function () {
                        var $el = $(this),
                            animName = $el.data("animation"),
                            animDelay = $el.data("delay") || "0s",
                            animDuration = $el.data("duration") || "1s";

                        $el.css({
                            "animation-delay": animDelay,
                            "animation-duration": animDuration,
                            "opacity": "1"
                        }).addClass("animated " + animName);
                    });
                }
                applyAnimations();
            });
        }
    }

    // handle Filter Slider ============
    var handleFilterSlider = function () {
        jQuery(document).ready(function ($) {
            $(".tab-filter-slider").each(function () {
                var $slider = $(this);
                var showItemCount = parseInt($slider.data("show-item")) || 7;
                var autoWidthEnabled = ($slider.data("auto-width") === undefined) ? true : !!parseInt($slider.data("auto-width"));
                var drag = ($slider.data("mouse-drag") === undefined) ? false : !parseInt($slider.data("mouse-drag"));

                var responsiveZeroItems = autoWidthEnabled ? showItemCount - 1 : showItemCount;
                $slider.owlCarousel({
                    // items: 8,
                    loop: false,
                    margin: 0,
                    autoWidth: autoWidthEnabled,
                    autoplay: false,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
					slideBy:1,
                    nav: true,
                    dots: false,
                    mouseDrag: drag,
                    autoHeight: true,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        0: {
                            items: 3
                        },
                        768: {
                            items: showItemCount
                        },
                        991: {
                            // autoWidth: false,
                            items: responsiveZeroItems
                        },
                        1200: {
                            // autoWidth: false,
                            items: showItemCount
                        }
                    }
                });
                setInterval(function () {
                    $slider.find(".owl-nav").removeClass("disabled");
                }, 0);
            });
        });
    };

    // handle Masonry Filter  ============
    var handleMasonryFilter = function () {
        const filterGroups = document.querySelectorAll('.filter-group');
        filterGroups.forEach(group => {
            const filterLinks = group.querySelectorAll('.filter-container a');
            const mixItems = group.querySelectorAll('.mix');
            const owlItemsMap = new WeakMap();

            filterLinks.forEach(link => {
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    filterLinks.forEach(l => l.classList.remove('active'));
                    link.classList.add('active');

                    const filter = link.getAttribute('data-filter');

                    // OWL Filter
                    handleOwlFilter(group, filter, owlItemsMap);

                    mixItems.forEach(item => {
                        if (filter === 'all' || item.classList.contains(filter)) {
                            item.style.display = 'block';
                            item.classList.remove('zooming-out');
                            void item.offsetWidth;
                            item.classList.add('show');
                        } else {
                            item.classList.remove('show');
                            item.classList.add('zooming-out');

                            setTimeout(() => {
                                item.style.display = 'none';
                                item.classList.remove('zooming-out');
                            }, 300);
                        }
                    });
                    // handleFlagToggle();
                });
            });
        });
    };
    function handleOwlFilter(group, filter, owlItemsMap) {
        const owlContainer = group.querySelector('.products-slider, .post-slider, .testimonial-slider, .team-slider, .awards-slider');
        if (!owlContainer) return;

        if (!owlItemsMap.has(group)) {
            const originalItems = Array.from(owlContainer.querySelectorAll('.product.mix, .post-item-trigger.mix, .testimonial-item.mix, .team-item.mix, .award-item.mix')).map(item => item.cloneNode(true));
            owlItemsMap.set(group, originalItems);
        }

        const originalOwlItems = owlItemsMap.get(group);

        $(owlContainer).trigger('destroy.owl.carousel');
        owlContainer.innerHTML = '';

        const filtered = originalOwlItems.filter(item => {
            return filter === 'all' || item.classList.contains(filter);
        });

        filtered.forEach(item => {
            owlContainer.appendChild(item.cloneNode(true));
        });

        setTimeout(() => {
            handleProductSlider();
            handlePostSlider();
            handleTeamSlider();
            handleTestimonialSlider();
            handleAwardsSlider();
        }, 100);
    }

    // Start Countdown --------------
    function startCountdown() {
		if($(".timer-container").length > 0 ) {
			let timers = document.querySelectorAll(".timer-container");
			let timers2 = document.querySelectorAll(".electromix_ct-countdown");
			if (timers2.length > 0) {
				timers2.forEach(timer => {
					const targetDate = new Date(timer.getAttribute("data-timer")).getTime();
					const countdownElements = timer.querySelectorAll(".electromix_ct-timer > span");
					function updateTimer() {
						const now = new Date().getTime();
						const timeLeft = targetDate - now;

						if (timeLeft > 0) {
							const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
							const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
							const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
							const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

							countdownElements[0].innerHTML = `<span>${splitText(String(days).padStart(2, '0'))}</span><span>DAY</span>`;
							countdownElements[1].innerHTML = `<span>${splitText(String(hours).padStart(2, '0'))}</span><span>HOUR</span>`;
							countdownElements[2].innerHTML = `<span>${splitText(String(minutes).padStart(2, '0'))}</span><span>MIN</span>`;
							countdownElements[3].innerHTML = `<span>${splitText(String(seconds).padStart(2, '0'))}</span><span>SEC</span>`;
						} else {
							timer.innerHTML = "<h2>We are live now!</h2>";
						}
					}
					updateTimer();
					setInterval(updateTimer, 1000);
				});
				function splitText(word) {
					let dayHtml = '';
					for (let i = 0; i < word.length; i++) {
						dayHtml += `<span>${word[i]}</span>`;
					}
					return dayHtml;
				}
			} else {
				timers.forEach(timer => {
					let targetDate = new Date(timer.getAttribute("data-timer")).getTime();
					let countdownElements = timer.querySelectorAll(".dealsofday-count h6");
					function updateTimer() {
						let now = new Date().getTime();
						let timeLeft = targetDate - now;
						if (timeLeft > 0) {
							let days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
							let hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
							let minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
							let seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

							countdownElements[0].innerText = String(days).padStart('0', 2);
							countdownElements[1].innerText = String(hours).padStart('0', 2);
							countdownElements[2].innerText = String(minutes).padStart('0', 2);
							countdownElements[3].innerText = String(seconds).padStart('0', 2);
						} else {
							timer.innerHTML = "<h2>We are live now!</h2>";
						}
					}
					updateTimer();
					setInterval(updateTimer, 1000);
				});
			}
		}
    }

    // handle Product Slider ============
    var handleProductSlider = function () {
        jQuery(document).ready(function ($) {
            $(".products-slider").each(function () {
                var $slider = $(this);
                var showItemCount = parseInt($slider.data("show-item")) || 4;
                var loopEnabled = ($slider.data("loop") === undefined) ? true : !!parseInt($slider.data("loop"));
                var owl = $slider.owlCarousel({
                    items: showItemCount,
                    loop: loopEnabled,
                    margin: 10,
                    autoplay: true,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
                    animateOut: 'fadeOut',
                    animateIn: 'fadeIn',
                    responsive: {
                        0: {
                            items: 1
                        },
                        575: {
                            items: 2
                        },
                        991: {
                            items: 3,
                            margin: 30
                        },
                        1199: {
                            items: showItemCount,
                            margin: 30
                        },
                    }
                });
                var container = $(this).prev();
                container.find('.custom-prev').off('click').on('click', function () {
                    owl.trigger('prev.owl.carousel');
                });
                container.find('.custom-next').off('click').on('click', function () {
                    owl.trigger('next.owl.carousel');
                });
            });
        });
    };

    // handle Product List Slider  ============
    var handleProductListSlider = function () {
    jQuery(function ($) {
        $(".products-list-slider").each(function () {
        var itemsCount = $(this).data("items") || 1;
        var axisContext = $(this).data("axis") || 'vertical'; 
        // Initialize Tiny Slider
        var slider = tns({
            container: this,
            items: itemsCount,
            axis: axisContext,
            swipeAngle: true,
            speed: 400,
            nav: false,
            controls: false,
            loop: false,
        });

        // 🧩 Find .heading-default inside the same column container
        var $heading = $(this).closest(".col-12, .col-lg-4").find(".heading-default");
        var $prevBtn = $heading.find(".custom-prev");
        var $nextBtn = $heading.find(".custom-next");

        if ($heading.length === 0) {
            console.warn("No heading-default found for slider:", this);
            return;
        }

        // Manual navigation
        $prevBtn.off("click").on("click", function () {
            slider.goTo("prev");
        });

        $nextBtn.off("click").on("click", function () {
            slider.goTo("next");
        });

        // ✅ Update button enable/disable states
        function updateButtonState() {
            var info = slider.getInfo();
            var currentIndex = info.displayIndex;
            var totalItems = info.slideCount;
            var visibleItems = info.items;

            // Disable prev if first
            if (currentIndex === 1) {
            $prevBtn.prop("disabled", true).attr("title", "No More");
            } else {
            $prevBtn.prop("disabled", false).attr("title", "");
            }

            // Disable next if last
            if (currentIndex + visibleItems - 1 >= totalItems) {
            $nextBtn.prop("disabled", true).attr("title", "No More");
            } else {
            $nextBtn.prop("disabled", false).attr("title", "");
            }
        }

        // Bind Tiny Slider events
        slider.events.on("indexChanged", updateButtonState);
        slider.events.on("transitionEnd", updateButtonState);

        // Run once on load
        updateButtonState();
        });
    });
    };
	
	var handleProductListSlider2 = function () {
		jQuery(function ($) {
			 setTimeout(function () {
			$(".electromix_magnifier_gallery_front").each(function () {
				var itemsCount = $(this).data("columns") || 1;
				var axisContext = $(this).data("axis") || 'vertical';

				// Initialize Tiny Slider
				var slider = tns({
					container: this,
					items: itemsCount,
					axis: axisContext,
					swipeAngle: false,
					speed: 400,
					nav: false,
					controls: false,
					loop: false,
					mouseDrag: true,
				});
				
				// if(itemsCount < 4) {
					// $('#slider-prev,#slider-next').hide();
				// }

				var $prevBtn = $(this).parents(".thumbnails").find("#slider-prev");
				var $nextBtn = $(this).parents(".thumbnails").find("#slider-next");

				// Manual navigation
				$prevBtn.off("click").on("click", function () {
					slider.goTo("prev");
				});

				$nextBtn.off("click").on("click", function () {
					slider.goTo("next");
				});
				
			// ✅ Update button enable/disable states
				function updateButtonState() {
					var info = slider.getInfo();
					var currentIndex = info.displayIndex;
					var totalItems = info.slideCount;
					var visibleItems = info.items;
					
					// Disable prev if first
					if (currentIndex === 1) {
					$prevBtn.css("opacity", "0.5").attr("title", "No More");
					} else {
					$prevBtn.css("opacity", "1.0").attr("title", "");
					}

					// Disable next if last
					if (currentIndex + visibleItems - 1 >= totalItems) {
					$nextBtn.css("opacity", "0.5").attr("title", "No More");
					} else {
					$nextBtn.css("opacity", "1.0").attr("title", "");
					}
				}

				// Bind Tiny Slider events
				slider.events.on("indexChanged", updateButtonState);
				slider.events.on("transitionEnd", updateButtonState);

				// Run once on load
				updateButtonState();
			});		
		}, 500); // Adjust the delay (in ms) as needed
		});
    };


    // handle Post Slider ============
    var handlePostSlider = function () {
        if (jQuery('.post-slider').length > 0) {
            jQuery(document).ready(function ($) {
                if (typeof $.fn.owlCarousel !== 'undefined') {
                    $('.post-slider').each(function () {
                        var owl = $(this).owlCarousel({
                            items: 1,
                            loop: true,
                            margin: 10,
                            autoplay: true,
                            autoplayTimeout: 3000,
                            autoplayHoverPause: true,
                            smartSpeed: 1000,
                            nav: false,
                            dots: false,
                            autoHeight: true,
                            animateOut: 'fadeOut',
                            animateIn: 'fadeIn',
                            responsive: {
                                768: {
                                    items: 2
                                },
                                991: {
                                    items: 3,
                                    margin: 30
                                }
                            }
                        });
                        var container = $(this).prev();
                        container.find('.custom-prev').off('click').on('click', function () {
                            owl.trigger('prev.owl.carousel');
                        });
                        container.find('.custom-next').off('click').on('click', function () {
                            owl.trigger('next.owl.carousel');
                        });
                    });
                }
            });
        }
    }

    // handle Footer Height ============
    var handleFooterHeight = function () {
        const footerSection = document.querySelector("#footer-section");
        const bgShape = footerSection?.querySelector(".bg-shape");
        const footerCopyright = document.querySelector(".footer-copyright");
        if (footerSection && bgShape) {
            const footerHeight = footerSection.offsetHeight;
            const copyrightHeight = (footerCopyright ? footerCopyright.offsetHeight : 0) - 10;
            bgShape.style.height = (footerHeight - copyrightHeight) + "px";
        }
    };

    // Product thumbnails Handle =========== 
    var handleProductThumbnails = function () {
        const productContainers = document.querySelectorAll('.product-img');
		productContainers.forEach(container => {
			const mainImage = container.querySelector('a > img');
			const thumbnailList = container.querySelector('.electromix_magnifier_gallery_front');

			if (!thumbnailList || !mainImage) return;

			const thumbnails = thumbnailList.querySelectorAll('img');

			thumbnails.forEach(thumb => {
				thumb.addEventListener('click', function () {

					const thumbSrc = this.getAttribute('src');

					// Remove size suffix: -300x300, -150x150, etc.
					const baseImage = thumbSrc.replace(/-\d+x\d+(?=\.\w+$)/, '');

					// Update main src
					mainImage.setAttribute('src', baseImage);

					// Update srcset WITHOUT touching width descriptors
					const oldSrcset = mainImage.getAttribute('srcset');
					if (oldSrcset) {
						const newSrcset = oldSrcset.split(',').map(entry => {
								const [url, size] = entry.trim().split(' ');
								const newUrl = url.replace(
									/\/[^\/]+(?=\s|$)/,
									'/' + baseImage.split('/').pop()
								);
								return `${newUrl} ${size}`;
							})
							.join(', ');

						mainImage.setAttribute('srcset', newSrcset);
					}

					// Active thumbnail class toggle
					thumbnails.forEach(img => {
						img.closest('.electromix_magnifier_thumbnail')
							?.classList.remove('active-thumbnail');
					});

					this.closest('.electromix_magnifier_thumbnail')
						?.classList.add('active-thumbnail');
				});
			});
		});
    };

    // Scroll To Top ============
    var handleScrollIndicator = function () {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        const scrollProgress = document.querySelectorAll('.scrollup');

        if (scrollProgress.length > 0) {
            scrollProgress.forEach(el => {
                if (scrollTop > 200) {
                    el.classList.add('is-active');
                } else {
                    el.classList.remove('is-active');
                }

                // Add click listener
                el.addEventListener('click', function () {
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                });
            });
            const scrollHeight = document.documentElement.scrollHeight;
            const windowHeight = document.documentElement.clientHeight;
            const maxScrollTop = scrollHeight - windowHeight;
            const scrollPercentage = (scrollTop / (maxScrollTop - 200)) * 100;
            const scrollPoint = document.querySelector('.scroll-point');
            if (scrollPoint) {
                scrollPoint.style.height = Math.min(scrollPercentage, 100) + '%';
            }
        }
    }

    // handle Product Category Menus ============
    function handleProductCategoryMenus() {
        if ($(window).width() >= 0) {
            jQuery('.category-menu-wrap .mobile-collapsed button')
                .off("click keypress")
                .on("click keypress", function (e) {
                    if (e.type === "keypress" && e.key !== "Enter") return;

                    let target = jQuery(this);
                    let menuObj = target.closest('li').children('a');
                    handleMenus(e, menuObj);
                });

            jQuery('.tabindex').attr("tabindex", "0");
            function handleMenus(e, menuObj) {
                if (menuObj.parent('li').has('ul').length > 0) {
                    e.preventDefault();

                    let dropdown = menuObj.nextAll('.dropdown-menu, .mega-menu').first();

                    if (menuObj.parent().hasClass('active')) {
                        dropdown.slideUp('slow', function () {
                            jQuery(this).css('display', 'none');
                        });
                        menuObj.parent().removeClass('active');
                    } else {
                        menuObj.parent().siblings('li').removeClass('active')
                            .children('.dropdown-menu, .mega-menu').slideUp('slow').css('display', 'none');
                        dropdown.css('display', 'block').slideDown();
                        menuObj.parent().addClass('active');
                    }
                }
            }

            jQuery(document).on("click.categoryMenu", function (e) {
                if (!jQuery(e.target).closest(".category-menu-wrap").length) {
                    jQuery('.category-menu-wrap li').removeClass('active');
                    jQuery('.category-menu-wrap .dropdown-menu, .category-menu-wrap .mega-menu')
                        .slideUp('slow').css('display', 'none');
                }
            });
        } else {
            jQuery('.tabindex').removeAttr("tabindex");
        }
    }

    // More Category Menu
    function toggleCategoryMenu(categoryLimit) {
        let menuList = document.querySelector('.product-category-menus-list ul.main-menu');
        if (!menuList) {
            return;
        }
        let menuItems = Array.from(menuList.children).filter(item => !item.classList.contains('more-item'));
        if (menuItems.length <= categoryLimit) {
            return;
        }
        let moreItem = document.querySelector('.product-category-menus-list .more-item');
        if (!moreItem) {
            const container = document.querySelector('.product-category-menus-list');
            if (container) {
                moreItem = document.createElement('div');
                moreItem.className = "more-item-btn";
                moreItem.innerHTML = '<button type="button" class="browse-more">More Category</button>';
                container.appendChild(moreItem);
            }
        }
        menuItems.forEach((item, index) => {
            if (index >= categoryLimit) {
                item.style.display = 'none';
            }
        });

        moreItem.querySelector(".browse-more").addEventListener('click', function () {
            let browseMore = this;
            let hiddenItems = menuItems.filter(item => item.style.display === 'none');

            if (!browseMore.classList.contains("active")) {
                browseMore.classList.add("active");
                hiddenItems.forEach(item => item.style.display = 'block');
                browseMore.innerHTML = 'No More';
            } else {
                browseMore.classList.remove("active");
                menuItems.forEach((item, index) => {
                    if (index >= categoryLimit) {
                        item.style.display = 'none';
                    }
                });
                browseMore.innerHTML = 'More Category';
            }
        });
    }

    // handle Grid List Toggle  ============
    var handleGridListToggle = function () {
        if (jQuery('.gridlistToggle').length > 0) {
            document.querySelectorAll('.gridlistToggle').forEach(item => {
                item.addEventListener('click', function () {
                    document.querySelectorAll('.gridlistToggle').forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    var productList = document.querySelector('.products');
                    if (productList) {
                        productList.classList.remove('grid2', 'grid3', 'list');
                        if (this.id === 'grid2') {
                            productList.classList.add('grid2');
                        } else if (this.id === 'grid3') {
                            productList.classList.add('grid3');
                        } else if (this.id === 'list') {
                            productList.classList.add('list');
                        }
                    }
                });
            });
        }
    };

    // handle Noui Slider  ============
    function handleNouiSlider() {
        var sliders = document.querySelectorAll('.price_slider');
        var labels = document.querySelectorAll('.price_label');
        sliders.forEach(function (slider, index) {
            noUiSlider.create(slider, {
                start: [100, 300],
                connect: true,
                range: {
                    min: 0,
                    max: 500
                }
            });
            var label = labels[index];
            var from = label.querySelector('.from');
            var to = label.querySelector('.to');
            label.style.display = 'block';
            slider.noUiSlider.on('update', function (values) {
                from.textContent = '$' + Math.round(values[0]);
                to.textContent = '$' + Math.round(values[1]);
            });
        });
    }

    // handle Benefit Slider  =================
    var handleBenefitSlider = function () {
        if (jQuery('.benefit-slider').length > 0) {
            jQuery(document).ready(function ($) {
                $(".benefit-slider").owlCarousel({
                    items: 3,
                    loop: false,
                    margin: 0,
                    autoplay: false,
                    autoplayTimeout: 3000,
                    autoplayHoverPause: true,
                    smartSpeed: 1000,
                    nav: false,
                    dots: false,
                    autoHeight: true,
					mouseDrag: false,
                    navText: ["<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>"],
                    responsive: {
                        1399: {
                            margin: 20,
                        }
                    }
                });
            });
        }
    }

    // handle Magnific Popup  ============
    function handleMagnificPopup() {
        const thumbnails = document.querySelectorAll('.electromix_thumbnail a');
        thumbnails.forEach(thumbnail => {
            thumbnail.addEventListener('click', function (e) {
                e.preventDefault();
                let videoType = thumbnail.getAttribute('videoId');
                let resultPass = document.querySelector('.woocommerce-product-gallery__image');
                const newSrc = this.querySelector('img').getAttribute('src');
                if (videoType) {
                    var innerHtmlPush = `<div class="tc_video_slide">
                                    <iframe width="100%" height="100%" id="product_video_iframe" class="product_video_iframe" video-type="youtube" src="https://www.youtube.com/embed/${videoType}"></iframe>
                                </div>`;
                } else {
                    var innerHtmlPush = `<div class="electromix_zoom_wrap">
                            <a href="javascript:void(0)" itemprop="image" class="electromix_zoom woocommerce-main-image" title="1">
                                <img src="${newSrc}" class="attachment-shop_single size-shop_single wp-post-image" alt="">
                            </a>
                        </div>`;
                }
                resultPass.innerHTML = innerHtmlPush;
                document.querySelectorAll('.electromix_thumbnail').forEach(li => {
                    li.classList.remove('active-thumbnail');
                });
                handleMagnificPopupZoom();
                this.parentElement.classList.add('active-thumbnail');
            });
        });
    }
    function handleMagnificPopupZoom() {
        if (jQuery('.magnifier_zoom_result').length > 0) {
            const zoomContainer = document.querySelector(".electromix_zoom_wrap a");
            const zoomImage = document.querySelector('.electromix_zoom img');
            const zoomResult = document.querySelector('.magnifier_zoom_result');
            zoomContainer.addEventListener("mousemove", function (e) {
                const bounds = zoomContainer.getBoundingClientRect();
                const x = e.clientX - bounds.left;
                const y = e.clientY - bounds.top;

                const xPercent = x / bounds.width;
                const yPercent = y / bounds.height;

                const imageWidth = zoomImage.offsetWidth;
                const imageHeight = zoomImage.offsetHeight;

                zoomImage.style.left = -(imageWidth * xPercent - bounds.width / 2) + "px";
                zoomImage.style.top = -(imageHeight * yPercent - bounds.height / 2) + "px";

                const newSrc = this.querySelector('img').getAttribute('src');
                zoomResult.setAttribute('style', `background-image:url(${newSrc}); background-repeat: no-repeat;`);
                zoomResult.style.backgroundPosition = `${xPercent * 100}% ${yPercent * 100}%`;
            });

            zoomContainer.addEventListener("mouseleave", function () {
                zoomImage.style.left = "0px";
                zoomImage.style.top = "0px";
            });

            // Show Head
            zoomContainer.addEventListener('mouseenter', () => {
                zoomResult.classList.add('visible');
            });
            zoomContainer.addEventListener('mouseleave', () => {
                zoomResult.classList.remove('visible');
            });
        }
    }

    // handle Input Number  ============
    function handleInputNumber() {
        jQuery('<div class="quantity-button quantity-up"><i class="fa fa-plus"></i></div><div class="quantity-button quantity-down"><i class="fa fa-minus"></i></div>').insertAfter('.quantity input');

        jQuery('.quantity').each(function () {
            var spinner = jQuery(this),
                input = spinner.find('input[type="number"]'),
                btnUp = spinner.find('.quantity-up'),
                btnDown = spinner.find('.quantity-down'),
                min = parseFloat(input.attr('min')) || 1,
                max = parseFloat(input.attr('max')) || Infinity;

            btnUp.click(function () {
                var oldValue = parseFloat(input.val()) || 0;
                var newVal = (oldValue >= max) ? oldValue : oldValue + 1;
                input.val(newVal).trigger("change");
            });

            btnDown.click(function () {
                var oldValue = parseFloat(input.val()) || 0;
                var newVal = (oldValue <= min) ? oldValue : oldValue - 1;
                input.val(newVal).trigger("change");
            });
        });
    }

    // handle Related Product Slider  ============
    var handleRelatedProductSlider = function () {
        if (jQuery('.related-product-slider').length > 0) {
            jQuery(document).ready(function ($) {
                if (typeof $.fn.owlCarousel !== 'undefined') {
                    $('.related-product-slider').each(function () {
                        var owl = $(this).owlCarousel({
                            items: 1,
                            loop: true,
                            margin: 5,
                            autoplay: true,
                            autoplayTimeout: 3000,
                            autoplayHoverPause: true,
                            smartSpeed: 1000,
                            nav: false,
                            dots: false,
                            autoHeight: true,
                            animateOut: 'fadeOut',
                            animateIn: 'fadeIn',
                            responsive: {
                                575: {
                                    margin: 10,
                                    items: 2,
                                },
                                768: {
                                    margin: 20,
                                },
                                991: {
                                    margin: 25,
                                    items: 3,
                                }
                            }
                        });
                        var container = $(this).prev();
                        container.find('.custom-prev').off('click').on('click', function () {
                            owl.trigger('prev.owl.carousel');
                        });
                        container.find('.custom-next').off('click').on('click', function () {
                            owl.trigger('next.owl.carousel');
                        });
                    });
                }
            });
        }
    }

    // handle Team Slider  ============
    var handleTeamSlider = function () {
        if (jQuery('.team-slider').length > 0) {
            jQuery(document).ready(function ($) {
                if (typeof $.fn.owlCarousel !== 'undefined') {
                    $('.team-slider').each(function () {
					 var itemsCount = $(this).data("items") || 3;
                        var owl = $(this).owlCarousel({
                            items: 2,
                            loop: true,
                            margin: 5,
                            autoplay: true,
                            autoplayTimeout: 3000,
                            autoplayHoverPause: true,
                            smartSpeed: 1000,
                            nav: false,
                            dots: false,
                            autoHeight: true,
                            animateOut: 'fadeOut',
                            animateIn: 'fadeIn',
                            responsive: {
                                575: {
                                    margin: 10,
                                    items: 2,
                                },
                                768: {
                                    margin: 20,
                                    items: 3,
                                },
                                991: {
                                    margin: 25,
                                    items: itemsCount,
                                }
                            }
                        });
                        var container = $(this).prev();
                        container.find('.custom-prev').off('click').on('click', function () {
                            owl.trigger('prev.owl.carousel');
                        });
                        container.find('.custom-next').off('click').on('click', function () {
                            owl.trigger('next.owl.carousel');
                        });
                    });
                }
            });
        }
    }

    // handle Testimonial Slider  ============
    var handleTestimonialSlider = function () {
        if (jQuery('.testimonial-slider').length > 0) {
            jQuery(document).ready(function ($) {
                if (typeof $.fn.owlCarousel !== 'undefined') {
                    $('.testimonial-slider').each(function () {
					var itemsCount = $(this).data("items") || 4;
                        var owl = $(this).owlCarousel({
                            items: 2,
                            loop: true,
                            margin: 5,
                            autoplay: true,
                            autoplayTimeout: 3000,
                            autoplayHoverPause: true,
                            smartSpeed: 1000,
                            nav: false,
                            dots: false,
                            autoHeight: true,
                            animateOut: 'fadeOut',
                            animateIn: 'fadeIn',
                            responsive: {
                                575: {
                                    margin: 10
                                },
                                768: {
                                    margin: 20
                                },
                                991: {
                                    margin: 30,
                                    items: itemsCount,
                                    center: (itemsCount%2 == 0 ) ? false : true
                                }
                            }
                        });
                        var container = $(this).prev();
                        container.find('.custom-prev').off('click').on('click', function () {
                            owl.trigger('prev.owl.carousel');
                        });
                        container.find('.custom-next').off('click').on('click', function () {
                            owl.trigger('next.owl.carousel');
                        });
                    });
                }
            });
        }
    }

    // handle Awards Slider  ============
    var handleAwardsSlider = function () {
        if (jQuery('.awards-slider').length > 0) {
            jQuery(document).ready(function ($) {
                if (typeof $.fn.owlCarousel !== 'undefined') {
                    $('.awards-slider').each(function () {
					var itemsCount = $(this).data("items") || 4;
                        var owl = $(this).owlCarousel({
                            items: 2,
                            loop: true,
                            margin: 5,
                            autoplay: true,
                            autoplayTimeout: 3000,
                            autoplayHoverPause: true,
                            smartSpeed: 1000,
                            nav: false,
                            dots: false,
                            autoHeight: true,
                            animateOut: 'fadeOut',
                            animateIn: 'fadeIn',
                            responsive: {
                                575: {
                                    margin: 10,
                                    items: 2,
                                },
                                768: {
                                    margin: 20,
                                    items: 3,
                                },
                                991: {
                                    margin: 25,
                                    items: itemsCount,
                                }
                            }
                        });
                        var container = $(this).prev();
                        container.find('.custom-prev').off('click').on('click', function () {
                            owl.trigger('prev.owl.carousel');
                        });
                        container.find('.custom-next').off('click').on('click', function () {
                            owl.trigger('next.owl.carousel');
                        });
                    });
                }
            });
        }
    }

    // handle Custom EMI modal  ============
    function handleCustomEMIModal() {
        const trigger = document.querySelector(".electromix_wcpemi-popup-trigger");
        const overlay = document.querySelector(".electromix_wcpemi-overlay");
        const modal = document.querySelector(".electromix_wcpemi");
        const closeBtn = document.querySelector(".electromix_wcpemi-header--close");

        if (trigger && overlay && modal && closeBtn) {
            trigger.addEventListener("click", function () {
                overlay.classList.add("active");
                modal.style.display = "block";
                setTimeout(() => {
                    modal.classList.add("active");
                }, 10);
            });

            function closeModal() {
                modal.classList.remove("active");
                overlay.classList.remove("active");
                setTimeout(() => {
                    modal.style.display = "none";
                }, 300);
            }

            closeBtn.addEventListener("click", closeModal);
            overlay.addEventListener("click", closeModal);
        }

        // EMI Method Item
        const tabs = document.querySelectorAll('.electromix_wcpemi-method__item');
        const emis = document.querySelectorAll('.electromix_wcpemi-emis');
        tabs.forEach((tab, index) => {
            tab.addEventListener('click', () => {
                tabs.forEach(t => t.classList.remove('electromix_wcpemi-method__item--selected'));
                tab.classList.add('electromix_wcpemi-method__item--selected');

                emis.forEach(e => e.classList.remove('electromix_wcpemi-emis--selected'));
                emis[index].classList.add('electromix_wcpemi-emis--selected');

                const currentEmis = emis[index];

                const banks = currentEmis.querySelectorAll('.electromix_wcpemi-bank__item');
                const plans = currentEmis.querySelectorAll('.electromix_wcpemi-plan');
                if (banks.length > 0) {
                    banks.forEach(b => b.classList.remove('electromix_wcpemi-bank__item--selected'));
                    banks[0].classList.add('electromix_wcpemi-bank__item--selected');
                }
                if (plans.length > 0) {
                    plans.forEach(p => p.classList.remove('electromix_wcpemi-plan--selected'));
                    plans[0].classList.add('electromix_wcpemi-plan--selected');
                }
            });
        });

        // EMI Bank Item
        document.querySelectorAll('.electromix_wcpemi-emis').forEach((emiBlock) => {
            const bankTabs = emiBlock.querySelectorAll('.electromix_wcpemi-bank__item');
            const bankPlans = emiBlock.querySelectorAll('.electromix_wcpemi-plan');

            bankTabs.forEach((tab, index) => {
                tab.addEventListener('click', () => {
                    bankTabs.forEach(t => t.classList.remove('electromix_wcpemi-bank__item--selected'));
                    tab.classList.add('electromix_wcpemi-bank__item--selected');
                    bankPlans.forEach(p => p.classList.remove('electromix_wcpemi-plan--selected'));
                    if (bankPlans[index]) {
                        bankPlans[index].classList.add('electromix_wcpemi-plan--selected');
                    }
                });
            });
        });
    }

    /* Magnific Video Popup =============== */
    var MagnificVideoPopup = function () {
        if ($.fn.magnificPopup) {
            $(".popup-youtube, .popup-vimeo").magnificPopup({
                disableOn: 700,
                type: 'iframe',
                mainClass: 'mfp-fade',
                removalDelay: 160,
                preloader: false,
                fixedContentPos: true,
                iframe: {
                    patterns: {
                        youtube: {
                            index: 'youtube.com/',
                            id: function (url) {
                                var match = url.match(/[\\?&]v=([^&#]*)/);
                                return match ? match[1] : null;
                            },
                            src: 'https://www.youtube.com/embed/%id%?autoplay=1'
                        },
                        vimeo: {
                            index: 'vimeo.com/',
                            id: function (url) {
                                var match = url.match(/vimeo.com\/(\d+)/);
                                return match ? match[1] : null;
                            },
                            src: 'https://player.vimeo.com/video/%id%?autoplay=1'
                        }
                    }
                }
            });
        }
    }

    /* handle Faq ScrollY =============== */
    var handleFaqScrollY = function () {
        $('#faq-section .faq-category-list a[href^="#"]').on('click', function (e) {
            e.preventDefault();
            var target = $(this).attr("href");

            if ($(target).length) {
                $('html, body').stop().animate({
                    scrollTop: $(target).offset().top - 90
                }, 500);
            }
        });
        $('#faq-section').on('scroll', function () {
            var scrollTop = $('#faq-section').scrollTop();

            $('#faq-section .page-section').each(function (i) {
                if ($(this).position().top <= scrollTop + 100) {
                    $('#faq-section .faq-category-list a.active').removeClass('active');
                    $('#faq-section .faq-category-list a').eq(i).addClass('active');
                }
            });
        });
        $(window).on('scroll', function () {
            var scrollTop = $(window).scrollTop();

            $('.faq-section .page-section').each(function (i) {
                if ($(this).offset().top <= scrollTop + 100) {
                    $('.faq-section .faq-category-list a.active').removeClass('active');
                    $('.faq-section .faq-category-list a').eq(i).addClass('active');
                }
            });
        });
    }

    // handle Trap Focus  ============
    var handleTrapFocus = function (focusDelay = 0) {
        let $containers = $('.docker-widget-popup.docker-left, .docker-widget-popup.docker-left.docker-mobile, .docker-widget-popup.docker-right');

        $containers.each(function () {
            let $container = $(this);
            let tabbable = $container
                .find('select, input, textarea, button, a, [href], [tabindex]:not([tabindex="-1"])')
                .filter(':visible');

            if (tabbable.length === 0) return;

            let firstTabbable = tabbable.first();
            let lastTabbable = tabbable.last();

            setTimeout(() => {
                firstTabbable.focus();
            }, focusDelay);

            firstTabbable.off('keydown.trap').on('keydown.trap', function (e) {
                if (e.which === 9 && e.shiftKey) {
                    e.preventDefault();
                    lastTabbable.focus();
                }
            });

            lastTabbable.off('keydown.trap').on('keydown.trap', function (e) {
                if (e.which === 9 && !e.shiftKey) {
                    e.preventDefault();
                    firstTabbable.focus();
                }
            });
        });
    }

    // Counter Number ============ 
    var counter = function () {
        if (jQuery('.counter').length) {
            jQuery('.counter').counterUp({
                delay: 100,
                time: 5000
            });
        }
    }

    // Adjust Map Position ============ 
    var adjustMapPosition = function () {
        const container = document.querySelector('.container');
        const frameMap = document.querySelector('.frame-map');
        if (!container || !frameMap) return;

        const containerLeft = container.getBoundingClientRect().left;
        const sizeFactor = window.innerWidth >= 991 ? 0.656 : 0.566;

        Object.assign(frameMap.style, {
            position: 'absolute',
            left: `-${containerLeft}px`,
            width: `${container.offsetWidth * sizeFactor + containerLeft}px`
        });
    }

 
    function updateSvgBackground() {
        setInterval(function () {
            if(window.innerWidth > 768){
                const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--sp-primary').trim();
                const dark2Color = getComputedStyle(document.documentElement).getPropertyValue('--dark-2').trim();
                const encodedSvg = encodeURIComponent(`
                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="30" height="60">
                    <path d="M0 0 C9.9 0 19.8 0 30 0 C30 19.8 30 39.6 30 60 C20.1 60 10.2 60 0 60 C0 40.2 0 20.4 0 0 Z" fill="${primaryColor}" />
                    <path d="M0 0 C7.26 0 14.52 0 22 0 C22 19.8 22 39.6 22 60 C14.74 60 7.48 60 0 60 C0.99282808 54.04303154 1.26740361 53.09663046 5.125 49.0625 C5.93324219 48.20398437 6.74148437 47.34546875 7.57421875 46.4609375 C9.66722456 44.33759827 11.79142084 42.25677211 13.9375 40.1875 C17.58180742 36.56010352 18.8815921 34.01293432 19.1875 28.8125 C17.66457114 23.92309682 15.05962511 21.36235124 11.56640625 17.6953125 C8.9191818 14.91512244 6.40883881 12.06240747 3.9375 9.125 C3.18339844 8.24070312 2.42929688 7.35640625 1.65234375 6.4453125 C0 4 0 4 0 0 Z" fill="${dark2Color}" transform="translate(8,0)" />
                </svg>
                `);
                const bgUrl = `url("data:image/svg+xml,${encodedSvg}")`;
                document.querySelector('.header-two .above-header .widget-left').style.setProperty('--svg-bg', bgUrl);
            }
        }, 0);
    }

    /* Function ============ */
    return {
        init: function () {
            handlePreloaderOnClick();
            handleStickyHeader();
            handlePasswordInput();
            handleHeaderMenu();
            handleMobileMenuActive();
            handleMenuCategoryToggle();
            initSearchAnimation();
            initSearchPlaceholders();
            handlePopupToggles();
            handlePopularProductSlider();
            handleMainSlider();
            handleFilterSlider();
            handleMasonryFilter();
            startCountdown();
            handleProductSlider();
            handleProductListSlider();
            handleProductListSlider2();
            handlePostSlider();
            handleFooterHeight();
            handleProductThumbnails();
            toggleCategoryMenu(9);
            handleProductCategoryMenus();
            handleGridListToggle();
            // handleNouiSlider();
            handleBenefitSlider();
            handleMagnificPopup();
            handleMagnificPopupZoom();
            handleInputNumber();
            handleRelatedProductSlider();
            handleTeamSlider();
            handleTestimonialSlider();
            handleAwardsSlider();
            handleCustomEMIModal();
            MagnificVideoPopup();
            handleFaqScrollY();
            handleTrapFocus();
            adjustMapPosition();
            // handleFlagToggle();
        },

        load: function () {
            counter();
        },

        resize: function () {
            screenWidth = $(window).width();
            handleHeaderMenu();
            handleFooterHeight();
            adjustMapPosition();
        },

        scroll: function () {
            setTimeout(() => {
                handleMobileMenu();
            }, 0);
            handleScrollIndicator();
			handleFooterHeight();
        }
    }
}(jQuery);


/* Document.ready Start */
document.addEventListener('DOMContentLoaded', function () {
    appStart.init();
    initCustomUIcommen();
    initCustomPaymentMethod();
});
/* Document.ready END */

/* Window Load START */
window.addEventListener('load', function () {
    appStart.load();
});
/* Window Load END */

/* Window Resize START */
window.addEventListener('resize', function () {
    appStart.resize();
});
/*  Window Resize END */

/* Window Scroll START */
window.addEventListener("scroll", function () {
    appStart.scroll();
});
/*  Window Scroll END */



function initCustomUIcommen() {
    // Address 2 Toggle
    const toggleButton = document.querySelector(".wc-block-components-address-form__address_2-toggle");
    const inputContainer = document.querySelector(".wc-block-components-address-form__address_2");
    if (toggleButton && inputContainer) {
        inputContainer.style.display = "none";
        toggleButton.addEventListener("click", function () {
            toggleButton.style.display = "none";
            inputContainer.style.display = "block";
        });
    }

    // Checkbox-controlled textarea
    const checkbox = document.getElementById("checkbox-control-1");
    const textarea = document.querySelector(".wc-block-components-textarea");
    if (checkbox && textarea) {
        textarea.style.display = "none";
        checkbox.addEventListener("change", function () {
            textarea.style.display = checkbox.checked ? "block" : "none";
        });
    }

    // Panel toggle buttons
    const toggleButtons = document.querySelectorAll(".wc-block-components-panel__button");
    toggleButtons.forEach(function (button) {
        const content = button.nextElementSibling;
        const isExpanded = button.getAttribute("aria-expanded") === "true";
        if (content) {
            content.style.display = isExpanded ? "block" : "none";
            button.addEventListener("click", function () {
                const currentlyVisible = content.style.display === "block";
                content.style.display = currentlyVisible ? "none" : "block";
                button.setAttribute("aria-expanded", !currentlyVisible);
            });
        }
    });
}

// Payment method accordion behavior
function initCustomPaymentMethod() {
    const radioButtons = document.querySelectorAll('input[name="radio-control-wc-payment-method-options"]');
    radioButtons.forEach(radio => {
        radio.addEventListener('change', () => {
            updateAccordionDisplay(radio);
        });
        if (radio.checked) {
            updateAccordionDisplay(radio);
        }
    });
    function updateAccordionDisplay(selectedRadio) {
        document.querySelectorAll('.wc-block-components-radio-control-accordion-option').forEach(option => {
            option.classList.remove('wc-block-components-radio-control-accordion-option--checked-option-highlighted');
            const content = option.querySelector('.wc-block-components-radio-control-accordion-content');
            if (content) {
                content.style.height = '0';
                content.style.opacity = '0';
                content.style.paddingTop = '0';
                content.style.paddingBottom = '0';
            }
        });
        const selectedOption = selectedRadio.closest('.wc-block-components-radio-control-accordion-option');
        if (selectedOption) {
            selectedOption.classList.add('wc-block-components-radio-control-accordion-option--checked-option-highlighted');
            const contentBox = selectedOption.querySelector('.wc-block-components-radio-control-accordion-content');
            if (contentBox) {
                contentBox.style.height = 'auto';
                let fullHeight = contentBox.scrollHeight + 20 + 'px';
                contentBox.style.height = '0';
                requestAnimationFrame(() => {
                    contentBox.style.height = fullHeight;
                    contentBox.style.opacity = '1';
                    contentBox.style.paddingTop = '0.5em';
                    contentBox.style.paddingBottom = '16px';
                });
            }
        }
    }
}

/* Empty Cart */ 
jQuery(document).on('click', '.clear-cart', function(e) {
    e.preventDefault();

    jQuery.post(wc_add_to_cart_params.ajax_url, {
        action: 'empty_cart'
    }, function() {
        location.reload();
    });
});