jQuery(document).ready(function($) {
    
    // Create slide alert container once
    if (!$('#rating-alert').length) {
        $('body').append('<div id="rating-alert"></div>');
    }

    // Function to show slide alert
    function showRatingAlert(message, type = 'success') {
        const $alert = $('#rating-alert');
        $alert.removeClass('success error').addClass(type)
              .text(message)
              .slideDown(300);

        // Auto hide after 4 seconds
        clearTimeout($alert.data('hideTimeout'));
        $alert.data('hideTimeout', setTimeout(() => {
            $alert.slideUp(300);
        }, 4000));
    }

    // Star click handler
    $('.rating-stars .star').on('click', function() {
        const $starsContainer = $(this).closest('.rating-stars');
        const postId = $starsContainer.data('post-id');
        const rating = $(this).data('rating');
        const originalAverage = $starsContainer.data('average'); // for rollback on error

        const t_sukses	= $starsContainer.data('text-succes');
        const t_error	= $starsContainer.data('text-error');
        const t_votes	= $starsContainer.data('text-1');
		
        // Visual feedback: fill stars
        $starsContainer.find('.star').removeClass('filled');
        $starsContainer.find('.star').each(function(i) {
            if (i < rating) $(this).addClass('filled');
        });

        // Disable further clicks while processing
        $starsContainer.addClass('rating-processing').css('pointer-events', 'none');

        $.post(ajax_object.ajax_url, {
            action: 'submit_rating',
            post_id: postId,
            rating: rating,
            nonce: ajax_object.nonce
        }, function(response) {
            $starsContainer.removeClass('rating-processing').css('pointer-events', '');

            if (response.success) {
                // Update stars permanently
                $starsContainer.find('.star').removeClass('filled');
                for (let i = 1; i <= 5; i++) {
                    if (i <= response.data.average) {
                        $starsContainer.find(`.star[data-rating="${i}"]`).addClass('filled');
                    }
                }
                // Update text
				//(184057 votes, avg: 4.1)
				//<span class="fbold"><?php echo $average; ?></span> (<?php echo $total_votes; ?>)
                $('.rating-stars').find('.rating-text').html(
                    ` <span class="fbold">${response.data.average} / 5</span> ( ${response.data.votes} <span id="hilang">${t_votes}</span> ) `
                );

                showRatingAlert(`${t_sukses}`, 'success');
            } else {
                // Revert visual on error
                $starsContainer.find('.star').removeClass('filled');
                for (let i = 1; i <= 5; i++) {
                    if (i <= originalAverage) {
                        $starsContainer.find(`.star[data-rating="${i}"]`).addClass('filled');
                    }
                }
                showRatingAlert(response.data || `${t_error}`, 'error');
            }
        }).fail(function() {
            $starsContainer.removeClass('rating-processing').css('pointer-events', '');
            showRatingAlert('Connection error. Please try again.', 'error');
        });
    });
});