var Wick = Wick || {};
Wick.Nav = function () {
    var $nav = $('.main-nav'),
        navs = [
            '.main-nav__top-level-wrap',
            '.main-nav__menu-wrapper',
            '.main-nav__sub-menu__wrapper',
            '.main-nav__offers',
            '.main-nav__sub-sub-menu__wrapper'
        ],
        navItems = [
            '.main-nav__top-level__item',
            '.main-nav__menu__item',
            '.main-nav__sub-menu__item, .main-nav__offers__wrapper',
            '.main-nav__sub-menu__item',
            '.main-nav__sub-sub-menu__item'
        ],
        navLabels = [
            '.main-nav__top-level__label'
        ],
        navDropdown = [
            '.main-nav__menu__label',
            '.main-nav__sub-menu__label'
        ],
        currentLevel = 0,
        desktopNav,
        mobileNav,
        navSubMenuIsHovered = false;


    function setBottomShadowWhenNoBreadcrumbs() {
        if (!$('.breadcrumbs').length) {
            $nav.addClass('with-bottom-shadow');
        }
    }

    function setActiveLink() {
        const pathname = location.pathname.toLowerCase();
        $('.main-nav li:not(.main-nav__sub-menu__view-more) > a').each(function() {
            const link = $(this).attr('href') || '';
            const lowerCaseLink = link.toLowerCase();

            if (pathname.endsWith(lowerCaseLink)) {
                $(this).addClass('active');
            }

            const replacedLink = replaceAndWithPlusSymbol(lowerCaseLink);
            if(pathname.endsWith(replacedLink)) {
                $(this).addClass('active');
            }
        })
    }

    function replaceAndWithPlusSymbol(link) {
        return link.replace(/-and-/g, '+')
    }

    function setCurrentVisibleLevel(lvl) {
        $nav.attr('data-active-lvl', lvl);
    }

    function resetSectionHeight(sectionName) {
        $(sectionName).removeAttr('style');
    }

    function resizeNavSection(firstSection, SecondSection, padding) {
        if (padding == null) {
            padding = 0;
        }
        $(firstSection).css({"min-height": $(SecondSection).height() + padding});
    }

    function mobileNavigation() {
        var self = this,
            $btnHamburger = $('.header-hamburger-menu'),
            $navSection = $('.main-nav__section'),
            hamburgerState = 'header-hamburger-menu_close-visible',
            $btnBack = $('.main-nav__back-btn'),
            $navOpener = $(navLabels.join(',')),
            $navDropdown = $(navDropdown.join(',')),
            mobileNavBodyClass = 'mobile-nav-opened',
            isHidden = 'js-down-sm-hidden',
            isVisible = 'js-visible';
            isOpen = 'js-open';

        this.toggleNavVisibility = function () {
            $btnHamburger.toggleClass(hamburgerState);
            $nav.toggleClass(isVisible);
            $('main, footer').toggleClass(isHidden);
            $(document).trigger('mobileNav.toggle');
        };

        this.toggleBodyClass = function () {
            $('body').toggleClass(mobileNavBodyClass);
        };

        this.checkLink = function($link) {
            if ($link.hasClass("main-nav__offers__label")) {
                if (!$link.is(navLabels[currentLevel]) || !$link.nextAll(navs.join(',')).length) {
                    return true;
                }
            } else {
                // Click on link from previous level or without submenu will directly follow the link
                if (!$link.is(navLabels[currentLevel - 1]) || !$link.nextAll(navs.join(',')).length) {
                    return true;
                }
            }

            return false
        }

        this.showNavSection = function (e) {
            var $link = $(this);

            if (self.checkLink($link)) {
                return true
            }

            $link.parent().addClass(isVisible);
            $navSection.addClass('slide-in');

            $('html, body').animate({
                scrollTop: $("body").offset().top
            });

            setTimeout(function () {
                $navSection.removeClass('slide-in');
            }, 300);

            setCurrentVisibleLevel(++currentLevel);
            return false;
        };

        this.closeOpenSub = function() {
            $('.js-open').removeClass(isOpen)
        }

        this.openSubNavigation = function (e) {
            var $link = $(this).parent();

            if ($link.hasClass(isOpen)) {
                $link.removeClass(isOpen)
            } else {
                $link.addClass(isOpen)
                $(this).next().focus()
            }

            return false
        },

        this.handleBackBtnClick = function () {
            $(navItems[currentLevel - 2]).removeClass(isVisible);
            $navSection.addClass('slide-in-l2r');
            setTimeout(function () {
                $navSection.removeClass('slide-in-l2r');
            }, 300);
            self.closeOpenSub()

            setCurrentVisibleLevel(--currentLevel);
        };

        this.init = function () {
            $btnHamburger.on('click.mobile', function () {
                self.toggleNavVisibility();
                self.toggleBodyClass();
            });
            $navOpener.on('click.mobile', self.showNavSection);
            $navDropdown.on('click.mobile', self.openSubNavigation);
            $btnBack.on('click.mobile', self.handleBackBtnClick);
        };

        this.destroy = function () {
            $btnHamburger.off('.mobile');
            $navOpener.off('.mobile');
            $btnBack.off('.mobile');
        };

        self.init();
    }

    function desktopNavigation() {
        var self = this,
            isHovered = 'is-hovered',
            isHoveredLvl1 = 'is-hovered-lvl-1';

        this.handleTouchstart = function () {
            console.log('start');
            var $link = $(this),
                $li = $link.parent(),
                hovered = $li.hasClass(isHovered);

            if (hovered || !$link.nextAll(navs.join(',')).length) {
                $link.data("shouldPrevent", false);
                return true;
            }

            $li.siblings().removeClass(isHovered);
            $li.addClass(isHovered);
            $nav.addClass(isHoveredLvl1);
            $link.data("shouldPrevent", true);
            $(document).off("touchstart.leaveNav").on("touchstart.leaveNav", function (e) {
                if (!$(e.target).parents('.main-nav').length) {
                    $nav.removeClass(isHoveredLvl1).find(navItems.join(',')).removeClass(isHovered);
                    $(document).off("touchstart.leaveNav")
                }
            });
        };

        this.handleTouchend = function (e) {
            console.log('end');
            $(this).data("shouldPrevent") && e.preventDefault();
        };

        this.bindHoverEvents = function () {
            $(navItems[0]).on('mouseenter.navDesktop', function () {
                $(this).addClass(isHovered)
                if ($(this).children(navs[1]).length) {
                    $nav.addClass(isHoveredLvl1);
                    resetSectionHeight(".main-nav__menu-wrapper");
                }
            }).on('mouseleave.navDesktop', function () {
                $(this).removeClass(isHovered)
                $nav.removeClass(isHoveredLvl1);
                $(navItems[1]).removeClass(isHovered);
                resetSectionHeight(".main-nav__menu-wrapper");
            });
        };

        this.bindTouchEvents = function () {
            $(document).on('touchstart.navTouchStart', navLabels.join(','), self.handleTouchstart);
            $(document).on('touchend.navTouchEnd', navLabels.join(','), self.handleTouchend);
        };

        this.init = function () {
            if (!Wick.Responsive.isTouchDevice()) {
                self.bindHoverEvents();
            } else {
                self.bindTouchEvents();
            }
        };

        this.destroy = function () {
            if (!Wick.Responsive.isTouchDevice()) {
                $(navItems.join(',')).off('.navDesktop');
                $(navs.join(',')).off('.navDesktop');
            } else {
                $(document).off('.navTouchStart .navTouchEnd');
            }
        };
        self.init();
    }

    var init = function () {
        setBottomShadowWhenNoBreadcrumbs();
        setCurrentVisibleLevel(++currentLevel);
        setActiveLink();

        Wick.Responsive.onBreakpoint(function () {
            desktopNav && desktopNav.destroy();
            desktopNav = null;
            if (!mobileNav) {
                mobileNav = new mobileNavigation();
            }
        }, 'down-lg');
        Wick.Responsive.onBreakpoint(function () {
            mobileNav && mobileNav.destroy();
            mobileNav = null;
            if (!desktopNav) {
                desktopNav = new desktopNavigation();
            }
        }, 'up-lg');
    };

    init();
};
