window.addEventListener("load", function(){

    jQuery(document).ready(function($){
        "use strict";

        $("body").addClass("page-loaded");

    });

});
// Keep globals intact
let timerInterval;
let timeClock = document.getElementById("wpi-time-clock");

function myTimer() {
    const date = new Date();
    if (timeClock) timeClock.innerHTML = date.toLocaleTimeString();
}

// Simple micro-throttle for scroll-intensive handlers
function throttle(fn, wait) {
    let inProgress = false;
    return function (...args) {
        if (inProgress) return;
        inProgress = true;
        setTimeout(() => {
            fn.apply(this, args);
            inProgress = false;
        }, wait);
    };
}

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

    // Cache commonly used selectors
    const $doc = $(document);
    const $win = $(window);
    const $body = $("body");
    const $primaryMenu = $(".primary-menu");
    const $siteNavigation = $(".site-navigation");
    const $headerSearchbar = $(".header-searchbar");
    const $offcanvasMenu = $("#offcanvas-menu");
    const $navbarOffcanvasBtn = $(".navbar-control-offcanvas");
    const $hamburgerOne = $("#hamburger-one");
    const $sidrWrapper = $("#sidr-nav");
    const $themeNavigation = $("#theme-navigation");

    // Tab-to-menu syncing
    $doc.on("click", ".tab-button", function () {
        const target = $(this).data("target");
        $primaryMenu.find("li").removeClass("active");
        $primaryMenu.find(".sub-menu").hide();
        const $menuItem = $primaryMenu.find('a[href="' + target + '"]');
        if ($menuItem.length) {
            $menuItem.closest("li").addClass("active");
            const $parentLi = $menuItem.closest(".menu-item-has-children");
            $parentLi.addClass("active");
            $parentLi.children(".sub-menu").css("display", "block");
        }
    }); // [3][14]

    // Accessible primary menu focus/touch management
    const menuHandler = {
        init() {
            if ($siteNavigation.length) this.traverse($siteNavigation);
        },
        traverse($navigation) {
            const $menu = $navigation.find("ul").first();
            if (!$menu.length) return;
            if (!$menu.hasClass("theme-menu")) $menu.addClass("theme-menu");

            const $links = $menu.find("a");
            const $linksWithChildren = $menu.find(
                ".menu-item-has-children > a, .page_item_has_children > a"
            );

            $links.on("focus blur", this.toggleFocus);
            $linksWithChildren.on("touchstart", this.toggleFocus);
        },
        toggleFocus(event) {
            const $self = $(this);
            if (event.type === "focus" || event.type === "blur") {
                $self.parentsUntil(".theme-menu", "li").toggleClass("focus");
            }
            if (event.type === "touchstart") {
                event.preventDefault();
                const $menuItem = $self.parent("li");
                $menuItem.siblings().removeClass("focus");
                $menuItem.toggleClass("focus");
            }
        },
    };
    menuHandler.init(); // [3][14]

    // Start time clock if present
    if (timeClock) {
        timerInterval = setInterval(myTimer, 1000);
    } // [1]

    // Tooltips
    $(".tooltips").append("<span></span>");
    $doc.on("mouseenter", ".tooltips", function () {
        $(this).find("span").empty().append($(this).attr("data-tooltip"));
    }); // [1]

    // Dark/Light mode via localStorage
    let switchMode = localStorage.getItem("switchMode");
    const $switchModeToggle = $(".theme-colormode-switcher");
    const enableDarkMode = function () {
        $body.addClass("theme-darkmode-enabled");
        localStorage.setItem("switchMode", "enabled");
    };
    const disableDarkMode = function () {
        $body.removeClass("theme-darkmode-enabled");
        localStorage.setItem("switchMode", null);
    };
    if (switchMode === "enabled") {
        enableDarkMode();
        $(".mode-icon-change").addClass("mode-icon-night").removeClass("mode-icon-light");
    } else {
        $(".mode-icon-change").addClass("mode-icon-light").removeClass("mode-icon-night");
    }
    $doc.on("click", ".theme-colormode-switcher", function () {
        $(".mode-icon-change").toggleClass("mode-icon-light mode-icon-night");
        switchMode = localStorage.getItem("switchMode");
        if (switchMode !== "enabled") {
            enableDarkMode();
        } else {
            disableDarkMode();
        }
    }); // [1]



    // Mark articles as loaded
    $(".theme-article-area").addClass("theme-article-loaded"); // [1]

    // Submenu Toggle
    $doc.on("click", ".submenu-toggle", function () {
        $(this).toggleClass("button-toggle-active");
        const currentClass = $(this).attr("data-toggle-target");
        $(currentClass).toggleClass("submenu-toggle-active");
    }); // [3][14]

    // Header Search open/close and focus trap
    $doc.on("click", ".header-searchbar", function () {
        $headerSearchbar.removeClass("header-searchbar-active");
        $body.removeClass("body-scroll-locked");
    });
    $doc.on("click", ".header-searchbar-inner", function (e) {
        e.stopPropagation();
    });
    $doc.on("click", "#search-closer", function () {
        $headerSearchbar.removeClass("header-searchbar-active");
        setTimeout(function () {
            $(".navbar-control-search").focus();
        }, 300);
        $body.removeClass("body-scroll-locked");
    });
    $doc.on("click", ".navbar-control-search", function () {
        $headerSearchbar.toggleClass("header-searchbar-active");
        setTimeout(function () {
            $(".header-searchbar .search-field").focus();
        }, 300);
        $body.addClass("body-scroll-locked");
    });
    $doc.on("focus", "input, a, button", function () {
        if ($headerSearchbar.hasClass("header-searchbar-active")) {
            if ($(this).hasClass("skip-link-search-top")) {
                $(".header-searchbar #search-closer").focus();
            }
            if (!$(this).parents(".header-searchbar").length) {
                $(".header-searchbar .search-field").focus();
            }
        }
    }); // [1]

    // Global Escape handler
    $doc.on("keyup", function (j) {
        if (j.key !== "Escape") return;
        if ($headerSearchbar.hasClass("header-searchbar-active")) {
            $headerSearchbar.removeClass("header-searchbar-active");
            $body.removeClass("body-scroll-locked");
            setTimeout(function () {
                $(".navbar-control-search").focus();
            }, 300);
        }
        if ($offcanvasMenu.hasClass("offcanvas-menu-active")) {
            $headerSearchbar.removeClass("header-searchbar-active");
            $offcanvasMenu.removeClass("offcanvas-menu-active");
            $navbarOffcanvasBtn.removeClass("active");
            $body.removeClass("body-scroll-locked");
            setTimeout(function () {
                $navbarOffcanvasBtn.focus();
            }, 300);
        }
        if ($body.hasClass("sidr-nav-open")) {
            $.sidr("close", "sidr-nav");
            $hamburgerOne.removeClass("active");
            $body.removeClass("body-scroll-locked");
            setTimeout(function () {
                $hamburgerOne.focus();
            }, 300);
        }
    }); // [1]

    // Offcanvas toggles
    $doc.on("click", ".navbar-control-offcanvas", function () {
        $(this).addClass("active");
        $body.addClass("body-scroll-locked");
        $offcanvasMenu.toggleClass("offcanvas-menu-active");
        $(".button-offcanvas-close").focus();
    });
    $doc.on("click", ".button-offcanvas-close", function () {
        $offcanvasMenu.removeClass("offcanvas-menu-active");
        $navbarOffcanvasBtn.removeClass("active");
        $body.removeClass("body-scroll-locked");
        setTimeout(function () {
            $navbarOffcanvasBtn.focus();
        }, 300);
    });
    $doc.on("click", "#offcanvas-menu", function () {
        $offcanvasMenu.removeClass("offcanvas-menu-active");
        $navbarOffcanvasBtn.removeClass("active");
        $body.removeClass("body-scroll-locked");
    });
    $doc.on("click", ".offcanvas-wraper", function (e) {
        e.stopPropagation();
    });
    $doc.on("focus", "input, a, button", function () {
        if ($offcanvasMenu.hasClass("offcanvas-menu-active")) {
            if ($(this).hasClass("skip-link-off-canvas")) {
                if (!$("#offcanvas-menu #social-nav-offcanvas").length == 0) {
                    $("#offcanvas-menu #social-nav-offcanvas ul li:last-child a").focus();
                } else if (!$("#offcanvas-menu #primary-nav-offcanvas").length == 0) {
                    $("#offcanvas-menu #primary-nav-offcanvas ul li:last-child a").focus();
                }
            }
        }
    });
    $doc.on("focus", ".skip-link-offcanvas", function () {
        $(".button-offcanvas-close").focus();
    }); // [3][14]

    // Sidr Widget Area
    if ($body.hasClass("rtl")) {
        $("#widgets-nav").sidr({ name: "sidr-nav", side: "right" });
    } else {
        $("#widgets-nav").sidr({ name: "sidr-nav", side: "left" });
    }
    $doc.on("click", "#hamburger-one", function () {
        $(this).toggleClass("active");
        if ($(this).hasClass("active")) {
            $body.addClass("body-scroll-locked");
        } else {
            $body.removeClass("body-scroll-locked");
        }
        setTimeout(function () {
            $(".sidr-offcanvas-close").focus();
        }, 300);
    });
    $doc.on("click", ".sidr-offcanvas-close", function () {
        $.sidr("close", "sidr-nav");
        $hamburgerOne.removeClass("active");
        $body.removeClass("body-scroll-locked");
        setTimeout(function () {
            $hamburgerOne.focus();
        }, 300);
    });
    $doc.on("focus", "input, a, button", function () {
        if ($body.hasClass("sidr-nav-open")) {
            if ($(this).hasClass("skip-link-offcanvas-first")) {
                $(".skip-link-offcanvas-last").focus();
            }
            if (!$(this).parents("#sidr-nav").length) {
                $(".sidr-offcanvas-close").focus();
            }
        }
    }); // [1]

    // RTL flag for sliders
    let rtled = $body.hasClass("rtl"); // [16]

    // Gutenberg gallery/slick (safe per-instance init)
    $('figure.wp-block-gallery.has-nested-images.columns-1, .wp-block-gallery.columns-1 ul.blocks-gallery-grid, .gallery-columns-1').each(function () {
        $(this).slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            fade: true,
            autoplay: false,
            autoplaySpeed: 8000,
            infinite: true,
            nextArrow: '<button type="button" class="slide-btn slide-btn-bg slide-next-icon">' + newsnation_custom.next_svg + "</button>",
            prevArrow: '<button type="button" class="slide-btn slide-btn-bg slide-prev-icon">' + newsnation_custom.prev_svg + "</button>",
            dots: false,
            rtl: rtled
        });
    }); // [16][7]

    // Banner tabs
    $doc.on("click", "#theme-banner-navs a", function () {
        $("#theme-banner-navs li").removeClass("active");
        $(this).parent().addClass("active");
        const currentTab = $(this).attr("href");
        $(".video-slider-right .wpi-banner-tab").hide();
        $(currentTab).show();
        return false;
    }); // [1]

    // Slick groups
    $(".theme-slider-block").each(function () {
        $(this).slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            fade: true,
            autoplay: false,
            autoplaySpeed: 8000,
            infinite: true,
            prevArrow: $(this).closest(".theme-block-navtabs").find(".slide-prev-lead"),
            nextArrow: $(this).closest(".theme-block-navtabs").find(".slide-next-lead"),
            dots: false
        });
    }); // [16]

    $(".theme-tiles-slide").each(function () {
        $(this).slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            fade: true,
            autoplay: false,
            autoplaySpeed: 8000,
            infinite: true,
            prevArrow: $(this).closest(".theme-block-tiles").find(".slide-prev-tiles"),
            nextArrow: $(this).closest(".theme-block-tiles").find(".slide-next-tiles"),
            dots: false
        });
    }); // [16]

    $(".theme-widget-slider").each(function () {
        $(this).slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            fade: true,
            autoplay: false,
            autoplaySpeed: 8000,
            infinite: true,
            prevArrow: $(this).closest(".theme-jumbo-banner").find(".slide-prev-banner"),
            nextArrow: $(this).closest(".theme-jumbo-banner").find(".slide-next-banner"),
            dots: false
        });
    }); // [16]

    $(".main-carousel-content").slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        fade: true,
        asNavFor: ".main-carousel-pagination",
        autoplay: true,
        speed: 900,
        autoplaySpeed: 6000,
        arrows: false
    }); // [16]

    $(".main-carousel-pagination").slick({
        slidesToShow: 4,
        slidesToScroll: 1,
        asNavFor: ".main-carousel-content",
        focusOnSelect: true,
        vertical: true,
        arrows: false,
        responsive: [
            { breakpoint: 991, settings: { slidesToShow: 2 } },
            { breakpoint: 575, settings: { slidesToShow: 1 } }
        ]
    }); // [16]

    $(".theme-widget-carousel").each(function () {
        $(this).slick({
            slidesToShow: 4,
            slidesToScroll: 1,
            dots: true,
            infinite: true,
            prevArrow: $(".slide-widget-prev"),
            nextArrow: $(".slide-widget-next"),
            responsive: [
                { breakpoint: 991, settings: { slidesToShow: 3, slidesToScroll: 3 } },
                { breakpoint: 768, settings: { slidesToShow: 2, slidesToScroll: 2, dots: false } },
                { breakpoint: 575, settings: { slidesToShow: 1 } }
            ]
        });
    }); // [16][10]

    $(".slider-content-container").slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: false,
        fade: true,
        asNavFor: ".pagination-content-container"
    }); // [16]

    $(".pagination-content-container").slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        asNavFor: ".slider-content-container",
        focusOnSelect: true,
        prevArrow: $(".slider-content-pagination .slide-prev"),
        nextArrow: $(".slider-content-pagination .slide-next")
    }); // [16]

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

    // Scroll up button show/hide (throttled)
    const toggleScrollUp = throttle(function () {
        if ($win.scrollTop() > $win.height() / 2) {
            $(".scroll-up").fadeIn(300);
        } else {
            $(".scroll-up").fadeOut(300);
        }
    }, 100); // [9][17][19]

    $win.on("scroll", toggleScrollUp);
    $doc.on("click", ".scroll-up", function () {
        $("html, body").animate({ scrollTop: 0 }, 700);
        return false;
    }); // [9][17]

    // Header affix on scroll
    (function () {
        const header = document.getElementById("theme-navigation");
        if (!header) return;
        const sticky = header.offsetTop;
        const onScroll = throttle(function () {
            if (window.pageYOffset > sticky) {
                header.classList.add("theme-navbar-affix");
            } else {
                header.classList.remove("theme-navbar-affix");
            }
        }, 50);
        // Use passive listener for scroll
        window.addEventListener("scroll", onScroll, { passive: true });
        onScroll();
    })(); // [9][12][15]

    // Navbar hide/show on scroll delta
    (function () {
        let didScroll = false;
        let lastScrollTop = 0;
        const delta = 5;
        const navbarHeight = $themeNavigation.outerHeight() || 0;

        $win.on("scroll", function () {
            didScroll = true;
        });

        setInterval(function () {
            if (!didScroll) return;
            const st = $win.scrollTop();
            if (Math.abs(lastScrollTop - st) <= delta) {
                didScroll = false;
                return;
            }
            if (st > lastScrollTop && st > navbarHeight) {
                $("#theme-navigation").removeClass("navbar-affix-down").addClass("navbar-affix-up");
            } else {
                if (st + $win.height() < $(document).height()) {
                    $("#theme-navigation").removeClass("navbar-affix-up").addClass("navbar-affix-down");
                }
            }
            lastScrollTop = st;
            didScroll = false;
        }, 250);
    })(); // [9][12][15]

    // Ticker
    $(".ticker-slides").marquee({
        delayBeforeStart: 0,
        duration: 25000,
        pauseOnHover: true,
        duplicated: true,
        direction: "left",
        startVisible: true
    }); // [1]

    // Masonry after images loaded
    if ($(".archive-layout-masonry").length > 0) {
        let grid;
        const hidden = "scale(0.5)";
        const visible = "scale(1)";
        grid = $(".archive-layout-masonry").imagesLoaded(function () {
            grid.masonry({
                itemSelector: ".theme-article-area",
                hiddenStyle: { transform: hidden, opacity: 0 },
                visibleStyle: { transform: visible, opacity: 1 }
            });
        });
    } // [1]

    // Header ad countdown & scroll
    const adCountDown = document.querySelector(".ad-countdown-timer");
    const headerAds = document.querySelector(".theme-header-ads");
    const adBtn = document.querySelector(".top-header-add");

    if (headerAds && adCountDown && adBtn) {
        const headerAdsHeight = headerAds.getBoundingClientRect().height;
        let counter = 6;

        const startScroll = () => {
            window.scrollTo({ top: headerAdsHeight, behavior: "smooth" });
            const onScroll = () => {
                if (window.scrollY >= headerAdsHeight) {
                    headerAds.classList.add("header-add-top");
                    clearInterval(startCount);
                    window.removeEventListener("scroll", onScroll, { passive: true });
                }
            };
            window.addEventListener("scroll", onScroll, { passive: true });
        };

        adBtn.addEventListener("click", startScroll);

        const startCount = setInterval(() => {
            counter--;
            if (counter <= 0) {
                clearInterval(startCount);
                startScroll();
            }
            adCountDown.textContent = `${counter}s`;
        }, 1000);
    } // [1]

    // Subscribe modal
    const subBtn = document.querySelector(".navbar-control-subscription");
    const modal = document.querySelector(".theme-modal");
    const closeBtn = document.querySelector(".theme-modal-close");
    if (modal && subBtn && closeBtn) {
        subBtn.addEventListener("click", () => {
            modal.classList.add("active");
        });
        closeBtn.addEventListener("click", (e) => {
            e.preventDefault();
            modal.classList.remove("active");
        });
    } // [1]
});
