// ###############
// # CLAROMENTIS #
// #  ---------  #
// #   CONTINUE  #
// # > NEW GAME  #
// #  LOAD GAME  #
// #    OPTIONS  #
// #       QUIT  #
// #  ---------  #
// ###############

define(['jquery', './lib/requirejs/domReady.js'], function ($, domReady) {
    return function () {
        domReady(function () {
            var $body = $('body');
            var $document = $(document);
            var $window = $(window);
            var lastWindowWidth = $window.width();
            var currentPath = (window.location.pathname + window.location.search).replace(/\/$/, '');

            // Mark submenu items
            $('.claro-nav-items ul > li:has(ul)').addClass('has-sub');

            /**
             * Order selected elements by an array of other selectors.
             *
             * @param {Array<String>} order - An array of jQuery selectors
             * @returns {$}
             */
            $.fn.orderChildren = function (order) {
                this.each(function () {
                    var el = $(this);

                    for(var i = order.length; i >= 0; i--) {
                        el.prepend(el.children(order[i]));
                    }
                });

                return this;
            };

            /**
             * Rearrange navigation menu for desktop or mobile view, based on the window width.
             */
            function rearrangeNav() {
                if ($(window).width() <= 767) {
                    $('#claroNav').orderChildren(['#head_searchbox', '.navbar-nav']);
                    $('.navbar-nav').orderChildren([
                        '.nav-item-profile', '.nav-item-calendar', '.nav-item-company-links', '.nav-item-bookmarks',
                        '.nav-item-applications', '.nav-item-whos-logged-in'
                    ]);
                } else if ($(window).width() >= 767) {
                    $('#claroNav').orderChildren(['#head_searchbox', '.navbar-nav']);
                    $('.navbar-nav').orderChildren([
                        '.nav-item-calendar', '.nav-item-company-links', '.nav-item-bookmarks',
                        '.nav-item-applications', '.nav-item-notifications', '.nav-item-whos-logged-in',
                        '.nav-item-profile'
                    ]);
                }
            }

            // Initialise the navigation menu
            rearrangeNav();
            mobileTitles();
            desktopSidemenu();
            openSubs();
            checkMenuUrl();

            // Reinitialise the navigation menu when the window is resized
            $window.on('resize', function () {
                var windowWidth = $window.width();

                if (lastWindowWidth !== windowWidth) {
                    rearrangeNav();
                    mobileTitles();
                    desktopSidemenu();
                    openSubs();
                    lastWindowWidth = windowWidth;
                }

                // Recalculate the menu wrapper width on window resize
                menuWrapperWidth = ($('.main_menu__inner').outerWidth() - 80);
                toggleProgressiveMenuButton(checkMenuWidth(false));
                alignLastItemSubmenu(checkMenuWidth(true));

                // Remove transition on window resize
                $(".nav-toggle, .claro-nav-items").addClass('no-transition');
            });

            // Restore transition after window resize
            $window.on('resize', _.debounce(function () {
                $(".nav-toggle, .claro-nav-items").removeClass('no-transition');
            }, 1000));

            // Navbar navigation, notification and application menu buttons
            $(".nav-toggle, .mobile-notification .notification-toggle, .mobile-applications .application-toggle").click(function () {
                $("li").removeClass("open-mobile");
                $("html").toggleClass("no-scroll");
                $(".back-close").toggleClass("in");
            });

            // Opens navigation menu
            $(".nav-toggle").click(function () {
                $(".head_nav").toggleClass("open");
                $(".nav-toggle, .claro-nav-items").toggleClass("in");
                $(".mobile-applications, .mobile-notification").toggleClass("fade-out");
            });

            // Opens notifications
            $(".mobile-notification .notification-toggle").click(function () {
                $(".nav-toggle, .claro-nav-items").removeClass("in");
                $(".nav-toggle, .mobile-applications").toggleClass("fade-out");
                $("#notifications").toggleClass("show");
            });

            // Opens applications
            $(".mobile-applications .application-toggle").click(function () {
                $(".nav-toggle, .claro-nav-items").removeClass("in");
                $(".navbar-applications").toggleClass("show");
                $(".nav-toggle, .mobile-notification").toggleClass("fade-out");
            });

            // Opens sub menus
            function openSubs() {
                if ($(window).width() <= 767) {
                    $(".claro-nav-items > ul > li a, .claro-nav-items > .header-menu-container > .main_menu__inner > ul > li a").click(function () {
                        $(this).parent("li").addClass("open-mobile");
                    });
                }
            }

            // Compares current page url with link url
            function checkUrlPath(linkUrl, link) {
                if (currentPath === linkUrl) {
                    link.attr('aria-current', 'page');
                } else {
                    link.removeAttr('aria-current');
                }
            }

            // Checks menu items urls to include aria-current attribute
            function checkMenuUrl() {
                var menuLinks = $(".client-css-menu-item-link");

                menuLinks.each(function() {
                    var $link = $(this); 
                    var linkUrl = new URL($link.attr('href'), window.location.origin);
                    var linkPath = (linkUrl.pathname + linkUrl.search).replace(/\/$/, '');
            
                    checkUrlPath(linkPath, $link);
                });
            }

            // Add top title <li> placeholder to sub menus
            $(".claro-nav-items ul ul").prepend($('<li class="submenu-header d-block d-md-none"><span class="submenu-header-back-button"></span><span class="submenu-header-link-wrap"></span></li>'));

            function mobileTitles() {
                if ($(window).width() <= 767) {
                    $("li").removeClass("open-mobile");

                    // Adds title of previously clicked item to submenu title
                    var menu = $('.claro-nav-items ul');

                    $('a', menu).on('click', function(){
                        var menutitle = $(this).text();
                        var menuUrl = new URL($(this).attr('href'), window.location.origin);
                        var menulink = (menuUrl.pathname + menuUrl.search).replace(/\/$/, '');
                        var menuappend = $(this).next('ul').children('li').first('.submenu-header').children('.submenu-header-link-wrap');

                        menuappend.html('<a class="submenu-header-link" href="' + menulink + '"' + '>'  + menutitle + '</a>');

                        var submenuLink = menuappend.find('.submenu-header-link');
                        checkUrlPath(menulink, submenuLink);
                    });

                    $('ul > li.has-sub > a').click(function (event) {
                        event.preventDefault();
                    });
                }
            }

            function desktopSidemenu() {
                if ($(window).width() >= 767) {
                    if (!$('button').hasClass('desktop-toggle')) {
                        $(".desktop-sideview .header-menu-container li.has-sub, .header-menu-container ul.main_menu__list ul li.has-sub").prepend('<button class="desktop-toggle d-none d-md-block"></button>');
                    }
                }
            }

            $('.desktop-sideview .header-menu-container li.has-sub > button, .header-menu-container ul.main_menu__list ul li.has-sub > button').on('click', function () {
                $(this).parent('.has-sub').toggleClass('open-mobile');
            });

            // Closes sub-menus individually
            $( ".submenu-header-back-button" ).click(function() {
                $(this).parent('.submenu-header').parent("ul").parent("li").removeClass("open-mobile");
            });

            // Back fade out
            $(".back-close").click(function(){
                $(".head_nav").removeClass("open");
                $(".nav-toggle, .claro-nav-items, .back-close, #notifications, .navbar-applications").removeClass("in");
                $("li").removeClass("open-mobile");
                $(".nav-toggle, .notification-toggle, .navbar-applications").removeClass("fade-out");
                $("html").removeClass("no-scroll");
            });

            // Ensure the progressive menu is collapsed on page load
            $('#more').prop("checked", false);

            // Interchange more or less text on click
            $('.main_menu__link').on('click', function() {
                if ( !$('#more').is(":checked") ) {
                    $(this).text(lmsg('main_menu.progressive_collapse.collapse')).addClass('after');
                } else {
                    $(this).text(lmsg('main_menu.progressive_collapse.expand')).removeClass('after');
                }
            });

            // Return the total width of all list items or all but the last one
            function checkMenuWidth(ignoreLast) {
                var totalMenuItemWidth = 0;

                $(".main_menu__list > li").each(function (index, value) {
                    //Ignore the last menu item when calculating width if ignore last is true
                    if (!(ignoreLast && index === $(".main_menu__list > li").length - 1)) {
                        totalMenuItemWidth += $(this).outerWidth()
                    }
                });

                return totalMenuItemWidth;
            }

            // Finds last item in main menu
            var lastMenuItem = $('.main_menu__list > li').last();

            // Allows for the 'more' button when calculating the difference between width of all list items and the wrapper
            var menuWrapperWidth = ($('.main_menu__inner').outerWidth() - 80);

            // Toggle the display of the progressive menu's 'more/less' depending on menu's width
            var progressiveMenuIsActive = false;

            function toggleProgressiveMenuButton(listItemsWidth){
                if (listItemsWidth < menuWrapperWidth) {
                    $('.main_menu__link').addClass('hide').removeClass('show');
                    progressiveMenuIsActive = false;
                } else {
                    $('.main_menu__link').addClass('show').removeClass('hide');
                    progressiveMenuIsActive = true;
                }
            }

            // Change the alignment of the last top level menu item's sub menu
            function alignLastItemSubmenu(itemsWidth) {
                if (itemsWidth + lastMenuItem.children('ul').width() > $(window).width() - 15 && progressiveMenuIsActive === false) {
                    lastMenuItem.children('ul').css('right', $(window).width() - $('.main_menu__list').width() - 16);
                } else {
                    lastMenuItem.children('ul').css('right', 'auto');
                }
            }

            toggleProgressiveMenuButton(checkMenuWidth(false));
            alignLastItemSubmenu(checkMenuWidth(true));

            // Animated menu - Show/hide menu when scrolling the page
            // Throttled to run every 250ms at most
            var lastScrollTop = 0,
                delta = 5,
                navbarHeight = $('.claro-navbar').outerHeight();

            $window.on('scroll', _.throttle(hasScrolled, 250));

            function hasScrolled() {
                // Don't try to hide in mobile view
                if (lastWindowWidth <= 767) {
                    $body.removeClass('hide-header');
                    return;
                }

                var st = $(this).scrollTop();

                // Make sure they scroll more than delta
                if (Math.abs(lastScrollTop - st) <= delta) {
                    return;
                }

                // Collapse progressive menu
                $('.head_nav .toggle').prop("checked", false);
                $('.main_menu__link').text("More").removeClass('after');

                // If they scrolled down and are past the navbar, add class .hide-header.
                if (st > lastScrollTop && st > navbarHeight) {
                    // scroll down
                    $body.removeClass('show-header').addClass('hide-header');
                } else {
                    // scroll up
                    if (st + $window.height() < $document.height()) {
                        $body.removeClass('hide-header').addClass('show-header');
                    }
                }

                lastScrollTop = st;
            }

            // show hidden menu header when the page is not scrollable
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList') {
                        const body = document.body;

                        if (body.classList.contains('hide-header') && !isPageScrollable()) {
                            body.classList.remove('hide-header');
                            body.classList.add('show-header');
                        }
                    }
                });
            });

            // start observing the page change
            observer.observe(document.body, {childList: true, subtree: true});

            // stop observing to clean up resources
            window.addEventListener('beforeunload', function (event) {
                observer.disconnect();
            });

            function isPageScrollable() {
                const pageHeight = document.documentElement.scrollHeight;
                const viewportHeight = window.innerHeight;

                return pageHeight > viewportHeight;
            }

            var mainMenuExists = !!document.querySelector('.header-menu-container');

            if (!mainMenuExists) {
                document.querySelector("body").classList.add("no-main-menu");
            }

            // Navbar tooltips
            var tooltipTimeout; // Store the timeout for showing the last active tooltip
            var activeTooltip = null; // Store the last active tooltip

            $('.navbar-nav .nav-item .nav-link').on('shown.bs.tooltip', function () {
                activeTooltip = $(this); // Store the tooltip that was last shown
            });

            $(window).on('scroll', _.throttle(function() {
                if (activeTooltip)
                    activeTooltip.tooltip('hide'); // Hide the last active tooltip

                // Clear any existing timeout
                clearTimeout(tooltipTimeout);

                // Re-show the last active tooltip after scrolling stops
                tooltipTimeout = setTimeout(function() {
                    if (activeTooltip && (activeTooltip.is(':hover') || activeTooltip.is(':focus'))) {
                        // Fully remove and reinitialize the tooltip before showing
                        activeTooltip.tooltip('dispose').tooltip().tooltip('show');
                    }
                }, 300); // Adjust delay as needed
            }, 250));
            //End of Navbar tooltips
        });
    }
});
