jQuery(document).ready(function ($) {
    var ajaxUrl = RF_JSObject.ajaxUrl;
    var _wpnonce = RF_JSObject._wpnonce;

    $(document).on('click', '.reactify-emoji', function () {
        var $this = $(this);
        var emojiType = $this.data('emoji');
        var postId = $this.closest('.reactify-react-container').data('post-id');

        // Remove 'emoji-reacted' class and decrement count for all emojis
        $('.reactify-emoji').each(function () {
            var $emoji = $(this);
            if ($emoji.hasClass('emoji-reacted')) {
                var currentCount = $emoji.data('count');
                $emoji.removeClass('emoji-reacted');
                if (currentCount > 0) {
                    var newCount = currentCount - 1;
                    $emoji.data('count', newCount);
                    $emoji.attr('data-count', newCount);
                }
            }
        });

        // Increment count and add 'emoji-reacted' class for clicked emoji
        var currentCount = $this.data('count');
        var newCount = currentCount + 1;
        $this.data('count', newCount);
        $this.attr('data-count', newCount);
        $this.addClass('emoji-reacted');

        // Calculate and update percentages
        updateEmojiPercentages();

        //Update count n actual value
        updateEmojiCounts();

        // AJAX request to update reaction on the server
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'reactify_reaction',
                emoji_type: emojiType,
                post_id: postId,
                security: _wpnonce
            }
        });
    });

    function updateEmojiPercentages() {
        var totalReactions = 0;
        var emojiCounts = {};

        // Collect all emoji counts and calculate total reactions
        $('.reactify-emoji').each(function () {
            var $emoji = $(this);
            var count = parseInt($emoji.data('count'));
            var emojiType = $emoji.data('emoji');
            emojiCounts[emojiType] = count;
            totalReactions += count;
        });

        // Calculate and update percentages for each emoji
        $('.reactify-emoji').each(function () {
            var $emoji = $(this);
            var emojiType = $emoji.data('emoji');
            var count = emojiCounts[emojiType];
            var percentage = totalReactions > 0 ? Math.round((count / totalReactions) * 100) : 0;
            $emoji.closest('.reactify-react-emoji').find('.reactify-react-percentage').text(percentage + '%');
        });
    }

    function updateEmojiCounts() {
        // Collect all emoji counts
        $('.reactify-emoji').each(function () {
            var $emoji = $(this);
            var count = $emoji.data('count');
            $emoji.closest('.reactify-react-emoji').find('.reactify-react-count').text(count);
        });
    }
});