jQuery(document).ready(function($) {
    $('.afi-gen-btn').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var $container = $btn.closest('div');
        var $spinner = $container.find('.spinner');
        var $row = $('#afi-col-' + $btn.data('post-id'));
        
        $btn.prop('disabled', true);
        $spinner.css('visibility', 'visible').addClass('is-active');

        // ajaxurl is defined globally in WordPress admin
        $.post(ajaxurl, {
            action: 'cafi_generate_image_ajax',
            post_id: $btn.data('post-id'),
            _wpnonce: $btn.data('nonce')
        }, function(response) {
            if (response.success) {
                $row.find('.afi-status-label').text('Updated');
                $row.find('.dashicons').removeClass('dashicons-no-alt').addClass('dashicons-yes').css('color', '#46b450');
                $btn.text('Update').removeClass('button-primary');
            } else {
                alert('Error: ' + (response.data || 'Unknown error'));
            }
            $btn.prop('disabled', false);
            $spinner.css('visibility', 'hidden').removeClass('is-active');
        }).fail(function() {
            alert('Request failed');
            $btn.prop('disabled', false);
            $spinner.css('visibility', 'hidden').removeClass('is-active');
        });
    });
});
