(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;
        }

        var previewStorageKey = 'nnaxfuf_show_thumbnails';
        var $container = $('#nnaxfuf-file-manager-container');
        var $toggle = $('#nnaxfuf-toggle-previews');
        var $label = $('[data-nnaxfuf-preview-label]');

        function syncPreviewUi(isEnabled) {
            if (!$toggle.length) {
                return;
            }

            if ($toggle.is(':checkbox')) {
                $toggle.prop('checked', isEnabled);
            } else {
                $toggle.attr('aria-pressed', isEnabled ? 'true' : 'false');
            }

            if ($label.length) {
                $label.text(isEnabled ? t('preview_hide', 'Hide image preview') : t('preview_show', 'Show image preview'));
            }
        }

        function setPreviewState(isEnabled) {
            $container.toggleClass('nnaxfuf-show-previews', isEnabled);
            localStorage.setItem(previewStorageKey, isEnabled ? '1' : '0');
            syncPreviewUi(isEnabled);
        }

        if (localStorage.getItem(previewStorageKey) === '1') {
            setPreviewState(true);
        } else {
            syncPreviewUi(false);
        }

        $toggle.on('change click', function (e) {
            if (!$toggle.is(':checkbox')) {
                e.preventDefault();
            }

            var nextState = $toggle.is(':checkbox')
                ? $(this).is(':checked')
                : !$container.hasClass('nnaxfuf-show-previews');

            setPreviewState(nextState);
        });
    });
})(window, window.jQuery);
