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

    $(function () {
        var i18n = (window.nnaxFmAjax && window.nnaxFmAjax.i18n) ? window.nnaxFmAjax.i18n : {};
        function t(key, fallback) {
            return (i18n && typeof i18n[key] === 'string' && i18n[key] !== '') ? i18n[key] : fallback;
        }

        // Cache DOM references once for predictable performance and readability.
        var $selectAll = $('#nnaxfuf_bulk_select_all');
        var $itemChecks = $('.nnaxfuf-bulk-item-checkbox');
        var $actionsBtn = $('#nnaxfuf_bulk_actions_btn');
        var $zipLink = $('#nnaxfuf_bulk_zip_download');
        var $moveBtn = $('#nnaxfuf_bulk_move_btn');
        var $moveForm = $('#nnaxfuf_bulk_move_form');
        var $moveItems = $('#nnaxfuf_bulk_move_items');
        var $moveCount = $('#nnaxfuf_bulk_move_count');
        var $deleteBtn = $('#nnaxfuf_bulk_delete_btn');
        var $deleteItems = $('#nnaxfuf_bulk_delete_items');
        var $deleteForm = $('#nnaxfuf_bulk_delete_form');
        var $deleteRecursiveBtn = $('#nnaxfuf_bulk_delete_recursive_btn');
        var $deleteRecursiveItems = $('#nnaxfuf_bulk_delete_recursive_items');
        var $deleteRecursiveForm = $('#nnaxfuf_bulk_delete_recursive_form');
        var $bulkWrap = $('.nnaxfuf-bulk-actions');

        if (!$actionsBtn.length || !$zipLink.length) {
            return;
        }

        // Reuse global UIkit confirm helper if available.
        // Fallback keeps functionality intact when UIkit modal is unavailable.
        var confirmWithUIKit = window.NUFM && window.NUFM.confirmWithUIKit
            ? window.NUFM.confirmWithUIKit
            : function (message, onConfirm) { if (window.confirm(message)) onConfirm(); };

        // Selection payload tokens follow backend parser format (e.g. file:123).
        function getSelectedTokens() {
            return $itemChecks.filter(':checked').map(function () {
                return $(this).val();
            }).get();
        }

        function hasNonMovableSelection() {
            var found = false;
            $itemChecks.filter(':checked').each(function () {
                if ($(this).data('nnaxfuf-can-move') !== 1) {
                    found = true;
                    return false;
                }
            });
            return found;
        }

        function hasNonDeletableSelection() {
            var found = false;
            $itemChecks.filter(':checked').each(function () {
                if ($(this).data('nnaxfuf-can-delete') !== 1) {
                    found = true;
                    return false;
                }
            });
            return found;
        }

        // Build compact ZIP endpoint URL:
        // tokens -> UTF-8 -> base64url -> /zip/{encoded}/auswahl/
        function buildZipUrl(tokens) {
            var baseUrl = ($bulkWrap.data('zip-url') || '').toString();
            try {
                if (!baseUrl) return '#';
                var normalizedBase = baseUrl.replace(/\/+$/, '') + '/';
                var itemsRaw = tokens.join(',');
                var itemsEncoded = window.btoa(unescape(encodeURIComponent(itemsRaw)))
                    .replace(/\+/g, '-')
                    .replace(/\//g, '_')
                    .replace(/=+$/, '');
                var finalUrl = normalizedBase + itemsEncoded + '/auswahl/';
                if (window.nnaxFmAjax && nnaxFmAjax.zip_download_nonce) {
                    finalUrl += '?nnaxfuf_zip_nonce=' + encodeURIComponent(String(nnaxFmAjax.zip_download_nonce));
                }
                return finalUrl;
            } catch (e) {
                return '#';
            }
        }

        // Single source of truth to keep all bulk UI parts in sync.
        function updateBulkUI() {
            var tokens = getSelectedTokens();
            var count = tokens.length;
            var moveHasPermissionIssues = hasNonMovableSelection();
            var deleteHasPermissionIssues = hasNonDeletableSelection();
            var moveAllowed = count > 0 && !moveHasPermissionIssues;
            var moveBlockedReason = '';
            if (count === 0) {
                moveBlockedReason = t('bulk_move_select_items', 'Select at least one item.');
            } else if (moveHasPermissionIssues) {
                moveBlockedReason = t('bulk_move_requires_permission', 'Selection contains items you cannot move.');
            }

            $actionsBtn.prop('disabled', false).text(t('bulk_actions', 'Bulk actions') + ' (' + count + ')');
            if ($moveBtn.length) {
                $moveBtn
                    .toggleClass('uk-disabled', !moveAllowed)
                    .attr('aria-disabled', moveAllowed ? 'false' : 'true')
                    .attr('title', moveAllowed ? '' : moveBlockedReason);
            }
            if ($moveItems.length) {
                $moveItems.val(moveAllowed ? tokens.join(',') : '');
            }
            if ($moveCount.length) {
                $moveCount.text(String(count));
            }
            var deleteAllowed = count > 0 && !deleteHasPermissionIssues;
            if ($deleteBtn.length) {
                $deleteBtn
                    .prop('disabled', !deleteAllowed)
                    .toggleClass('uk-disabled', !deleteAllowed)
                    .attr('aria-disabled', deleteAllowed ? 'false' : 'true');
            }
            if ($deleteRecursiveBtn.length) {
                $deleteRecursiveBtn
                    .prop('disabled', !deleteAllowed)
                    .toggleClass('uk-disabled', !deleteAllowed)
                    .attr('aria-disabled', deleteAllowed ? 'false' : 'true');
            }
            if ($deleteItems.length) {
                $deleteItems.val(deleteAllowed ? tokens.join(',') : '');
            }
            if ($deleteRecursiveItems.length) {
                $deleteRecursiveItems.val(deleteAllowed ? tokens.join(',') : '');
            }

            if (count > 0) {
                $zipLink.attr('href', buildZipUrl(tokens)).removeClass('uk-disabled').attr('aria-disabled', 'false');
            } else {
                $zipLink.attr('href', '#').addClass('uk-disabled').attr('aria-disabled', 'true');
            }

            if ($selectAll.length) {
                $selectAll.prop('checked', count > 0 && count === $itemChecks.length);
            }
        }

        // Master checkbox toggles all row checkboxes.
        if ($selectAll.length) {
            $selectAll.on('change', function () {
                var checked = $(this).is(':checked');
                $itemChecks.prop('checked', checked);
                updateBulkUI();
            });
        }

        if ($itemChecks.length) {
            $itemChecks.on('change', updateBulkUI);
        }

        // Prevent dead-link navigation when nothing is selected.
        $zipLink.on('click', function (e) {
            if ($(this).hasClass('uk-disabled')) {
                e.preventDefault();
            }
        });

        // Client-side guard + confirm before destructive operation.
        $moveForm.on('submit', function (e) {
            var tokens = getSelectedTokens();
            if (!tokens.length || hasNonMovableSelection()) {
                e.preventDefault();
                return;
            }
            if ($moveItems.length) {
                $moveItems.val(tokens.join(','));
            }
        });

        $moveBtn.on('click', function (e) {
            if ($(this).hasClass('uk-disabled') || $(this).attr('aria-disabled') === 'true') {
                e.preventDefault();
            }
        });

        // Client-side guard + confirm before destructive operation.
        $deleteForm.on('submit', function (e) {
            var tokens = getSelectedTokens();
            if (!tokens.length || hasNonDeletableSelection()) {
                e.preventDefault();
                return;
            }

            e.preventDefault();
            var form = this;
            confirmWithUIKit(t('bulk_delete_confirm', 'Delete selected items?'), function () {
                form.submit();
            });
        });

        // Separate confirmation text for recursive delete to communicate impact clearly.
        $deleteRecursiveForm.on('submit', function (e) {
            var tokens = getSelectedTokens();
            if (!tokens.length || hasNonDeletableSelection()) {
                e.preventDefault();
                return;
            }

            e.preventDefault();
            var form = this;
            confirmWithUIKit(t('bulk_delete_recursive_confirm', 'Delete selected items recursively (including subfolders)?'), function () {
                form.submit();
            });
        });

        updateBulkUI();
    });
})(window, window.jQuery);
