const gameSquare = document.getElementById('game-square');
const restartButton = document.getElementById('restart');
const messageBox = document.getElementById('message');
const title = document.querySelector('h1');

let gameStarted = false;
let startTime;
let reactionTime;
let gameEnded = false;
let timeoutId;

gameSquare.addEventListener('click', () => {
    if (gameEnded) {
        return;
    }

    if (!gameStarted) {
        gameStarted = true;
        title.style.display = 'none';
        gameSquare.classList.add('green');
        messageBox.style.display = 'none';

        timeoutId = setTimeout(() => {
            if (gameStarted) {
                gameSquare.classList.remove('green');
                gameSquare.classList.add('red');
                startTime = Date.now();
            }
        }, Math.floor(Math.random() * (6000 - 1500 + 1)) + 1500);
    } else if (gameSquare.classList.contains('red')) {
        const endTime = Date.now();
        reactionTime = endTime - startTime;
        displayResults();
    } else {
        gameSquare.style.display = 'none';
        messageBox.innerHTML = 'Du klikkede for tidligt!<br>Prøv igen!';
        messageBox.style.display = 'block';
        restartButton.style.display = 'block';
        gameEnded = true;
        clearTimeout(timeoutId);
    }
});

function displayResults() {
    messageBox.innerHTML = `Din reaktionstid var ${reactionTime} ms.`;
    messageBox.style.display = 'block';
    restartButton.style.display = 'block';
    gameSquare.style.display = 'none';
    gameEnded = true;
    clearTimeout(timeoutId);
}

function resetGame() {
    gameStarted = false;
    gameEnded = false;
    gameSquare.style.display = 'block';
    gameSquare.classList.remove('red', 'green');
    restartButton.style.display = 'none';
    messageBox.style.display = 'block';
    messageBox.innerHTML = 'Tryk på firkanten for at starte testen. <br> <br> Tryk igen når firkanten bliver rød, så hurtigt du kan.';
    title.style.display = 'block';
}

restartButton.addEventListener('click', () => {
    resetGame();
    clearTimeout(timeoutId);
});

document.body.addEventListener('click', (event) => {
    if (event.target === restartButton) {
        event.stopPropagation();
    }
});
