/**
 * Modern Rating & Comment System JavaScript
 * Compatible with existing ratings table structure
 */

class ModernRatingSystem {
    constructor() {
        this.currentRatings = {};
        this.isSubmitting = false;
        this.init();
    }

    init() {
        this.initStarRatings();
        this.initCommentActions();
        this.initFormValidation();
        this.initAnimations();
        this.initRecommendationOptions();
    }

    // Initialize star rating functionality
    initStarRatings() {
        const starRatings = document.querySelectorAll('.star-rating');

        starRatings.forEach(rating => {
            const stars = rating.querySelectorAll('.star');
            const ratingType = rating.dataset.rating || 'overall';
            let isHovering = false;

            // Container event listeners to prevent flickering
            rating.addEventListener('mouseenter', () => {
                isHovering = true;
            });

            rating.addEventListener('mouseleave', () => {
                isHovering = false;
                const currentRating = this.currentRatings[ratingType] || 0;
                this.highlightStars(stars, currentRating);
            });

            stars.forEach((star, index) => {
                star.addEventListener('mouseenter', (e) => {
                    e.stopPropagation();
                    if (isHovering && ratingType !== 'overall') {
                        this.highlightStars(stars, index + 1);
                    }
                });

                star.addEventListener('click', (e) => {
                    e.stopPropagation();

                    // Prevent clicking on overall rating
                    if (ratingType === 'overall') {
                        this.showNotification('امتیاز کلی به صورت خودکار محاسبه می‌شود', 'info');
                        return;
                    }

                    const ratingValue = index + 1;
                    this.setRating(ratingType, ratingValue, stars);
                    this.updateHiddenInput(ratingType, ratingValue);
                    this.showRatingFeedback(ratingValue, rating);
                });
            });
        });
    }

    // Highlight stars up to the given count
    highlightStars(stars, count) {
        stars.forEach((star, index) => {
            if (index < count) {
                star.classList.add('active');
            } else {
                star.classList.remove('active');
            }
        });
    }

    // Set rating value
    setRating(type, value, stars) {
        this.currentRatings[type] = value;
        this.highlightStars(stars, value);

        // Add animation effect
        stars.forEach((star, index) => {
            if (index < value) {
                star.style.animation = 'starGlow 0.3s ease';
                setTimeout(() => {
                    star.style.animation = '';
                }, 300);
            }
        });

        // Auto-calculate overall rating if it's not the overall rating itself
        if (type !== 'overall') {
            this.calculateOverallRating();
        }
    }

    // Calculate overall rating based on other ratings
    calculateOverallRating() {
        const ratingTypes = ['service', 'quality', 'location', 'price', 'cleanliness'];
        const ratings = [];

        // Collect all non-zero ratings
        ratingTypes.forEach(type => {
            if (this.currentRatings[type] && this.currentRatings[type] > 0) {
                ratings.push(this.currentRatings[type]);
            }
        });

        // Calculate average if we have ratings
        if (ratings.length > 0) {
            const average = ratings.reduce((sum, rating) => sum + rating, 0) / ratings.length;
            const overallRating = Math.round(average);

            // Update overall rating
            this.currentRatings['overall'] = overallRating;
            this.updateHiddenInput('overall', overallRating);

            // Update overall rating display
            const overallStars = document.querySelector('.star-rating[data-rating="overall"]');
            if (overallStars) {
                const stars = overallStars.querySelectorAll('.star');
                this.highlightStars(stars, overallRating);

                // Show calculated rating feedback
                this.showCalculatedRatingFeedback(overallRating, overallStars);
            }
        }
    }

    // Show feedback for calculated rating
    showCalculatedRatingFeedback(rating, container) {
        // Remove existing feedback
        const existingFeedback = container.parentNode.querySelector('.calculated-rating-feedback');
        if (existingFeedback) {
            existingFeedback.remove();
        }

        // Create feedback element
        const feedback = document.createElement('div');
        feedback.className = 'calculated-rating-feedback';
        feedback.style.cssText = `
            margin-top: 0.5rem;
            padding: 0.5rem;
            background: rgba(255, 215, 0, 0.1);
            border: 1px solid rgba(255, 215, 0, 0.3);
            border-radius: 6px;
            font-size: 0.9rem;
            color: #856404;
            text-align: center;
        `;

        const ratingTexts = {
            1: 'ضعیف',
            2: 'متوسط',
            3: 'خوب',
            4: 'عالی',
            5: 'فوق‌العاده'
        };

        feedback.innerHTML = `
            <i class="fas fa-calculator"></i>
            امتیاز کلی محاسبه شده: ${rating} ستاره (${ratingTexts[rating] || ''})
        `;

        container.parentNode.appendChild(feedback);

        // Auto-hide after 3 seconds
        setTimeout(() => {
            if (feedback.parentNode) {
                feedback.style.opacity = '0';
                setTimeout(() => {
                    if (feedback.parentNode) {
                        feedback.remove();
                    }
                }, 300);
            }
        }, 3000);
    }

