document.addEventListener('DOMContentLoaded', () => {
    fetchTestimonials();
});

async function fetchTestimonials() {
    const track = document.getElementById('testimonials-track');
    if (!track) return;

    try {
        const response = await fetch('/api/testimonials');
        if (!response.ok) throw new Error('Failed to fetch testimonials');
        
        const testimonials = await response.json();
        
        if (testimonials.length === 0) {
            track.innerHTML = '<div style="color: var(--text-secondary); padding: 2rem;">No reviews yet.</div>';
            return;
        }

        // Clear loading spinner
        track.innerHTML = '';

        // Render testimonials
        // We need enough items to scroll smoothly. If few items, duplicate them more times.
        // For infinite scroll, we need at least 2 sets of items.
        // If we have very few items (e.g. < 5), we might need 3 or 4 sets to fill the screen width.
        
        const minItemsForScroll = 10; // Ensure we have enough width
        let itemsToRender = [...testimonials];
        
        while (itemsToRender.length < minItemsForScroll) {
            itemsToRender = [...itemsToRender, ...testimonials];
        }
        
        // Duplicate the final set once more for the seamless loop
        const finalItems = [...itemsToRender, ...itemsToRender];

        finalItems.forEach(t => {
            const card = createTestimonialCard(t);
            track.appendChild(card);
        });

        // Calculate animation duration based on width
        // Adjust speed: 50px per second seems reasonable
        const cardWidth = 350 + 32; // width + gap (approx)
        const totalWidth = finalItems.length * cardWidth;
        const duration = totalWidth / 100; // Slower speed

        track.style.animation = `scroll ${duration}s linear infinite`;
        
        // Pause on hover is handled in CSS

    } catch (error) {
        console.error('Error loading testimonials:', error);
        track.innerHTML = '<div style="color: var(--text-secondary); padding: 2rem;">Failed to load reviews.</div>';
    }
}

function createTestimonialCard(t) {
    const card = document.createElement('div');
    card.className = 'testimonial-card';
    
    const rankClass = `rank-${t.player_rank.toLowerCase()}`;
    
    card.innerHTML = `
        <div class="player-info">
            <div class="player-avatar">${t.player_avatar || t.player_name.charAt(0)}</div>
            <div class="player-details">
                <h3 class="player-name">${t.player_name}</h3>
                <span class="player-rank ${rankClass}">${t.player_rank}</span>
            </div>
        </div>
        <div class="testimonial-text" title="${t.message}">
            "${t.message}"
        </div>
        <div class="rating">
            ${Array(5).fill(0).map((_, i) => 
                `<i class="fas fa-star ${i < t.rating ? '' : 'text-muted'}" style="${i >= t.rating ? 'color: rgba(255,255,255,0.1);' : ''}"></i>`
            ).join('')}
        </div>
    `;
    
    return card;
}
