(function ($) {
    function initTaxonomyMenu($nav, widgetId) {
        const $ = jQuery;
        const $btn = $nav.find('.dropdown-toggle');
        const $vlinks = $nav.find('.links');
        const $hlinks = $nav.find('.hidden-links');
        const $heading = $nav.find('.oea-taxonomy-heading');
        let totalSpace = 0;
        let breakWidths = [];

        $vlinks.children().each(function () {
            const $item = $(this);
            const elementWidth = $item.outerWidth(true);
            const itemTotalWidth = elementWidth;
            totalSpace += itemTotalWidth;
            breakWidths.push(totalSpace);
        });

        function checkMenu() {
            const isNoHeading = $nav.hasClass('no-heading');
            const isReversed = $nav.hasClass('reversed');
            const btnWidth = $btn.outerWidth(true);
            const headingWidth = $heading.outerWidth(true);
            const availableSpace = isNoHeading ? $nav.width() - btnWidth : $nav.width() - btnWidth - headingWidth;
            const numOfVisibleItems = $vlinks.children().length;
            const requiredSpace = breakWidths[numOfVisibleItems - 1];

            if (requiredSpace > availableSpace) {
                $vlinks.children().last().prependTo($hlinks);
                checkMenu();
            } else if (availableSpace > breakWidths[numOfVisibleItems]) {
                $hlinks.children().first().appendTo($vlinks);
            }

            $btn.attr('count', $hlinks.children().length);
            if ($hlinks.children().length === 0) {
                $btn.addClass('hidden');
            } else {
                $btn.removeClass('hidden');
            }
        }

        $btn.on('mouseenter', function () {
            $hlinks.stop(true, true).slideDown(200);
            $hlinks.removeClass('hidden');
        });

        $hlinks.on('mouseenter', function () {
            $(this).stop(true, true).show();
        });

        $nav.on('mouseleave', function () {
            $hlinks.stop(true, true).slideUp(200);
            $hlinks.addClass('hidden');
        });

        $(window).on('resize.taxonomy-' + widgetId, checkMenu);
        checkMenu();

        setTimeout(() => {
            $nav.addClass('loaded');
        }, 100);
    }

    $(document).ready(function () {
        $('nav.oea-taxonomy-menu[data-widget-id]').each(function () {
            var widgetId = $(this).data('widget-id');
            initTaxonomyMenu($(this), widgetId);
        });
    });
})(jQuery);