jQuery(document).ready(function ($) {
    // When a reaction is clicked
    $(document).on('click', '.emoji-reaction', function () {
        const $button = $(this);
        const postID = $button.data('post-id');
        const reactionID = $button.data('reaction-id');
        const nonce = emojiReactions.nonce;

        // AJAX request to store the reaction
        $.ajax({
            url: emojiReactions.ajax_url,
            type: 'POST',
            data: {
                action: 'store_instant_emoji_reaction',
                post_id: postID,
                reaction_id: reactionID,
                nonce: nonce
            },
            success: function (response) {
                if (response.success) {
                    // Reset classes for all reactions to make sure they are clickable
                    $('.emoji-reaction').removeClass('active inactive');

                    // Add 'active' class to the clicked emoji and 'inactive' to the others
                    $button.addClass('active');
                    $('.emoji-reaction').not($button).addClass('inactive');

                    // Update the reaction counts dynamically
                    $.each(response.data.reaction_counts, function(reaction_id, count) {
                        // Update the count for each emoji
                        $('[data-reaction-id="' + reaction_id + '"] .reaction-count').text(count);
                    });
                } else {
                    alert('Failed to save reaction.');
                    // Revert to the initial state if the AJAX request fails
                    $('.emoji-reaction').removeClass('active inactive');
                }
            },
            error: function () {
                alert('An error occurred. Please try again.');
                // Reset all reactions if there's an error
                $('.emoji-reaction').removeClass('active inactive');
            }
        });
    });
});
