jQuery(document).ready(function($) {
    $('#diyseo_loading').hide();
    $('#diyseo_generate_article').on('click', function() {
        var data = {
            action: 'diyseo_generate_article',
            post_id: diyseoParams.postId,
            post_title: $('#diyseo_post_title').val(),
            word_count: $('#diyseo_word_count').val(),
            nonce: diyseoParams.nonce
        };

        $('#diyseo_loading').show(); // Show loading animation

        $.post(ajaxurl, data, function(response) {
            $('#diyseo_loading').hide(); // Hide loading animation

            if (response.success) {
                var content = response.data.content;
                content = content.replace(/<h1>.*?<\/h1>/i, ''); // Remove content between <h1> tags
                wp.data.dispatch('core/editor').editPost({
                    title: $('#diyseo_post_title').val(), // Update the post title
                    content: content // Update the post content
                });
            } else {
                // Handle failure
                console.log('Failed to generate article.');
            }
        });
    });
});