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');
        const t_message	= $starsContainer.data('text-2');
        const t_message2	= $starsContainer.data('text-3');
		
        // 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-text').html( `<span class="fbold">${response.data.average} / 5</span> ( ${response.data.votes}<span id="hilang"> {t_votes}</span>) ` );

                //showRatingAlert(`${t_sukses}`, 'success');
				// ---- SUCCESS POPUP ----
				showRatingPopup({
					title: t_sukses,
					message: t_message,
					stats: '',
					type: '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');
				// ---- ERROR POPUP ----
				showRatingPopup({
					title: t_error,
					message: t_message2,
					type: 'error'
				});
            }
        }).fail(function() {
            $starsContainer.removeClass('rating-processing').css('pointer-events', '');
            //showRatingAlert('Connection error. Please try again.', 'error'); 
			showRatingPopup({
				title: 'Error',
				message: 'Failed to submit rating. Please try again.',
				type: 'error'
			});
        });
    });
	
	// ---------- 3. Popup Functions ----------
    var popupTimer;
    function showRatingPopup(opts) {
        var $overlay 	= $('#rating-popup-overlay');
        var $popup   	= $('#rating-popup');
        var $title   	= $popup.find('.rating-popup-title');
        var $msg     	= $popup.find('.rating-popup-message');
        var $stats   	= $popup.find('.rating-popup-stats');
        var $timerz		= $('.rating-stars').data('timer');

        // Set content
        $title.text(opts.title || '');
        $msg.text(opts.message || '');
        $stats.text(opts.stats || '');
        
        // Apply type
        $popup.removeClass('success error').addClass(opts.type || 'success');
        if (opts.type === 'error') $stats.hide(); else $stats.show();

        // Show
        $overlay.addClass('show');
        $popup.addClass('show');

        clearTimeout(popupTimer);
        popupTimer = setTimeout(hideRatingPopup, $timerz);
		
        if (opts.type !== 'error') {
            popupTimer = setTimeout(hideRatingPopup, $timerz);
        }
    }
	
	// === HIDE POPUP ===
    function hideAutoPopup() {
        $('#rating-popup-overlay, #rating-popup').removeClass('show');
    }

    function hideRatingPopup() {
        $('#rating-popup-overlay, #rating-popup').removeClass('show');
    }

    // Close events
    $(document).on('click', '.rating-popup-close, .rating-popup-ok, #rating-popup-overlay', hideRatingPopup);
    $(document).on('keyup', function(e) {
        if (e.key === 'Escape') hideRatingPopup();
    });
	
});

