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

    $(document).ready(function () {

        let lastScrollTop = 0;
        const stickyOption = travelficStickySettings?.stickyBehavior || 'always';
        const $header = $('.tft_has_sticky');
        const $scrollTopBtn = $(".tft-scroll-to-top");
        const $wpAdminBar = $('#wpadminbar');
        const scrollThreshold = 20; 

        $(window).on('scroll', function () {
            const currentScroll = $(this).scrollTop();
            const scrollDiff = Math.abs(currentScroll - lastScrollTop);
            const wasSticky = $header.hasClass('tf-navbar-shrink'); 

            // Scroll-to-top button visibility
            if (currentScroll > 0) {
                $scrollTopBtn.css('display', 'flex');
            } else {
                $scrollTopBtn.fadeOut();
            }

            // Sticky behavior
            if (currentScroll > 0 && scrollDiff > scrollThreshold) {
                if (stickyOption === 'always') {
                    showSticky();
                } else if (stickyOption === 'up' && currentScroll < lastScrollTop) {
                    showSticky();
                } else if (stickyOption === 'down' && currentScroll > lastScrollTop) {
                    showSticky();
                } else {
                    hideSticky();
                }
            } else if (currentScroll <= 0) {
                hideSticky();
            }

            lastScrollTop = currentScroll;

            function showSticky() {
                if (!$header.hasClass('tf-navbar-shrink')) {
                    $header.addClass('tf-navbar-shrink');
                    setTimeout(() => {
                        $header.removeClass('tf-header-animate');
                    }, 500);
                }
            }

            function hideSticky() {
                // Only animate if the header was actually sticky before hiding
                if (wasSticky && $header.hasClass('tf-navbar-shrink')) {
                    $header.removeClass('tf-navbar-shrink');
                    
                    // Trigger remove animation
                    $header.addClass('tf-header-animate');

                    // Remove animate class after 500ms
                    setTimeout(() => {
                        $header.removeClass('tf-header-animate');
                    },500);
                } else {
                    $header.removeClass('tf-navbar-shrink tf-header-animate');
                }
            }

            // Admin bar offset
            if ($(window).width() > 600 && $wpAdminBar.length) {
                if ($(".tf-navbar-shrink").length) {
                    $('.tf-navbar-shrink').css("top", $wpAdminBar.height());
                } else {
                    $('.tft_has_sticky').css("top", 0);
                }
            }
        });

        $(".tft-scroll-to-top").on("click", function (e) {
            e.preventDefault();
            $("html, body").animate({ scrollTop: 0 }, 300);
        });

        // search click prevent
        $('.tft-header-search a').on('click', function (e) {
            e.preventDefault();
        });

        //Header Search Bar
        $('.tft-search-icon').on('click', function (e) {
            $(this).toggleClass('active-search-icon');
            $('.tft-header-search').toggleClass('active-search');
            e.stopPropagation();
        });

        //Header Search Bar
        $('#search_header').on('click', function (event) {
            event.stopPropagation();
        });

        // Header mobile menu
        $('.tft-mobile_menubar').on('click', function (e) {
            e.preventDefault();
            $('.tft-mobile_menubar').toggleClass('tft-mobile-menu-icon');
            $('.tft-mobile-main-menu').toggleClass('tft-active-mobile')
        });

        /**
         * Single Form date picker
         */
        if ($("#tour-booking-date").length) {
            $("#tour-booking-date").flatpickr({
                minDate: "today"
            });
        }

        /**
         * Accordion singnle tour
         */

        $(function () {
            $(".tft-single-accordion:not(:first-of-type) .tft-accordion-details").css("display", "none");
            $(".tft-single-accordion:not(:first-of-type) .tft-accordion-details").addClass("open");

            $(".tft-accordion-heading").click(function () {
                $(".open").not(this).removeClass("open").next().slideUp(600);
                $(this).toggleClass("open").next().slideToggle(600);
                $(this).find('span').toggleClass('active-icon');
            });
        });

        /**
         * Keybord navigation 
         */
        $(document).on('focus', '.tft-header-desktop .tft-site-navigation ul li a', function (e) {      
            $(this).parents('ul').addClass('show');
            $(this).siblings('ul').addClass('show');
            $(this).closest('li').siblings().find('ul').removeClass('show');
        });
        
        /**
         * Mobile Menu drop Down
         */
        $(document).on('click', '.travelfic-dropdown button, .page_item_has_children > a', function (e) {
            if ($(window).width() < 992) {
                var $el = $(this);
                var $li = $el.closest('li');

                if ($li.hasClass('page_item_has_children') || $li.hasClass('menu-item-has-children')) {
                    e.preventDefault();

                    // Toggle submenu
                    if ($el.hasClass('active')) {
                        $el.removeClass('active');
                        $li.find('> .sub-menu, > .children').removeClass('show');
                    } else {
                        $el.addClass('active');
                        $li.find('> .sub-menu, > .children').addClass('show');
                    }
                }
            }
        });
        // Handle window resize separately
        $(window).on('resize', function () {
            if ($(window).width() >= 992) {
                $('.travelfic-dropdown button.active, .page_item_has_children > a.active').removeClass('active');
                $('.sub-menu.show, .children.show').removeClass('show');
            }
        });

        // Handle window resize separately
        function initMenu() {
            var isDesignThree = $('header').hasClass('tft-header-design__three');
            var breakpoint = isDesignThree ? 1200 : 992;
            
            if ($(window).width() >= breakpoint) {
                setupMenuHover();
            } 
        }

        // Setup hover events for menu
        function setupMenuHover() {
            // Remove previous handlers to avoid duplicates
            $('.menu-item-has-children, .page_item_has_children')
                .off('mouseenter.menuHover mouseleave.menuHover');

            // Handle mouseenter (hover in)
            $('.menu-item-has-children, .page_item_has_children').on('mouseenter.menuHover', function() {
                var $this = $(this);
                var submenu = $this.children('.sub-menu, .children');
                if (!submenu.length) return;
                
                // Reset positioning
                submenu.css({
                    'left': '',
                    'right': '',
                    'top': '',
                    'bottom': '',
                    'display': 'block',
                    'visibility': 'hidden'
                });
                
                var isFirstLevel = $this.parents('.sub-menu, .children').length === 0;
                var windowWidth = $(window).width();
                var parentOffset = $this.offset();
                var parentWidth = $this.outerWidth();
                var submenuWidth = submenu.outerWidth();
                
                // FIRST LEVEL - Always show below
                if (isFirstLevel) {
                    submenu.css({
                        'top': '100%',
                        'left': '0',
                        'visibility': 'visible'
                    });
                } 
                // NESTED LEVELS - Show right if space, otherwise below
                else {
                    var spaceOnRight = windowWidth - (parentOffset.left + parentWidth + submenuWidth);
                    
                    if (spaceOnRight > 10) { // Added 10px buffer
                        // Show to the right if space available
                        submenu.css({
                            'top': '0',
                            'left': '100%',
                            'visibility': 'visible'
                        });
                    } else {
                        // Show below if no space on right
                        submenu.css({
                            'top': '100%',
                            'left': '0',
                            'visibility': 'visible'
                        });
                    }
                }
            });

            // Handle mouseleave (hover out)
            $('.menu-item-has-children, .page_item_has_children').on('mouseleave.menuHover', function() {
                $(this).children('.sub-menu, .children').stop(true, true).fadeOut(200);
            });
        }

        if ($("body").hasClass("tf_tours-template-default")) {
            $("body").removeClass("tft-customizer-typography");
        }

        // Initial setup
        initMenu();
        
        // Handle resize
        $(window).on('resize', function() {
          initMenu();
        });

        // latest posts empty check
        if ($('.tf-sidebar .wp-block-latest-posts__list').is(':empty')) {
            $('.tf-sidebar .wp-block-latest-posts__list').html('<span>No posts available</span>');
        }

        // Tagcloud empty check 
        if ($('.tf-sidebar .widget_tag_cloud').is(':empty')) {
            $('.tf-sidebar .widget_tag_cloud').html('<span>No tags available</span>');
        }


    });

}(jQuery));