$(function () {
    // 1. Preloader logic
    setTimeout(function () {
        const preloader = document.getElementById('preloader');
        if (preloader) {
            preloader.classList.add('hide');
            setTimeout(() => preloader.remove(), 500);
        }
    }, 1500);

    // 2. Copy Button functionality
    $(".copy-btn").on("click", function () {
        const value = $(this).data("copy");
        if (navigator.clipboard) {
            navigator.clipboard.writeText(String(value));
        }
        const $button = $(this);
        const originalText = $button.text();
        const originalHtml = $button.html();
        
        // Show success indicator (checks if it's text-only or has HTML)
        if (originalText.trim() === "") {
            // Probably icon based, maybe don't change text
        } else {
            $button.text("✓");
        }
        
        setTimeout(function () {
            if (originalText.trim() === "") {
                $button.html(originalHtml);
            } else {
                $button.text(originalText);
            }
        }, 1200);
    });

    // 3. Print Button functionality
    $(".print-btn").on("click", function () {
        window.print();
    });

    // 4. Navigation & Dropdowns Logic
    const desktopBreakpoint = window.matchMedia("(min-width: 992px)");
    const mobileMenuBreakpoint = window.matchMedia("(max-width: 991px)");
    const mainMenu = document.getElementById("mainMenu");
    const menuToggler = document.querySelector('.navbar-toggler[data-bs-target="#mainMenu"]');
    const dropdownElements = document.querySelectorAll(".main-nav .navbar-nav .dropdown");
    const languageSwitchers = document.querySelectorAll(".language-switch.dropdown");

    function bindDesktopDropdownHover() {
        if (!dropdownElements.length) return;
        dropdownElements.forEach(function (dropdownElement) {
            const toggle = dropdownElement.querySelector(".dropdown-toggle");
            if (!toggle) return;

            const instance = bootstrap.Dropdown.getOrCreateInstance(toggle);

            dropdownElement.addEventListener("mouseenter", function () {
                if (desktopBreakpoint.matches) {
                    instance.show();
                }
            });

            dropdownElement.addEventListener("mouseleave", function () {
                if (desktopBreakpoint.matches) {
                    instance.hide();
                }
            });
        });
    }

    function closeMobileAccordion(exceptDropdown) {
        if (!dropdownElements.length) return;
        dropdownElements.forEach(function (dropdownElement) {
            if (exceptDropdown && dropdownElement === exceptDropdown) return;

            const toggle = dropdownElement.querySelector(".dropdown-toggle");
            const menu = dropdownElement.querySelector(".dropdown-menu");
            if (!toggle || !menu) return;

            dropdownElement.classList.remove("mobile-open");
            toggle.setAttribute("aria-expanded", "false");
            if (mobileMenuBreakpoint.matches) {
                menu.style.maxHeight = "0px";
            }
        });
    }

    function syncDropdownToggleMode() {
        if (!dropdownElements.length) return;
        dropdownElements.forEach(function (dropdownElement) {
            const toggle = dropdownElement.querySelector(".dropdown-toggle");
            const menu = dropdownElement.querySelector(".dropdown-menu");
            if (!toggle || !menu) return;

            if (toggle.dataset.desktopToggle === undefined) {
                const desktopToggle = toggle.getAttribute("data-bs-toggle") || "dropdown";
                toggle.dataset.desktopToggle = desktopToggle;
            }

            if (mobileMenuBreakpoint.matches) {
                toggle.removeAttribute("data-bs-toggle");
                toggle.setAttribute("role", "button");
                if (!dropdownElement.classList.contains("mobile-open")) {
                    menu.style.maxHeight = "0px";
                }
            } else {
                toggle.setAttribute("data-bs-toggle", toggle.dataset.desktopToggle);
                toggle.removeAttribute("role");
                toggle.setAttribute("aria-expanded", "false");
                dropdownElement.classList.remove("mobile-open");
                menu.style.maxHeight = "";
            }
        });
    }

    function bindMobileAccordion() {
        if (!dropdownElements.length) return;
        dropdownElements.forEach(function (dropdownElement) {
            const toggle = dropdownElement.querySelector(".dropdown-toggle");
            const menu = dropdownElement.querySelector(".dropdown-menu");
            if (!toggle || !menu) return;
            if (toggle.dataset.mobileAccordionBound === "true") return;

            toggle.dataset.mobileAccordionBound = "true";
            toggle.addEventListener("click", function (event) {
                if (!mobileMenuBreakpoint.matches) return;

                event.preventDefault();
                event.stopPropagation();

                const isOpen = dropdownElement.classList.contains("mobile-open");
                closeMobileAccordion(dropdownElement);

                if (isOpen) {
                    dropdownElement.classList.remove("mobile-open");
                    toggle.setAttribute("aria-expanded", "false");
                    menu.style.maxHeight = "0px";
                    return;
                }

                dropdownElement.classList.add("mobile-open");
                toggle.setAttribute("aria-expanded", "true");
                menu.style.maxHeight = menu.scrollHeight + "px";
            });
        });
    }

    function refreshOpenAccordionHeights() {
        if (!mobileMenuBreakpoint.matches || !dropdownElements.length) return;

        dropdownElements.forEach(function (dropdownElement) {
            if (!dropdownElement.classList.contains("mobile-open")) return;
            const menu = dropdownElement.querySelector(".dropdown-menu");
            if (!menu) return;
            menu.style.maxHeight = menu.scrollHeight + "px";
        });
    }

    function applyLanguageSelection(languageCode) {
        const selectedItem = document.querySelector('.language-switch .dropdown-item[data-language="' + languageCode + '"]');
        if (!selectedItem) return;

        const selectedFlag = selectedItem.dataset.flag || "";
        const selectedAlt = selectedItem.dataset.alt || "";
        const selectedName = selectedItem.dataset.name || selectedItem.textContent.trim();

        languageSwitchers.forEach(function (switcher) {
            const buttonFlag = switcher.querySelector(".language-btn img");
            const buttonName = switcher.querySelector(".language-btn span");

            if (buttonFlag) {
                buttonFlag.src = selectedFlag;
                buttonFlag.alt = selectedAlt;
            }

            if (buttonName) {
                buttonName.textContent = selectedName;
            }

            const items = switcher.querySelectorAll(".dropdown-item[data-language]");
            items.forEach(function (item) {
                const isActive = item.dataset.language === languageCode;
                item.classList.toggle("active", isActive);
                if (isActive) {
                    item.setAttribute("aria-current", "true");
                } else {
                    item.removeAttribute("aria-current");
                }
            });
        });
    }

    function bindLanguageSwitcher() {
        const items = document.querySelectorAll(".language-switch .dropdown-item[data-language]");
        if (!items.length) return;
        items.forEach(function (item) {
            item.addEventListener("click", function (event) {
                event.preventDefault();

                const languageCode = item.dataset.language;
                applyLanguageSelection(languageCode);

                const dropdownRoot = item.closest(".language-switch.dropdown");
                const toggle = dropdownRoot ? dropdownRoot.querySelector(".language-btn.dropdown-toggle") : null;
                if (toggle) {
                    const dropdownInstance = bootstrap.Dropdown.getOrCreateInstance(toggle);
                    dropdownInstance.hide();
                }
            });
        });

        const initialItem = document.querySelector(".language-switch .dropdown-item.active[data-language]");
        if (initialItem) {
            applyLanguageSelection(initialItem.dataset.language);
        }
    }

    // Initialize all nav-related features
    bindDesktopDropdownHover();
    bindMobileAccordion();
    bindLanguageSwitcher();
    syncDropdownToggleMode();

    if (mainMenu) {
        mainMenu.addEventListener("show.bs.collapse", function () {
            if (mobileMenuBreakpoint.matches) {
                document.body.classList.add("mobile-menu-open");
            }
        });

        mainMenu.addEventListener("hide.bs.collapse", function () {
            document.body.classList.remove("mobile-menu-open");
            closeMobileAccordion();
        });

        mainMenu.addEventListener("shown.bs.collapse", function () {
            refreshOpenAccordionHeights();
        });
    }

    mobileMenuBreakpoint.addEventListener("change", function () {
        if (!mobileMenuBreakpoint.matches) {
            document.body.classList.remove("mobile-menu-open");
        }
        syncDropdownToggleMode();
        refreshOpenAccordionHeights();
    });

    window.addEventListener("resize", function () {
        refreshOpenAccordionHeights();
    });

    document.addEventListener("click", function (event) {
        if (!mobileMenuBreakpoint.matches || !mainMenu || !mainMenu.classList.contains("show")) return;
        if (mainMenu.contains(event.target)) return;
        if (menuToggler && menuToggler.contains(event.target)) return;

        const collapseInstance = bootstrap.Collapse.getOrCreateInstance(mainMenu);
        collapseInstance.hide();
    });

    // 5. Header Visibility on Scroll
    let lastScrollY = window.scrollY;
    const siteHeader = document.querySelector('.site-header');

    if (siteHeader) {
        window.addEventListener('scroll', function () {
            if (mobileMenuBreakpoint.matches && document.body.classList.contains('mobile-menu-open')) {
                return;
            }

            const currentScrollY = window.scrollY;

            if (currentScrollY > lastScrollY && currentScrollY > 150) {
                siteHeader.classList.add('header-hidden');
            } else if (currentScrollY < lastScrollY) {
                siteHeader.classList.remove('header-hidden');
            }

            lastScrollY = currentScrollY;
        }, { passive: true });
    }

    // 6. Gallery Popup (Lightbox)
    const images = $('.gallery-img');
    const popup = $('.gallery-popup');
    const popupImg = $('.popup-image');
    const counter = $('.image-counter');

    if (images.length && popup.length) {
        let currentIndex = 0;

        function updateSlider() {
            const src = $(images[currentIndex]).attr('src');
            popupImg.attr('src', src);
            counter.text((currentIndex + 1) + ' / ' + images.length);
        }

        images.on('click', function () {
            currentIndex = images.index(this);
            updateSlider();
            popup.fadeIn();
        });

        $('.next').on('click', function () {
            currentIndex = (currentIndex + 1) % images.length;
            updateSlider();
        });

        $('.prev').on('click', function () {
            currentIndex = (currentIndex - 1 + images.length) % images.length;
            updateSlider();
        });

        $('.popup-close, .popup-overlay').on('click', function () {
            popup.fadeOut();
        });

        $(document).on('keydown', function (e) {
            if (!popup.is(':visible')) return;

            if (e.key === 'Escape') popup.fadeOut();
            if (e.key === 'ArrowRight') $('.next').click();
            if (e.key === 'ArrowLeft') $('.prev').click();
        });
    }

    // 7. Breadcrumb Slider Animation
    const breadcrumbSlider = $('.breadcrumb-card');
    if (breadcrumbSlider.length) {
        $('.breadcrumb-nav.next').on('click', function () {
            breadcrumbSlider.animate({
                scrollLeft: breadcrumbSlider.scrollLeft() + 200
            }, 300);
        });

        $('.breadcrumb-nav.prev').on('click', function () {
            breadcrumbSlider.animate({
                scrollLeft: breadcrumbSlider.scrollLeft() - 200
            }, 300);
        });
    }

    // 8. Category List Slider Animation
    const categorySlider = $('.category-list');
    if (categorySlider.length) {
        $('.menulinks-nav.next').on('click', function () {
            categorySlider.animate({
                scrollLeft: categorySlider.scrollLeft() + 200
            }, 300);
        });

        $('.menulinks-nav.prev').on('click', function () {
            categorySlider.animate({
                scrollLeft: categorySlider.scrollLeft() - 200
            }, 300);
        });
    }
});
