(function (window, $) {
    if (!$) return;

    $(function () {
        var $submenuItems = $('.nnaxfuf-settings-submenu-item');
        var $sortOptions = $('.nnaxfuf-sort-option');
        var $tableSortButtons = $('.nnaxfuf-table-sort');
        var $toggleShowAll = $('#nnaxfuf-toggle-show-all');
        var submenuHideTimers = new WeakMap();

        function getCurrentSortState() {
            var params = new URLSearchParams(window.location.search || '');
            var key = (params.get('nnaxfuf_sort') || 'name').toString();
            var direction = (params.get('nnaxfuf_order') || 'asc').toString();

            if (['name', 'size', 'date'].indexOf(key) === -1) key = 'name';
            if (['asc', 'desc'].indexOf(direction) === -1) direction = 'asc';

            return { key: key, direction: direction };
        }

        function markActiveSort(key, direction) {
            $sortOptions.removeClass('is-active').attr('aria-pressed', 'false');
            $tableSortButtons.removeClass('is-active').attr('aria-pressed', 'false');
            $tableSortButtons.attr('data-sort-direction', 'asc');

            $sortOptions
                .filter('[data-sort-key="' + key + '"][data-sort-direction="' + direction + '"]')
                .addClass('is-active')
                .attr('aria-pressed', 'true');

            $tableSortButtons
                .filter('[data-sort-key="' + key + '"]')
                .addClass('is-active')
                .attr('aria-pressed', 'true')
                .attr('data-sort-direction', direction);
        }

        function applySortByReload(key, direction) {
            var url = new URL(window.location.href);
            url.searchParams.set('nnaxfuf_sort', key);
            url.searchParams.set('nnaxfuf_order', direction);
            url.searchParams.delete('nnaxfuf_paged');
            window.location.assign(url.toString());
        }

        function resolveSubmenuDirection($item, $submenu) {
            if (!$item.length || !$submenu.length) return;

            $item.removeClass('nnaxfuf-settings-submenu-left nnaxfuf-settings-submenu-right');

            var itemRect = $item.get(0).getBoundingClientRect();
            var submenuWidth = Math.max($submenu.outerWidth() || 220, 220);
            var viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;
            var openLeft = itemRect.right + submenuWidth + 24 > viewportWidth && itemRect.left - submenuWidth > 0;

            $item.addClass(openLeft ? 'nnaxfuf-settings-submenu-left' : 'nnaxfuf-settings-submenu-right');
        }

        function showSubmenu($item) {
            var $submenu = $item.find('.nnaxfuf-settings-submenu').first();
            var $trigger = $item.find('.nnaxfuf-settings-submenu-trigger').first();
            var timer = submenuHideTimers.get($item.get(0));
            if (timer) {
                window.clearTimeout(timer);
                submenuHideTimers.delete($item.get(0));
            }
            resolveSubmenuDirection($item, $submenu);
            $submenu.prop('hidden', false);
            $item.addClass('is-open');
            $trigger.attr('aria-expanded', 'true');
        }

        function hideSubmenu($item) {
            var $submenu = $item.find('.nnaxfuf-settings-submenu').first();
            var $trigger = $item.find('.nnaxfuf-settings-submenu-trigger').first();
            var timer = submenuHideTimers.get($item.get(0));
            if (timer) {
                window.clearTimeout(timer);
                submenuHideTimers.delete($item.get(0));
            }
            $submenu.prop('hidden', true);
            $item.removeClass('is-open');
            $trigger.attr('aria-expanded', 'false');
        }

        function scheduleHideSubmenu($item) {
            var key = $item.get(0);
            var timer = submenuHideTimers.get(key);
            if (timer) {
                window.clearTimeout(timer);
            }
            timer = window.setTimeout(function () {
                hideSubmenu($item);
            }, 140);
            submenuHideTimers.set(key, timer);
        }

        if ($submenuItems.length) {
            $submenuItems.each(function () {
                var $item = $(this);
                var $submenu = $item.find('.nnaxfuf-settings-submenu').first();
                if (!$submenu.length) return;

                $item.on('mouseenter focusin', function () {
                    showSubmenu($item);
                });

                $item.on('mouseleave', function () {
                    scheduleHideSubmenu($item);
                });

                $item.on('focusout', function (e) {
                    if (this.contains(e.relatedTarget)) return;
                    hideSubmenu($item);
                });
            });

            $(window).on('resize', function () {
                $submenuItems.each(function () {
                    var $item = $(this);
                    if (!$item.hasClass('is-open')) return;
                    resolveSubmenuDirection($item, $item.find('.nnaxfuf-settings-submenu').first());
                });
            });
        }

        $sortOptions.on('click', function () {
            var key = ($(this).data('sort-key') || 'name').toString();
            var direction = ($(this).data('sort-direction') || 'asc').toString();
            applySortByReload(key, direction);
        });

        $tableSortButtons.on('click', function () {
            var $btn = $(this);
            var key = ($btn.data('sort-key') || 'name').toString();
            var currentDirection = ($btn.attr('data-sort-direction') || 'asc').toString();
            var direction = $btn.hasClass('is-active') ? (currentDirection === 'asc' ? 'desc' : 'asc') : 'asc';
            applySortByReload(key, direction);
        });

        $toggleShowAll.on('click', function () {
            var isShowAll = String($toggleShowAll.attr('data-show-all') || '0') === '1';
            var url = new URL(window.location.href);

            if (isShowAll) {
                url.searchParams.delete('nnaxfuf_show');
            } else {
                url.searchParams.set('nnaxfuf_show', 'all');
            }

            url.searchParams.delete('nnaxfuf_paged');
            window.location.assign(url.toString());
        });

        var currentSort = getCurrentSortState();
        markActiveSort(currentSort.key, currentSort.direction);
    });
})(window, window.jQuery);
