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

    window.NUFM = window.NUFM || {};
    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;
    }

    function escapeHtml(value) {
        return String(value).replace(/[&<>"']/g, function (char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#39;'
            }[char] || char;
        });
    }

    function confirmWithUIKit(message, onConfirm, options) {
        var opts = options || {};
        var cancelLabel = (opts.cancelLabel || t('confirm_cancel', 'Cancel')).toString();
        var confirmLabel = (opts.confirmLabel || t('confirm_ok', 'Confirm')).toString();
        var cancelClass = (opts.cancelClass || 'uk-button uk-button-default uk-modal-close').toString();
        var confirmClass = (opts.confirmClass || 'uk-button uk-button-danger').toString();

        if (window.UIkit && UIkit.modal && typeof UIkit.modal.dialog === 'function') {
            var modal = UIkit.modal.dialog(
                '<div class="uk-modal-body">' +
                    '<p class="uk-margin-remove">' + escapeHtml(message) + '</p>' +
                '</div>' +
                '<div class="uk-modal-footer uk-text-right">' +
                    '<button type="button" class="' + escapeHtml(cancelClass) + '">' + escapeHtml(cancelLabel) + '</button> ' +
                    '<button type="button" class="' + escapeHtml(confirmClass) + ' nnaxfuf-confirm-ok">' + escapeHtml(confirmLabel) + '</button>' +
                '</div>'
            );

            if (modal && modal.$el) {
                modal.$el.classList.add('nnaxfuf-modal');
                var confirmBtn = modal.$el.querySelector('.nnaxfuf-confirm-ok');
                if (confirmBtn) {
                    confirmBtn.addEventListener('click', function () {
                        modal.hide();
                        onConfirm();
                    });
                }
            }
            if (modal && typeof modal.show === 'function') {
                modal.show();
            }
            return;
        }

        if (window.confirm(message)) {
            onConfirm();
        }
    }

    function closeOpenDropdowns() {
        if (window.UIkit && typeof window.UIkit.dropdown === 'function') {
            document.querySelectorAll('.uk-dropdown[uk-dropdown], .uk-dropdown[data-uk-dropdown]').forEach(function (dropdownEl) {
                if (!dropdownEl.classList.contains('uk-open')) {
                    return;
                }

                try {
                    var dropdown = window.UIkit.dropdown(dropdownEl);
                    if (dropdown && typeof dropdown.hide === 'function') {
                        dropdown.hide(false);
                        return;
                    }
                } catch (e) {
                    // Ignore and fall back to class cleanup.
                }

                dropdownEl.classList.remove('uk-open');
            });
        }

        document.querySelectorAll('.nnaxfuf-settings-submenu-item.is-open').forEach(function (item) {
            item.classList.remove('is-open');
        });
        document.querySelectorAll('.nnaxfuf-settings-submenu').forEach(function (submenu) {
            submenu.hidden = true;
        });
    }

    window.NUFM.confirmWithUIKit = confirmWithUIKit;

    $(function () {
        if (window.history && window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }

        $(document).on('submit', 'form.nnaxfuf-confirm-submit', function (e) {
            var message = ($(this).data('nnaxfuf-confirm-message') || '').toString().trim();
            if (!message) {
                return;
            }

            e.preventDefault();
            var form = this;
            var cancelLabel = ($(this).data('nnaxfuf-confirm-cancel-label') || t('confirm_cancel', 'Cancel')).toString();
            var confirmLabel = ($(this).data('nnaxfuf-confirm-ok-label') || t('confirm_delete', 'Delete')).toString();
            var cancelClass = ($(this).data('nnaxfuf-confirm-cancel-class') || 'uk-button uk-button-default uk-modal-close').toString();
            var confirmClass = ($(this).data('nnaxfuf-confirm-ok-class') || 'uk-button uk-button-danger').toString();

            confirmWithUIKit(message, function () {
                form.submit();
            }, {
                cancelLabel: cancelLabel,
                confirmLabel: confirmLabel,
                cancelClass: cancelClass,
                confirmClass: confirmClass
            });
        });

        $(document).on('beforeshow', '.uk-modal', function () {
            closeOpenDropdowns();
        });

        $(document).on('click', '.nnaxfuf-search-toggle', function (e) {
            e.preventDefault();

            var $btn = $(this);
            var $wrap = $btn.closest('.nnaxfuf-search-wrap');
            var $panel = $wrap.find('.nnaxfuf-search-panel').first();
            if (!$panel.length) {
                return;
            }

            var isOpen = !$panel.hasClass('uk-hidden');
            if (isOpen) {
                $panel.addClass('uk-hidden');
                $btn.attr('aria-expanded', 'false');
            } else {
                $panel.removeClass('uk-hidden');
                $btn.attr('aria-expanded', 'true');
                var $input = $panel.find('.nnaxfuf-search-input').first();
                if ($input.length) {
                    $input.trigger('focus');
                }
            }
        });

        $(document).on('keydown', '.nnaxfuf-search-input', function (e) {
            if (e.key !== 'Enter') {
                return;
            }

            var value = ($(this).val() || '').toString().trim();
            if (value === '') {
                e.preventDefault();
                return;
            }

            var $form = $(this).closest('form.nnaxfuf-search-form');
            if ($form.length) {
                e.preventDefault();
                $form.trigger('submit');
            }
        });
    });
})(window, window.jQuery);