    // Update hidden form input
    updateHiddenInput(type, value) {
        let inputName = type === 'overall' ? 'rating' : `${type}_rating`;
        const input = document.querySelector(`input[name="${inputName}"]`);
        if (input) {
            input.value = value;
        }
    }

    // Show rating feedback
    showRatingFeedback(rating, container) {
        const feedbackMessages = {
            1: 'بسیار ضعیف',
            2: 'ضعیف',
            3: 'متوسط',
            4: 'خوب',
            5: 'عالی'
        };

        let feedback = container.parentNode.querySelector('.rating-feedback');
        if (!feedback) {
            feedback = document.createElement('div');
            feedback.className = 'rating-feedback';
            feedback.style.cssText = `
                margin-top: 0.5rem;
                font-size: 0.9rem;
                font-weight: 600;
                text-align: center;
                color: var(--rating-warning);
                opacity: 0;
                transition: opacity 0.3s ease;
            `;
            container.parentNode.appendChild(feedback);
        }

        feedback.textContent = feedbackMessages[rating] || '';
        feedback.style.opacity = '1';

        setTimeout(() => {
            if (feedback) feedback.style.opacity = '0';
        }, 2000);
    }

    // Initialize recommendation options
    initRecommendationOptions() {
        const recommendationOptions = document.querySelectorAll('.recommendation-option');
        recommendationOptions.forEach(option => {
            option.addEventListener('click', () => {
                recommendationOptions.forEach(opt => opt.classList.remove('selected'));
                option.classList.add('selected');

                const radio = option.querySelector('input[type="radio"]');
                if (radio) {
                    radio.checked = true;
                }
            });
        });
    }

    // Initialize comment actions (like, reply, etc.)
    initCommentActions() {
        document.addEventListener('click', (e) => {
            if (e.target.matches('.comment-like-btn') || e.target.closest('.comment-like-btn')) {
                e.preventDefault();
                this.handleCommentReaction(e.target.closest('.comment-like-btn'), 'helpful');
            }

            if (e.target.matches('.comment-dislike-btn') || e.target.closest('.comment-dislike-btn')) {
                e.preventDefault();
                this.handleCommentReaction(e.target.closest('.comment-dislike-btn'), 'not_helpful');
            }

            if (e.target.matches('.comment-reply-btn') || e.target.closest('.comment-reply-btn')) {
                e.preventDefault();
                this.toggleReplyForm(e.target.closest('.comment-reply-btn'));
            }
        });
    }

    // Handle comment reactions
    async handleCommentReaction(button, type) {
        const ratingId = button.dataset.commentId || button.dataset.ratingId;
        const countSpan = button.querySelector('.count');

        if (!ratingId) {
            this.showNotification('خطا در شناسایی نظر', 'error');
            return;
        }

        try {
            const response = await fetch('/api/ratings/react', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                },
                body: JSON.stringify({
                    rating_id: ratingId,
                    vote_type: type
                })
            });

            const data = await response.json();

