/**
 * Game Loader Script
 * Fetches the list of enabled games from the server and generates the UI dynamically.
 */

document.addEventListener('DOMContentLoaded', async () => {
    const gamesGrid = document.querySelector('.games-grid');
    if (!gamesGrid) return;

    try {
        // Fetch enabled games from the API
        const response = await fetch('/api/games');
        if (!response.ok) {
            throw new Error('Failed to fetch games');
        }
        
        const enabledGames = await response.json();
        
        // Store games globally for filtering
        window.allGames = enabledGames;
        
        // Clear existing static content
        gamesGrid.innerHTML = '';
        
        if (enabledGames.length === 0) {
            gamesGrid.innerHTML = `
                <div class="game-card" style="grid-column: 1/-1; text-align: center; padding: 4rem 2rem; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 300px;">
                    <div class="game-icon" style="font-size: 4rem; margin-bottom: 1.5rem; filter: grayscale(1); opacity: 0.5;">💤</div>
                    <h2 class="game-title" style="margin-bottom: 1rem;">No Games Available</h2>
                    <p class="game-description" style="max-width: 400px; margin: 0 auto;">
                        We're currently updating our game library. Please check back soon for new adventures!
                    </p>
                </div>
            `;
            return;
        }

        // Initialize category filter
        initializeCategoryFilter(enabledGames);
        
        // Note: renderGames will be called by initializeCategoryFilter if filters are saved,
        // otherwise it will be called at the end of initializeCategoryFilter
        
        // Add tracking listeners
        document.querySelectorAll('.play-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const card = btn.closest('.game-card');
                const gameId = card ? card.getAttribute('data-game') : null;
                
                if (gameId && window.trackGameStart && !btn.disabled) {
                    window.trackGameStart(gameId);
                }
            });
        });
        
    } catch (error) {
        console.error('Error loading games:', error);
        gamesGrid.innerHTML = `
            <div class="error-state">
                <p>Failed to load games. Please try refreshing the page.</p>
            </div>
        `;
    }
});

/**
 * Create HTML element for a game card
 */
/**
 * Create HTML element for a game card
 */
function createGameCard(game) {
    const card = document.createElement('div');
    card.className = 'game-card neon-featured';
    card.setAttribute('data-game', game.id);

    // Handle Coming Soon
    if (game.isComingSoon) {
        card.classList.add('coming-soon');
    }

    // Handle Maintenance
    if (game.maintenanceMode) {
        card.classList.add('maintenance');
    }

    let innerHTML = '';

    // Always inject Neon Background
    innerHTML += `
        <div class="neon-grid-bg"></div>
        <div class="neon-glow"></div>
    `;

    // Special Template: Gomoku (Keep AI banner if desired, or merge)
    if (game.id === 'gomoku') {
        innerHTML += `
            <div class="ai-hero-banner">
                <div class="ai-banner-bg"></div>
                <div class="ai-circuit-pattern">
                    <div class="circuit-line"></div>
                    <div class="circuit-line"></div>
                    <div class="circuit-line"></div>
                    <div class="circuit-dot"></div>
                    <div class="circuit-dot"></div>
                    <div class="circuit-dot"></div>
                </div>
                <div class="ai-banner-content">
                    <div class="ai-badge-large">
                        <span class="ai-icon-large">🤖</span>
                        <span class="ai-text-large">AI POWERED</span>
                    </div>
                    <div class="ai-subtitle">Advanced Neural Strategy Engine</div>
                </div>
                <div class="ai-glow-effect"></div>
            </div>
            <div class="ai-particles">
                <div class="particle"></div>
                <div class="particle"></div>
                <div class="particle"></div>
                <div class="particle"></div>
                <div class="particle"></div>
            </div>
        `;
    }

    // Start Card Content Wrapper
    innerHTML += `<div class="card-content">`;

    // Coming Soon Badge
    if (game.isComingSoon) {
        innerHTML += `<div class="coming-soon-badge">Coming Soon</div>`;
    }

    // Icon
    let iconClass = 'game-icon';
    if (game.id === 'gomoku') iconClass += ' ai-icon-glow';
    innerHTML += `<div class="${iconClass}">${game.icon}</div>`;

    // Title & Description
    innerHTML += `
        <h2 class="game-title">${game.name}</h2>
        <p class="game-description">${game.description}</p>
    `;

    // Stats
    innerHTML += `
        <div class="game-stats">
            <span class="stat">👥 ${game.players}</span>
            <span class="stat">⏱️ ${game.estimatedTime}</span>
        </div>
    `;

    // Button
    let btnClass = 'play-btn neon-btn'; // Use neon button for all
    let btnText = 'Play Now';
    let btnHref = game.path;
    let btnDisabled = false;

    if (game.isComingSoon) {
        btnText = 'Play Now';  // Keep consistent button text, badge shows "Coming Soon"
        btnDisabled = true;
        btnHref = null;
        // Remove special effects for disabled button
        btnClass = 'play-btn'; 
    } else if (game.maintenanceMode) {
        btnText = 'Maintenance';
        btnClass += ' maintenance-btn';
        // Keep href for maintenance page redirect
    }

    if (btnDisabled) {
        innerHTML += `<button class="${btnClass}" disabled>${btnText}</button>`;
    } else {
        innerHTML += `<a href="${btnHref}" class="${btnClass}">${btnText}</a>`;
    }

    // End Card Content Wrapper
    innerHTML += `</div>`;

    card.innerHTML = innerHTML;
    return card;
}

