jQuery(function ($) {
    "use strict";

    const $mobileMenu = $("#theme-mobile-menu");
    const $overlay = $(".theme-mobile-menu-overlay");
    const $openBtn = $(".theme-mobile-menu-btn");
    const $closeBtn = $(".theme-mobile-menu-close");

    let lastFocusedElement = null;

    function getFocusableElements($root) {
        return $root
            .find('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex^="-"])')
            .filter(":visible");
    }

    function disableFocus($root) {
        getFocusableElements($root).each(function () {
            const $el = $(this);
            if (!$el.attr("data-wira-tabindex")) {
                const current = $el.attr("tabindex");
                $el.attr("data-wira-tabindex", typeof current === "undefined" ? "" : current);
            }
            $el.attr("tabindex", "-1");
        });
    }

    function restoreFocus($root) {
        $root.find("[data-wira-tabindex]").each(function () {
            const $el = $(this);
            const original = $el.attr("data-wira-tabindex");
            $el.removeAttr("data-wira-tabindex");
            if (original === "") {
                $el.removeAttr("tabindex");
            } else {
                $el.attr("tabindex", original);
            }
        });
    }

    function setMenuOpen(isOpen) {
        if (!$mobileMenu.length) return;

        if (isOpen) {
            lastFocusedElement = document.activeElement;

            $mobileMenu.removeAttr("hidden").attr("aria-hidden", "false");
            $overlay.removeAttr("hidden");

            // Allow transition: render first, then add class.
            requestAnimationFrame(function () {
                $mobileMenu.addClass("show");
                $overlay.addClass("show");
            });

            $openBtn.attr("aria-expanded", "true");

            $mobileMenu[0].inert = false;
            $overlay[0].inert = false;
            restoreFocus($mobileMenu);

            // Focus close button first for predictable trap start.
            setTimeout(function () {
                $closeBtn.trigger("focus");
            }, 0);
        } else {
            $mobileMenu.removeClass("show").attr("aria-hidden", "true");
            $overlay.removeClass("show");
            $openBtn.attr("aria-expanded", "false");

            // Remove from tab order while visually off-canvas.
            disableFocus($mobileMenu);
            $mobileMenu[0].inert = true;
            $overlay[0].inert = true;

            // Delay hiding until transition ends.
            setTimeout(function () {
                $mobileMenu.attr("hidden", true);
                $overlay.attr("hidden", true);
            }, 350);

            if (lastFocusedElement && typeof lastFocusedElement.focus === "function") {
                lastFocusedElement.focus();
            } else {
                $openBtn.trigger("focus");
            }
        }
    }

    function isMenuOpen() {
        return $mobileMenu.length && $mobileMenu.hasClass("show");
    }

    function initMobileMenuContent() {
        // Clone main menu into mobile nav container.
        const $mainMenuHtml = $("#theme-main-navbar").html();
        if ($mainMenuHtml) {
            $(".theme-mobile-nav").html($mainMenuHtml);
        }

        // Build accessible submenu toggles for mobile.
        $(".theme-mobile-nav li.menu-item-has-children").each(function (index) {
            const $li = $(this);
            const $submenu = $li.children("ul.dropdown-menu, ul.dropdown-submenu, .theme-mega-menu").first();
            const $link = $li.children("a").first();

            if (!$submenu.length || !$link.length) return;
            if ($li.children(".theme-submenu-toggle").length) return;

            const submenuId = "wira-mobile-submenu-" + index;
            $submenu.attr({ id: submenuId, hidden: true, "aria-hidden": "true" });

            const $toggle = $(
                '<button type="button" class="theme-submenu-toggle" aria-expanded="false" aria-controls="' +
                    submenuId +
                    '"><span class="screen-reader-text">Toggle submenu</span><i class="fas fa-chevron-down" aria-hidden="true"></i></button>'
            );

            $toggle.on("click", function (e) {
                e.preventDefault();
                e.stopPropagation();

                const expanded = $(this).attr("aria-expanded") === "true";
                $(this).attr("aria-expanded", expanded ? "false" : "true");

                if (expanded) {
                    $submenu.slideUp(200, function () {
                        $submenu.attr({ hidden: true, "aria-hidden": "true" });
                    });
                } else {
                    $submenu.removeAttr("hidden").attr("aria-hidden", "false").hide().slideDown(200);
                }
            });

            // Space/Enter on the parent link toggles submenu instead of navigating (mobile only).
            $link.on("keydown", function (e) {
                if (e.key !== "Enter" && e.key !== " ") return;
                e.preventDefault();
                $toggle.trigger("click");
            });

            $link.on("click", function (e) {
                // First click toggles submenu if it's collapsed.
                if ($toggle.attr("aria-expanded") === "false") {
                    e.preventDefault();
                    $toggle.trigger("click");
                }
            });

            $link.after($toggle);
        });
    }

    // Initialize menu content and lock focus out while closed.
    initMobileMenuContent();
    disableFocus($mobileMenu);
    if ($mobileMenu.length) {
        $mobileMenu[0].inert = true;
    }
    if ($overlay.length) {
        $overlay[0].inert = true;
    }

    // Mobile menu toggle.
    $openBtn.on("click", function () {
        setMenuOpen(true);
    });

    $closeBtn.add($overlay).on("click", function () {
        setMenuOpen(false);
    });

    // Focus trap + escape handling.
    $(document).on("keydown", function (e) {
        if (!isMenuOpen()) return;

        if (e.key === "Escape") {
            e.preventDefault();
            setMenuOpen(false);
            return;
        }

        if (e.key !== "Tab") return;

        const $focusables = getFocusableElements($mobileMenu);
        if (!$focusables.length) {
            e.preventDefault();
            $closeBtn.trigger("focus");
            return;
        }

        const first = $focusables[0];
        const last = $focusables[$focusables.length - 1];

        if (e.shiftKey) {
            if (document.activeElement === first || document.activeElement === $mobileMenu[0]) {
                e.preventDefault();
                last.focus();
            }
        } else {
            if (document.activeElement === last) {
                e.preventDefault();
                first.focus();
            }
        }
    });

    // Set background image from data-background
    $("[data-background]").each(function () {
        const bg = $(this).data("background");
        if (bg) {
            $(this).css("background-image", "url(" + bg + ")");
        }
    });

    // Back to top button
    const $backToTop = $(".theme-back-to-top");
    $backToTop.css({ bottom: "-60px", opacity: 0, display: "block" });

    $(window).on("scroll", function () {
        if ($(this).scrollTop() > 300) {
            $backToTop.stop().animate({ bottom: "20px", opacity: 1 }, 300);
        } else {
            $backToTop.stop().animate({ bottom: "-40px", opacity: 0 }, 300);
        }
    });

    $backToTop.on("click", function (e) {
        e.preventDefault();
        $("html, body").animate({ scrollTop: 0 }, 600);
    });

    // Fixed Header
    var $wira_header = $('.theme-add-sticky-header');
    if ($wira_header.length) {
        $(window).on('scroll', function () {
            if ($(this).scrollTop() > 0) {
                $wira_header.addClass('theme-header-sticky');
            } else {
                $wira_header.removeClass('theme-header-sticky');
            }
        });
    }

    // Preloader
    function hidePreloader() {
        const $preloader = $(".theme-preloader");
        if (!$preloader.length) return;

        $preloader.stop(true, true).fadeOut(500, function () {
            $preloader.css("display", "none");
        });
    }

    $(window).on("load", hidePreloader);
    $(window).on("pageshow", hidePreloader);

    // Fallback: hide preloader even if load event doesn't fire (e.g. cached pages)
    setTimeout(hidePreloader, 3000);

});