            if (data.success) {
                // Update count
                if (countSpan) {
                    countSpan.textContent = data.count;
                }

                // Toggle active state
                button.classList.toggle('active', data.user_reacted);

                // Add animation
                button.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    button.style.transform = '';
                }, 150);

                this.showNotification(data.message, 'success');
            } else {
                this.showNotification(data.message || 'خطا در ثبت نظر', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showNotification('خطا در ارسال درخواست', 'error');
        }
    }

    // Initialize form validation
    initFormValidation() {
        const ratingForm = document.querySelector('#modern-rating-form');
        if (ratingForm) {
            ratingForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.submitRatingForm(ratingForm);
            });
        }
    }

    // Submit rating form
    async submitRatingForm(form) {
        if (this.isSubmitting) return;

        if (!this.validateRatingForm(form)) {
            return;
        }

        this.isSubmitting = true;
        const submitBtn = form.querySelector('.rating-submit-btn');
        const originalText = submitBtn.textContent;

        // Show loading state
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> در حال ارسال...';

        try {
            const formData = new FormData(form);

            const response = await fetch('/ratings', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            });

            // Check if response is JSON
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                throw new Error('Server returned non-JSON response');
            }

            const data = await response.json();

            if (response.ok && data.success) {
                this.showNotification(data.message, 'success');
                form.reset();
                this.currentRatings = {};
                this.resetStarRatings();
                this.resetRecommendationOptions();

                // Optionally reload the page after a delay to show new rating
                setTimeout(() => {
                    window.location.reload();
                }, 2000);
            } else {
                this.showNotification(data.message || 'خطا در ثبت نظر', 'error');
                if (data.errors) {
                    this.showFormErrors(data.errors);
                }
            }
        } catch (error) {
            console.error('Error:', error);
            this.showNotification('خطا در ارسال نظر. لطفاً دوباره تلاش کنید', 'error');
        } finally {
            this.isSubmitting = false;
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    }

    // Validate rating form
    validateRatingForm(form) {
        const requiredFields = ['name', 'email', 'rating', 'title_id'];
        let isValid = true;

        // Clear previous errors
        form.querySelectorAll('.field-error').forEach(error => error.remove());
        form.querySelectorAll('.error').forEach(field => field.classList.remove('error'));

        requiredFields.forEach(field => {
            const input = form.querySelector(`[name="${field}"]`);
            if (input && !input.value.trim()) {
                if (field !== 'title_id') { // Don't show error for hidden field
                    this.showFieldError(input, 'این فیلد الزامی است');
                }
                isValid = false;
            }
        });

        // Validate email
        const emailInput = form.querySelector('[name="email"]');
        if (emailInput && emailInput.value && !this.isValidEmail(emailInput.value)) {
            this.showFieldError(emailInput, 'ایمیل معتبر وارد کنید');
            isValid = false;
        }

        // Validate rating - check if any rating is provided
        const ratingInput = form.querySelector('[name="rating"]');
        const hasAnyRating = ['service_rating', 'quality_rating', 'location_rating', 'price_rating', 'cleanliness_rating']
            .some(name => {
                const input = form.querySelector(`[name="${name}"]`);
                return input && input.value && input.value > 0;
            });

        if (!hasAnyRating && (!ratingInput || !ratingInput.value || ratingInput.value < 1)) {
            this.showNotification('لطفاً حداقل یک امتیاز را انتخاب کنید', 'warning');
            isValid = false;
        }

        return isValid;
    }

    // Show field error
    showFieldError(input, message) {
        input.classList.add('error');

        let errorDiv = input.parentNode.querySelector('.field-error');
        if (!errorDiv) {
            errorDiv = document.createElement('div');
            errorDiv.className = 'field-error';
            input.parentNode.appendChild(errorDiv);
        }
        errorDiv.textContent = message;
    }

    // Show form errors
    showFormErrors(errors) {
        Object.keys(errors).forEach(fieldName => {
            const input = document.querySelector(`[name="${fieldName}"]`);
            if (input && errors[fieldName][0]) {
                this.showFieldError(input, errors[fieldName][0]);
            }
        });
    }

    // Validate email
    isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // Reset star ratings
    resetStarRatings() {
        document.querySelectorAll('.star-rating .star').forEach(star => {
            star.classList.remove('active');
        });
        document.querySelectorAll('input[name$="_rating"]').forEach(input => {
            input.value = '';
        });
    }

    // Reset recommendation options
    resetRecommendationOptions() {
        document.querySelectorAll('.recommendation-option').forEach(option => {
            option.classList.remove('selected');
            const radio = option.querySelector('input[type="radio"]');
            if (radio) radio.checked = false;
        });
    }

    // Initialize animations
    initAnimations() {
        // Intersection Observer for fade-in animations
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('fade-in-up');
                }
            });
        }, { threshold: 0.1 });

        document.querySelectorAll('.comment-item, .rating-category-item').forEach(el => {
            observer.observe(el);
        });
    }

    // Show notification
    showNotification(message, type = 'info') {
        // Remove existing notifications
        document.querySelectorAll('.rating-notification').forEach(n => n.remove());

        // Create notification element
        const notification = document.createElement('div');
        notification.className = `rating-notification ${type}`;

        const iconMap = {
            success: 'fas fa-check-circle',
            error: 'fas fa-exclamation-circle',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };

        notification.innerHTML = `
            <div class="notification-content ${type}">
                <i class="${iconMap[type] || iconMap.info}"></i>
                <span>${message}</span>
            </div>
        `;

        // Add to page
        document.body.appendChild(notification);

        // Show with animation
        setTimeout(() => notification.classList.add('show'), 100);

        // Auto remove
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 300);
        }, 4000);
    }

    // Toggle reply form
    toggleReplyForm(button) {
        // This would be implemented if using the comment system
        this.showNotification('قابلیت پاسخ به زودی اضافه خواهد شد', 'info');
    }
}

// Initialize rating system when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.modernRatingSystem = new ModernRatingSystem();
});

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ModernRatingSystem;
}
