/**
 * KooKoa Folders — Settings Page JS
 * Extracted from settings.php inline <script> (blocco 27)
 */
(function($) {
'use strict';

$(document).ready(function() {

    // ── Tab switching ──
    $('.kookoawpf-settings-tab').on('click', function() {
        const tab = $(this).data('tab');
        if (!tab) return; // external/non-tab link — let default browser behavior run
        $('.kookoawpf-settings-tab').removeClass('active');
        $(this).addClass('active');
        $('.kookoawpf-tab-panel').hide().removeClass('active');
        $('.kookoawpf-tab-panel[data-panel="' + tab + '"]').show().addClass('active');
    });

    // ── Deep link: ?tab=… opens the matching tab on page load (used by
    // the sidebar "FileBird detected" hint to land directly on the
    // Migrate section). The anchor #kookoawpf-migrate-section is then
    // scrolled into view manually because the browser fired its native
    // jump before the tab was made visible.
    (function deepLinkOpenTab() {
        const params = new URLSearchParams(window.location.search);
        const tab    = params.get('tab');
        if (tab) {
            const $tab = $('.kookoawpf-settings-tab[data-tab="' + tab + '"]');
            if ($tab.length) {
                $tab.trigger('click');
            }
        }
        if (window.location.hash) {
            const $target = $(window.location.hash);
            if ($target.length) {
                setTimeout(function() {
                    $target[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
                }, 50);
            }
        }
    })();

    // ── Number spinner buttons (sidebar width) ──
    $('#kookoawpf-settings-width-row').on('click', '.kookoawpf-number-spinner-btn', function(e) {
        e.preventDefault();
        const $input = $(this).closest('.kookoawpf-number-spinner').find('input');
        let val = parseInt($input.val()) || 300;
        const min = parseInt($input.attr('min')) || 300;
        const max = parseInt($input.attr('max')) || 600;
        const step = parseInt($input.attr('step')) || 10;
        if ($(this).data('dir') === 'up') {
            val = Math.min(val + step, max);
        } else {
            val = Math.max(val - step, min);
        }
        $input.val(val).trigger('change');
    });

    // ── Sidebar width blur fallback ──
    // Replaces the previous inline onblur handler so we don't have to escape
    // a PHP value into a JS context. min/max/default come from data-* attrs.
    $('#kookoawpf-settings-width-row').on('blur', 'input[name="kookoawpf_width"]', function() {
        const $input = $(this);
        const v   = parseInt($input.val(), 10);
        const min = parseInt($input.attr('min'), 10) || 300;
        const max = parseInt($input.attr('max'), 10) || 600;
        if (isNaN(v) || v < min || v > max) {
            $input.val($input.data('default'));
        }
    });

    // ── Copy/Cut/Paste linked toggles ──
    (function() {
        function getCtx(key) { return $('input[name="kookoawpf_ctx[]"][value="' + key + '"]'); }
        $(document).on('change', 'input[name="kookoawpf_ctx[]"]', function() {
            const key = $(this).val(), on = $(this).is(':checked');
            const $copy = getCtx('copy'), $cut = getCtx('cut'), $paste = getCtx('paste');
            if (key === 'copy' || key === 'cut') {
                if (on) {
                    // Turning on copy or cut → auto-enable paste
                    $paste.prop('checked', true);
                } else {
                    // Turning off → if both copy and cut are off, disable paste
                    if (!$copy.is(':checked') && !$cut.is(':checked')) {
                        $paste.prop('checked', false);
                    }
                }
            }
            if (key === 'paste') {
                if (!on) {
                    // Turning off paste → disable copy and cut
                    $copy.prop('checked', false);
                    $cut.prop('checked', false);
                } else if (on && !$copy.is(':checked') && !$cut.is(':checked')) {
                    // Turning on paste alone → block it
                    $(this).prop('checked', false);
                }
            }
        });
    })();

    // ── Smart Startup Folder: toggle "Specific folder" dropdowns ──
    $(document).on('change', 'input[name="kookoawpf_startup_mode"]', function() {
        const mode = $('input[name="kookoawpf_startup_mode"]:checked').val();
        $('#kookoawpf-settings-startup-specific').toggle(mode === 'specific');
    });

    // ── EXIF sub-toggle: enable/disable based on master "Media hover info" ──
    $(document).on('change', '#kookoawpf-show-metadata-tooltip', function() {
        const $sub = $('#kookoawpf-show-exif');
        if ($(this).is(':checked')) {
            $sub.prop('disabled', false);
        } else {
            $sub.prop('disabled', true);
        }
    });

    // ── Apply retro dark custom dropdown to Startup Folder selects ──
    if (typeof KookoawpfCustomSelect !== 'undefined' && KookoawpfCustomSelect.replace) {
        $('select.kookoawpf-startup-folder-select').each(function() {
            KookoawpfCustomSelect.replace($(this));
        });
    }

    // ── Shared save function ──
    function saveAllSettings($btn) {
        const postTypes = [];
        // Pick checked checkboxes AND hidden inputs. The FREE fallback in
        // tab-general.php renders Media as <input type="hidden"> when PRO is
        // not loaded; without including hidden here the option saves empty,
        // which used to break Smart Startup Folder "Last opened folder" mode.
        $('input[name="kookoawpf_post_types[]"]:checked, input[name="kookoawpf_post_types[]"][type="hidden"]').each(function() { postTypes.push($(this).val()); });

        const startupFolderIds = {};
        $('select.kookoawpf-startup-folder-select').each(function() {
            const name = $(this).attr('name') || '';
            const m = name.match(/\[([^\]]+)\]/);
            if (m && m[1]) {
                startupFolderIds[m[1]] = $(this).val();
            }
        });

        const data = {
            action: 'kookoawpf_save_settings',
            nonce: kookoawpfData.nonce,
            post_types: postTypes,
            show_count: $('input[name="kookoawpf_show_count"]').is(':checked') ? 'yes' : '',
            show_folder_stats: $('input[name="kookoawpf_show_folder_stats"]').is(':checked') ? 'yes' : '',
            show_breadcrumb: $('input[name="kookoawpf_show_breadcrumb"]').is(':checked') ? 'yes' : '',
            breadcrumb_style: $('input[name="kookoawpf_breadcrumb_style"]:checked').val() || 'default',
            show_subfolder_cards: $('input[name="kookoawpf_show_subfolder_cards"]').is(':checked') ? 'yes' : '',
            show_metadata_tooltip: $('input[name="kookoawpf_show_metadata_tooltip"]').is(':checked') ? 'yes' : '',
            show_exif: $('input[name="kookoawpf_show_exif"]').is(':checked') ? 'yes' : '',
            sidebar_width: $('input[name="kookoawpf_width"]').val(),
            font_size: $('input[name="kookoawpf_font_size"]:checked').val() || 'default',
            default_color: $('input[name="kookoawpf_color"]').val(),
            keep_data: $('input[name="kookoawpf_keep_data"]').is(':checked') ? 'yes' : '',
            force_english: $('input[name="kookoawpf_force_english"]').is(':checked') ? 'yes' : '',
            shortcuts_enabled: $('input[name="kookoawpf_shortcuts_enabled"]').is(':checked') ? 'yes' : '',
            ctx_enabled: (function() {
                const arr = [];
                $('input[name="kookoawpf_ctx[]"]:checked').each(function() { arr.push($(this).val()); });
                return arr;
            })(),
            custom_colors: (function() {
                const arr = [];
                $('input[name="kookoawpf_custom_colors[]"]').each(function() { if ($(this).val()) arr.push($(this).val()); });
                return arr;
            })(),
            icon_blocks_enabled: (function() {
                const arr = [];
                $('input[name="kookoawpf_icon_blocks[]"]:checked').each(function() { arr.push($(this).val()); });
                return arr;
            })(),
            startup_mode: $('input[name="kookoawpf_startup_mode"]:checked').val() || 'all',
            startup_folder_ids: startupFolderIds,
            allowed_roles: (function() {
                const arr = ['administrator'];
                $('input[name="kookoawpf_allowed_roles[]"]:checked').each(function() {
                    const v = $(this).val();
                    if (v !== 'administrator') arr.push(v);
                });
                return arr;
            })()
        };

        // Extension point: companion plugins can mutate `data` to add their own fields
        $(document).trigger('kookoawpf:collectSettings', [data]);

        $.post(kookoawpfData.ajaxUrl, data, function(r) {
            if (r.success) {
                const S = (kookoawpfData && kookoawpfData.strings) || {};
                $btn.text(S.settingsSaved);
                setTimeout(function() { $btn.text(S.saveSettings); }, 2000);
            }
        });
    }

    $('#kookoawpf-save-settings').on('click', function() { saveAllSettings($(this)); });
    $('#kookoawpf-save-rc-settings').on('click', function() { saveAllSettings($(this)); });
    $('#kookoawpf-save-ctx-settings').on('click', function() { saveAllSettings($(this)); });
    $('#kookoawpf-save-ci-settings').on('click', function() { saveAllSettings($(this)); });

    // ── Export from Settings ──
    $('#kookoawpf-settings-export').on('click', function() {
        const $btn = $(this);
        const S = (kookoawpfData && kookoawpfData.strings) || {};
        $btn.addClass('kookoawpf-btn-loading').prop('disabled', true).text(S.exporting);

        $.post(kookoawpfData.ajaxUrl, {
            action: 'kookoawpf_export_folders',
            nonce: kookoawpfData.nonce,
            scope: 'all',
            post_type: ''
        }, function(r) {
            const $icon = $('<span>', {
                'class': 'dashicons dashicons-upload',
                style: 'vertical-align:middle;margin-right:4px;margin-top:-2px;'
            });
            $btn.removeClass('kookoawpf-btn-loading').prop('disabled', false)
                .empty().append($icon).append(document.createTextNode(' ' + S.exportAllFolders));

            if (!r.success) {
                alert(r.data.message || S.exportFailed);
                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');
            const date = new Date().toISOString().slice(0, 10);
            a.href = url;
            a.download = 'kookoa-folders-' + date + '.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        });
    });

    // ── Import from Settings: file select ──
    let settingsImportData = null;

    $('#kookoawpf-settings-import-file').on('change', function(e) {
        const file = e.target.files[0];
        settingsImportData = null;
        $('#kookoawpf-settings-import').prop('disabled', true);
        $('#kookoawpf-settings-import-preview').hide().empty();

        if (!file) return;

        if (!file.name.toLowerCase().endsWith('.json')) {
            alert(kookoawpfData.strings.invalidFile);
            $(this).val('');
            return;
        }

        const reader = new FileReader();
        reader.onload = function(ev) {
            let json;
            try {
                json = JSON.parse(ev.target.result);
            } catch(err) { return; }

            if (!json.plugin || json.plugin !== 'kookoa-folders' || !json.folders) return;

            settingsImportData = ev.target.result;
            $('#kookoawpf-settings-import').prop('disabled', false);

            let html = '';
            const S = (kookoawpfData && kookoawpfData.strings) || {};
            const labelExported = $('<span>').text(S.importPreviewExported).html();
            const labelFrom     = $('<span>').text(S.importPreviewFrom).html();
            if (json.exported_at) html += '<div style="color:#ffffff;margin-bottom:6px;">' + labelExported + ' ' + $('<span>').text(json.exported_at).html() + '</div>';
            if (json.site_url) html += '<div style="color:#ffffff;margin-bottom:8px;">' + labelFrom + ' ' + $('<span>').text(json.site_url).html() + '</div>';
            $.each(json.folders, function(pt, tree) {
                html += '<div style="color:#39FF14;margin-bottom:4px;">\ud83d\udcc2 ' + $('<span>').text(pt).html() + '</div>';
                html += renderPreviewTree(tree, 1);
            });
            $('#kookoawpf-settings-import-preview').html(html).show();
        };
        reader.readAsText(file);
    });

    function renderPreviewTree(tree, depth) {
        let html = '';
        let indent = '';
        for (let i = 0; i < depth; i++) indent += '&nbsp;&nbsp;';
        if (!Array.isArray(tree)) return html;
        for (let j = 0; j < tree.length; j++) {
            const n = tree[j];
            const safeColor = (n.color && /^#[0-9a-fA-F]{3,8}$/.test(n.color)) ? n.color : '';
            const dot = safeColor ? '<span style="color:' + safeColor + ';">\u25cf</span> ' : '';
            let badges = '';
            if (n.pinned) badges += ' \u2b50';
            if (n.locked) badges += ' \ud83d\udd12';
            html += '<div>' + indent + dot + $('<span>').text(n.name).html() + badges + '</div>';
            if (n.children && n.children.length) html += renderPreviewTree(n.children, depth + 1);
        }
        return html;
    }

    // ── Import from Settings: execute ──
    $('#kookoawpf-settings-import').on('click', function() {
        if (!settingsImportData) return;
        const mode = $('input[name="kookoawpf_settings_import_mode"]:checked').val();

        if (mode === 'replace') {
            const Sc = (kookoawpfData && kookoawpfData.strings) || {};
            if (!confirm(Sc.importReplaceConfirm)) return;
        }

        const $btn = $(this);
        const S = (kookoawpfData && kookoawpfData.strings) || {};
        $btn.addClass('kookoawpf-btn-loading').css('pointer-events', 'none').text(S.importing);

        $.post(kookoawpfData.ajaxUrl, {
            action: 'kookoawpf_import_folders',
            nonce: kookoawpfData.nonce,
            json_data: settingsImportData,
            mode: mode
        }, function(r) {
            const $icon = $('<span>', {
                'class': 'dashicons dashicons-download',
                style: 'vertical-align:middle;margin-right:4px;margin-top:-2px;'
            });
            $btn.removeClass('kookoawpf-btn-loading')
                .empty().append($icon).append(document.createTextNode(' ' + S.importFolders));

            if (r.success) {
                alert('\u2705 ' + r.data.message);
                settingsImportData = null;
                $('#kookoawpf-settings-import-file').val('');
                $('#kookoawpf-settings-import-preview').hide();
                $btn.prop('disabled', true);
            } else {
                alert('\u274c ' + (r.data.message || S.importFailed));
                $btn.prop('disabled', false);
            }
        });
    });
    // ── Custom Color Slots ──
    $(document).on('click', '.kookoawpf-ci-dot-empty', function() {
        $(this).closest('.kookoawpf-ci-custom-slot').find('.kookoawpf-ci-color-input').trigger('click');
    });
    $(document).on('click', '.kookoawpf-ci-dot-custom', function() {
        $(this).closest('.kookoawpf-ci-custom-slot').find('.kookoawpf-ci-color-input').trigger('click');
    });
    $(document).on('input', '.kookoawpf-ci-color-input', function() {
        const val = $(this).val();
        const $slot = $(this).closest('.kookoawpf-ci-custom-slot');
        $slot.find('input[name="kookoawpf_custom_colors[]"]').val(val);
        const $dot = $slot.find('.kookoawpf-ci-dot');
        $dot.removeClass('kookoawpf-ci-dot-empty').addClass('kookoawpf-ci-dot-custom')
            .css('background-color', val).attr('data-color', val).text('');
        if (!$slot.find('.kookoawpf-ci-slot-remove').length) {
            const S = (kookoawpfData && kookoawpfData.strings) || {};
            $('<button>', {
                type: 'button',
                'class': 'kookoawpf-ci-slot-remove',
                title: S.removeColor
            }).text('×').appendTo($slot);
        }
    });
    $(document).on('click', '.kookoawpf-ci-slot-remove', function(e) {
        e.stopPropagation();
        const $slot = $(this).closest('.kookoawpf-ci-custom-slot');
        $slot.find('input[name="kookoawpf_custom_colors[]"]').val('');
        $slot.find('.kookoawpf-ci-dot').removeClass('kookoawpf-ci-dot-custom').addClass('kookoawpf-ci-dot-empty')
            .css('background-color', '').removeAttr('data-color').text('');
        $(this).remove();
    });

    // ── Keyboard Shortcuts modal ──
    $('#kookoawpf-settings-view-shortcuts').on('click', function(e) {
        e.preventDefault();
        $('#kookoawpf-settings-shortcuts-modal').fadeIn(150);
    });
    $('#kookoawpf-settings-shortcuts-modal').on('click', '.kookoawpf-modal-overlay, .kookoawpf-modal-close', function() {
        $('#kookoawpf-settings-shortcuts-modal').fadeOut(150);
    });

    // Settings color palette click
    $(document).on('click', '.kookoawpf-settings-color-dot', function() {
        const c = $(this).data('color');
        $('.kookoawpf-settings-color-dot').removeClass('kookoawpf-settings-color-active');
        $(this).addClass('kookoawpf-settings-color-active');
        $('input[name="kookoawpf_color"]').val(c);
    });

    // ── Upload Folder Structure ──
    (function() {
        const $btn = $('#kookoawpf-upload-folder-btn');
        const $input = $('#kookoawpf-folder-input');
        const $progress = $('#kookoawpf-upload-folder-progress');
        const $bar = $progress.find('.kookoawpf-upload-folder-bar');
        const $status = $progress.find('.kookoawpf-upload-folder-status');
        let _uploading = false;

        $btn.on('click', function() {
            if (_uploading) return;
            $input.val('').trigger('click');
        });

        $input.on('change', function() {
            const files = this.files;
            if (!files || !files.length) return;

            const S = (kookoawpfData && kookoawpfData.strings) || {};

            // 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) {
                alert(S.uploadNoValidFiles);
                return;
            }

            // Parse folder structure from webkitRelativePath
            const folderPaths = {};
            const fileMap = []; // { file, folderPath }

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

                // Register all folder levels
                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('/') });
            }

            // Sort folder paths by depth (parent first)
            const sortedPaths = Object.keys(folderPaths).sort(function(a, b) {
                return a.split('/').length - b.split('/').length;
            });

            if (!sortedPaths.length && !fileMap.length) {
                alert(S.uploadNoFilesOrFolders);
                return;
            }

            _uploading = true;
            $btn.addClass('kookoawpf-btn-loading').prop('disabled', true);
            $progress.show();
            $bar.css('width', '0%');

            const totalSteps = sortedPaths.length + fileMap.length;
            let currentStep = 0;

            function updateProgress(text) {
                currentStep++;
                const pct = Math.round((currentStep / totalSteps) * 100);
                $bar.css('width', pct + '%');
                $status.text(text);
            }

            // Step 1: Create folders sequentially
            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;
                }

                const cfTpl = S.uploadCreatingFolders;
                updateProgress(
                    cfTpl
                        .replace('%1$s', String(parseInt(index + 1, 10) || 0))
                        .replace('%2$s', String(parseInt(sortedPaths.length, 10) || 0))
                        .replace('%3$s', String(info.name))
                );

                $.post(kookoawpfData.ajaxUrl, {
                    action: 'kookoawpf_create_folder',
                    nonce: kookoawpfData.nonce,
                    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);
                }).fail(function() {
                    createFolders(index + 1);
                });
            }

            // Step 2: Upload files sequentially
            function uploadFiles(index) {
                if (index >= fileMap.length) {
                    onComplete();
                    return;
                }

                const item = fileMap[index];
                let folderId = 0;
                if (item.folderPath && folderPaths[item.folderPath]) {
                    folderId = folderPaths[item.folderPath].termId || 0;
                }

                const ufTpl = S.uploadingFiles;
                updateProgress(
                    ufTpl
                        .replace('%1$s', String(parseInt(index + 1, 10) || 0))
                        .replace('%2$s', String(parseInt(fileMap.length, 10) || 0))
                        .replace('%3$s', String(item.file.name))
                );

                const fd = new FormData();
                fd.append('action', 'upload-attachment');
                fd.append('_wpnonce', kookoawpfData.uploadNonce || $('#_wpnonce').val());
                fd.append('async-upload', item.file);
                if (folderId) {
                    fd.append('kookoawpf_upload_folder', String(folderId));
                }

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

            function onComplete() {
                _uploading = false;
                $btn.removeClass('kookoawpf-btn-loading').prop('disabled', false);
                $bar.css('width', '100%');
                const doneTpl = S.uploadDone;
                $status.text(
                    doneTpl
                        .replace('%1$s', String(parseInt(sortedPaths.length, 10) || 0))
                        .replace('%2$s', String(parseInt(fileMap.length, 10) || 0))
                );
                setTimeout(function() {
                    $progress.fadeOut(400, function() {
                        $bar.css('width', '0%');
                        $status.text('');
                    });
                }, 5000);
            }

            createFolders(0);
        });
    })();

    // ── Rate Us section — "Rate this plugin" click handler ──
    // The dismiss "×" stays hidden until the user has clicked through
    // to WordPress.org at least once. On click, we fire-and-forget the
    // mark-clicked AJAX (server flips the user_meta flag) and reveal
    // the "×" so the user can hide the card now.
    $(document).on('click', '.kookoawpf-review-btn', function() {
        const $dismiss = $('#kookoawpf-review-dismiss');
        if ($dismiss.is(':hidden')) {
            $.post(ajaxurl, {
                action: 'kookoawpf_mark_review_clicked',
                nonce:  kookoawpfData.nonce
            });
            $dismiss.fadeIn(200);
        }
    });

    // ── Rate Us section — dismiss handler ──
    // Single-shot click on the "×" button: AJAX writes the user_meta
    // flag and the entire section fades out.
    $(document).on('click', '#kookoawpf-review-dismiss', function() {
        const $section = $('#kookoawpf-review-section');
        $.post(ajaxurl, {
            action: 'kookoawpf_dismiss_review',
            nonce:  kookoawpfData.nonce
        });
        $section.fadeOut(250, function() { $section.remove(); });
    });

    // ── Migrate from other plugins ──
    // All user-facing copy below comes from kookoawpfData.strings (localized
    // by includes/class-kookoawpf.php::get_localized_strings) so every
    // language the plugin ships gets translated migrate UX for free.
    const MS = (kookoawpfData && kookoawpfData.strings) ? kookoawpfData.strings : {};
    function migrateStr(key, fallback) {
        return Object.prototype.hasOwnProperty.call(MS, key) ? MS[key] : fallback;
    }
    function migrateSprintf(template, value) {
        return String(template).replace(/%[ds]|%\d+\$[ds]/, value);
    }

    // Two-step flow: click "Import Now" reveals the Merge/Replace radios
    // and a confirm button. Cancel reverts. The actual import runs only
    // after the confirm button (so the user always picks Merge vs Replace
    // explicitly — there is no implicit default that could trash data).
    $(document).on('click', '.kookoawpf-migrate-import-btn', function() {
        const $card = $(this).closest('.kookoawpf-migrate-card');
        $card.find('.kookoawpf-migrate-card-mode').slideDown(150);
        $(this).hide();
    });
    $(document).on('click', '.kookoawpf-migrate-cancel-btn', function() {
        const $card = $(this).closest('.kookoawpf-migrate-card');
        $card.find('.kookoawpf-migrate-card-mode').slideUp(150);
        $card.find('.kookoawpf-migrate-import-btn').show();
    });
    $(document).on('click', '.kookoawpf-migrate-confirm-btn', function() {
        const $btn   = $(this);
        const $card  = $btn.closest('.kookoawpf-migrate-card');
        const id     = $btn.data('importer-id');
        const mode   = $card.find('input[name="kookoawpf_migrate_mode_' + id + '"]:checked').val() || 'merge';
        const $res   = $card.find('.kookoawpf-migrate-card-result');

        const startLabel = migrateStr('migrateStartImport', 'Start Import');

        $btn.prop('disabled', true).text(migrateStr('migrateImporting', 'Importing...'));
        $card.find('.kookoawpf-migrate-cancel-btn').prop('disabled', true);

        $.post(ajaxurl, {
            action:      'kookoawpf_run_importer',
            nonce:       kookoawpfData.nonce,
            importer_id: id,
            mode:        mode
        }).done(function(resp) {
            if (!resp || !resp.success) {
                const msg = (resp && resp.data && resp.data.message)
                    ? resp.data.message
                    : migrateStr('migrateImportFailed', 'Import failed.');
                $res.removeClass('kookoawpf-migrate-result-success').addClass('kookoawpf-migrate-result-error');
                $res.empty()
                    .append($('<strong></strong>').text(migrateStr('migrateErrorLabel', 'Error.')))
                    .append(' ')
                    .append(document.createTextNode(msg))
                    .show();
                $btn.prop('disabled', false).text(startLabel);
                $card.find('.kookoawpf-migrate-cancel-btn').prop('disabled', false);
                return;
            }
            const s        = resp.data.summary || {};
            const folders  = parseInt(s.folders_created || 0, 10);
            const assigned = parseInt(s.items_assigned || 0, 10);
            const skipped  = parseInt(s.items_skipped || 0, 10);

            const foldersTpl  = folders === 1
                ? migrateStr('migrateFoldersCreatedOne', '%d folder created')
                : migrateStr('migrateFoldersCreatedMany', '%d folders created');
            const assignedTpl = assigned === 1
                ? migrateStr('migrateItemsAssignedOne', '%d item assigned')
                : migrateStr('migrateItemsAssignedMany', '%d items assigned');

            let summaryText = migrateSprintf(foldersTpl, folders) + ', ' + migrateSprintf(assignedTpl, assigned);
            if (skipped > 0) {
                summaryText += ', ' + migrateSprintf(migrateStr('migrateSkipped', '%d skipped (already organized)'), skipped);
            }
            summaryText += '.';

            $res.removeClass('kookoawpf-migrate-result-error').addClass('kookoawpf-migrate-result-success');
            $res.empty()
                .append($('<strong></strong>').text(migrateStr('migrateImportedLabel', 'Imported.')))
                .append(' ')
                .append(document.createTextNode(summaryText))
                .show();

            if (s.errors && s.errors.length) {
                const warnTpl  = s.errors.length === 1
                    ? migrateStr('migrateWarningOne', '%d warning')
                    : migrateStr('migrateWarningMany', '%d warnings');
                const warnText = migrateSprintf(warnTpl, s.errors.length) + ' — ' + migrateStr('migrateSeeBrowserConsole', 'see browser console.');
                $res.append('<br>').append(
                    $('<span></span>').css('color', '#FF9500').text(warnText)
                );
                if (window.console && console.warn) {
                    s.errors.forEach(function(e) { console.warn('[KooKoa Folders importer]', e); });
                }
            }

            if (resp.data.deactivate && resp.data.deactivate.slug) {
                const dSlug   = resp.data.deactivate.slug;
                const dLabel  = resp.data.deactivate.label;
                const promptText = migrateSprintf(migrateStr('migrateSourceStillActive', '%s is still active. Deactivate it now?'), dLabel);
                const $prompt = $('<div class="kookoawpf-migrate-deactivate-prompt"></div>');
                $prompt.append(document.createTextNode(promptText)).append(' ');
                $('<button type="button" class="button kookoawpf-migrate-deactivate-btn"></button>')
                    .attr('data-plugin', dSlug)
                    .text(migrateSprintf(migrateStr('migrateDeactivateLabel', 'Deactivate %s'), dLabel))
                    .appendTo($prompt);
                $res.append($prompt);
            }

            $card.find('.kookoawpf-migrate-card-mode').slideUp(150);
        }).fail(function() {
            $res.removeClass('kookoawpf-migrate-result-success').addClass('kookoawpf-migrate-result-error');
            $res.empty()
                .append($('<strong></strong>').text(migrateStr('migrateErrorLabel', 'Error.')))
                .append(' ')
                .append(document.createTextNode(migrateStr('migrateNetworkFailure', 'Network failure.')))
                .show();
            $btn.prop('disabled', false).text(startLabel);
            $card.find('.kookoawpf-migrate-cancel-btn').prop('disabled', false);
        });
    });

    // Single-shot dismiss for one card.
    $(document).on('click', '.kookoawpf-migrate-dismiss', function() {
        const $card = $(this).closest('.kookoawpf-migrate-card');
        const id    = $(this).data('importer-id');
        $.post(ajaxurl, {
            action:      'kookoawpf_dismiss_importer',
            nonce:       kookoawpfData.nonce,
            importer_id: id
        });
        $card.fadeOut(200, function() {
            $card.remove();
            // Reveal the footer links so the user does not have to refresh
            // to find Reset / Permanent-hide once the last card disappears.
            updateMigrateFooterLinks();
        });
    });

    // Show/hide the Reset and Permanent-hide footer links based on the
    // current state of the section. Called after dismiss so the footer
    // updates in place — no page reload required.
    function updateMigrateFooterLinks() {
        const $section = $('#kookoawpf-migrate-section');
        if (!$section.length) return;
        const cardsLeft = $section.find('.kookoawpf-migrate-card').length;
        // Reset link appears as soon as one card has been dismissed.
        $('#kookoawpf-migrate-reset').closest('p').show();
        // Permanent-hide appears only when nothing is left to import.
        if (cardsLeft === 0) {
            $('#kookoawpf-migrate-hide-forever').closest('p').show();
        }
    }

    // Post-import deactivate button (rendered dynamically inside result box).
    $(document).on('click', '.kookoawpf-migrate-deactivate-btn', function() {
        const $btn         = $(this);
        const plugin       = $btn.data('plugin');
        const fallbackText = $btn.text(); // already-localized label like "Deactivate FileBird".
        $btn.prop('disabled', true).text(migrateStr('migrateDeactivating', 'Deactivating...'));
        $.post(ajaxurl, {
            action: 'kookoawpf_deactivate_source_plugin',
            nonce:  kookoawpfData.nonce,
            plugin: plugin
        }).done(function(resp) {
            if (resp && resp.success) {
                $btn.closest('.kookoawpf-migrate-deactivate-prompt')
                    .empty()
                    .append(
                        $('<strong></strong>')
                            .css('color', '#39FF14')
                            .text(migrateStr('migrateDeactivated', 'Deactivated.'))
                    );
            } else {
                $btn.prop('disabled', false).text(fallbackText);
            }
        }).fail(function() {
            $btn.prop('disabled', false).text(fallbackText);
        });
    });

    // Reset import detection — re-shows previously imported/dismissed cards.
    $(document).on('click', '#kookoawpf-migrate-reset', function(e) {
        e.preventDefault();
        $.post(ajaxurl, {
            action: 'kookoawpf_reset_importers',
            nonce:  kookoawpfData.nonce
        }).done(function() {
            window.location.reload();
        });
    });

    // Permanent hide of the entire Migrate section. Requires explicit
    // confirmation because there is no UI to undo it — only "Reset import
    // detection" (which clears every flag, including this one) or a DB edit.
    $(document).on('click', '#kookoawpf-migrate-hide-forever', function(e) {
        e.preventDefault();
        if (!window.confirm(migrateStr('migrateRemoveConfirm', 'Remove the Migrate section permanently?\n\nThis cannot be undone from the UI. Use this only if you are done importing from other plugins and never want to see this section again.'))) {
            return;
        }
        $.post(ajaxurl, {
            action: 'kookoawpf_hide_migrate_section',
            nonce:  kookoawpfData.nonce
        }).done(function() {
            window.location.reload();
        });
    });
});
})(jQuery);
