jQuery(document).ready(function($) {
    $('.recast-sync-button').on('click', function() {
        var button = $(this);
        var postId = button.data('post-id');
        var nonce = button.data('nonce');
        var spinner = button.siblings('.spinner');
        var message = button.siblings('.recast-sync-message');
        
        button.prop('disabled', true);
        spinner.addClass('is-active');
        message.hide();
        
        $.ajax({
            url: recastMetaBox.ajaxUrl,
            type: 'POST',
            data: {
                action: 'recast_sync_post',
                post_id: postId,
                nonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    message.html('<div class="notice notice-success"><p>' + response.data.message + '</p></div>').show();
                    // Reload page to update meta box
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    message.html('<div class="notice notice-error"><p>' + response.data.message + '</p></div>').show();
                }
            },
            error: function() {
                message.html('<div class="notice notice-error"><p>' + recastMetaBox.errorMessage + '</p></div>').show();
            },
            complete: function() {
                button.prop('disabled', false);
                spinner.removeClass('is-active');
            }
        });
    });
});

