(function($) {
    "use strict";

    $(document).ready(function() {

        /**
         * ========================================================
         * Init Provider State on Page Load
         *   - Uses current <select> value
         *   - Ensures data-* attributes are correct
         * ========================================================
         */
        var initialProvider = $('#sc-wordai-ai-provider').val() || 'openai';        


        /**
         * ========================================================
         * Provider dropdown change handler
         *   - Apply state immediately (for UI)
         *   - Save provider via AJAX
         *   - Show modal and reload on close
         * ========================================================
         */

        /**
         * Fetch provider-aware runtime settings (image flags etc.) after switching provider
         * WITHOUT reloading (used in editor popups).
         *
         * Requires backend AJAX: sc_wordai_get_provider_runtime_settings
         */        
        // window.scWordAISyncContentPopupRuntimeSettings = function() {
        //     // Only run if the content popup exists on this page
        //     if (!$('.sc-wordai-popup-provider-block').length) return;

        //     return $.ajax({
        //         type: 'POST',
        //         url: sftcy_wordai_metabox_script_obj.adminajax_url,
        //         data: {
        //         action: 'sc_wordai_get_provider_runtime_settings',
        //         security: sftcy_wordai_metabox_script_obj.nonce
        //         }
        //     }).done(function (resp) {
        //         console.log('scWordAISyncContentPopupRuntimeSettings: ' );
        //         console.log(resp);

        //         if (!resp || resp.status !== 'success') return;

        //         // ✅ update global provider from server truth
        //         window.SFTCY_WORDAI_ACTIVE_PROVIDER = resp.provider || window.SFTCY_WORDAI_ACTIVE_PROVIDER;

        //         // ✅ update suggested title number dropdown
        //         if (resp.content && typeof resp.content.suggested_title_number !== 'undefined') {
        //             const n = parseInt(resp.content.suggested_title_number, 10) || 2;
        //             $dialog.find('#scwordai-suggested-titles-number').val(String(n));
        //         }                

        //         // ✅ update image hidden fields (these control upload + featured image)
        //         if (resp.image) {
        //             $('.sc-wordai-generated-images-save-to-gallery-status').val(Number(resp.image.save_to_gallery || 0));
        //             $('.sc-wordai-generated-image-set-feature-status').val(Number(resp.image.set_featured || 0));
        //             $('.sc-wordai-will-generate-images-number').val(Number(resp.image.image_number || 1));
        //         }

        //         // ✅ show/hide manual save row if you implemented the ALWAYS-rendered container
        //         // (recommended: .sc-wordai-save-to-gallery-row)
        //         const saveToGallery = Number(resp.image?.save_to_gallery || 0);
        //         if ($('.sc-wordai-save-to-gallery-row').length) {
        //         if (saveToGallery === 1) {
        //             $('.sc-wordai-save-to-gallery-row').hide();
        //         } else {
        //             $('.sc-wordai-save-to-gallery-row').show();
        //         }
        //         }

        //         // ✅ prevent mixing old provider images with new provider uploads
        //         $('.sc-wordai-generated-images-urls').val('');
        //         $('.sc-wordai-generated-images-model-name').val('');
        //     });
        // }


        /**
         * Unified runtime sync for ALL popups (Content modal + Suggest Title modal)
         * - Uses one backend ajax: sc_wordai_get_provider_runtime_settings
         * - Updates:
         *    ✅ global provider state
         *    ✅ Content Generation modal image flags + UI
         *    ✅ Suggest Title modal suggested title number
         * - Safe: if a specific dialog isn't present, it skips that part
         */
        window.scWordAISyncPopupRuntimeSettings = function (requestedProvider) {

            // If no popup provider blocks exist at all, no need to run
            if (!$('.sc-wordai-popup-provider-block').length) return;

            return $.ajax({
                type: 'POST',
                url: sftcy_wordai_metabox_script_obj.adminajax_url,
                data: {
                    action: 'sc_wordai_get_provider_runtime_settings',
                    security: sftcy_wordai_metabox_script_obj.nonce,
                    provider: requestedProvider || window.SFTCY_WORDAI_ACTIVE_PROVIDER || ''
                }
            }).done(function (resp) {

                // console.log('scWordAISyncPopupRuntimeSettings:', resp);

                if (!resp || resp.status !== 'success') return;

                // ✅ server truth wins
                window.SFTCY_WORDAI_ACTIVE_PROVIDER = resp.provider || window.SFTCY_WORDAI_ACTIVE_PROVIDER;

                /**
                 * ==========================================================
                 * 1) Suggest Title Popup: update suggested title number
                 * ==========================================================
                 */
                const $suggestDialog = $('#suggest-titles-button-click-dialog');
                if ($suggestDialog.length && resp.content && typeof resp.content.suggested_title_number !== 'undefined') {
                    const n = parseInt(resp.content.suggested_title_number, 10) || 2;
                    $suggestDialog.find('#scwordai-suggested-titles-number').val(String(n));
                }

                /**
                 * ==========================================================
                 * 2) Content Generation Popup: update image flags + UI
                 * ==========================================================
                 */
                const $contentDialog = $('#metabox-button-click-dialog');
                if ($contentDialog.length && resp.image) {

                    // hidden fields used by image upload + featured image
                    $contentDialog.find('.sc-wordai-generated-images-save-to-gallery-status')
                        .val(Number(resp.image.save_to_gallery || 0));

                    $contentDialog.find('.sc-wordai-generated-image-set-feature-status')
                        .val(Number(resp.image.set_featured || 0));

                    $contentDialog.find('.sc-wordai-will-generate-images-number')
                        .val(Number(resp.image.image_number || 1));

                    // show/hide manual save row (if you always render it)
                    const saveToGallery = Number(resp.image.save_to_gallery || 0);
                    const $saveRow = $contentDialog.find('.sc-wordai-save-to-gallery-row');
                    if ($saveRow.length) {
                        if (saveToGallery === 1) $saveRow.hide();
                        else $saveRow.show();
                    }

                    // prevent mixing old provider images with new provider uploads
                    $contentDialog.find('.sc-wordai-generated-images-urls').val('');
                    $contentDialog.find('.sc-wordai-generated-images-model-name').val('');
                }

            });
        };


        function providerLabel(provider) {
            const labels = sftcy_wordai_metabox_script_obj.provider_labels || {};
            return labels[provider] || 'OpenAI';
        }

        function normalizeProvider(provider) {
            provider = String(provider || '').toLowerCase();
            return ['openai', 'google', 'anthropic', 'xai'].indexOf(provider) !== -1 ? provider : 'openai';
        }

        function syncProviderPickerIcons(provider) {
            $('select.sc-wordai-ai-provider-select').each(function () {
                const activeProvider = normalizeProvider(provider || $(this).val() || window.SFTCY_WORDAI_ACTIVE_PROVIDER || sftcy_wordai_metabox_script_obj.active_provider || initialProvider);
                const $wrapper = $(this).closest('.sc-wordai-select-wrapper');
                if (!$wrapper.length) return;

                $wrapper.attr('data-active-provider', activeProvider);
                $wrapper.find('.sc-wordai-provider-current-icon__item')
                    .removeClass('is-active')
                    .filter('.sc-wordai-provider-current-icon__item--' + activeProvider)
                    .addClass('is-active');

                const $activeOption = $wrapper.find('.sc-wordai-provider-option[data-provider-value="' + activeProvider + '"]');
                const label = $.trim($activeOption.find('.sc-wordai-provider-option-label').text()) || providerLabel(activeProvider);
                const iconHtml = $activeOption.find('.sc-wordai-provider-option-icon').html() || '';

                $wrapper.find('.sc-wordai-provider-combobox-label').text(label);
                $wrapper.find('.sc-wordai-provider-combobox-icon').html(iconHtml);
                $wrapper.find('.sc-wordai-provider-option')
                    .removeClass('is-active')
                    .attr('aria-selected', 'false');
                $activeOption
                    .addClass('is-active')
                    .attr('aria-selected', 'true');
            });
        }

        window.scWordaiSyncProviderPickerIcons = syncProviderPickerIcons;
        syncProviderPickerIcons();

        function closeProviderPickers($except) {
            $('.sc-wordai-select-wrapper.is-open').not($except || $()).removeClass('is-open')
                .find('.sc-wordai-provider-combobox').attr('aria-expanded', 'false');
        }

        $('body').on('click', '.sc-wordai-provider-combobox', function (event) {
            event.preventDefault();
            event.stopPropagation();

            const $button = $(this);
            const $wrapper = $button.closest('.sc-wordai-select-wrapper');
            const $select = $wrapper.find('select.sc-wordai-ai-provider-select').first();

            if ($select.prop('disabled')) return;

            const willOpen = !$wrapper.hasClass('is-open');
            closeProviderPickers($wrapper);
            $wrapper.toggleClass('is-open', willOpen);
            $button.attr('aria-expanded', willOpen ? 'true' : 'false');
        });

        $('body').on('click', '.sc-wordai-provider-option', function (event) {
            event.preventDefault();
            event.stopPropagation();

            const $option = $(this);
            const provider = normalizeProvider($option.data('provider-value'));
            const $wrapper = $option.closest('.sc-wordai-select-wrapper');
            const $select = $wrapper.find('select.sc-wordai-ai-provider-select').first();

            closeProviderPickers();

            if ($select.prop('disabled')) return;

            if ($select.val() === provider) {
                syncProviderPickerIcons(provider);
                return;
            }

            $select.val(provider).trigger('change');
        });

        $(document).on('click', function () {
            closeProviderPickers();
        });

        $(document).on('keydown', function (event) {
            if (event.key === 'Escape') {
                closeProviderPickers();
            }
        });

        function providerIconHtml(provider) {
            const iconUrls = {
                openai: sftcy_wordai_metabox_script_obj.openai_icon_url || '',
                google: sftcy_wordai_metabox_script_obj.gemini_icon_url || ''
            };

            if (iconUrls[provider]) {
                return '<span class="sc-wordai-provider-modal-icon"><img src="' + iconUrls[provider] + '" alt="" /></span>';
            }

            const iconClass = provider === 'anthropic'
                ? 'fa-solid fa-brain'
                : (provider === 'xai' ? 'fa-solid fa-bolt' : 'fa-solid fa-wand-magic-sparkles');

            return '<span class="sc-wordai-provider-modal-icon"><i class="' + iconClass + '"></i></span>';
        }

        function showInlineMsg($scope, type, msg) {
            let $box = $scope.find('.sc-wordai-provider-switch-msg').first();

            $box
            .removeClass('is-success is-error')
            .addClass(type === 'success' ? 'is-success' : 'is-error')
            .text(msg)
            .stop(true, true)
            .fadeIn(120);

            setTimeout(function () {
            $box.fadeOut(250);
            }, type === 'success' ? 2500 : 4500);
        }

        $('body').on('change', 'select.sc-wordai-ai-provider-select', function () {
            if ($(this).prop('disabled')) return; // ✅ ignore change while generating
            const $select  = $(this);
            const provider = $select.val();
            const context  = String($select.data('context') || '');
            const previousProvider = String($select.attr('data-provider') || window.SFTCY_WORDAI_ACTIVE_PROVIDER || sftcy_wordai_metabox_script_obj.active_provider || 'openai');

            // where to show inline msg for popups            
            const $popupRow = $select.closest('.sc-wordai-popup-provider-block');

            if (context === 'suggest_title_popup') {
                const $suggestDialog = $('#suggest-titles-button-click-dialog');
                $suggestDialog.find('.sc-wordai-suggested-titles-list').empty();
                $suggestDialog.find('.scwordai-suggested-title-wrapper').hide();
                $suggestDialog.find('.prompt-alert-msg, .update-suggested-title-msg').empty();
                $suggestDialog.find('#scwordai-suggested-titles-number').prop('disabled', true);
            }
            

            $.ajax({
                type: 'POST',
                url: sftcy_wordai_metabox_script_obj.adminajax_url,
                data: {
                    action: 'sc_wordai_ai_provider_save',
                    security: sftcy_wordai_metabox_script_obj.nonce,
                    provider: provider
                },
                success: function (resp) {
                    if (!resp || resp.status !== 'success') {
                    if (context === 'suggest_title_popup') {
                        $('#suggest-titles-button-click-dialog #scwordai-suggested-titles-number').prop('disabled', false);
                    }
                    if ($popupRow.length) {
                        showInlineMsg($popupRow, 'error', (resp && resp.message) ? resp.message : 'Provider switch failed.');
                    }
                    return;
                    }

                    /* ================================
                    * ✅ UPDATE GLOBAL PROVIDER STATE
                    * ================================ */
                    window.SFTCY_WORDAI_ACTIVE_PROVIDER = provider;

                    // keep all AI Provider selector dropdowns in sync visually
                    $('select.sc-wordai-ai-provider-select')
                        .val(provider)
                        .attr('data-provider', provider);
                    syncProviderPickerIcons(provider);


                    /* ==========================================================
                    * ✅ IMPORTANT: POPUP CONTEXTS MUST SYNC RUNTIME SETTINGS
                    * (so image upload + featured image flags stay correct)
                    * ========================================================== */
                    // if (context === 'content_popup') {
                    //     scWordAISyncContentPopupRuntimeSettings();
                    // }              
                    
                    if (context === 'content_popup' || context === 'suggest_title_popup') {
                        const syncRequest = scWordAISyncPopupRuntimeSettings(provider);
                        if (context === 'suggest_title_popup' && syncRequest) {
                            syncRequest.always(function () {
                                $('#suggest-titles-button-click-dialog #scwordai-suggested-titles-number').prop('disabled', false);
                            });
                        }
                    }

                    // ✅ Settings pages: keep modal + reload
                    if (context === 'settings_header') {
                        scWordaiShowInfoDialog(
                            providerLabel(provider) + ' selected',
                            '<div class="sc-wordai-provider-switch-dialog-body">' +
                                providerIconHtml(provider) +
                                '<div><strong>' + providerLabel(provider) + ' settings will load now.</strong>' +
                                '<p>Click OK to reload this page with the selected provider settings. Close this window to keep the previous provider.</p></div>' +
                            '</div>',
                            function () { location.reload(true); },
                            function () {
                                $('select.sc-wordai-ai-provider-select')
                                    .val(previousProvider)
                                    .attr('data-provider', previousProvider);
                                window.SFTCY_WORDAI_ACTIVE_PROVIDER = previousProvider;
                                syncProviderPickerIcons(previousProvider);
                                $.ajax({
                                    type: 'POST',
                                    url: sftcy_wordai_metabox_script_obj.adminajax_url,
                                    data: {
                                        action: 'sc_wordai_ai_provider_save',
                                        security: sftcy_wordai_metabox_script_obj.nonce,
                                        provider: previousProvider
                                    }
                                });
                            }
                        );
                        return;
                    }

                    // ✅ Popups: no modal, no reload, just inline confirmation
                    if ($popupRow.length) {
                    showInlineMsg($popupRow, 'success', 'AI Provider switched to ' + providerLabel(provider) + '.');
                    }
                },
                error: function () {
                    if (context === 'suggest_title_popup') {
                        $('#suggest-titles-button-click-dialog #scwordai-suggested-titles-number').prop('disabled', false);
                    }
                    if ($popupRow.length) {
                    showInlineMsg($popupRow, 'error', 'Request failed.');
                    }
                }
            });
        });        



        /**
         * ========================================================
         * Unified Save Handler (OpenAI + Gemini)
         *   - Uses data-apisettings-action from form
         * ========================================================
         */
        $('body').on('submit', '#scwordai-apisettings-form', function(e) {
            e.preventDefault();

            var $form            = $(this);
            var postFormData     = $form.serialize();
            var scWordAIFeedback = $('.sc-wordai-api-settings-msg');
            var ajaxAction       = $form.data('apisettings-action') || 'sc_wordai_openai_apisettings_data';

            scWordAIFeedback.removeClass('success-msg alert-msg error-msg').html('');

            $.ajax({
                type: 'POST',
                url: sftcy_wordai_metabox_script_obj.adminajax_url,
                data: {
                    action:   ajaxAction,
                    security: sftcy_wordai_metabox_script_obj.nonce,
                    postData: postFormData
                },
                success: function(response) {
                    var jsonData = response;
                    if (typeof response === 'string') {
                        try { jsonData = JSON.parse(response); } catch(e) {}
                    }

                    if (!jsonData || typeof jsonData.status === 'undefined') {
                        console.error('Unexpected API settings response', response);
                        scWordAIFeedback.html(
                            '<span class="error-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_error_icon +
                                ' Unexpected response from server.' +
                            '</span>'
                        );
                        return;
                    }

                    if (jsonData.status === 'success') {
                        scWordAIFeedback.html(
                            '<span class="success-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' +
                                jsonData.feedbackMsg +
                            '</span>'
                        );
                    } else if (jsonData.status === 'warning') {
                        scWordAIFeedback.html(
                            '<span class="alert-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' +
                                jsonData.feedbackMsg +
                            '</span>'
                        );
                    } else {
                        scWordAIFeedback.html(
                            '<span class="error-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' +
                                jsonData.feedbackMsg +
                            '</span>'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    console.error(xhr, status, error);
                    scWordAIFeedback.html(
                        '<span class="error-msg">' +
                            sftcy_wordai_metabox_script_obj.wordai_error_icon +
                            ' Failed to save API settings. Please try again.' +
                        '</span>'
                    );
                }
            });

            return false;
        });


        /**
         * ========================================================
         * Unified Reset Handler (OpenAI + Gemini)
         *   - Uses data-reset-action from form
         * ========================================================
         */
        $('body').on('click', '.scwordai-apisettings-form-reset-data-btn', function(e) {
            e.preventDefault();

            var $form            = $('#scwordai-apisettings-form');
            if (!$form.length) {
                return;
            }

            var provider         = $form.data('provider') || 'openai';
            var ajaxAction       = $form.data('reset-action') || 'sc_wordai_openai_apisettings_reset_data';
            var scWordAIFeedback = $('.sc-wordai-api-settings-msg');

            var providerName = providerLabel(provider);
            var dialogTitle = 'Reset ' + providerName + ' API Settings';
            var dialogMessage = 'Are you sure you want to reset all ' + providerName + ' API settings to their default values?';

            SFTCY_WordAI.showDialog(
                dialogTitle,
                dialogMessage,
                function() {

                    scWordAIFeedback
                        .removeClass('success-msg alert-msg error-msg')
                        .html(
                            '<span class="info-msg">' +
                                '<i class="fa-solid fa-spinner fa-spin"></i> Resetting settings...' +
                            '</span>'
                        );

                    $.ajax({
                        type: 'POST',
                        url: sftcy_wordai_metabox_script_obj.adminajax_url,
                        data: {
                            action:   ajaxAction,
                            security: sftcy_wordai_metabox_script_obj.nonce
                        },
                        success: function(response) {
                            var jsonData = response;
                            if (typeof response === 'string') {
                                try { jsonData = JSON.parse(response); } catch(e) {}
                            }

                            if (!jsonData || typeof jsonData.status === 'undefined') {
                                console.error('Unexpected reset response', response);
                                scWordAIFeedback.html(
                                    '<span class="error-msg">' +
                                        sftcy_wordai_metabox_script_obj.wordai_error_icon +
                                        ' Unexpected response from server.' +
                                    '</span>'
                                );
                                return;
                            }

                            if (jsonData.status === 'success') {
                                scWordAIFeedback.html(
                                    '<span class="success-msg">' +
                                        sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' +
                                        jsonData.feedbackMsg +
                                    '</span>'
                                );

                                var successTitle = providerName + ' Settings Reset';
                                var successMsg = 'Your ' + providerName + ' API settings have been restored to default values.';

                                SFTCY_WordAI.showDialog(
                                    successTitle,
                                    successMsg,
                                    function() {
                                        window.location.reload(true);
                                    },
                                    { type: 'alert', variant: 'success', buttons: { ok: 'OK' } }
                                );
                            }
                            else if (jsonData.status === 'warning') {
                                scWordAIFeedback.html(
                                    '<span class="alert-msg">' +
                                        sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' +
                                        jsonData.feedbackMsg +
                                    '</span>'
                                );

                                SFTCY_WordAI.showDialog(
                                    'Notice',
                                    jsonData.feedbackMsg,
                                    null,
                                    { type: 'alert', variant: 'warning', buttons: { ok: 'Got It' } }
                                );
                            }
                            else {
                                scWordAIFeedback.html(
                                    '<span class="error-msg">' +
                                        sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' +
                                        jsonData.feedbackMsg +
                                    '</span>'
                                );

                                SFTCY_WordAI.showDialog(
                                    'Error',
                                    jsonData.feedbackMsg,
                                    null,
                                    { type: 'alert', variant: 'error', buttons: { ok: 'Close' } }
                                );
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error(xhr, status, error);

                            scWordAIFeedback.html(
                                '<span class="error-msg">' +
                                    sftcy_wordai_metabox_script_obj.wordai_error_icon +
                                    ' Failed to reset settings. Please try again.' +
                                '</span>'
                            );

                            SFTCY_WordAI.showDialog(
                                'Server Error',
                                'Could not complete the reset operation. Please check your connection or contact support.',
                                null,
                                { type: 'alert', variant: 'error' }
                            );
                        }
                    });
                },
                { variant: 'warning', type: 'confirm', buttons: { ok: 'Yes, Reset', cancel: 'Cancel' } }
            );
        });

       /**
        *  Content Settings - Save
        *  Save Content Settings Form
        *  Unified Save Handler for Content Settings (OpenAI + Gemini)
        */        
        $('body').on('submit', '#scwordai-content-settings-form', function (e) {
            e.preventDefault();

            let $form            = $(this);
            let postFormData     = $form.serialize();
            let scWordAIFeedback = $('.sc-wordai-api-settings-msg');

            let ajaxAction = $form.data('save-action') || 'sc_wordai_openai_content_settings_data';

            scWordAIFeedback.removeClass('success-msg alert-msg error-msg').html('');

            $.ajax({
                type: 'POST',
                url: sftcy_wordai_metabox_script_obj.adminajax_url,
                data: {
                    action:   ajaxAction,
                    security: sftcy_wordai_metabox_script_obj.nonce,
                    postData: postFormData
                },
                success: function(response) {
                    let jsonData = response;
                    if (typeof response === 'string') {
                        try { jsonData = JSON.parse(response); } catch (e) {}
                    }

                    if (jsonData.status === 'success') {
                        scWordAIFeedback.html(
                            '<span class="success-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' +
                                jsonData.feedbackMsg +
                            '</span>'
                        );
                    }
                    else if (jsonData.status === 'warning') {
                        scWordAIFeedback.html(
                            '<span class="alert-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' +
                                jsonData.feedbackMsg +
                            '</span>'
                        );
                    }
                    else {
                        scWordAIFeedback.html(
                            '<span class="error-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' +
                                jsonData.feedbackMsg +
                            '</span>'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    console.error(xhr, status, error);
                    scWordAIFeedback.html(
                        '<span class="error-msg">' +
                            sftcy_wordai_metabox_script_obj.wordai_error_icon +
                            ' Failed to save content settings. Please try again.' +
                        '</span>'
                    );
                }
            });

            return false;
        });

        /**
         * ============================================================================
         * Content Settings - Reset
         * Unified Reset Handler for Content Settings (OpenAI + Google Gemini)
         * Matches API Reset UX 100% — Confirm → Spinner → Success Modal → Reload
         * ============================================================================
         */
        $('body').on('click', '.scwordai-content-settings-form-reset-data-btn', function (e) {
            e.preventDefault();

            const $form = $('#scwordai-content-settings-form');
            if (!$form.length) return;

            const provider   = $form.data('provider') || 'openai';
            const ajaxAction = $form.data('reset-action') || 'sc_wordai_openai_content_settings_reset_data';
            const $feedback  = $('.sc-wordai-api-settings-msg');

            // Provider-aware dialog title & messages
            const providerName = providerLabel(provider);
            const dialogTitle = 'Reset ' + providerName + ' Content Settings';
            const dialogMessage = 'Are you sure you want to reset all ' + providerName + ' content settings to their default values?';

            // Confirmation modal
            SFTCY_WordAI.showDialog(
                dialogTitle,
                dialogMessage,
                function () {

                    // Show spinner while processing
                    $feedback
                        .removeClass('success-msg alert-msg error-msg')
                        .html(
                            '<span class="info-msg">' +
                                '<i class="fa-solid fa-spinner fa-spin"></i> Resetting content settings...' +
                            '</span>'
                        );

                    // Ajax reset
                    $.ajax({
                        type: 'POST',
                        url: sftcy_wordai_metabox_script_obj.adminajax_url,
                        data: {
                            action: ajaxAction,
                            security: sftcy_wordai_metabox_script_obj.nonce
                        },
                        success: function (response) {

                            let json = response;
                            if (typeof response === 'string') {
                                try { json = JSON.parse(response); } catch (e) {}
                            }

                            if (!json || typeof json.status === 'undefined') {
                                $feedback.html(
                                    '<span class="error-msg">' +
                                        sftcy_wordai_metabox_script_obj.wordai_error_icon +
                                        ' Unexpected server response.' +
                                    '</span>'
                                );
                                return;
                            }

                            // SUCCESS
                            if (json.status === 'success') {

                                $feedback.html(
                                    '<span class="success-msg">' +
                                        sftcy_wordai_metabox_script_obj.wordai_success_icon +
                                        ' ' + json.feedbackMsg +
                                    '</span>'
                                );

                                const successTitle = providerName + ' Content Settings Reset';
                                const successMessage = 'Your ' + providerName + ' content settings have been restored to default values.';

                                // Show success confirmation
                                SFTCY_WordAI.showDialog(
                                    successTitle,
                                    successMessage,
                                    function () {
                                        window.location.reload(true);
                                    },
                                    { type: 'alert', variant: 'success', buttons: { ok: 'OK' } }
                                );

                                return;
                            }

                            // WARNING
                            if (json.status === 'warning') {
                                $feedback.html(
                                    '<span class="alert-msg">' +
                                        sftcy_wordai_metabox_script_obj.wordai_info_icon +
                                        ' ' + json.feedbackMsg +
                                    '</span>'
                                );

                                SFTCY_WordAI.showDialog(
                                    'Notice',
                                    json.feedbackMsg,
                                    null,
                                    { type: 'alert', variant: 'warning', buttons: { ok: 'Got It' } }
                                );

                                return;
                            }

                            // ERROR
                            $feedback.html(
                                '<span class="error-msg">' +
                                    sftcy_wordai_metabox_script_obj.wordai_error_icon +
                                    ' ' + json.feedbackMsg +
                                '</span>'
                            );

                            SFTCY_WordAI.showDialog(
                                'Error',
                                json.feedbackMsg,
                                null,
                                { type: 'alert', variant: 'error', buttons: { ok: 'Close' } }
                            );
                        },

                        error: function (xhr, status, error) {
                            console.error('Content Reset Error:', xhr, status, error);

                            $feedback.html(
                                '<span class="error-msg">' +
                                    sftcy_wordai_metabox_script_obj.wordai_error_icon +
                                    ' Failed to reset content settings. Please try again.' +
                                '</span>'
                            );

                            SFTCY_WordAI.showDialog(
                                'Server Error',
                                'Could not complete the reset operation. Please check your connection or try again later.',
                                null,
                                { type: 'alert', variant: 'error', buttons: { ok: 'OK' } }
                            );
                        }
                    });
                },

                // Confirm modal config
                {
                    variant: 'warning',
                    type: 'confirm',
                    buttons: { ok: 'Yes, Reset', cancel: 'Cancel' }
                }
            );
        });


    /**
     * ============================================================
     *  Image Settings - Save
     *  WordAI - Unified Image Settings Save Handler
     *  Supports: OpenAI, Google Gemini, Future Providers
     * ============================================================
     */
    jQuery('body').on("submit", "#scwordai-image-settings-form", function (e) {
        e.preventDefault();

        let $form      = jQuery(this);
        let provider   = $form.data('provider') || 'openai';
        let ajaxAction = $form.data('save-action') || 'sc_wordai_openai_image_settings_data';
        let postData   = $form.serialize();

        let scWordAIFeedback = jQuery('.sc-wordai-api-settings-msg');
        scWordAIFeedback.removeClass('success-msg alert-msg error-msg').html('');

        jQuery.ajax({
            type: 'POST',
            url : sftcy_wordai_metabox_script_obj.adminajax_url,
            data: {
                action   : ajaxAction,
                security : sftcy_wordai_metabox_script_obj.nonce,
                postData : postData
            },
            success: function (response) {
                let jsonData = response;

                if (typeof response === 'string') {
                    try { jsonData = JSON.parse(response); } catch (e) {}
                }

                // SUCCESS
                if (jsonData.status === 'success') {
                    scWordAIFeedback.html(
                        '<span class="success-msg">' +
                        sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' +
                        jsonData.feedbackMsg +
                        '</span>'
                    );

                    setTimeout(function () {
                        window.location.reload(true);
                    }, 1500);
                }

                // WARNING
                else if (jsonData.status === 'warning') {
                    scWordAIFeedback.html(
                        '<span class="alert-msg">' +
                        sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' +
                        jsonData.feedbackMsg +
                        '</span>'
                    );
                }

                // FAIL
                else {
                    scWordAIFeedback.html(
                        '<span class="error-msg">' +
                        sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' +
                        jsonData.feedbackMsg +
                        '</span>'
                    );
                }
            },

            error: function (xhr, status, error) {
                console.error(xhr, status, error);

                scWordAIFeedback.html(
                    '<span class="error-msg">' +
                    sftcy_wordai_metabox_script_obj.wordai_error_icon +
                    ' Server error. Please try again.' +
                    '</span>'
                );
            }
        });

        return false;
    });


    /**
     * ============================================================
     *  Image Settings - Reset
     *  WordAI - Unified Image Settings Reset Handler
     * ============================================================
     */
    jQuery('body').on('click', '.scwordai-image-settings-form-reset-data-btn', function (e) {
        e.preventDefault();

        let $form        = jQuery('#scwordai-image-settings-form');
        let provider     = $form.data('provider') || 'openai';
        let ajaxAction   = $form.data('reset-action') || 'sc_wordai_openai_image_settings_reset_data';
        let scFeedback   = jQuery('.sc-wordai-api-settings-msg');

        let providerName = providerLabel(provider);
        let dialogTitle = 'Reset ' + providerName + ' Image Settings';
        let dialogMessage = 'Are you sure you want to reset all ' + providerName + ' image settings to default?';

        SFTCY_WordAI.showDialog(
            dialogTitle,
            dialogMessage,
            function () {
                scFeedback
                    .removeClass('success-msg alert-msg error-msg')
                    .html('<span class="info-msg"><i class="fa-solid fa-spinner fa-spin"></i> Resetting settings...</span>');

                jQuery.ajax({
                    type: 'POST',
                    url : sftcy_wordai_metabox_script_obj.adminajax_url,
                    data: {
                        action   : ajaxAction,
                        security : sftcy_wordai_metabox_script_obj.nonce
                    },
                    success: function (response) {
                        let jsonData = response;

                        if (typeof response === 'string') {
                            try { jsonData = JSON.parse(response); } catch (e) {}
                        }

                        if (jsonData.status === 'success') {
                            scFeedback.html(
                                '<span class="success-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' +
                                jsonData.feedbackMsg +
                                '</span>'
                            );

                            SFTCY_WordAI.showDialog(
                                dialogTitle,
                                jsonData.feedbackMsg,
                                function () { window.location.reload(true); },
                                { type: 'alert', variant: 'success', buttons: { ok: 'OK' } }
                            );
                        }

                        else if (jsonData.status === 'warning') {
                            scFeedback.html(
                                '<span class="alert-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' +
                                jsonData.feedbackMsg +
                                '</span>'
                            );
                        }

                        else {
                            scFeedback.html(
                                '<span class="error-msg">' +
                                sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' +
                                jsonData.feedbackMsg +
                                '</span>'
                            );
                        }
                    },

                    error: function (xhr, status, error) {
                        console.error(xhr, status, error);

                        scFeedback.html(
                            '<span class="error-msg">' +
                            sftcy_wordai_metabox_script_obj.wordai_error_icon +
                            ' Failed to reset settings.' +
                            '</span>'
                        );
                    }
                });
            },
            { variant: 'warning', type: 'confirm', buttons: { ok: 'Yes, Reset', cancel: 'Cancel' } }
        );
    });





    }); // document ready

})(jQuery);
