(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 $uploadModal = $('#nnaxfuf-upload-modal');
        var $uploadInput = $('#nnaxfuf_files');
        var $uploadList = $('#nnaxfuf-upload-file-list');

        function renderUploadFileList(files) {
            $uploadList.empty();

            if (!files || !files.length) {
                $uploadList.append($('<li>').addClass('uk-text-muted').text(t('upload_list_empty', 'No files selected yet.')));
                return;
            }

            Array.prototype.forEach.call(files, function (file) {
                var sizeKB = file.size / 1024;
                var sizeStr = sizeKB >= 1024 ? (sizeKB / 1024).toFixed(2) + ' MB' : sizeKB.toFixed(1) + ' KB';

                $uploadList.append($('<li>').append($('<strong>').text(file.name), $('<span>').text(' – ' + sizeStr)));
            });
        }

        if ($uploadInput.length && $uploadList.length) {
            renderUploadFileList([]);

            $uploadInput.on('change', function () {
                renderUploadFileList(this.files || []);
            });
        }

        if ($uploadModal.length && window.UIkit && UIkit.util) {
            UIkit.util.on($uploadModal[0], 'hidden', function () {
                if ($uploadInput.length) {
                    $uploadInput.val('');
                }
                renderUploadFileList([]);
            });
        }
    });
})(window, window.jQuery);
