<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Juegos de Taylor Swift - Edición Deluxe Plus</title>
    <style>
        :root {
            --primary: #ff8fab;
            --secondary: #ffc2d1;
            --background: #ffe1e8;
            --text: #2d3436;
        }
        
        body {
            font-family: 'Arial', sans-serif;
            background-color: var(--background);
            margin: 0;
            padding: 20px;
            color: var(--text);
        }

        .header {
            text-align: center;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 20px;
            color: white;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .stats {
            display: flex;
            justify-content: space-around;
            max-width: 600px;
            margin: 0 auto 20px;
            background: white;
            padding: 10px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .games-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .game-card {
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }

        .game-card:hover {
            transform: translateY(-5px);
        }

        .btn {
            background: var(--primary);
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 5px;
        }

        .btn:hover {
            background: #ff6b8b;
            transform: scale(1.05);
        }

        .result {
            margin-top: 10px;
            font-weight: bold;
            padding: 5px;
            border-radius: 5px;
            text-align: center;
        }

        input[type="text"], 
        input[type="number"],
        select {
            padding: 8px;
            margin: 5px;
            border: 1px solid var(--secondary);
            border-radius: 5px;
            width: calc(100% - 20px);
        }

        .memory-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin-top: 10px;
        }

        .memory-card {
            aspect-ratio: 1;
            background: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 0;
            transition: all 0.3s ease;
            border-radius: 5px;
        }

        .memory-card.flipped {
            background: white;
            font-size: 14px;
            border: 2px solid var(--primary);
        }

        .progress-bar {
            width: 100%;
            height: 20px;
            background: #eee;
            border-radius: 10px;
            margin: 10px 0;
            overflow: hidden;
        }

        .progress {
            height: 100%;
            background: var(--primary);
            transition: width 0.3s ease;
        }

        .confetti {
            position: fixed;
            width: 10px;
            height: 10px;
            background: var(--primary);
            animation: confetti 3s ease-in-out infinite;
            pointer-events: none;
        }

        .unscramble-container {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin: 10px 0;
        }

        .letter-tile {
            padding: 10px;
            background: var(--secondary);
            border-radius: 5px;
            cursor: pointer;
            user-select: none;
        }

        .timeline-container {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin: 10px 0;
        }

        .timeline-item {
            padding: 10px;
            background: var(--secondary);
            border-radius: 5px;
            cursor: move;
        }

        @keyframes confetti {
            0% { transform: translateY(0) rotate(0deg); }
            100% { transform: translateY(100vh) rotate(720deg); }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🎵 Juegos de Taylor Swift - Edición Deluxe Plus 🎵</h1>
        <p>¡Demuestra cuánto sabes sobre Taylor!</p>
    </div>

    <div class="stats">
        <div>Nivel: <span id="level">1</span></div>
        <div>Puntos: <span id="score">0</span></div>
        <div>Racha: <span id="streak">0</span></div>
        <div>Mejor Puntuación: <span id="highScore">0</span></div>
    </div>

    <div class="games-container" id="gamesContainer"></div>

    <script>
// Banco de preguntas y respuestas
const questionBank = {
    lyrics: [
        { lyric: "Cause baby I'm a _________", answer: "nightmare" },
        { lyric: "Are we out of the _________?", answer: "woods" },
        { lyric: "I stay up too _________ ", answer: "late" },
        { lyric: "Nice to meet you, where you _________", answer: "been" },
        { lyric: "We are never ever ever getting back _________", answer: "together" },
        { lyric: "I knew you were _________ when you walked in", answer: "trouble" },
        { lyric: "Shake it _________, shake it off", answer: "off" },
        { lyric: "Look what you made me _________", answer: "do" },
        { lyric: "Baby just say _________", answer: "yes" },
        { lyric: "I'm feeling twenty-_________ everything", answer: "two" },
        { lyric: "All of the _________ (all of the _________)", answer: "lights" },
        { lyric: "Out of the _________, into the rain", answer: "dark" },
        { lyric: "Meet me at _________ ", answer: "midnight" },
        { lyric: "Karma is my _________ star", answer: "lucky" },
        { lyric: "It's me, hi, I'm the _________", answer: "problem" },
        { lyric: "Draw the _________ wide", answer: "curtains" },
        { lyric: "Paint the town _________ ", answer: "red" },
        { lyric: "Dancing with our hands _________", answer: "tied" },
        { lyric: "I had a marvelous _________", answer: "time" },
        { lyric: "Welcome to New _________ ", answer: "york" }
    ],
    albums: [
        { song: "Love Story", album: "fearless" },
        { song: "Shake It Off", album: "1989" },
        { song: "Cardigan", album: "folklore" },
        { song: "Anti-Hero", album: "midnights" },
        { song: "Cruel Summer", album: "lover" },
        { song: "All Too Well", album: "red" },
        { song: "Enchanted", album: "speak now" },
        { song: "Tim McGraw", album: "taylor swift" },
        { song: "August", album: "folklore" },
        { song: "Karma", album: "midnights" },
        { song: "You Belong With Me", album: "fearless" },
        { song: "Blank Space", album: "1989" },
        { song: "Willow", album: "evermore" },
        { song: "Lavender Haze", album: "midnights" },
        { song: "Lover", album: "lover" }
    ],
    trivia: [
        { question: "¿En qué año nació Taylor Swift?", answer: "1989" },
        { question: "¿Cuál fue su primer álbum de estudio?", answer: "taylor swift" },
        { question: "¿En qué ciudad nació Taylor?", answer: "reading" },
        { question: "¿Cuál es el nombre de su gato blanco?", answer: "benjamin button" },
        { question: "¿Qué número considera Taylor su favorito?", answer: "13" },
        { question: "¿En qué año lanzó '1989'?", answer: "2014" },
        { question: "¿Qué instrumento tocaba Taylor en sus inicios?", answer: "guitarra" },
        { question: "¿Cuál fue su primer sencillo número 1 en Billboard Hot 100?", answer: "shake it off" },
        { question: "¿En qué estado creció Taylor?", answer: "pennsylvania" },
        { question: "¿Cuántos álbumes ha regrabado hasta 2024?", answer: "4" }
    ],
    unscramble: [
        { word: "FEARLESS", hint: "Álbum que incluye 'Love Story'" },
        { word: "SWIFTIE", hint: "Nombre que reciben los fans de Taylor" },
        { word: "FOLKLORE", hint: "Álbum sorpresa lanzado en 2020" },
        { word: "REPUTATION", hint: "Álbum con serpientes como símbolo" },
        { word: "ENCHANTED", hint: "Canción de Speak Now que se hizo viral en TikTok" }
    ],
    timeline: [
        { event: "Lanzamiento de Taylor Swift", year: 2006 },
        { event: "Lanzamiento de Fearless", year: 2008 },
        { event: "Lanzamiento de Speak Now", year: 2010 },
        { event: "Lanzamiento de Red", year: 2012 },
        { event: "Lanzamiento de 1989", year: 2014 }
    ],
    memoryPairs: [
        "1989", "Red", "Fearless", "Speak Now",
        "Folklore", "Evermore", "Midnights", "Lover",
        "Reputation", "Taylor Swift"
    ]
};

// Estado del juego
let gameState = {
    level: 1,
    score: 0,
    streak: 0,
    highScore: parseInt(localStorage.getItem('taylorHighScore')) || 0,
    usedQuestions: {
        lyrics: [],
        albums: [],
        trivia: [],
        unscramble: [],
        timeline: []
    },
    memoryGame: {
        flippedCards: [],
        matchedPairs: 0
    }
};

// Funciones auxiliares
function getRandomItem(array) {
    return array[Math.floor(Math.random() * array.length)];
}

function createConfetti() {
    for(let i = 0; i < 50; i++) {
        const confetti = document.createElement('div');
        confetti.className = 'confetti';
        confetti.style.left = Math.random() * window.innerWidth + 'px';
        confetti.style.backgroundColor = ['#ff8fab', '#ffc2d1', '#ffb3c6', '#ff69b4'][Math.floor(Math.random() * 4)];
        confetti.style.animationDuration = (Math.random() * 3 + 2) + 's';
        document.body.appendChild(confetti);
        setTimeout(() => confetti.remove(), 5000);
    }
}

function updateStats() {
    document.getElementById('level').textContent = gameState.level;
    document.getElementById('score').textContent = gameState.score;
    document.getElementById('streak').textContent = gameState.streak;
    document.getElementById('highScore').textContent = gameState.highScore;
}

function correctAnswer() {
    const points = 100 * gameState.level;
    gameState.score += points;
    gameState.streak++;
    if(gameState.score > gameState.highScore) {
        gameState.highScore = gameState.score;
        localStorage.setItem('taylorHighScore', gameState.highScore);
    }
    if(gameState.streak % 3 === 0) {
        gameState.level++;
        createConfetti();
        setTimeout(generateNewGames, 1500);
    }
    updateStats();
    document.dispatchEvent(new Event('scoreUpdate'));
    return points;
}

function wrongAnswer() {
    gameState.streak = 0;
    updateStats();
}

// Creación de juegos
function createLyricsGame() {
    const unusedLyrics = questionBank.lyrics.filter(q => !gameState.usedQuestions.lyrics.includes(q.lyric));
    if (unusedLyrics.length === 0) {
        gameState.usedQuestions.lyrics = [];
    }
    const question = getRandomItem(unusedLyrics);
    gameState.usedQuestions.lyrics.push(question.lyric);

    const gameCard = document.createElement('div');
    gameCard.className = 'game-card';
    gameCard.innerHTML = `
        <h2>Completa la Letra</h2>
        <p>${question.lyric}</p>
        <input type="text" id="lyricsInput" placeholder="Completa la letra">
        <button class="btn" onclick="checkLyrics('${question.answer}')">Verificar</button>
        <div id="lyricsResult" class="result"></div>
    `;
    return gameCard;
}

function createAlbumGame() {
    const unusedAlbums = questionBank.albums.filter(q => !gameState.usedQuestions.albums.includes(q.song));
    if (unusedAlbums.length === 0) {
        gameState.usedQuestions.albums = [];
    }
    const question = getRandomItem(unusedAlbums);
    gameState.usedQuestions.albums.push(question.song);

    const gameCard = document.createElement('div');
    gameCard.className = 'game-card';
    gameCard.innerHTML = `
        <h2>¿De Qué Álbum Es?</h2>
        <p>¿En qué álbum aparece "${question.song}"?</p>
        <input type="text" id="albumInput" placeholder="Nombre del álbum">
        <button class="btn" onclick="checkAlbum('${question.album}')">Verificar</button>
        <div id="albumResult" class="result"></div>
    `;
    return gameCard;
}

function createTriviaGame() {
    const unusedTrivia = questionBank.trivia.filter(q => !gameState.usedQuestions.trivia.includes(q.question));
    if (unusedTrivia.length === 0) {
        gameState.usedQuestions.trivia = [];
    }
    const question = getRandomItem(unusedTrivia);
    gameState.usedQuestions.trivia.push(question.question);

    const gameCard = document.createElement('div');
    gameCard.className = 'game-card';
    gameCard.innerHTML = `
        <h2>Trivia Swiftie</h2>
        <p>${question.question}</p>
        <input type="text" id="triviaInput" placeholder="Tu respuesta">
        <button class="btn" onclick="checkTrivia('${question.answer}')">Verificar</button>
        <div id="triviaResult" class="result"></div>
    `;
    return gameCard;
}

function createMemoryGame() {
    const gameCard = document.createElement('div');
    gameCard.className = 'game-card memory-game';
    gameCard.innerHTML = `
        <h2>Memoria Taylor</h2>
        <div class="memory-grid" id="memoryGrid"></div>
        <div id="memoryResult" class="result"></div>
    `;
    return gameCard;
}

// Funciones de verificación
function checkLyrics(answer) {
    const input = document.getElementById('lyricsInput').value.toLowerCase();
    const result = document.getElementById('lyricsResult');
    
    if (input === answer.toLowerCase()) {
        const points = correctAnswer();
        result.textContent = `¡Correcto! +${points} puntos 🎉`;
        result.style.color = "green";
    } else {
        result.textContent = "¡Intenta de nuevo! 😊";
        result.style.color = "red";
        wrongAnswer();
    }
}

function checkAlbum(answer) {
    const input = document.getElementById('albumInput').value.toLowerCase();
    const result = document.getElementById('albumResult');
    
    if (input === answer.toLowerCase()) {
        const points = correctAnswer();
        result.textContent = `¡Correcto! +${points} puntos 🎉`;
        result.style.color = "green";
    } else {
        result.textContent = "¡Intenta de nuevo! 😊";
        result.style.color = "red";
        wrongAnswer();
    }
}

function checkTrivia(answer) {
    const input = document.getElementById('triviaInput').value.toLowerCase();
    const result = document.getElementById('triviaResult');
    
    if (input === answer.toLowerCase()) {
        const points = correctAnswer();
        result.textContent = `¡Correcto! +${points} puntos 🎉`;
        result.style.color = "green";
    } else {
        result.textContent = "¡Intenta de nuevo! 😊";
        result.style.color = "red";
        wrongAnswer();
    }
}

// Juego de memoria
function startMemoryGame() {
    const grid = document.getElementById('memoryGrid');
    if (!grid) return;

    // Crear pares de cartas
    const pairs = [...questionBank.memoryPairs];
    const cards = [...pairs, ...pairs];
    cards.sort(() => Math.random() - 0.5);

    grid.innerHTML = cards.map((card, index) => `
        <div class="memory-card" data-index="${index}" data-value="${card}">
            <div class="memory-card-inner">
                <div class="memory-card-front">?</div>
                <div class="memory-card-back">${card}</div>
            </div>
        </div>
    `).join('');

    // Agregar eventos
    grid.querySelectorAll('.memory-card').forEach(card => {
        card.addEventListener('click', handleMemoryCardClick);
    });
}

function handleMemoryCardClick() {
    const card = this;
    if (
        card.classList.contains('flipped') || 
        gameState.memoryGame.flippedCards.length >= 2
    ) return;

    card.classList.add('flipped');
    gameState.memoryGame.flippedCards.push(card);

    if (gameState.memoryGame.flippedCards.length === 2) {
        setTimeout(checkMemoryMatch, 1000);
    }
}

function checkMemoryMatch() {
    const [card1, card2] = gameState.memoryGame.flippedCards;
    const match = card1.dataset.value === card2.dataset.value;

    if (match) {
        gameState.memoryGame.matchedPairs++;
        const points = correctAnswer();
        document.getElementById('memoryResult').textContent = `¡Par encontrado! +${points} puntos 🎉`;
        
        if (gameState.memoryGame.matchedPairs === questionBank.memoryPairs.length) {
            document.getElementById('memoryResult').textContent = "¡Juego completado! 🎉";
            setTimeout(generateNewGames, 1500);
        }
    } else {
        card1.classList.remove('flipped');
        card2.classList.remove('flipped');
        wrongAnswer();
    }

    gameState.memoryGame.flippedCards = [];
}

// Sistema de guardado
function saveProgress() {
    const saveData = {
        gameState: gameState,
        timestamp: Date.now()
    };
    localStorage.setItem('taylorGameState', JSON.stringify(saveData));
}

function loadProgress() {
    const saved = localStorage.getItem('taylorGameState');
    if (saved) {
        const saveData = JSON.parse(saved);
        if (Date.now() - saveData.timestamp < 24 * 60 * 60 * 1000) {
            gameState = saveData.gameState;
        } else {
            localStorage.removeItem('taylorGameState');
                    }
                }
                updateStats();
            }

            // Función mejorada para generar nuevos juegos
            function generateNewGames() {
                const container = document.getElementById('gamesContainer');
                container.innerHTML = '';
                
                // Crear nuevas instancias de los juegos
                const games = [
                    createLyricsGame(),
                    createAlbumGame(),
                    createTriviaGame(),
                    createMemoryGame(),
                    createUnscrambleGame(),
                    createTimelineGame()
                ];

                // Mezclar el orden de los juegos
                games.sort(() => Math.random() - 0.5);

                // Mostrar solo 4 juegos aleatorios
                games.slice(0, 4).forEach(game => container.appendChild(game));
                
                // Inicializar juegos específicos
                startMemoryGame();
                initializeTimeline();
            }

            // Sistema de logros
            const achievements = {
                perfectStreak: { name: "Racha Perfecta", description: "Obtén una racha de 10 respuestas correctas", unlocked: false },
                highScore: { name: "Alta Puntuación", description: "Alcanza 5000 puntos", unlocked: false },
                masterLevel: { name: "Nivel Maestro", description: "Alcanza el nivel 5", unlocked: false }
            };

            function checkAchievements() {
                if (gameState.streak >= 10 && !achievements.perfectStreak.unlocked) {
                    unlockAchievement('perfectStreak');
                }
                if (gameState.score >= 5000 && !achievements.highScore.unlocked) {
                    unlockAchievement('highScore');
                }
                if (gameState.level >= 5 && !achievements.masterLevel.unlocked) {
                    unlockAchievement('masterLevel');
                }
            }

            function unlockAchievement(achievementId) {
                achievements[achievementId].unlocked = true;
                createConfetti();
                alert(`¡Logro Desbloqueado! ${achievements[achievementId].name}\n${achievements[achievementId].description}`);
            }

            // Inicialización mejorada
            window.onload = function() {
                loadProgress();
                generateNewGames();
                
                // Guardar progreso cada 30 segundos
                setInterval(saveProgress, 30000);
                
                // Verificar logros cada vez que se actualiza la puntuación
                document.addEventListener('scoreUpdate', checkAchievements);
            }; corrige el codigo