(function () {
    "use strict";

    // Helper function to select elements
    const $ = (selector) => document.querySelector(selector);
    const $$ = (selector) => document.querySelectorAll(selector);

    // Scroll back to top
    document.addEventListener('DOMContentLoaded', function () {

        const progressPath = $('.progress-wrap path');
        if (progressPath) {
            const pathLength = progressPath.getTotalLength();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'none';
            progressPath.style.strokeDasharray = pathLength + ' ' + pathLength;
            progressPath.style.strokeDashoffset = pathLength;
            progressPath.getBoundingClientRect();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'stroke-dashoffset 10ms linear';

            const updateProgress = function () {
                const scroll = window.pageYOffset || document.documentElement.scrollTop;
                const height = document.documentElement.scrollHeight - window.innerHeight;
                const progress = pathLength - (scroll * pathLength / height);
                progressPath.style.strokeDashoffset = progress;
            };

            updateProgress();
            window.addEventListener('scroll', updateProgress);

            const offset = 50;
            const duration = 550;

            window.addEventListener('scroll', function () {
                const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                const progressWrap = $('.progress-wrap');
                if (progressWrap) {
                    if (scrollTop > offset) {
                        progressWrap.classList.add('active-progress');
                    } else {
                        progressWrap.classList.remove('active-progress');
                    }
                }
            });

            const progressWrap = $('.progress-wrap');
            if (progressWrap) {
                progressWrap.addEventListener('click', function (e) {
                    e.preventDefault();

                    const start = window.pageYOffset;
                    const duration = 600;
                    const startTime = performance.now();

                    function scrollStep(currentTime) {
                        const elapsed = currentTime - startTime;
                        const progress = Math.min(elapsed / duration, 1);

                        window.scrollTo(0, start * (1 - progress));

                        if (progress < 1) {
                            requestAnimationFrame(scrollStep);
                        }
                    }

                    requestAnimationFrame(scrollStep);
                });
            }
        }
    });


    // Document Ready
    document.addEventListener('DOMContentLoaded', function () {

        // menu_toggle
        const menuToggle = $('.menu_toggle');
        if (menuToggle) {
            menuToggle.addEventListener('click', function (event) {
                event.preventDefault();
                document.body.classList.toggle('menu_active');
            });
        }

        // Sticky header
        function toggleSticky() {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const siteHeader = $('header');
            if (siteHeader) {
                if (scrollTop > 100) {
                    siteHeader.classList.add('sticky');
                } else {
                    siteHeader.classList.remove('sticky');
                }
            }
        }

        // Run once on page load
        toggleSticky();

        // Run on scroll
        window.addEventListener('scroll', toggleSticky);


        // toggle_btn
        document.addEventListener("click", function (e) {
            const btn = e.target.closest(".toggle_btn");
            if (!btn) return;

            const currentWrap = btn.closest(".toggle_wrap");

            // remove active from other toggle_wraps
            document.querySelectorAll(".toggle_wrap.active").forEach(wrap => {
                if (wrap !== currentWrap) {
                    wrap.classList.remove("active");
                }
            });

            // toggle active on current
            currentWrap.classList.toggle("active");
        });


        // toggle_this
        const toggles = document.querySelectorAll('.toggle_this');

        if (toggles) {
            toggles.forEach(function (el) {
                el.addEventListener('click', function (e) {
                    e.stopPropagation(); // prevent body click
                    this.classList.toggle('active');
                });
            });

            document.body.addEventListener('click', function () {
                toggles.forEach(function (el) {
                    el.classList.remove('active');
                });
            });
        }


        // product_single_img
        if (document.querySelectorAll('.product_single_img')) {
            document.querySelectorAll('.product_single_img').forEach(wrapper => {

                const img = wrapper.querySelector('img');
                const zoom = 2; // zoom strength

                wrapper.addEventListener('mousemove', function (e) {

                    const rect = wrapper.getBoundingClientRect();

                    const x = e.clientX - rect.left;
                    const y = e.clientY - rect.top;

                    const xPercent = (x / rect.width) * 100;
                    const yPercent = (y / rect.height) * 100;

                    wrapper.style.backgroundImage = `url(${img.src})`;
                    wrapper.style.backgroundRepeat = 'no-repeat';
                    wrapper.style.backgroundSize = `${zoom * 100}%`;
                    wrapper.style.backgroundPosition = `${xPercent}% ${yPercent}%`;

                    img.style.opacity = 0; // hide original image
                });

                wrapper.addEventListener('mouseleave', function () {
                    wrapper.style.backgroundImage = 'none';
                    img.style.opacity = 1;
                });

            });

        }

        // gridlist_row
        const gridBtn = document.querySelector('.grid_btn');
        const listBtn = document.querySelector('.list_btn');
        const row = document.querySelector('.gridlist_row');

        if (row) {
            gridBtn.addEventListener('click', function () {
                row.classList.add('grid_row');
                row.classList.remove('list_row');
            });

            listBtn.addEventListener('click', function () {
                row.classList.add('list_row');
                row.classList.remove('grid_row');
            });
        }

        // fillter_toggle
        const filterToggle = document.querySelectorAll('.fillter_toggle');
        const sidebar = document.querySelector('.sidebar');

        if (sidebar) {
            filterToggle.forEach((filterToggleBtn) => {
                filterToggleBtn.addEventListener('click', function () {
                    sidebar.classList.toggle('active');
                });
            })
        }

        // icon_box1
        if (document.querySelectorAll('a.icon_box1')) {
            document.querySelectorAll('a.icon_box1').forEach(function (item) {
                item.addEventListener('click', function (e) {
                    e.preventDefault();
                    this.classList.toggle('active');
                });
            });
        }

        // btn-minus
        const quantityRow = document.querySelectorAll('.quantity-row');

        if (quantityRow) {
            quantityRow.forEach(function (row) {

                const minusBtn = row.querySelector('#btn-minus');
                const plusBtn = row.querySelector('#btn-plus');
                const input = row.querySelector('#qty-input');

                if (!minusBtn || !plusBtn || !input) return;

                const step = parseFloat(input.step) || 0.5;
                const min = parseFloat(input.min) || 0;

                plusBtn.addEventListener('click', function () {
                    let current = parseFloat(input.value) || 0;
                    input.value = (current + step).toFixed(1);
                });

                minusBtn.addEventListener('click', function () {
                    let current = parseFloat(input.value) || 0;
                    let newValue = current - step;

                    if (newValue >= min) {
                        input.value = newValue.toFixed(1);
                    }
                });

            });
        }


        const icon_box3 = document.querySelectorAll('a.icon_box3');

        if (icon_box3) {
            icon_box3.forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();

                    // 1️⃣ Add show class to product_popup
                    const popup = document.querySelector('.product_popup');
                    popup.classList.add('show');

                    // 2️⃣ Get closest parent .card
                    const card = this.closest('.card');
                    if (!card) return;

                    // 3️⃣ Get required elements inside that card
                    const imgSrc = card.querySelector('.card_img > .ps_img1')?.getAttribute('src');
                    const titleText = card.querySelector('.card_info h5')?.innerHTML;
                    const priceText = card.querySelector('.price')?.innerHTML;

                    // 4️⃣ Replace popup content
                    if (imgSrc) {
                        const replaceImg = document.querySelectorAll('.replace_img');
                        if (replaceImg) {
                            replaceImg.forEach((replaceImage) => {
                                replaceImage.setAttribute('src', imgSrc);
                            })
                        }
                    }

                    if (titleText) {
                        const replaceTitle = document.querySelector('.product-section .title_24');
                        if (replaceTitle) replaceTitle.innerHTML = titleText;
                    }

                    if (priceText) {
                        const replacePrice = document.querySelector('.price_replace');
                        if (replacePrice) replacePrice.innerHTML = priceText;
                    }
                });
            });
        }

        if (document.querySelectorAll('.toggle_popup')) {
            document.querySelectorAll('.toggle_popup').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    const popup = document.querySelector('.product_popup');
                    if (popup) {
                        popup.classList.remove('show');
                    }
                });
            });
        }


        // allSelectors
        const allSelectors = document.querySelectorAll('.language_selector_wrap');

        if (allSelectors) {
            allSelectors.forEach(selectorWrap => {
                const selectorBtn = selectorWrap.querySelector('.language_btn .btn_text');
                const languageList = selectorWrap.querySelector('.language_list');
                const languages = languageList.querySelectorAll('li');

                // Toggle dropdown
                selectorWrap.querySelector('.language_btn').addEventListener('click', () => {
                    // Close other dropdowns first
                    allSelectors.forEach(otherWrap => {
                        if (otherWrap !== selectorWrap) {
                            otherWrap.querySelector('.language_list').style.display = 'none';
                        }
                    });

                    // Toggle current dropdown
                    languageList.style.display = languageList.style.display === 'block' ? 'none' : 'block';
                });

                // Select language
                languages.forEach(lang => {
                    lang.addEventListener('click', () => {
                        selectorBtn.textContent = lang.textContent;
                        languageList.style.display = 'none';
                        console.log('Selected language:', lang.dataset.lang);
                    });
                });

                // Close if clicking outside
                document.addEventListener('click', (e) => {
                    if (!selectorWrap.contains(e.target)) {
                        languageList.style.display = 'none';
                    }
                });
            });
        }

    });


    // hero_area
    if (document.querySelector('.hero_slider')) {
        new Swiper('.hero_slider', {
            loop: false,
            speed: 1000,

            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },

            // 🔹 Fade instead of slide
            effect: 'fade',
            fadeEffect: {
                crossFade: true
            },

            watchSlidesProgress: true,

            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },

            navigation: {
                nextEl: ".hero_area .swiper-button-next",
                prevEl: ".hero_area .swiper-button-prev",
            },

        });
    }

    // product_slider
    if (document.querySelector('.product_slider')) {
        new Swiper('.product_slider', {
            loop: false,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            speed: 1000,
            slidesPerView: 5,
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
                nextEl: ".product_slider_area .swiper-button-next",
                prevEl: ".product_slider_area .swiper-button-prev",
            },
            breakpoints: {
                1200: {
                    slidesPerView: 5,
                    spaceBetween: 20,
                },
                992: {
                    slidesPerView: 4,
                    spaceBetween: 20,
                },
                768: {
                    slidesPerView: 3,
                    spaceBetween: 16,
                },
                576: {
                    slidesPerView: 2,
                    spaceBetween: 16,
                },
                0: {
                    slidesPerView: 2,
                    spaceBetween: 16,
                }
            }
        });
    }

    // apie_slider
    if (document.querySelector('.apie_slider')) {
        new Swiper('.apie_slider', {
            loop: false,
            speed: 1000,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            slidesPerView: 2,
            spaceBetween: 30,
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            breakpoints: {
                768: {
                    slidesPerView: 2,
                },
                576: {
                    slidesPerView: 1,
                },
                0: {
                    slidesPerView: 1,
                }
            }
        });
    }

    // ps_sm_slider
    if (document.querySelector('.ps_sm_slider')) {
        new Swiper('.ps_sm_slider', {
            loop: false,
            speed: 1000,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            slidesPerView: 1,
            spaceBetween: 0,
            navigation: {
                nextEl: ".product_sm_slider .swiper-button-next",
                prevEl: ".product_sm_slider .swiper-button-prev",
            },
        });
    }

    // product_single
    if (document.querySelector('.product_single .mySwiper')) {
        var swiper1 = new Swiper(".product_single .mySwiper", {
            spaceBetween: 10,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            slidesPerView: 4,
            freeMode: true,
            watchSlidesProgress: true,
        });
    }
    if (document.querySelector('.product_single .mySwiper2')) {
        var swiper3 = new Swiper(".product_single .mySwiper2", {
            spaceBetween: 10,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            navigation: {
                nextEl: ".product_single .swiper-button-next",
                prevEl: ".product_single .swiper-button-prev",
            },
            thumbs: {
                swiper: swiper1,
            },
        });
    }

    // mySwiper
    if (document.querySelector('.product_popup .mySwiper')) {
        var swiper = new Swiper(".product_popup .mySwiper", {
            spaceBetween: 10,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            slidesPerView: 4,
            freeMode: true,
            watchSlidesProgress: true,
        });
    }
    if (document.querySelector('.product_popup .mySwiper2')) {
        var swiper2 = new Swiper(".product_popup .mySwiper2", {
            spaceBetween: 10,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            navigation: {
                nextEl: ".product_popup .swiper-button-next",
                prevEl: ".product_popup .swiper-button-prev",
            },
            thumbs: {
                swiper: swiper,
            },
        });
    }

})();