jQuery(document).ready(function($) {
    $('#diyseo_generate_faq').on('click', function() {
        const button = $(this);
        const loadingSpan = $('#diyseo_faq_loading');
        const contentTextarea = $('#diyseo_faq_content');
        
        button.prop('disabled', true);
        loadingSpan.show();
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'diyseo_generate_faq',
                nonce: diyseoFaqParams.nonce,
                post_id: $('#post_ID').val()
            },
            success: function(response) {
                if (response.success) {
                    contentTextarea.val(response.data.content);
                    
                    // Add the FAQ content to the end of the post content
                    const editor = wp.data.dispatch('core/editor');
                    if (editor) {
                        const currentContent = wp.data.select('core/editor').getEditedPostContent();
                        editor.editPost({
                            content: currentContent + '\n\n' + response.data.content
                        });
                    }
                } else {
                    alert('Failed to generate FAQ section. Please try again.');
                }
            },
            error: function() {
                alert('Failed to generate FAQ section. Please try again.');
            },
            complete: function() {
                button.prop('disabled', false);
                loadingSpan.hide();
            }
        });
    });

    // Save the FAQ content when the post is saved
    $('#diyseo_faq_content').on('change', function() {
        const content = $(this).val();
        wp.data.dispatch('core/editor').editPost({
            meta: {
                _diyseo_faq_content: content
            }
        });
    });
});