const startButton = document.getElementById('startButton');
const menu = document.getElementById('menu');
const game = document.getElementById('game');
const squares = document.querySelectorAll('.square');

let sequence = [];
let playerSequence = [];
let level = 0;
let isPlayerTurn = false;

startButton.addEventListener('click', startGame);

squares.forEach(square => {
    square.addEventListener('click', handleSquareClick);
});

function startGame() {
    menu.style.display = 'none';
    game.style.display = 'block';
    level = 0;
    sequence = [];
    nextLevel();
}

function nextLevel() {
    playerSequence = [];
    level++;
    const nextColor = squares[Math.floor(Math.random() * squares.length)].id;
    sequence.push(nextColor);
    playSequence();
}

function playSequence() {
    isPlayerTurn = false;
    let delay = 1000;
    sequence.forEach((color, index) => {
        setTimeout(() => {
            lightUp(color);
        }, delay * (index + 1));
    });
    setTimeout(() => {
        isPlayerTurn = true;
    }, delay * sequence.length);
}

function lightUp(color) {
    const square = document.getElementById(color);
    square.classList.add('active');
    setTimeout(() => {
        square.classList.remove('active');
    }, 500);
}

function handleSquareClick(event) {
    if (!isPlayerTurn) return;

    const color = event.target.id;
    playerSequence.push(color);
    lightUp(color);

    if (color !== sequence[playerSequence.length - 1]) {
        // Display the scary image
        const background = document.getElementById('background');
        background.src = 'https://gallery.screamer.wiki/_images/a69304e9d4f0160c0e765a2be9afad38/268%20-%20Face%20Zombie%20creepy.jpg'; 
        background.style.display = 'block'; // Make sure the image is visible
        background.style.position = 'fixed'; // Position it to cover the entire screen
        background.style.top = '0';
        background.style.left = '0';
        background.style.width = '100%';
        background.style.height = '100%';
        background.style.zIndex = '1000'; // Ensure it is on top of other elements
        background.style.objectFit = 'cover'; // Stretch the image to cover the screen

        // Play the scary sound
        let audio = new Audio('https://file.garden/Zh545vFdohdB9PWf/scare.mp3');
        audio.play().catch(error => console.log('Audio play failed:', error)); // Catch any play errors
        
        // Show the menu and hide the game
        menu.style.display = 'block';
        game.style.display = 'none';
    } else if (playerSequence.length === sequence.length) {
        setTimeout(nextLevel, 1000);
    }
}
