(function () {
    'use strict';
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.star-rating-widget .star.clickable')
            .forEach(star => {
                star.addEventListener('click', function () {
                    const widget = this.closest('.star-rating-widget');
                    const itemType = widget.dataset.itemType;
                    const itemId = widget.dataset.itemId;
                    const rating = this.dataset.value;

                    fetch('rate_item.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: `item_type=${encodeURIComponent(itemType)}`
                            + `&item_id=${encodeURIComponent(itemId)}`
                            + `&rating=${encodeURIComponent(rating)}`
                    })
                        .then(r => r.json())
                        .then(data => {
                            if (!data.success) return;
                            widget.querySelectorAll('.star').forEach(s => {
                                const v = parseInt(s.dataset.value, 10);
                                s.classList.toggle('user-rated', v <= data.user_rating);
                                s.classList.toggle('filled', v <= Math.round(data.avg_rating));
                                s.querySelector('i').className =
                                    (v <= data.user_rating || v <= Math.round(data.avg_rating))
                                        ? 'fas fa-star' : 'far fa-star';
                            });
                            widget.querySelector('.star-rating-info').textContent =
                                `${data.avg_rating} (${data.total_ratings})`;
                        })
                        .catch(() => { });
                });
            });
    });
})();
