/**
 * LolaCore Settings JavaScript — 1.0.0 (BYOM)
 *
 * BYOK logic (API key validation, model loading from own providers) removed.
 * AI model configuration is now handled natively by WordPress 7.0 AI Settings.
 */
jQuery(document).ready(function($) {
    // Ensure the file input is cleared on load to prevent cached files from breaking the 'change' event
    $('#maint-import-file').val('');

    // ========================================================
    // DIRTY STATE TRACKER
    // Snapshots initial form values, tracks changes, shows/hides
    // the sticky footer, and guards against accidental navigation.
    // ========================================================
    const $footer     = $('#lc-sticky-footer');
    const $dirtyLabel = $('#lc-dirty-label');
    let savedValues   = {};
    let isDirty       = 0;

    /**
     * Capture the current value of every tracked form element.
     * Inputs flagged with data-no-dirty="1" are self-saving (their own AJAX)
     * and must stay out of the global dirty tracker.
     */
    function snapshotFormValues() {
        savedValues = {};
        $('#lolacore-settings-form').find('input, select, textarea').each(function() {
            const $el = $(this);
            if ($el.attr('data-no-dirty') === '1') return;
            const id  = $el.attr('id') || $el.attr('name');
            if (!id) return;
            if ($el.is(':checkbox') || $el.is(':radio')) {
                savedValues[id] = $el.is(':checked');
            } else {
                savedValues[id] = $el.val();
            }
        });
        // Also track domain toggles (outside the form)
        $('.lc-domain-toggle').each(function() {
            const key = 'domain_' + $(this).data('domain');
            savedValues[key] = $(this).is(':checked');
        });
    }

    /**
     * Recount how many fields differ from their saved snapshot.
     */
    function recalcDirty() {
        isDirty = 0;
        $('#lolacore-settings-form').find('input, select, textarea').each(function() {
            const $el = $(this);
            if ($el.attr('data-no-dirty') === '1') return;
            const id  = $el.attr('id') || $el.attr('name');
            if (!id || !(id in savedValues)) return;
            if ($el.is(':checkbox') || $el.is(':radio')) {
                if ($el.is(':checked') !== savedValues[id]) isDirty++;
            } else {
                if ($el.val() !== savedValues[id]) isDirty++;
            }
        });
        $('.lc-domain-toggle').each(function() {
            const key = 'domain_' + $(this).data('domain');
            if (key in savedValues && $(this).is(':checked') !== savedValues[key]) isDirty++;
        });
        updateFooterVisibility();
    }

    function updateFooterVisibility() {
        if (isDirty > 0) {
            const label = isDirty === 1
                ? 'You have 1 unsaved change.'
                : 'You have ' + isDirty + ' unsaved changes.';
            $dirtyLabel.text(label);
            $footer.slideDown(200);
        } else {
            $footer.slideUp(200);
        }
    }

    // Take initial snapshot
    snapshotFormValues();

    // Listen for changes on all tracked elements
    $('#lolacore-settings-form').on('change input', 'input, select, textarea', function() {
        recalcDirty();
    });
    $(document).on('change', '.lc-domain-toggle', function() {
        recalcDirty();
    });

    // Beforeunload guard
    $(window).on('beforeunload', function() {
        if (isDirty > 0) {
            return 'You have unsaved changes. Leave anyway?';
        }
    });

    // --- 1. Avatar Picker (wp.media) ---
    let frame;

    $('#btn-change-avatar').on('click', function(e) {
        e.preventDefault();

        if (frame) {
            frame.open();
            return;
        }

        frame = wp.media({
            title:    'Select Lola Avatar',
            button:   { text: 'Use this image' },
            multiple: false
        });

        frame.on('select', function() {
            const attachment = frame.state().get('selection').first().toJSON();
            const thumbUrl   = attachment.sizes && attachment.sizes.thumbnail
                ? attachment.sizes.thumbnail.url
                : attachment.url;

            $('#lola_avatar_attachment_id').val(attachment.id);
            $('#current-lola-avatar').attr('src', thumbUrl);
            $('.header-avatar').attr('src', thumbUrl);
            recalcDirty();
        });

        frame.open();
    });

    $('#btn-restore-avatar').on('click', function() {
        $('#lola_avatar_attachment_id').val(0);
        const defaultUrl = lolacore_ajax.default_avatar_url;
        $('#current-lola-avatar').attr('src', defaultUrl);
        $('.header-avatar').attr('src', defaultUrl);
        recalcDirty();
    });

    // --- 2. Restore Memory Defaults ---
    $('#btn-restore-memory-defaults').on('click', function() {
        showConfirmModal(
            'Restore Defaults',
            'Are you sure you want to restore memory defaults?',
            'Restore Defaults',
            'danger',
            function() {
                $.ajax({
                    url:  lolacore_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action:      'lolacore_restore_defaults',
                        _ajax_nonce: lolacore_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#memory_decay_rate').val('0.02');
                            $('#memory_archive_threshold').val('0.10');
                            $('#memory_max_context_entries').val('20');
                            $('#log_retention_days').val('90');
                            snapshotFormValues();
                            recalcDirty();
                            showMessage('Memory defaults restored.', 'success');
                        } else {
                            showMessage('Failed to restore defaults.', 'error');
                        }
                    }
                });
            }
        );
    });

    // --- 3. Save Settings Form ---
    $('#lolacore-settings-form').on('submit', function(e) {
        e.preventDefault();

        const $btn     = $('#btn-save-settings');
        const $spinner = $('#save-spinner');

        $btn.prop('disabled', true);
        $spinner.addClass('is-active');

        const formData = $(this).serialize() + '&action=lolacore_save_settings&_ajax_nonce=' + lolacore_ajax.nonce;

        const disabledDomains = [];
        $('.lc-domain-toggle').each(function() {
            if (!$(this).is(':checked')) {
                disabledDomains.push($(this).data('domain'));
            }
        });

        const domainsPromise = $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'lolacore_save_domains',
                _ajax_nonce: lolacore_ajax.nonce,
                disabled_domains: JSON.stringify(disabledDomains)
            }
        });

        const settingsPromise = $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: formData
        });

        $.when(settingsPromise, domainsPromise).done(function(settingsRes, domainsRes) {
            const sRes = settingsRes[0];
            if (sRes.success) {
                isDirty = 0;
                snapshotFormValues();
                updateFooterVisibility();
                showMessage(sRes.data.message, 'success');
                setTimeout(() => location.reload(), 1200);
            } else {
                showMessage(sRes.data.message || 'Error saving settings.', 'error');
            }
        }).fail(function() {
            showMessage('Server error occurred.', 'error');
        }).always(function() {
            $btn.prop('disabled', false);
            $spinner.removeClass('is-active');
        });
    });

    // --- 4. Discard Settings ---
    $('#btn-discard-settings').on('click', function(e) {
        e.preventDefault();
        // Revert all tracked fields to their saved snapshot values
        $('#lolacore-settings-form').find('input, select, textarea').each(function() {
            const $el = $(this);
            const id  = $el.attr('id') || $el.attr('name');
            if (!id || !(id in savedValues)) return;
            if ($el.is(':checkbox') || $el.is(':radio')) {
                $el.prop('checked', savedValues[id]);
            } else {
                $el.val(savedValues[id]);
            }
        });
        $('.lc-domain-toggle').each(function() {
            const key = 'domain_' + $(this).data('domain');
            if (key in savedValues) $(this).prop('checked', savedValues[key]);
        });
        isDirty = 0;
        updateFooterVisibility();
        showMessage('Changes discarded.', 'success');
    });

    // --- 5. Ability Domain Toggles ---
    $('#lc-toggle-abilities-list').on('click', function(e) {
        e.preventDefault();
        const $list = $('#lc-abilities-list');
        $list.slideToggle(200);
        const text = $list.is(':visible') ? 'Hide' : 'View all';
        // We will just let the arrow handle context or keep the original text,
        // Actually, just toggling is fine.
    });

    // --- 6. Safety & Confirmations ---
    $('#btn-save-safety').on('click', function() {
        const $btn     = $(this);
        const $spinner = $('#safety-spinner');

        $btn.prop('disabled', true);
        $spinner.addClass('is-active');

        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action:                 'lolacore_save_safety',
                _ajax_nonce:            lolacore_ajax.nonce,
                safety_confirm_writes:  $('#safety_confirm_writes').is(':checked') ? '1' : '0',
                safety_require_backup:  $('#safety_require_backup').is(':checked') ? '1' : '0',
                safety_learning_mode:   $('#safety_learning_mode').is(':checked')  ? '1' : '0'
            }
        }).done(function(res) {
            if (res.success) {
                if (res.data && res.data.values) {
                    $('#safety_confirm_writes').prop('checked', res.data.values.safety_confirm_writes === '1');
                    $('#safety_require_backup').prop('checked', res.data.values.safety_require_backup === '1');
                    $('#safety_learning_mode').prop('checked',  res.data.values.safety_learning_mode  === '1');
                }
                showMessage(res.data.message, res.data.warning ? 'error' : 'success');
            } else {
                showMessage((res.data && res.data.message) || 'Failed to save safety settings.', 'error');
            }
        }).fail(function() {
            showMessage('Server error while saving safety settings.', 'error');
        }).always(function() {
            $btn.prop('disabled', false);
            $spinner.removeClass('is-active');
        });
    });

    // --- 7. Maintenance: Re-scan ---
    $('#btn-maint-rescan').on('click', function() {
        const $btn = $(this);
        showConfirmModal(
            'Re-scan Site',
            'Re-scan the site? This rebuilds the scan snapshot Lola uses as reference.',
            'Re-scan',
            'primary',
            function() {
                runMaintenanceAction($btn, 'lolacore_maintenance_rescan');
            }
        );
    });

    // --- 8. Maintenance: Export ---
    $('#btn-maint-export').on('click', function() {
        const $btn = $(this);
        $btn.prop('disabled', true);
        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: { action: 'lolacore_maintenance_export', _ajax_nonce: lolacore_ajax.nonce }
        }).done(function(res) {
            if (res.success && res.data && res.data.content) {
                triggerDownload(res.data.filename || 'lolacore-memory.json', res.data.content);
                showMessage('Memory exported.', 'success');
            } else {
                showMessage((res.data && res.data.message) || 'Export failed.', 'error');
            }
        }).fail(function() {
            showMessage('Server error during export.', 'error');
        }).always(function() {
            $btn.prop('disabled', false);
        });
    });

    // --- 9. Maintenance: Import ---
    $('#btn-maint-import').on('click', function() {
        $('#maint-import-file').trigger('click');
    });

    $('#maint-import-file').on('change', function() {
        const file = this.files && this.files[0];
        if (!file) {
            return;
        }
        
        const $input = $(this);
        showConfirmModal(
            'Import Memory',
            'Import memory from "<strong>' + file.name + '</strong>"? Existing facts will be kept; imported facts are added.',
            'Import',
            'primary',
            function() {
                const $btn = $('#btn-maint-import');
                $btn.prop('disabled', true);

                const formData = new FormData();
                formData.append('action', 'lolacore_maintenance_import');
                formData.append('_ajax_nonce', lolacore_ajax.nonce);
                formData.append('memory_file', file);

                $.ajax({
                    url:         lolacore_ajax.ajax_url,
                    type:        'POST',
                    data:        formData,
                    processData: false,
                    contentType: false
                }).done(function(res) {
                    if (res.success) {
                        showMessage(res.data.message, 'success');
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        showMessage((res.data && res.data.message) || 'Import failed.', 'error');
                    }
                }).fail(function() {
                    showMessage('Server error during import.', 'error');
                }).always(function() {
                    $btn.prop('disabled', false);
                    $('#maint-import-file').val('');
                });
            },
            function() {
                $input.val('');
            }
        );
    });

    // --- 10. Maintenance: Compact ---
    $('#btn-maint-compact').on('click', function() {
        const $btn = $(this);
        showConfirmModal(
            'Compact Memory',
            '<p style="margin-bottom:12px;">Compacting cleans up Lola\'s memory by removing information she no longer needs. Think of it as tidying up an old filing cabinet — useful files stay, forgotten ones go.</p>' +
            '<p style="margin-bottom:8px;"><strong>What gets deleted:</strong></p>' +
            '<ul style="margin:0 0 12px 18px; list-style:disc; line-height:1.7;">' +
                '<li><strong>Archived facts</strong> — information Lola already marked as outdated (e.g., old plugin versions after an update).</li>' +
                '<li><strong>Forgotten facts</strong> — facts that haven\'t been accessed in a long time and whose relevance score dropped below 0.10.</li>' +
            '</ul>' +
            '<p style="margin-bottom:8px;"><strong>What stays safe:</strong></p>' +
            '<ul style="margin:0 0 12px 18px; list-style:disc; line-height:1.7;">' +
                '<li>All actively used facts that Lola references in conversations.</li>' +
                '<li>Recent facts and anything with a healthy relevance score.</li>' +
            '</ul>' +
            '<p style="color:var(--lc-text-secondary); font-size:13px;">💡 <strong>Tip:</strong> Export a backup before compacting if you want to keep a full snapshot. This action cannot be undone.</p>',
            'Compact Now',
            'danger',
            function() {
                runMaintenanceAction($btn, 'lolacore_maintenance_compact');
            }
        );
    });

    // --- 11. Maintenance: Wipe (double confirm) ---
    $('#btn-maint-wipe').on('click', function() {
        $('#lc-wipe-token').val('');
        $('#lc-wipe-modal').fadeIn(200);
        setTimeout(() => $('#lc-wipe-token').focus(), 250);
    });

    $('#btn-wipe-cancel').on('click', function() {
        $('#lc-wipe-modal').fadeOut(200);
    });

    $('#btn-wipe-confirm').on('click', function() {
        const token = $('#lc-wipe-token').val().trim();
        if (token !== 'WIPE') {
            showMessage('Wipe cancelled. Confirmation token did not match.', 'error');
            $('#lc-wipe-modal').fadeOut(200);
            return;
        }
        $('#lc-wipe-modal').fadeOut(200);
        runMaintenanceAction($('#btn-maint-wipe'), 'lolacore_maintenance_wipe', { confirmation: 'WIPE' });
    });

    /**
     * Run a maintenance AJAX action with a button busy state and standardized
     * success/error messaging. Used by re-scan, compact, and wipe.
     */
    function runMaintenanceAction($btn, action, extraData) {
        const originalLabel = $btn.text();
        $btn.prop('disabled', true).text('Working…');

        const data = $.extend({
            action:      action,
            _ajax_nonce: lolacore_ajax.nonce
        }, extraData || {});

        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: data
        }).done(function(res) {
            if (res.success) {
                showMessage(res.data.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showMessage((res.data && res.data.message) || 'Action failed.', 'error');
            }
        }).fail(function() {
            showMessage('Server error during maintenance action.', 'error');
        }).always(function() {
            $btn.prop('disabled', false).text(originalLabel);
        });
    }

    /**
     * Triggers a browser download of a text payload as a file.
     */
    function triggerDownload(filename, content) {
        const blob = new Blob([content], { type: 'application/json' });
        const url  = window.URL.createObjectURL(blob);
        const a    = document.createElement('a');
        a.href     = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }

    // --- Helpers ---

    /**
     * Display an inline notification above the save button.
     *
     * @param {string} msg   Message text.
     * @param {string} type  'success' | 'error'
     */
    function showMessage(msg, type) {
        const color = type === 'success' ? '#00a32a' : '#d63638';
        const html  = `<div style="padding:10px;margin-bottom:15px;border-left:4px solid ${color};background:#fff;box-shadow:0 1px 1px rgba(0,0,0,0.04);">
            <p style="margin:0;">${msg}</p>
        </div>`;

        const $container = $('#lolacore-settings-messages');
        $container.html(html).show();
        setTimeout(() => $container.fadeOut(), 4000);
    }
    /**
     * Show a generic confirmation modal.
     *
     * @param {string} title   The modal title.
     * @param {string} message The modal message.
     * @param {string} btnText The text for the confirm button.
     * @param {string} btnType The CSS class for the confirm button ('primary', 'danger').
     * @param {function} onConfirm Callback when user clicks Confirm.
     * @param {function} onCancel Optional callback when user clicks Cancel.
     */
    function showConfirmModal(title, message, btnText, btnType, onConfirm, onCancel) {
        $('#lc-confirm-title').text(title);
        $('#lc-confirm-message').html(message);
        
        const $btnConfirm = $('#btn-confirm-ok');
        $btnConfirm.text(btnText).removeClass('primary danger ghost').addClass(btnType);
        
        $btnConfirm.off('click').on('click', function() {
            $('#lc-confirm-modal').fadeOut(200);
            if (typeof onConfirm === 'function') onConfirm();
        });

        $('#btn-confirm-cancel').off('click').on('click', function() {
            $('#lc-confirm-modal').fadeOut(200);
            if (typeof onCancel === 'function') onCancel();
        });

        $('#lc-confirm-modal').fadeIn(200);
    }

    // --- 12. Skills: Toggle ---
    $(document).on('change', '.lolacore-skill-toggle', function() {
        const $toggle  = $(this);
        const name     = $toggle.data('skillName');
        const enabled  = $toggle.is(':checked') ? '1' : '0';

        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action:      'lolacore_skill_toggle',
                _ajax_nonce: lolacore_ajax.nonce,
                skill_name:  name,
                enabled:     enabled
            }
        }).done(function(res) {
            if (res.success) {
                showMessage(res.data.message, 'success');
            } else {
                // Revert the toggle
                $toggle.prop('checked', !$toggle.is(':checked'));
                showMessage((res.data && res.data.message) || 'Toggle failed.', 'error');
            }
        }).fail(function() {
            $toggle.prop('checked', !$toggle.is(':checked'));
            showMessage('Server error while toggling skill.', 'error');
        });
    });

    // --- 13. Skills: Delete ---
    $(document).on('click', '.lc-skill-delete-btn', function() {
        const $btn  = $(this);
        const name  = $btn.data('skillName');
        const $row  = $btn.closest('.lc-skill-row');

        showConfirmModal(
            'Delete Skill',
            'Delete skill "<strong>' + $('<span>').text(name).html() + '</strong>"? This cannot be undone.',
            'Delete',
            'danger',
            function() {
                $btn.prop('disabled', true);
                $.ajax({
                    url:  lolacore_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action:      'lolacore_skill_delete',
                        _ajax_nonce: lolacore_ajax.nonce,
                        skill_name:  name
                    }
                }).done(function(res) {
                    if (res.success) {
                        $row.addClass('lc-skill-row--removing');
                        setTimeout(function() { $row.remove(); }, 400);
                        showMessage(res.data.message, 'success');
                    } else {
                        showMessage((res.data && res.data.message) || 'Delete failed.', 'error');
                    }
                }).fail(function() {
                    showMessage('Server error while deleting skill.', 'error');
                }).always(function() {
                    $btn.prop('disabled', false);
                });
            }
        );
    });

    // --- 14. Skills: Reload ---
    $('#lolacore-reload-skills').on('click', function() {
        const $btn = $(this);
        $btn.prop('disabled', true).text('Reloading…');

        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action:      'lolacore_skill_reload',
                _ajax_nonce: lolacore_ajax.nonce
            }
        }).done(function(res) {
            if (res.success) {
                showMessage(res.data.message, 'success');
                setTimeout(function() { window.location.reload(); }, 1200);
            } else {
                showMessage((res.data && res.data.message) || 'Reload failed.', 'error');
                $btn.prop('disabled', false).text('Reload skills');
            }
        }).fail(function() {
            showMessage('Server error while reloading skills.', 'error');
            $btn.prop('disabled', false).text('Reload skills');
        });
    });

    // --- 15. Skills: Import Modal ---
    var $importModal = $('#lolacore-import-modal')[0];

    $('#lolacore-import-skill-btn').on('click', function() {
        if ($importModal && typeof $importModal.showModal === 'function') {
            $importModal.showModal();
        }
    });

    $('#lolacore-import-cancel').on('click', function() {
        if ($importModal && typeof $importModal.close === 'function') {
            $importModal.close();
        }
    });

    // Tab switching
    $(document).on('click', '.lc-skill-import-tab', function() {
        var tab = $(this).data('tab');
        $('.lc-skill-import-tab').removeClass('active');
        $(this).addClass('active');
        $('.lc-skill-import-panel').hide();
        $('.lc-skill-import-panel[data-panel="' + tab + '"]').show();
    });

    // File input label
    $('#lolacore-import-file').on('change', function() {
        var name = this.files && this.files[0] ? this.files[0].name : 'No file selected';
        $('#lolacore-import-file-name').text(name);
    });

    // Import submit
    $('#lolacore-import-submit').on('click', function() {
        var $btn       = $(this);
        var $label     = $btn.find('.lc-btn-label');
        var $spinner   = $btn.find('.lc-btn-spinner');
        var $error     = $('#lolacore-import-error');
        var activeTab  = $('.lc-skill-import-tab.active').data('tab');

        $error.hide().text('');
        $label.hide();
        $spinner.show();
        $btn.prop('disabled', true);

        if (activeTab === 'upload') {
            var fileInput = document.getElementById('lolacore-import-file');
            if (!fileInput || !fileInput.files || !fileInput.files[0]) {
                $error.text('Please select a file.').show();
                $label.show(); $spinner.hide(); $btn.prop('disabled', false);
                return;
            }
            var formData = new FormData();
            formData.append('action', 'lolacore_skill_import');
            formData.append('_ajax_nonce', lolacore_ajax.nonce);
            formData.append('skill_file', fileInput.files[0]);

            $.ajax({
                url:         lolacore_ajax.ajax_url,
                type:        'POST',
                data:        formData,
                processData: false,
                contentType: false
            }).done(handleImportResponse).fail(handleImportFail)
              .always(function() { $label.show(); $spinner.hide(); $btn.prop('disabled', false); });
        } else {
            var content = $('#lolacore-import-paste').val();
            if (!content || !content.trim()) {
                $error.text('Skill content cannot be empty.').show();
                $label.show(); $spinner.hide(); $btn.prop('disabled', false);
                return;
            }
            $.ajax({
                url:  lolacore_ajax.ajax_url,
                type: 'POST',
                data: {
                    action:      'lolacore_skill_import',
                    _ajax_nonce: lolacore_ajax.nonce,
                    content:     content
                }
            }).done(handleImportResponse).fail(handleImportFail)
              .always(function() { $label.show(); $spinner.hide(); $btn.prop('disabled', false); });
        }

        function handleImportResponse(res) {
            if (res.success) {
                showMessage(res.data.message, 'success');
                if ($importModal && typeof $importModal.close === 'function') {
                    $importModal.close();
                }
                setTimeout(function() { window.location.reload(); }, 1200);
            } else {
                $error.text((res.data && res.data.message) || 'Import failed.').show();
            }
        }
        function handleImportFail() {
            $error.text('Server error during import.').show();
        }
    });

    // --- 16. Skills: Source Viewer (read-only) ---
    // Editing is delegated to Lola via the updateSkillDraft tool.
    // The "View source" button just toggles the read-only markdown panel.
    $(document).on('click', '.lc-skill-view-btn', function() {
        var $row    = $(this).closest('.lc-skill-row');
        var $viewer = $row.find('.lc-skill-viewer');
        $viewer.slideToggle(200);
    });

    // --- 17. Skills: Master Section Toggle (Beta) ---
    // Self-saving via its own AJAX endpoint. Marked data-no-dirty so the global
    // dirty tracker ignores it; UI updates apply in place without reloading.
    $('#lolacore-skills-section-toggle').on('change', function() {
        var $toggle  = $(this);
        var enabled  = $toggle.is(':checked');
        var $section = $('#lolacore-skills');
        var $content = $section.find('.lc-skills-content');

        $toggle.prop('disabled', true);

        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action:      'lolacore_skills_section_toggle',
                _ajax_nonce: lolacore_ajax.nonce,
                enabled:     enabled ? '1' : '0'
            }
        }).done(function(res) {
            if (res.success) {
                $section.toggleClass('lc-skills-section--off', !enabled);
                $content.toggleClass('lc-skills-content--disabled', !enabled);
                showMessage(res.data.message, 'success');
            } else {
                $toggle.prop('checked', !enabled);
                showMessage((res.data && res.data.message) || 'Toggle failed.', 'error');
            }
        }).fail(function() {
            $toggle.prop('checked', !enabled);
            showMessage('Server error while toggling Skills system.', 'error');
        }).always(function() {
            $toggle.prop('disabled', false);
        });
    });

    // --- 20. Skills: Save Advanced Params ---
    $('#lolacore-save-skill-params').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text('Saving…');

        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action:           'lolacore_save_skill_params',
                _ajax_nonce:      lolacore_ajax.nonce,
                max_active:       $('#lolacore-param-max-active').val(),
                max_per_prompt:   $('#lolacore-param-max-per-prompt').val(),
                char_budget:      $('#lolacore-param-char-budget').val(),
                cache_ttl_min:    $('#lolacore-param-cache-ttl').val(),
                require_approval: $('#lolacore-param-require-approval').is(':checked') ? '1' : '0'
            }
        }).done(function(res) {
            if (res.success) {
                showMessage(res.data.message, 'success');
                // Reflect server-clamped values back to inputs.
                if (res.data.values) {
                    var v = res.data.values;
                    if (v.max_active !== undefined)       $('#lolacore-param-max-active').val(v.max_active);
                    if (v.max_per_prompt !== undefined)   $('#lolacore-param-max-per-prompt').val(v.max_per_prompt);
                    if (v.char_budget !== undefined)      $('#lolacore-param-char-budget').val(v.char_budget);
                    if (v.cache_ttl_min !== undefined)    $('#lolacore-param-cache-ttl').val(v.cache_ttl_min);
                    if (v.require_approval !== undefined) $('#lolacore-param-require-approval').prop('checked', !!v.require_approval);
                }
            } else {
                showMessage((res.data && res.data.message) || 'Save failed.', 'error');
            }
        }).fail(function() {
            showMessage('Server error while saving skill parameters.', 'error');
        }).always(function() {
            $btn.prop('disabled', false).text('Save');
        });
    });

    // --- 21. Skills: Restore Defaults ---
    $('#lolacore-restore-skill-defaults').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text('Restoring…');

        $.ajax({
            url:  lolacore_ajax.ajax_url,
            type: 'POST',
            data: {
                action:      'lolacore_restore_skill_defaults',
                _ajax_nonce: lolacore_ajax.nonce
            }
        }).done(function(res) {
            if (res.success) {
                showMessage(res.data.message, 'success');
                // Repopulate inputs from the response defaults.
                if (res.data.defaults) {
                    var d = res.data.defaults;
                    if (d.max_active !== undefined)       $('#lolacore-param-max-active').val(d.max_active);
                    if (d.max_per_prompt !== undefined)   $('#lolacore-param-max-per-prompt').val(d.max_per_prompt);
                    if (d.char_budget !== undefined)      $('#lolacore-param-char-budget').val(d.char_budget);
                    if (d.cache_ttl_min !== undefined)    $('#lolacore-param-cache-ttl').val(d.cache_ttl_min);
                    if (d.require_approval !== undefined) $('#lolacore-param-require-approval').prop('checked', !!d.require_approval);
                }
            } else {
                showMessage((res.data && res.data.message) || 'Restore failed.', 'error');
            }
        }).fail(function() {
            showMessage('Server error while restoring defaults.', 'error');
        }).always(function() {
            $btn.prop('disabled', false).text('Restore defaults');
        });
    });
});
