// script.js

// Function to get URL parameter
function getQueryParam(param) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(param);
}

function createRecommendedGameElement(gameKey) {
    const game = gamesData[gameKey];
    const gameElement = document.createElement('a');
    gameElement.href = `inter.php?game=${gameKey}`;
    gameElement.className = 'recommended-game';

    const gameImage = document.createElement('img');
    gameImage.src = game.icon;
    gameImage.alt = game.title + ' Icon';

    const gameTitle = document.createElement('div');
    gameTitle.className = 'recommended-game-title';
    gameTitle.textContent = game.title;

    gameElement.appendChild(gameImage);
    gameElement.appendChild(gameTitle);

    return gameElement;
}

function getRandomGames(excludeKey, num) {
    const gameKeys = Object.keys(gamesData).filter(key => key !== excludeKey);
    const randomGames = [];
    while (randomGames.length < num && gameKeys.length > 0) {
        const randomIndex = Math.floor(Math.random() * gameKeys.length);
        const selectedGame = gameKeys.splice(randomIndex, 1)[0];
        randomGames.push(selectedGame);
    }
    return randomGames;
}

document.addEventListener('DOMContentLoaded', () => {
    // Get the game key from the URL
    const gameKey = getQueryParam('game');
    
    if (gameKey && gamesData[gameKey]) {
        const game = gamesData[gameKey];
        
        // Update the HTML content with game details
        document.getElementById('gameTitle').textContent = game.title;
        document.getElementById('gameDescription').textContent = game.description;
        document.getElementById('gameHowToPlay').textContent = game.howToPlay;
        document.getElementById('playButton').href = game.htmlFile;
        
        // Update the game icon
        const gameIcon = document.getElementById('gameIcon');
        gameIcon.src = game.icon;
        gameIcon.alt = game.title + ' Icon';
    } else {
        // Handle case where the game key is not valid
        document.querySelector('.game-container').innerHTML = '<p>Game not found.</p>';
    }

    // Populate recommended games
    const recommendedGamesContainer = document.getElementById('recommendedGames');
    const recommendedGames = getRandomGames(gameKey, 4);
    recommendedGames.forEach(gameKey => {
        const gameElement = createRecommendedGameElement(gameKey);
        recommendedGamesContainer.appendChild(gameElement);
    });
});
