// Array of card values (8 pairs of letters)
const cardValues = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
let cards = [...cardValues, ...cardValues];

const gameContainer = document.getElementById('game-container');
let flippedCards = [];
let matchedCards = 0;
let failedAttempts = 0;
const maxFailedAttempts = 4;

// Function to shuffle the cards
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]];
  }
}

// Function to create cards with letters
function createCards() {
  cards.forEach((value) => {
    const card = document.createElement('div');
    card.classList.add('card');
    card.dataset.value = value;
    card.addEventListener('click', flipCard);
    gameContainer.appendChild(card);
  });
}

// Function to handle card flip
function flipCard() {
  if (flippedCards.length < 2 && !this.classList.contains('flip')) {
    this.classList.add('flip');
    this.textContent = this.dataset.value;
    flippedCards.push(this);

    if (flippedCards.length === 2) {
      checkMatch();
    }
  }
}

// Function to check for a match
function checkMatch() {
  const [card1, card2] = flippedCards;
  if (card1.dataset.value === card2.dataset.value) {
    matchedCards += 2;
    flippedCards = []; // Clear flipped cards

    if (matchedCards === cards.length) {
      setTimeout(() => alert('You Won!'), 500);
    }
  } else {
    failedAttempts++;
    if (failedAttempts >= maxFailedAttempts) {
      setTimeout(() => alert('Game Over'), 500);
      document.querySelectorAll('.card').forEach(card => card.removeEventListener('click', flipCard));
    } else {
      setTimeout(() => {
        card1.classList.remove('flip');
        card2.classList.remove('flip');
        card1.textContent = '';
        card2.textContent = '';
        flippedCards = []; // Reset for the next attempt
      }, 1000);
    }
  }
}

// Function to initialize the game with a preview
function initializeGame() {
  shuffle(cards); // Shuffle cards at the start of each new game

  createCards();

  // Show all cards initially
  document.querySelectorAll('.card').forEach(card => {
    card.classList.add('flip');
    card.textContent = card.dataset.value;
  });

  // Wait 3 seconds, then hide all unmatched cards
  setTimeout(() => {
    document.querySelectorAll('.card').forEach(card => {
      card.classList.remove('flip');
      card.textContent = ''; // Hide the letter
    });
  }, 3000); // Adjust this time as desired for preview
}

// Start the game
initializeGame();


