(function($) {
    'use strict';

    // Media-modal dialogs module. Extends the KookoawpfMediaModal object
    // defined in media-modal.js with the dialog-building + dialog-handler
    // surface: the on-demand builder modals (Divi strips display:none HTML,
    // so the colour/icon/delete/move/shortcuts dialogs are created from JSON
    // on demand), the create/rename folder dialog, the z-index boost+poll
    // helper for PHP-rendered dialogs, and the capture-phase click/keydown
    // handlers used on pages without the main sidebar.
    //
    // Loaded after media-modal.js (enqueue dependency), so the shared object
    // already exists; Object.assign merges these methods onto it. Method
    // bodies are copied verbatim from the original monolithic file — no logic
    // change, only the wrapper.

    const FO = window.KookoaWPF;
    const KookoawpfCustomSelect = window.KookoawpfCustomSelect;
    const Utils = window.KookoaWPFUtils;
    const M = window.KookoawpfMediaModal;
    if (!M) return;

    Object.assign(M, {

        /**
         * Create a single modal dialog on-demand for builder pages.
         */
        _createSingleBuilderModal: function(id, data) {
            if ($('#' + id).length) return; // already exists
            const S = FO.data.strings || {};
            let $target = $('.media-modal:visible');
            if (!$target.length) $target = $('body');

            // Defence-in-depth hex check before colour values reach
            // attributes / inline styles. PHP already sanitises with
            // sanitize_hex_color, so this is purely belt-and-braces.
            // Delegates to the shared, unit-tested KookoaWPFUtils.isValidHexColor.
            function _validHex(s) {
                return Utils.isValidHexColor(s);
            }

            // Each branch builds a STATIC skeleton (no localized strings,
            // no dynamic data inside HTML literals) and then populates the
            // dynamic parts via .text() / .attr() / .css() on jQuery nodes.
            // Static English literals are kept as-is — they're not user
            // controlled and don't need DOM-API treatment.
            let html = '';
            let $node = null;
            if (id === 'kookoawpf-modal-color') {
                html = '<div id="kookoawpf-modal-color" class="kookoawpf-modal" style="display:none;">'
                    + '<div class="kookoawpf-modal-overlay"></div>'
                    + '<div class="kookoawpf-modal-content kookoawpf-modal-sm">'
                    + '<div class="kookoawpf-modal-header"><h3 class="kookoawpf-modal-title"></h3><button type="button" class="kookoawpf-modal-close">&times;</button></div>'
                    + '<div class="kookoawpf-modal-body">'
                    + '<div id="kookoawpf-color-palette" class="kookoawpf-color-palette"></div>'
                    + '<div class="kookoawpf-color-reset-row"><a href="#" id="kookoawpf-color-reset" class="kookoawpf-color-reset-link" style="display:none;"></a></div>'
                    + '<input type="hidden" id="kookoawpf-color-folder-id" value="0" />'
                    + '</div></div></div>';
                $node = $(html);
                $node.find('.kookoawpf-modal-title').text(S.iconColor || 'Folder Color');
                $node.find('#kookoawpf-color-reset').text(S.resetColor || 'Reset color');
                const $palette = $node.find('#kookoawpf-color-palette');
                if (data.colorRows) {
                    for (let r = 0; r < data.colorRows.length; r++) {
                        const $row = $('<div class="kookoawpf-color-row"></div>');
                        for (let c = 0; c < data.colorRows[r].length; c++) {
                            const color = _validHex(data.colorRows[r][c]);
                            if (!color) continue;
                            $row.append(
                                $('<span class="kookoawpf-color-swatch"></span>')
                                    .attr('data-color', color)
                                    .css('background-color', color)
                            );
                        }
                        $palette.append($row);
                    }
                }
                if (data.customColors && data.customColors.length) {
                    $palette.append('<div class="kookoawpf-color-separator"></div>');
                    const $customRow = $('<div class="kookoawpf-color-row kookoawpf-color-row-custom"></div>');
                    for (let i = 0; i < data.customColors.length; i++) {
                        const custom = _validHex(data.customColors[i]);
                        if (!custom) continue;
                        $customRow.append(
                            $('<span class="kookoawpf-color-swatch"></span>')
                                .attr('data-color', custom)
                                .css('background-color', custom)
                        );
                    }
                    $palette.append($customRow);
                }
            } else if (id === 'kookoawpf-modal-icon') {
                html = '<div id="kookoawpf-modal-icon" class="kookoawpf-modal" style="display:none;">'
                    + '<div class="kookoawpf-modal-overlay"></div><div class="kookoawpf-modal-content">'
                    + '<div class="kookoawpf-modal-header"><h3 class="kookoawpf-modal-title"></h3><button type="button" class="kookoawpf-modal-close">&times;</button></div>'
                    + '<div class="kookoawpf-modal-body kookoawpf-icon-picker-body">'
                    + '<div class="kookoawpf-icon-reset-row" id="kookoawpf-icon-reset-row" style="display:none;"><button type="button" id="kookoawpf-icon-reset" class="button"></button></div>'
                    + '<div class="kookoawpf-icon-categories"></div>'
                    + '<input type="hidden" id="kookoawpf-icon-folder-id" value="0" /></div></div></div>';
                $node = $(html);
                $node.find('.kookoawpf-modal-title').text(S.changeIcon || 'Change Icon');
                $node.find('#kookoawpf-icon-reset').text(S.resetToDefault);
                const $cats = $node.find('.kookoawpf-icon-categories');
                if (data.iconCategories) {
                    const keys = Object.keys(data.iconCategories);
                    for (let k = 0; k < keys.length; k++) {
                        const cat = data.iconCategories[keys[k]];
                        const $cat = $('<div class="kookoawpf-icon-category"></div>');
                        $cat.append($('<div class="kookoawpf-icon-category-label"></div>').text(cat.label));
                        const $grid = $('<div class="kookoawpf-icon-grid"></div>');
                        for (let ic = 0; ic < cat.icons.length; ic++) {
                            const iconChar = String(cat.icons[ic]);
                            $grid.append(
                                $('<span class="kookoawpf-icon-option"></span>')
                                    .attr('data-icon', iconChar)
                                    .text(iconChar)
                            );
                        }
                        $cat.append($grid);
                        $cats.append($cat);
                    }
                }
            } else if (id === 'kookoawpf-modal-delete') {
                html = '<div id="kookoawpf-modal-delete" class="kookoawpf-modal" style="display:none;">'
                    + '<div class="kookoawpf-modal-overlay"></div><div class="kookoawpf-modal-content kookoawpf-modal-sm">'
                    + '<div class="kookoawpf-modal-header"><h3 class="kookoawpf-modal-title"></h3><button type="button" class="kookoawpf-modal-close">&times;</button></div>'
                    + '<div class="kookoawpf-modal-body"><p class="kookoawpf-delete-msg"></p>'
                    + '<input type="hidden" id="kookoawpf-delete-folder-id" value="0" /></div>'
                    + '<div class="kookoawpf-modal-footer">'
                    + '<button type="button" class="button kookoawpf-modal-cancel"></button>'
                    + '<button type="button" class="button button-primary kookoawpf-btn-danger" id="kookoawpf-confirm-delete"></button>'
                    + '</div></div></div>';
                $node = $(html);
                $node.find('.kookoawpf-modal-title').text(S.deleteTitle || S['delete'] || 'Delete Folder');
                $node.find('.kookoawpf-delete-msg').text(S.deleteMsg);
                $node.find('.kookoawpf-modal-cancel').text(S.cancelBulk || 'Cancel');
                $node.find('#kookoawpf-confirm-delete').text(S['delete'] || 'Delete');
            } else if (id === 'kookoawpf-modal-move-to-folder') {
                html = '<div id="kookoawpf-modal-move-to-folder" class="kookoawpf-modal" style="display:none;">'
                    + '<div class="kookoawpf-modal-overlay"></div>'
                    + '<div class="kookoawpf-modal-content kookoawpf-modal-sm">'
                    + '<div class="kookoawpf-modal-header"><h3 class="kookoawpf-modal-title"></h3><button type="button" class="kookoawpf-modal-close">&times;</button></div>'
                    + '<div class="kookoawpf-modal-body">'
                    + '<input type="hidden" id="kookoawpf-move-to-folder-id" value="0" />'
                    + '<label class="kookoawpf-mtf-label"></label>'
                    + '<select id="kookoawpf-move-to-folder-select" style="width:100%;padding:8px;font-size:14px;">'
                    + '<option value="root" class="kookoawpf-mtf-root"></option>'
                    + '</select>'
                    + '</div>'
                    + '<div class="kookoawpf-modal-footer">'
                    + '<button type="button" class="button kookoawpf-modal-cancel"></button>'
                    + '<button type="button" class="button button-primary" id="kookoawpf-confirm-move-to-folder"></button>'
                    + '</div></div></div>';
                $node = $(html);
                $node.find('.kookoawpf-modal-title').text(S.moveToFolder || 'Move to Folder...');
                $node.find('.kookoawpf-mtf-label').text(S.destination || 'Destination');
                $node.find('.kookoawpf-mtf-root').text(S.rootFolder || '— Root (no parent) —');
                $node.find('.kookoawpf-modal-cancel').text(S.cancel || 'Cancel');
                $node.find('#kookoawpf-confirm-move-to-folder').text(S.move || 'Move');
            } else if (id === 'kookoawpf-modal-shortcuts') {
                // Skeleton: structural markup only — labels are localized
                // below via DOM API so translations stay safe.
                html = '<div id="kookoawpf-modal-shortcuts" class="kookoawpf-modal" style="display:none;">'
                    + '<div class="kookoawpf-modal-overlay"></div>'
                    + '<div class="kookoawpf-modal-content kookoawpf-modal-shortcuts-content">'
                    + '<button type="button" class="kookoawpf-modal-close">&times;</button>'
                    + '<h3 class="kookoawpf-shortcuts-title"></h3>'
                    + '<table class="kookoawpf-shortcuts-table"><tbody></tbody></table>'
                    + '</div></div>';
                $node = $(html);
                $node.find('.kookoawpf-shortcuts-title').text(S.keyboardShortcuts);
                const rows = [
                    { label: S.shortcutCreateFolder,   key: 'Alt + N' },
                    { label: S.shortcutNewSubfolder,   key: 'Alt + S' },
                    { label: S.shortcutRenameFolder,   key: 'F2' },
                    { label: S.deleteTitle,            key: 'Del' },
                    { label: S.shortcutMoveToFolder,   key: 'Alt + M' },
                    { sep: true },
                    { label: S.shortcutCopyFolder,     key: 'Ctrl + C' },
                    { label: S.shortcutCutFolder,      key: 'Ctrl + X' },
                    { label: S.shortcutPasteFolder,    key: 'Ctrl + V' },
                    { label: S.shortcutDuplicate,      key: 'Ctrl + D' },
                    { sep: true },
                    { label: S.shortcutChangeColor,    key: 'Alt + C' },
                    { label: S.changeIcon,             key: 'Alt + I' },
                    { label: S.shortcutPinUnpin,       key: 'Alt + P' },
                    { label: S.shortcutLockUnlock,     key: 'Alt + L' },
                    { sep: true },
                    { label: S.shortcutNavigate,       key: '↑ ↓' },
                    { label: S.shortcutExpandCollapse, key: '→ ←' },
                    { label: S.shortcutReorderFolder,  key: 'Shift + ↑ ↓' },
                    { sep: true },
                    { label: S.keyboardShortcuts,      key: 'Alt + K' },
                    { label: S.shortcutCloseModal,     key: 'Esc' },
                    { label: S.shortcutConfirmAction,  key: 'Enter' }
                ];
                const $tbody = $node.find('tbody');
                rows.forEach(function(r) {
                    if (r.sep) {
                        $('<tr>', { 'class': 'kookoawpf-shortcuts-sep' })
                            .append($('<td>', { colspan: 2 }))
                            .appendTo($tbody);
                        return;
                    }
                    $('<tr>')
                        .append($('<td>').text(r.label))
                        .append($('<td>').text(r.key))
                        .appendTo($tbody);
                });
            }

            if ($node && $node.length) {
                $target.append($node);
            }
        },

        /**
         * Open a retro-dark folder dialog (create/rename) inside the media modal.
         * Injects HTML dynamically if needed, with z-index above WP media modal.
         */
        _openModalFolderDialog: function(action, name, folderId, $sidebar, $frame) {
            const self = this;
            const S = FO.data.strings;
            const dlgId = 'kookoawpf-modal-folder-dialog';
            let $dlg = $('#' + dlgId);

            if (!$dlg.length) {
                // Static skeleton — localized labels and button text are set
                // through .text() below so they never enter an HTML literal.
                // dlgId is a fixed plugin constant (kookoawpf-modal-folder-dialog),
                // so embedding it inline as id="" / for="" is fine.
                const html = '<div id="' + dlgId + '" class="kookoawpf-modal" style="display:none;z-index:200001;">'
                    + '<div class="kookoawpf-modal-overlay"></div>'
                    + '<div class="kookoawpf-modal-content">'
                    + '<div class="kookoawpf-modal-header">'
                    + '<h3 id="' + dlgId + '-title"></h3>'
                    + '<button type="button" class="kookoawpf-modal-close">&times;</button>'
                    + '</div>'
                    + '<div class="kookoawpf-modal-body">'
                    + '<label class="kookoawpf-fdlg-name-label"></label>'
                    + '<input type="text" id="' + dlgId + '-name" maxlength="100" />'
                    + '<div id="' + dlgId + '-parent-row" style="margin-top:12px;">'
                    + '<label class="kookoawpf-fdlg-parent-label"></label>'
                    + '<select id="' + dlgId + '-parent" style="width:100%;padding:8px;font-size:14px;">'
                    + '<option value="0" class="kookoawpf-fdlg-root-opt"></option>'
                    + '</select>'
                    + '</div>'
                    + '</div>'
                    + '<div class="kookoawpf-modal-footer">'
                    + '<button type="button" class="button kookoawpf-modal-cancel"></button>'
                    + '<button type="button" class="button button-primary" id="' + dlgId + '-save"></button>'
                    + '</div>'
                    + '</div></div>';
                // Always append to body first (singleton)
                $('body').append(html);
                $dlg = $('#' + dlgId);
                $dlg.find('.kookoawpf-fdlg-name-label').text(S.folderName || 'Folder Name');
                $dlg.find('.kookoawpf-fdlg-parent-label').text(S.parentFolder || 'Parent Folder');
                $dlg.find('.kookoawpf-fdlg-root-opt').text(S.noneRoot || '— None (Root folder) —');
                $dlg.find('.kookoawpf-modal-cancel').text(S.cancel || 'Cancel');
                $dlg.find('#' + dlgId + '-save').text(S.save || 'Save');

                // Close handlers
                $dlg.on('click', '.kookoawpf-modal-close, .kookoawpf-modal-cancel, .kookoawpf-modal-overlay', function() {
                    $dlg.hide();
                });
            }

            // Move into the correct visible .media-modal for z-index stacking
            const $modalEl = $frame.closest('.media-modal');
            if ($modalEl.length && !$modalEl.find('#' + dlgId).length) {
                $dlg.appendTo($modalEl);
            }

            // Configure dialog
            const isCreate = (action === 'create');
            $('#' + dlgId + '-title').text(isCreate ? (S.newFolder || 'New Folder') : (S.rename || 'Rename'));
            $('#' + dlgId + '-name').val(name || '');

            // Parent folder dropdown (only for create)
            const $parentRow = $('#' + dlgId + '-parent-row');
            const $parentSel = $('#' + dlgId + '-parent');
            if (isCreate) {
                $parentRow.show();
                $parentSel.find('option:gt(0)').remove();
                // Populate from tree data
                const $tree = $sidebar.find('.kookoawpf-modal-jstree');
                const inst = $tree.length ? $tree.jstree(true) : null;
                if (inst) {
                    const _addOpts = function(nodeId, depth) {
                        const n = inst.get_node(nodeId);
                        if (!n || !n.children || !n.children.length) return;
                        for (let i = 0; i < n.children.length; i++) {
                            const cn = inst.get_node(n.children[i]);
                            if (!cn || !cn.id) continue;
                            // Smart folders are virtual queries — they can't host children.
                            if (cn.data && cn.data.is_dynamic) continue;
                            const cid = cn.id.replace('folder_', '');
                            const ctext = $('<div>').html(cn.text).find('.kookoawpf-count').remove().end().text().trim();
                            let prefix = '';
                            for (let d = 0; d < depth; d++) prefix += '— ';
                            const $opt = $('<option>').val(cid).text(prefix + ctext);
                            if (String(cid) === String(folderId)) $opt.prop('selected', true);
                            $parentSel.append($opt);
                            _addOpts(cn.id, depth + 1);
                        }
                    };
                    _addOpts('#', 0);
                }
                // Set selected value and refresh custom select wrapper
                if (folderId) {
                    $parentSel.val(String(folderId));
                }
                if (typeof KookoawpfCustomSelect !== 'undefined') {
                    if (!$parentSel.data('kookoawpf-cs-init')) {
                        KookoawpfCustomSelect.replace($parentSel);
                    } else {
                        KookoawpfCustomSelect.refresh($parentSel);
                    }
                }
            } else {
                $parentRow.hide();
            }

            const $nameInput = $('#' + dlgId + '-name');

            // Save button state
            const $saveBtn = $('#' + dlgId + '-save');
            const toggleSave = function() {
                const hasVal = $nameInput.val().trim().length > 0;
                $saveBtn.prop('disabled', !hasVal);
                if (hasVal) {
                    $saveBtn.removeAttr('style');
                } else {
                    $saveBtn.attr('style', 'background:#2ea043 !important;border:3px solid #39FF14 !important;color:#0d1117 !important;opacity:0.4 !important;cursor:not-allowed !important;');
                }
            };
            toggleSave();
            $nameInput.off('input.kwpfModalDlg').on('input.kwpfModalDlg', toggleSave);

            // Save handler (rebind each time)
            $saveBtn.off('click.kwpfModalDlg').on('click.kwpfModalDlg', function() {
                const newName = $nameInput.val().trim();
                if (!newName) return;
                $dlg.hide();

                if (isCreate) {
                    const parentVal = $parentSel.val() || '0';
                    FO.ajax('kookoawpf_create_folder', { name: newName, post_type: 'attachment', parent_id: parentVal }, function(r) {
                        if (r.success) {
                            const newTermId = r.data && r.data.term_id ? r.data.term_id : null;
                            FO.showNotice(S.folderCreated || 'Folder created.', 'success');
                            self._refreshModalTree($sidebar, $frame, newTermId ? { openToNodeId: newTermId } : {});
                            if (FO.tree && FO.tree.length) FO.refreshTree(null, newTermId ? { openToNodeId: newTermId } : {});
                        } else {
                            FO.showNotice((r.data && r.data.message) || 'Error', 'error');
                        }
                    });
                } else {
                    const _rnTree = $sidebar.find('.kookoawpf-modal-jstree');
                    const _rnInst = _rnTree.length ? _rnTree.jstree(true) : null;
                    const _rnNode = _rnInst ? _rnInst.get_node('folder_' + folderId) : null;
                    const _rnDynamic = _rnNode && _rnNode.data && _rnNode.data.is_dynamic;
                    FO.ajax('kookoawpf_rename_folder', { folder_id: folderId, name: newName, post_type: 'attachment' }, function(r) {
                        if (r.success) {
                            FO.showNotice(_rnDynamic ? (S.smartFolderRenamed || '⚡ Smart folder renamed.') : (S.folderRenamed || 'Folder renamed.'), 'success');
                            self._refreshModalTree($sidebar, $frame);
                            if (FO.tree && FO.tree.length) FO.refreshTree();
                        } else {
                            FO.showNotice((r.data && r.data.message) || 'Error', 'error');
                        }
                    });
                }
            });

            // Enter key to save
            $nameInput.off('keydown.kwpfModalDlg').on('keydown.kwpfModalDlg', function(e) {
                if (e.keyCode === 13) { e.preventDefault(); $saveBtn.trigger('click.kwpfModalDlg'); }
            });

            $dlg.show();
            setTimeout(function() { $nameInput.focus().select(); }, 100);
        },

        /**
         * Open a PHP-rendered modal (color/icon/delete) with z-index boost,
         * poll for close, then call refreshFn.
         */
        _boostAndPoll: function(selector, fid, openFn, refreshFn) {
            const dlgId = selector.replace('#', '');
            let $m = $(selector);
            // Recreate dialog on-demand if Divi stripped it
            if ($m.length === 0 && FO._builderModalData) {
                M._createSingleBuilderModal(dlgId, FO._builderModalData);
                $m = $(selector);
            }
            if (!$m.length) return false;
            // Move inside visible .media-modal for z-index stacking
            const $visibleModal = $('.media-modal:visible');
            if ($visibleModal.length && !$visibleModal.find(selector).length) {
                $m.appendTo($visibleModal);
            }
            $m.css('z-index', 200001);
            openFn(fid);
            let pollCount = 0;
            const poll = setInterval(function() {
                pollCount++;
                if ($m.is(':hidden') || pollCount > 150) { // max 30s
                    clearInterval(poll);
                    $m.css('z-index', '');
                    // Skip refreshFn if deleteFolder is handling its own refresh
                    // (prevents race: refreshFn fires before delete AJAX completes → stale data)
                    if ($m.is(':hidden') && !FO._deleteHandlesRefresh) refreshFn();
                }
            }, 200);
            return true;
        },

        /**
         * Bind click handlers for color/icon/delete modals on pages where
         * FO.init() hasn't run (no main sidebar). Uses capture-phase listeners
         * to bypass WP media modal stopPropagation.
         */
        _bindModalHandlers: function() {
            if (this._modalHandlersBound) return;
            // If initModals() already ran, jQuery handlers are bound — skip capture-phase duplicates
            if (FO._modalsInitialized) return;
            this._modalHandlersBound = true;

            // Close modal on X, Cancel, or overlay click (capture phase)
            document.addEventListener('click', function(e) {
                const t = e.target;
                if (t.matches('.kookoawpf-modal-close, .kookoawpf-modal-cancel, .kookoawpf-modal-overlay')) {
                    const $modal = $(t).closest('.kookoawpf-modal');
                    if ($modal.length) $modal.hide();
                }
            }, true);

            // ESC to close — stop propagation so WP doesn't close the media modal
            document.addEventListener('keydown', function(e) {
                if (e.keyCode === 27) {
                    const $visible = $('.kookoawpf-modal:visible').not('.media-modal');
                    if ($visible.length) {
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        e.preventDefault();
                        $visible.hide();
                    }
                }
            }, true);

            // Color swatch click
            document.addEventListener('click', function(e) {
                const t = e.target;
                if (t.matches('.kookoawpf-color-swatch')) {
                    const color = $(t).data('color');
                    const fid = $('#kookoawpf-color-folder-id').val();
                    if (color && fid) {
                        $('.kookoawpf-color-swatch').removeClass('kookoawpf-color-active');
                        $(t).addClass('kookoawpf-color-active');
                        FO.updateFolderColor(fid, color);
                        $('#kookoawpf-modal-color').hide();
                    }
                }
            }, true);

            // Color reset
            document.addEventListener('click', function(e) {
                const t = e.target;
                if (t.id === 'kookoawpf-color-reset' || $(t).closest('#kookoawpf-color-reset').length) {
                    e.preventDefault();
                    const defaultColor = (FO.data && FO.data.defaultColor) ? FO.data.defaultColor : '#39FF14';
                    const fid = $('#kookoawpf-color-folder-id').val();
                    if (fid) {
                        FO.updateFolderColor(fid, defaultColor, true);
                        FO.showNotice(FO.data.strings.colorReset || 'Color reset.');
                        $('#kookoawpf-modal-color').hide();
                    }
                }
            }, true);

            // Icon option click
            document.addEventListener('click', function(e) {
                const t = e.target;
                if (t.matches('.kookoawpf-icon-option')) {
                    const icon = $(t).data('icon');
                    const fid = $('#kookoawpf-icon-folder-id').val();
                    if (fid) FO.updateFolderIcon(fid, icon);
                }
            }, true);

            // Icon reset
            document.addEventListener('click', function(e) {
                if (e.target.id === 'kookoawpf-icon-reset') {
                    const fid = $('#kookoawpf-icon-folder-id').val();
                    if (fid) FO.updateFolderIcon(fid, '');
                }
            }, true);

            // Delete confirm — only for media modal context (builder pages without main sidebar).
            // Delegates to FO.deleteFolder() for optimistic removal + proper AJAX + modal refresh.
            // Always passes 'attachment' as postType because modal media folders use attachment taxonomy.
            document.addEventListener('click', function(e) {
                if (e.target.id === 'kookoawpf-confirm-delete') {
                    if (!$(e.target).closest('.media-modal').length) return;
                    const fid = $('#kookoawpf-delete-folder-id').val();
                    if (fid) {
                        FO.deleteFolder(fid, 'attachment');
                    }
                }
            }, true);

            // Enter key on Move to Folder dialog in modal
            document.addEventListener('keydown', function(e) {
                if (e.keyCode === 13 && $('#kookoawpf-modal-move-to-folder:visible').length) {
                    const $btn = $('#kookoawpf-confirm-move-to-folder');
                    if ($btn.closest('.media-modal').length) {
                        e.preventDefault();
                        $btn[0].click();
                    }
                }
            }, true);

            // Enter key on Delete dialog in modal
            document.addEventListener('keydown', function(e) {
                if (e.keyCode === 13 && $('#kookoawpf-modal-delete:visible').length) {
                    const $btn = $('#kookoawpf-confirm-delete');
                    if ($btn.closest('.media-modal').length) {
                        e.preventDefault();
                        $btn[0].click();
                    }
                }
            }, true);

            // Move to folder confirm — only for media modal context
            document.addEventListener('click', function(e) {
                if (e.target.id === 'kookoawpf-confirm-move-to-folder') {
                    if (!$(e.target).closest('.media-modal').length) return;
                    const fid = parseInt($('#kookoawpf-move-to-folder-id').val(), 10);
                    const target = $('#kookoawpf-move-to-folder-select').val();
                    if (!fid || !target) return;
                    const newParentId = (target === 'root') ? 0 : parseInt(target, 10);
                    const _mmSidebar = $(e.target).closest('.media-modal').find('.kookoawpf-modal-jstree');
                    const _mmInst = _mmSidebar.length ? _mmSidebar.jstree(true) : null;
                    const _mmNode = _mmInst ? _mmInst.get_node('folder_' + fid) : null;
                    const _mmDynamic = _mmNode && _mmNode.data && _mmNode.data.is_dynamic;
                    FO.ajax('kookoawpf_move_folder', {
                        folder_id: fid, new_parent_id: newParentId,
                        post_type: 'attachment', sibling_order: []
                    }, function(r) {
                        if (r.success) {
                            FO.showNotice(_mmDynamic ? (FO.data.strings.smartFolderMoved || '⚡ Smart folder moved.') : (FO.data.strings.folderMoved || 'Folder moved.'), 'success');
                        } else {
                            FO.showNotice((r.data && r.data.message) || 'Error', 'error');
                        }
                        $('#kookoawpf-modal-move-to-folder').hide();
                    });
                }
            }, true);
        }

    });

})(jQuery);
