jQuery(document).ready(function($) {
    // Listen for changes on any score dropdown
    $('.asm-score-dropdown').on('change', function() {
        var dropdown = $(this);
        var album = dropdown.data('album');
        var score = dropdown.val();

        // Get the author and cover_url from the respective inputs in the same row
        var row = $('#asm-row-' + album);
        var author = dropdown.data('author');
        var cover_url = dropdown.data('cover');

        // Status cell
        var statusCell = row.find('.asm-status');

        if (score === '') {
            // If no score is selected, do not proceed
            statusCell.html('<span style="color: orange;">No score selected.</span>');
            return;
        }

        // Show loading message
        statusCell.html('<span style="color: blue;">Updating...</span>');

        // AJAX request
        $.ajax({
            url: asm_ajax_obj.ajax_url,
            type: 'POST',
            data: {
                action: 'asm_update_score',
                nonce: asm_ajax_obj.nonce,
                album: album,
                score: score,
                author: author,
                cover_url: cover_url
            },
            success: function(response) {
                if (response.success) {
                    statusCell.html('<span style="color: green;">' + response.data + '</span>');
                } else {
                    statusCell.html('<span style="color: red;">' + response.data + '</span>');
                }
            },
            error: function() {
                statusCell.html('<span style="color: red;">AJAX error.</span>');
            }
        });
    });
});
