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

    window.NUFMDetail = window.NUFMDetail || {};

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

        function escapeHtml(value) {
            return $('<div>').text(String(value || '')).html();
        }

        function openDetailModalForItem(itemId) {
            if (!itemId) return;

            var detailsRequest;
            applyDetailModalData({
                item_id: itemId,
                title: t('loading', 'Loading...'),
                rename_value: t('loading', 'Loading...'),
                locked_extension: '',
                owner: t('loading', 'Loading...'),
                shared: t('loading', 'Loading...'),
                date: t('loading', 'Loading...'),
                modified: t('loading', 'Loading...'),
                download_url: '#',
                type: 'generic',
                is_folder: false,
                folder_file_count: '0',
                folder_file_count_recursive: '0',
                folder_subfolder_count: '0',
                folder_size_human: '–',
                mime_type: '–',
                size_human: '–',
                custom_meta_fields: [],
                can_share: false,
                can_rename: false,
                can_view_history: false
            });

            detailsRequest = fetchAndApplyItemDetails(itemId);
            if (detailsRequest && typeof detailsRequest.done === 'function') {
                detailsRequest.done(function (response) {
                    if (response && response.success && response.data && response.data.can_view_history) {
                        loadHistory(itemId);
                    }
                });
            }
        }

        function applyDetailModalData(detail) {
            const itemId = detail.item_id || '';
            const title = detail.title || '–';
            const renameValue = detail.rename_value || title;
            const lockedExtension = detail.locked_extension || '';
            const owner = detail.owner || '–';
            const shared = detail.shared || '–';
            const date = detail.date || '–';
            const modified = detail.modified || '–';
            const downloadUrl = detail.download_url || '#';
            const type = detail.type || '';
            const isFolder = Boolean(detail.is_folder) || type === 'folder';
            const fileCount = String(detail.folder_file_count || '0');
            const fileCountRecursive = String(detail.folder_file_count_recursive || '0');
            const folderSubfolderCount = String(detail.folder_subfolder_count || '0');
            const folderSizeHuman = detail.folder_size_human || '–';
            const mimeType = detail.mime_type || '–';
            const sizeHuman = detail.size_human || '–';
            const customMetaFields = Array.isArray(detail.custom_meta_fields) ? detail.custom_meta_fields : [];
            const canShare = Boolean(detail.can_share);
            const canRename = (typeof detail.can_rename === 'boolean') ? detail.can_rename : true;
            const canViewHistory = Boolean(detail.can_view_history);
            const inlineUrl = detail.inline_download_url || downloadUrl;

            const ownerEl = document.getElementById('nnaxfuf_detail_owner');
            const sharedEl = document.getElementById('nnaxfuf_detail_shared');
            const dateEl = document.getElementById('nnaxfuf_detail_date');
            const modifiedEl = document.getElementById('nnaxfuf_detail_modified');
            const urlEl = document.getElementById('nnaxfuf_detail_url');
            const typeEl = document.getElementById('nnaxfuf_detail_type');
            const mimeEl = document.getElementById('nnaxfuf_detail_mime');
            const sizeEl = document.getElementById('nnaxfuf_detail_size');
            const previewEl = document.getElementById('nnaxfuf_detail_preview');
            const previewWrapEl = document.querySelector('.nnaxfuf-detail-preview-wrap');
            const folderCountEl = document.getElementById('nnaxfuf_detail_folder_file_count');
            const folderCountRecursiveEl = document.getElementById('nnaxfuf_detail_folder_file_count_recursive');
            const folderSubfolderCountEl = document.getElementById('nnaxfuf_detail_folder_subfolder_count');
            const folderSizeEl = document.getElementById('nnaxfuf_detail_folder_size');
            const fileOnlyEls = document.querySelectorAll('.nnaxfuf-detail-file-only');
            const folderOnlyEls = document.querySelectorAll('.nnaxfuf-detail-folder-only');
            const ownerOnlyEls = document.querySelectorAll('.nnaxfuf-detail-owner-only');
            const historyOnlyEls = document.querySelectorAll('.nnaxfuf-detail-history-only');
            const shareBtnEl = document.getElementById('nnaxfuf_detail_share_btn');
            const downloadBtnEl = document.getElementById('nnaxfuf_detail_download_btn');
            const saveBtnEl = document.getElementById('nnaxfuf_save_detail_title');
            const extensionHintEl = document.getElementById('nnaxfuf_detail_extension_hint');
            const customMetaFieldsEl = document.getElementById('nnaxfuf_detail_custom_meta_fields');

            if (ownerEl) ownerEl.textContent = owner;
            if (sharedEl) sharedEl.textContent = shared;
            if (dateEl) dateEl.textContent = date;
            if (modifiedEl) modifiedEl.textContent = modified;
            if (folderCountEl) folderCountEl.textContent = fileCount;
            if (folderCountRecursiveEl) folderCountRecursiveEl.textContent = fileCountRecursive;
            if (folderSubfolderCountEl) folderSubfolderCountEl.textContent = folderSubfolderCount;
            if (folderSizeEl) folderSizeEl.textContent = folderSizeHuman;
            if (mimeEl) mimeEl.textContent = mimeType;
            if (sizeEl) sizeEl.textContent = sizeHuman;

            fileOnlyEls.forEach(function (el) { el.hidden = isFolder; });
            folderOnlyEls.forEach(function (el) { el.hidden = !isFolder; });
            ownerOnlyEls.forEach(function (el) { el.hidden = !canShare; });
            historyOnlyEls.forEach(function (el) { el.hidden = !canViewHistory; });
            if (previewWrapEl) previewWrapEl.hidden = isFolder;

            if (!canViewHistory && window.UIkit && typeof window.UIkit.tab === 'function') {
                var tabsEl = document.getElementById('nnaxfuf_detail_tabs');
                if (tabsEl) {
                    var tabInstance = window.UIkit.tab(tabsEl);
                    if (tabInstance && typeof tabInstance.show === 'function') {
                        tabInstance.show(0);
                    }
                }
            }

            if (urlEl) {
                if (isFolder) {
                    urlEl.textContent = '–';
                    urlEl.removeAttribute('href');
                } else {
                    urlEl.textContent = downloadUrl;
                    urlEl.href = downloadUrl;
                }
            }

            if (typeEl) typeEl.textContent = isFolder ? t('folder_label', 'Folder') : String(type).toUpperCase();

            if (downloadBtnEl) {
                const hasDownload = Boolean(downloadUrl && downloadUrl !== '#');
                downloadBtnEl.hidden = !isFolder || !hasDownload;
                downloadBtnEl.setAttribute('href', (isFolder && hasDownload) ? downloadUrl : '#');
            }

            if (shareBtnEl) {
                shareBtnEl.hidden = !canShare;
                if (canShare) {
                    shareBtnEl.setAttribute('data-nnaxfuf-item-type', isFolder ? 'folder' : 'file');
                    shareBtnEl.setAttribute('data-nnaxfuf-item-title', title);
                    if (isFolder) {
                        shareBtnEl.setAttribute('data-nnaxfuf-folder-id', itemId);
                        shareBtnEl.removeAttribute('data-nnaxfuf-file-id');
                    } else {
                        shareBtnEl.setAttribute('data-nnaxfuf-file-id', itemId);
                        shareBtnEl.removeAttribute('data-nnaxfuf-folder-id');
                    }
                }
            }

            const $titleInput = $('#nnaxfuf_detail_title_input');
            if ($titleInput.length) {
                $titleInput.val(renameValue).prop('disabled', !canRename).data('item-id', itemId).data('locked-ext', lockedExtension);
            }
            if (saveBtnEl) {
                saveBtnEl.hidden = !canRename;
                saveBtnEl.disabled = !canRename;
            }
            if (extensionHintEl) {
                if (!isFolder && lockedExtension) {
                    extensionHintEl.textContent = t('fixed_extension', 'File extension is fixed:') + ' .' + lockedExtension;
                    extensionHintEl.hidden = false;
                } else {
                    extensionHintEl.textContent = '';
                    extensionHintEl.hidden = true;
                }
            }
 
            if (customMetaFieldsEl) {
                customMetaFieldsEl.innerHTML = '';
                if (!isFolder && !customMetaFields.length) {
                    customMetaFieldsEl.innerHTML = '<p class="uk-text-muted uk-text-small uk-margin-remove">' + t('no_meta_fields_configured', 'No meta fields configured.') + '</p>';
                } else if (!isFolder) {
                    customMetaFields.forEach(function (field) {
                        if (!field || !field.key || !field.label) return;

                        var metaType = (field.type || 'text').toString();
                        var metaValue = (typeof field.value === 'string') ? field.value : '';
                        var row = document.createElement('div');
                        row.className = 'uk-margin-small';

                        var label = document.createElement('label');
                        label.className = 'uk-form-label uk-text-small';
                        label.textContent = field.label;

                        var controls = document.createElement('div');
                        controls.className = 'uk-form-controls';

                        var inputEl;
                        if (metaType === 'textarea') {
                            inputEl = document.createElement('textarea');
                            inputEl.className = 'uk-textarea uk-form-small';
                            inputEl.rows = 2;
                            inputEl.value = metaValue;
                        } else {
                            inputEl = document.createElement('input');
                            inputEl.className = 'uk-input uk-form-small';
                            inputEl.type = ['text', 'date', 'number', 'email', 'url'].indexOf(metaType) !== -1 ? metaType : 'text';
                            inputEl.value = metaValue;
                        }

                        inputEl.setAttribute('data-nnaxfuf-meta-key', field.key);
                        inputEl.disabled = !canRename;

                        controls.appendChild(inputEl);
                        row.appendChild(label);
                        row.appendChild(controls);
                        customMetaFieldsEl.appendChild(row);
                    });
                }
            }

            if (previewEl) {
                if (isFolder) {
                    previewEl.innerHTML = '';
                    return;
                }

                var isMobileViewport = window.matchMedia && window.matchMedia('(max-width: 959px)').matches;
                var html = '';
                if (type === 'image') {
                    html = '<img src="' + inlineUrl + '" alt="' + t('image_preview_alt', 'File preview') + '" style="max-width:100%;height:auto;">';
                } else if (type === 'pdf') {
                    if (isMobileViewport) {
                        html = '<p class="uk-text-muted">' + t('no_preview_for_type', 'No preview available for this file type.') + '</p>' +
                            '<p><a class="uk-button uk-button-default uk-button-small" href="' + downloadUrl + '" target="_blank" rel="noopener noreferrer">' +
                            '<span uk-icon="icon: download"></span><span class="uk-margin-small-left">' + t('download', 'Download') + '</span></a></p>';
                    } else {
                        html = '<iframe src="' + inlineUrl + '" style="width:100%;height:60vh;border:0;" title="' + t('pdf_preview_title', 'PDF preview') + '"></iframe>';
                    }
                } else {
                    html = '<p class="uk-text-muted">' + t('no_preview_for_type', 'No preview available for this file type.') + '</p>' +
                        '<p><a class="uk-button uk-button-default uk-button-small" href="' + downloadUrl + '" target="_blank" rel="noopener noreferrer">' +
                        '<span uk-icon="icon: download"></span><span class="uk-margin-small-left">' + t('download', 'Download') + '</span></a></p>';
                }
                previewEl.innerHTML = html;
            }
        }

        function fetchAndApplyItemDetails(itemId) {
            return $.ajax({
                url: nnaxFmAjax.ajax_url,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'nnaxfuf_get_item_details',
                    nonce: nnaxFmAjax.item_details_nonce || nnaxFmAjax.nonce,
                    item_id: itemId
                }
            }).done(function (response) {
                if (response && response.success && response.data) {
                    applyDetailModalData(response.data);
                } else {
                    UIkit.notification({ message: t('details_load_failed', 'Details could not be loaded.'), status: 'warning' });
                }
            }).fail(function () {
                UIkit.notification({ message: t('network_error_details', 'Network error while loading details.'), status: 'danger' });
            });
        }

        document.addEventListener('click', function (event) {
            const btn = event.target.closest('.nnaxfuf-open-detail-modal');
            if (!btn) return;

            const itemId = btn.getAttribute('data-nnaxfuf-item-id') || '';
            if (!itemId) return;
            openDetailModalForItem(itemId);
        });

        function loadHistory(itemId) {
            var $container = $('#nnaxfuf_detail_history');
            $container.html('<p class="uk-text-muted uk-text-small"><span uk-spinner="ratio: 0.5"></span> ' + t('loading_history', 'Loading history...') + '</p>');

            $.ajax({
                url: nnaxFmAjax.ajax_url,
                type: 'POST',
                data: {
                    action: 'nnaxfuf_get_history',
                    nonce: nnaxFmAjax.item_details_nonce || nnaxFmAjax.nonce,
                    item_id: itemId
                }
            }).done(function (response) {
                    if (response.success) {
                        $container.empty();
                        if (response.data.length === 0) {
                            $container.html('<p class="uk-text-muted uk-text-small">' + t('no_history', 'No activity recorded.') + '</p>');
                        } else {
                            var $list = $('<ul class="uk-list uk-list-bullet uk-text-small">');
                            response.data.forEach(function (log) {
                                var actionText = '<strong>' + log.user + '</strong> ' + log.action;
                                var detailText = (log.details || '').toString().trim();
                                if (detailText) {
                                    actionText += '<br><span class="uk-text-muted uk-text-meta">' + detailText + '</span>';
                                }
                                actionText += ' <span class="uk-text-muted uk-text-meta">(' + log.date + ')</span>';
                                $list.append($('<li>').html(actionText));
                            });
                            $container.append($list);
                        }
                    }
            });
        }

        $(document).on('click', '#nnaxfuf_save_detail_title', function () {
            var $btn = $(this);
            var $input = $('#nnaxfuf_detail_title_input');
            var itemId = $input.data('item-id');
            var newName = $input.val().trim();
            var lockedExt = ($input.data('locked-ext') || '').toString().trim().toLowerCase();
            var customMeta = {};

            if (lockedExt) {
                newName = newName.replace(/\.[^.]+$/, '').trim();
                $input.val(newName);
            }

            if (!itemId) {
                UIkit.notification({ message: t('error_missing_item_id', 'Error: No item ID found.'), status: 'danger' });
                return;
            }
            if (!newName) {
                UIkit.notification({ message: t('please_enter_name', 'Please enter a name.'), status: 'warning' });
                return;
            }

            $('#nnaxfuf_detail_custom_meta_fields').find('[data-nnaxfuf-meta-key]').each(function () {
                var metaKey = ($(this).attr('data-nnaxfuf-meta-key') || '').toString();
                if (!metaKey) return;
                customMeta[metaKey] = $(this).val();
            });

            $btn.prop('disabled', true).text(t('saving', 'Saving...'));

            $.ajax({
                url: nnaxFmAjax.ajax_url,
                type: 'POST',
                data: {
                    action: 'nnaxfuf_rename_item',
                    rename_nonce: nnaxFmAjax.rename_nonce || nnaxFmAjax.item_details_nonce || nnaxFmAjax.nonce,
                    item_id: itemId,
                    new_name: newName,
                    custom_meta: customMeta
                }
            }).done(function (response) {
                if (response.success) {
                    UIkit.notification({ message: response.data.message, status: 'success' });
                    UIkit.modal('#nnaxfuf-detail-modal').hide();
                    location.reload();
                } else {
                    UIkit.notification({ message: response.data.message, status: 'danger' });
                }
            }).fail(function () {
                UIkit.notification({ message: t('network_error_save', 'Network error while saving.'), status: 'danger' });
            }).always(function () {
                $btn.prop('disabled', false).text(t('save_changes', 'Save changes'));
            });
        });

        window.NUFMDetail.openDetailModalForItem = openDetailModalForItem;
        window.NUFMDetail.fetchAndApplyItemDetails = fetchAndApplyItemDetails;
        window.NUFMDetail.loadHistory = loadHistory;
        window.NUFMDetail.applyDetailModalData = applyDetailModalData;
    });
})(window, window.jQuery);