/**
 * Load Testimonials
 */
async function loadTestimonials() {
    const container = document.querySelector('.testimonials-grid');
    if (!container) 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) {
            container.innerHTML = '<p style="text-align:center; color:var(--text-secondary);">No testimonials yet.</p>';
            return;
        }

        container.innerHTML = testimonials.map(t => `
            <div class="testimonial-card">
                <div class="player-info">
                    <div class="player-avatar">${t.player_avatar}</div>
                    <div class="player-details">
                        <h3 class="player-name">${t.player_name}</h3>
                        <span class="player-rank">${t.player_rank}</span>
                    </div>
                </div>
                <p class="testimonial-text">"${t.message}"</p>
                <div class="rating">${'⭐'.repeat(t.rating)}</div>
            </div>
        `).join('');
        
    } catch (error) {
        console.error('Error loading testimonials:', error);
        container.innerHTML = '<p style="text-align:center; color:var(--text-secondary);">Failed to load testimonials.</p>';
    }
}

// Initialize loading
document.addEventListener('DOMContentLoaded', () => {
    loadTestimonials();
});

/**
 * Initialize Category Filter
 */
function initializeCategoryFilter(games) {
    const categoryDropdown = document.getElementById('category-filter');
    const playerModeDropdown = document.getElementById('player-mode-filter');
    
    if (!categoryDropdown || !playerModeDropdown) return;
    
    // Extract unique categories
    const categories = [...new Set(games.map(g => g.category).filter(Boolean))];
    categories.sort();
    
    // Populate category dropdown
    categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category;
        option.textContent = category.charAt(0).toUpperCase() + category.slice(1);
        categoryDropdown.appendChild(option);
    });
    
    // Load saved filter state from localStorage
    const savedCategory = localStorage.getItem('gameFilter_category');
    const savedPlayerMode = localStorage.getItem('gameFilter_playerMode');
    
    if (savedCategory) {
        categoryDropdown.value = savedCategory;
    }
    if (savedPlayerMode) {
        playerModeDropdown.value = savedPlayerMode;
    }
    
    // Add change event listeners
    categoryDropdown.addEventListener('change', () => {
        localStorage.setItem('gameFilter_category', categoryDropdown.value);
        applyFilters();
    });
    
    playerModeDropdown.addEventListener('change', () => {
        localStorage.setItem('gameFilter_playerMode', playerModeDropdown.value);
        applyFilters();
    });
    
    // Apply saved filters on initial load
    if (savedCategory || savedPlayerMode) {
        applyFilters();
    } else {
        // No saved filters, render all games
        renderGames(games);
    }
}

/**
 * Apply all active filters
 */
function applyFilters() {
    const games = window.allGames || [];
    const categoryDropdown = document.getElementById('category-filter');
    const playerModeDropdown = document.getElementById('player-mode-filter');
    
    const selectedCategory = categoryDropdown ? categoryDropdown.value : 'all';
    const selectedPlayerMode = playerModeDropdown ? playerModeDropdown.value : 'all';
    
    let filtered = games;
    
    // Apply category filter
    if (selectedCategory !== 'all') {
        filtered = filtered.filter(g => g.category === selectedCategory);
    }
    
    // Apply player mode filter
    if (selectedPlayerMode !== 'all') {
        filtered = filtered.filter(g => g.playerMode === selectedPlayerMode);
    }
    
    renderGames(filtered);
}

/**
 * Filter games by category (legacy - now uses applyFilters)
 */
function filterGamesByCategory(category) {
    applyFilters();
}

/**
 * Render games to the grid
 */
function renderGames(games) {
    const gamesGrid = document.querySelector('.games-grid');
    if (!gamesGrid) return;
    
    // Clear grid
    gamesGrid.innerHTML = '';
    
    if (games.length === 0) {
        gamesGrid.innerHTML = `
            <div class="game-card" style="grid-column: 1/-1; text-align: center; padding: 4rem 2rem;">
                <div class="game-icon" style="font-size: 4rem; margin-bottom: 1.5rem; opacity: 0.5;">🔍</div>
                <h2 class="game-title" style="margin-bottom: 1rem;">No Games Found</h2>
                <p class="game-description" style="max-width: 400px; margin: 0 auto;">
                    No games match the selected category. Try selecting a different category.
                </p>
            </div>
        `;
        return;
    }
    
    // Render each game
    games.forEach((game, index) => {
        const card = createGameCard(game);
        card.style.animation = `fadeInUp 0.6s ease-out ${index * 0.1}s both`;
        gamesGrid.appendChild(card);
    });
    
    // Re-attach tracking listeners
    document.querySelectorAll('.play-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const card = btn.closest('.game-card');
            const gameId = card ? card.getAttribute('data-game') : null;
            
            if (gameId && window.trackGameStart && !btn.disabled) {
                window.trackGameStart(gameId);
            }
        });
    });
}
