/**
 * KooKoa Folders — Export / Import / Upload Folder
 *
 * Extracted from admin.js (block 7).
 * IIFE that adds methods directly to FO (window.KookoaWPF).
 *
 * Depends on: kookoawpf-admin (FO.data, FO.ajax, FO.showNotice, FO.refreshTree)
 *
 * @since 1.0.0
 */
(function($) {
    'use strict';

    const FO = window.KookoaWPF;
    if (!FO) return;

    // ========================
    // Export / Import
    // ========================

    FO.initExportImport = function() {
        const self = this;

        // Export/Import parent item — swallow the click so the dropdown stays
        // open while the user moves the cursor into the submenu.
        $(document).on('click', '[data-action="export-import"]', function(e) {
            e.preventDefault();
        });
        // Export/Import from "More" dropdown submenu
        $(document).on('click', '#kookoawpf-more-export', function(e) {
            e.preventDefault();
            if ($(this).hasClass('kookoawpf-ui-disabled')) return;
            $('#kookoawpf-more-dropdown').hide();
            self.exportFolders();
        });
        $(document).on('click', '#kookoawpf-more-import', function(e) {
            e.preventDefault();
            $('#kookoawpf-more-dropdown').hide();
            $('#kookoawpf-import-file').val('').trigger('click');
        });

        // Upload Folder from "More" dropdown
        if (!$('#kookoawpf-upload-folder-input').length) {
            $('body').append('<input type="file" id="kookoawpf-upload-folder-input" webkitdirectory directory multiple style="display:none;">');
        }
        $(document).on('click', '#kookoawpf-more-upload-folder', function(e) {
            e.preventDefault();
            $('#kookoawpf-more-dropdown').hide();
            $('#kookoawpf-upload-folder-input').val('').trigger('click');
        });
        $(document).on('change', '#kookoawpf-upload-folder-input', function() {
            const files = this.files;
            if (!files || !files.length) return;

            // Filter out hidden/system files
            const validFiles = [];
            for (let i = 0; i < files.length; i++) {
                const f = files[i];
                if (!f.webkitRelativePath) continue;
                const name = f.name;
                if (name.charAt(0) === '.' || name === 'Thumbs.db' || name === 'desktop.ini') continue;
                validFiles.push(f);
            }

            if (!validFiles.length) {
                self.showNotice(self.data.strings.uploadNoValidFiles, 'error');
                return;
            }

            // Parse folder structure
            const folderPaths = {};
            const fileMap = [];

            for (let i = 0; i < validFiles.length; i++) {
                const rel = validFiles[i].webkitRelativePath;
                const parts = rel.split('/');
                parts.pop();
                if (!parts.length) continue;

                for (let d = 1; d <= parts.length; d++) {
                    const path = parts.slice(0, d).join('/');
                    if (!folderPaths[path]) {
                        folderPaths[path] = {
                            name: parts[d - 1],
                            parentPath: d > 1 ? parts.slice(0, d - 1).join('/') : null,
                            termId: null
                        };
                    }
                }
                fileMap.push({ file: validFiles[i], folderPath: parts.join('/') });
            }

            const sortedPaths = Object.keys(folderPaths).sort(function(a, b) {
                return a.split('/').length - b.split('/').length;
            });

            if (!sortedPaths.length && !fileMap.length) {
                self.showNotice(self.data.strings.uploadNoFilesOrFolders, 'error');
                return;
            }

            // Single persistent progress notice — updated in-place
            const $progressNotice = $('<div class="kookoawpf-notice kookoawpf-notice-success" style="position:fixed;top:32px;right:20px;z-index:200003;min-width:300px;"></div>');
            $progressNotice.text(
                self.data.strings.uploadStarting
                    .replace('%1$s', String(sortedPaths.length))
                    .replace('%2$s', String(fileMap.length))
            );
            $('body').append($progressNotice);

            FO._suppressUploadNotice = true;

            function updateProgress(text) {
                $progressNotice.text(text);
            }

            function createFolders(index) {
                if (index >= sortedPaths.length) {
                    uploadFiles(0);
                    return;
                }
                const path = sortedPaths[index];
                const info = folderPaths[path];
                let parentId = 0;
                if (info.parentPath && folderPaths[info.parentPath]) {
                    parentId = folderPaths[info.parentPath].termId || 0;
                }
                updateProgress(
                    self.data.strings.uploadCreatingFolders
                        .replace('%1$s', String(index + 1))
                        .replace('%2$s', String(sortedPaths.length))
                        .replace('%3$s', String(info.name))
                );

                self.ajax('kookoawpf_create_folder', {
                    name: info.name,
                    post_type: 'attachment',
                    parent_id: parentId
                }, function(r) {
                    if (r.success && r.data && r.data.term_id) {
                        info.termId = r.data.term_id;
                    }
                    createFolders(index + 1);
                });
            }

            function uploadFiles(index) {
                if (index >= fileMap.length) {
                    $progressNotice.remove();
                    self.showNotice(
                        self.data.strings.uploadDone
                            .replace('%1$s', String(sortedPaths.length))
                            .replace('%2$s', String(fileMap.length)),
                        'success'
                    );
                    self.refreshTree();
                    // Delay flag reset — last XHR load listener fires async after this callback
                    setTimeout(function() { FO._suppressUploadNotice = false; }, 2000);
                    return;
                }
                const item = fileMap[index];
                let folderId = 0;
                if (item.folderPath && folderPaths[item.folderPath]) {
                    folderId = folderPaths[item.folderPath].termId || 0;
                }
                updateProgress(
                    self.data.strings.uploadingFiles
                        .replace('%1$s', String(index + 1))
                        .replace('%2$s', String(fileMap.length))
                        .replace('%3$s', String(item.file.name))
                );

                const fd = new FormData();
                fd.append('action', 'upload-attachment');
                fd.append('_wpnonce', self.data.uploadNonce);
                fd.append('async-upload', item.file);
                if (folderId) {
                    fd.append('kookoawpf_upload_folder', String(folderId));
                }

                $.ajax({
                    url: self.data.ajaxUrl,
                    type: 'POST',
                    data: fd,
                    processData: false,
                    contentType: false,
                    success: function() { uploadFiles(index + 1); },
                    error: function() { uploadFiles(index + 1); }
                });
            }

            createFolders(0);
        });

        // Legacy header button support (kept for backward compat)
        $(document).on('click', '#kookoawpf-btn-export', function() { self.exportFolders(); });
        $(document).on('click', '#kookoawpf-btn-import', function() { $('#kookoawpf-import-file').val('').trigger('click'); });

        $(document).on('change', '#kookoawpf-import-file', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            if (!file.name.endsWith('.json')) { self.showNotice(self.data.strings.invalidFile, 'error'); return; }

            const reader = new FileReader();
            reader.onload = function(ev) {
                let json;
                try { json = JSON.parse(ev.target.result); }
                catch (err) { self.showNotice(self.data.strings.invalidFile, 'error'); return; }

                if (!json.plugin || json.plugin !== 'kookoa-folders' || !json.folders) {
                    self.showNotice(self.data.strings.invalidFile, 'error');
                    return;
                }

                self._importJsonData = ev.target.result;

                const $info = $('<div>');
                $info.append($('<strong>').text(file.name)).append('<br>');
                if (json.exported_at) $info.append($('<span>').text(self.data.strings.importPreviewExported + ' ' + json.exported_at)).append('<br>');
                if (json.site_url) $info.append($('<span>').text(self.data.strings.importPreviewFrom + ' ' + json.site_url)).append('<br>');
                if (json.version) $info.append($('<span>').text(self.data.strings.importPreviewVersion.replace('%s', String(json.version))));
                $('#kookoawpf-import-info').html('').append($info.contents());

                const $preview = $('<div>');
                $.each(json.folders, function(pt, tree) {
                    $preview.append($('<div style="color:#39FF14;margin-bottom:4px;">').text('📂 ' + pt));
                    $preview.append(self._renderImportPreview(tree, 1));
                });
                $('#kookoawpf-import-preview').html('').append($preview.contents()).show();
                $('input[name="kookoawpf_import_mode"][value="merge"]').prop('checked', true);
                $('#kookoawpf-modal-import').show();
            };
            reader.readAsText(file);
        });

        $(document).on('change', 'input[name="kookoawpf_import_mode"]', function() {
            const isReplace = $(this).val() === 'replace';
            const desc = isReplace
                ? self.data.strings.importModeReplaceDesc
                : self.data.strings.importModeMergeDesc;
            $('#kookoawpf-import-mode-desc').text(desc).css('color', isReplace ? '#FF3B30' : '#39FF14');
        });

        $(document).on('click', '#kookoawpf-confirm-import', function() {
            self.importFolders($('input[name="kookoawpf_import_mode"]:checked').val());
        });
    };

    FO._renderImportPreview = function(tree, depth) {
        const $frag = $('<div>');
        let indent = '';
        for (let i = 0; i < depth; i++) indent += '\u00A0\u00A0';
        if (!Array.isArray(tree)) return $frag;

        for (let j = 0; j < tree.length; j++) {
            const node = tree[j];
            const $row = $('<div>');
            $row.append(document.createTextNode(indent));
            if (node.color && /^#[0-9a-fA-F]{3,8}$/.test(node.color)) {
                $row.append($('<span>').css('color', node.color).text('●')).append(' ');
            }
            let badges = '';
            if (node.pinned) badges += ' ⭐';
            if (node.locked) badges += ' 🔒';
            $row.append(document.createTextNode((node.name || '') + badges));
            $frag.append($row);
            if (node.children && node.children.length) {
                $frag.append(this._renderImportPreview(node.children, depth + 1));
            }
        }
        return $frag;
    };

    FO.exportFolders = function() {
        const self = this;
        self.ajax('kookoawpf_export_folders', { post_type: self.data.postType, scope: 'all' }, function(r) {
            if (!r.success) { self.showNotice((r.data && r.data.message) || self.data.strings.errorGeneric, 'error'); return; }

            const json = JSON.stringify(r.data.json, null, 2);
            const blob = new Blob([json], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'kookoa-folders-' + new Date().toISOString().slice(0, 10) + '.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            self.showNotice(self.data.strings.exportSuccess, 'success');
        });
    };

    FO.importFolders = function(mode) {
        const self = this;
        if (!self._importJsonData) return;

        $('#kookoawpf-confirm-import').addClass('kookoawpf-btn-loading').css('pointer-events', 'none').text(self.data.strings.importing);
        self.ajax('kookoawpf_import_folders', { json_data: self._importJsonData, mode: mode || 'merge' }, function(r) {
            $('#kookoawpf-confirm-import').removeClass('kookoawpf-btn-loading').css('pointer-events', '').text(self.data.strings.importButtonIdle);
            $('#kookoawpf-modal-import').hide();
            if (r.success) { self.showNotice((r.data && r.data.message) || self.data.strings.importSuccess, 'success'); self.refreshTree(); }
            else { self.showNotice((r.data && r.data.message) || self.data.strings.errorGeneric, 'error'); }
            self._importJsonData = null;
        });
    };

})(jQuery);
