const gameBoard = document.getElementById('game-board');
const restartButton = document.getElementById('restart');
const triesCounter = document.getElementById('tries-counter');
const timeCounter = document.getElementById('time-counter');
const statsContainer = document.querySelector('.stats');

const correctAttemptsCounter = document.createElement('p');
correctAttemptsCounter.id = 'correct-attempts-counter';
correctAttemptsCounter.style.display = 'none';
statsContainer.appendChild(correctAttemptsCounter);

const cardValues = ['🍎', '🍌', '🍓', '🍇', '🍊', '🍋', '🍉', '🍍', '🍑', '🍒', '🍏', '🥥'];

let cards = [...cardValues, ...cardValues];

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

let flippedCards = [];
let matchedPairs = 0;
let tries = 0;
let timer = null;
let elapsedTime = 0;
let timerStarted = false;
let firstCardClicked = false;
const totalPairs = cardValues.length;

function initGame() {
  cards = shuffle(cards);
  gameBoard.innerHTML = '';
  flippedCards = [];
  matchedPairs = 0;
  tries = 0;
  triesCounter.textContent = '0';
  elapsedTime = 0;
  timeCounter.textContent = '0';
  timerStarted = false;
  firstCardClicked = false;

  if (timer) {
    clearInterval(timer);
    timer = null;
  }

  gameBoard.style.display = "grid";
  correctAttemptsCounter.style.display = 'none';

  cards.forEach((value) => {
    const card = document.createElement('div');
    card.classList.add('card');
    card.dataset.value = value;
    card.innerHTML = `
      <div class="card-inner">
        <div class="card-front">?</div>
        <div class="card-back">${value}</div>
      </div>
    `;
    card.addEventListener('click', flipCard);
    gameBoard.appendChild(card);
  });
}

function flipCard() {
  if (!firstCardClicked) {
    firstCardClicked = true;

    document.querySelectorAll('.card').forEach(card => {
      card.classList.add('flipped');
    });

    setTimeout(() => {
      document.querySelectorAll('.card').forEach(card => {
        card.classList.remove('flipped');
      });
    }, 2000);
  }

  if (flippedCards.length < 2 && !this.classList.contains('flipped')) {
    if (!timerStarted) {
      startTimer();
      timerStarted = true;
    }

    this.classList.add('flipped');
    flippedCards.push(this);

    if (flippedCards.length === 2) {
      tries++;
      triesCounter.textContent = tries;
      setTimeout(checkForMatch, 1000);
    }
  }
}

function checkForMatch() {
  const [card1, card2] = flippedCards;

  if (card1.dataset.value === card2.dataset.value) {
    matchedPairs++;
  } else {
    card1.classList.remove('flipped');
    card2.classList.remove('flipped');
  }

  flippedCards = [];
  checkGameOver();
}

function checkGameOver() {
  if (matchedPairs === totalPairs) {
    clearInterval(timer);
    gameBoard.style.display = "none";
    const percentage = (matchedPairs / tries) * 100;
    correctAttemptsCounter.innerHTML = `Andel af korrekte forsøg: <span style="font-weight: bold;">${percentage.toFixed(2)}%</span>`;
    correctAttemptsCounter.style.display = 'block';
  }
}

function startTimer() {
  timer = setInterval(() => {
    elapsedTime++;
    timeCounter.textContent = elapsedTime;
  }, 1000);
}

restartButton.addEventListener('click', initGame);
initGame();
