// Rating System for QR Rapido
(function() {
    'use strict';

    let selectedRating = 0;
    const ratingModal = document.querySelector('[data-rating-modal]');
    const ratingForm = document.getElementById('ratingForm');
    const ratingValue = document.getElementById('ratingValue');
    const successMessage = document.getElementById('ratingSuccess');
    const submitButton = document.getElementById('submitRating');

    // Initialize
    function init() {
        setupEventListeners();
    }

    function setupEventListeners() {
        // Rating trigger button
        const ratingTrigger = document.querySelector('[data-rating-trigger]');
        if (ratingTrigger) {
            ratingTrigger.addEventListener('click', openRatingModal);
        }

        // Star rating clicks
        const stars = document.querySelectorAll('[data-star]');
        stars.forEach(star => {
            star.addEventListener('click', handleStarClick);
            star.addEventListener('mouseover', handleStarHover);
        });

        // Star rating container mouse leave
        const starContainer = document.querySelector('[data-star-rating]');
        if (starContainer) {
            starContainer.addEventListener('mouseleave', resetStarHover);
        }

        // Form submission
        if (ratingForm) {
            ratingForm.addEventListener('submit', handleFormSubmit);
        }

        // Modal reset on close
        if (ratingModal) {
            ratingModal.addEventListener('hidden.bs.modal', resetForm);
        }
    }

    function openRatingModal(e) {
        e.preventDefault();

        // Close support FAB menu
        const fabMenu = document.querySelector('[data-support-fab-menu]');
        if (fabMenu) {
            fabMenu.hidden = true;
        }

        // Open rating modal
        const modal = new bootstrap.Modal(ratingModal);
        modal.show();
    }

    function handleStarClick(e) {
        const starValue = parseInt(e.currentTarget.dataset.star);
        selectedRating = starValue;
        ratingValue.value = starValue;
        updateStars(starValue, true);
    }

    function handleStarHover(e) {
        const starValue = parseInt(e.currentTarget.dataset.star);
        updateStars(starValue, false);
    }

    function resetStarHover() {
        updateStars(selectedRating, true);
    }

    function updateStars(rating, permanent) {
        const stars = document.querySelectorAll('[data-star]');
        stars.forEach(star => {
            const starValue = parseInt(star.dataset.star);
            if (starValue <= rating) {
                star.classList.remove('far');
                star.classList.add('fas', 'text-warning');
            } else {
                star.classList.remove('fas', 'text-warning');
                star.classList.add('far');
            }
        });
    }

    async function handleFormSubmit(e) {
        e.preventDefault();

        // Validate rating
        if (selectedRating === 0) {
            alert('Por favor, selecione uma avaliação com estrelas.');
            return;
        }

        // Get form data
        const formData = {
            rating: selectedRating,
            name: document.getElementById('ratingName').value.trim(),
            email: document.getElementById('ratingEmail').value.trim(),
            comment: document.getElementById('ratingComment').value.trim(),
            url: window.location.href,
            userAgent: navigator.userAgent,
            timestamp: new Date().toISOString()
        };

        // Disable submit button
        submitButton.disabled = true;
        submitButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Enviando...';

        try {
            // Send to backend
            const response = await fetch('/api/ratings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            if (response.ok) {
                // Show success message
                ratingForm.classList.add('d-none');
                successMessage.classList.remove('d-none');

                // Close modal after 3 seconds
                setTimeout(() => {
                    const modal = bootstrap.Modal.getInstance(ratingModal);
                    if (modal) {
                        modal.hide();
                    }
                }, 3000);
            } else {
                throw new Error('Failed to submit rating');
            }
        } catch (error) {
            console.error('Error submitting rating:', error);
            alert('Erro ao enviar avaliação. Por favor, tente novamente.');

            // Re-enable submit button
            submitButton.disabled = false;
            submitButton.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Enviar Avaliação';
        }
    }

    function resetForm() {
        // Reset stars
        selectedRating = 0;
        ratingValue.value = '';
        updateStars(0, true);

        // Reset form fields
        ratingForm.reset();

        // Show form, hide success message
        ratingForm.classList.remove('d-none');
        successMessage.classList.add('d-none');

        // Re-enable submit button
        submitButton.disabled = false;
        submitButton.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Enviar Avaliação';
    }

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
