const cards = document.querySelectorAll(".memory-card");
const refresh = document.querySelector(".refresh img");
const final = document.querySelector(".final");
const congrats = document.querySelector("#congratsSection");
const minute = document.querySelector(".minute");
const second = document.querySelector(".second");
const again = document.querySelector(".again");
const totalTime = document.querySelector("#totalTime");

let hasFlippedCard = false;
let firstCard, secondCard;
let lockBoard = false;
let totalSeconds = 0;
let interval;
let finalTime;
let click = -1;

// Function to create memory cards based on the selected grid size
function createMemoryCards(rows, cols) {
  const memoryGameSection = document.querySelector(".memory-game");
  memoryGameSection.innerHTML = "";

  const numPairs = (rows * cols) / 2;
  const countries = generatePairs(numPairs);

  const countryNumberMap = new Map();
  let currentNumber = 1;
  const countryExists = new Map();
  countries.forEach((country) => {
    if (!countryNumberMap.has(country)) {
      countryNumberMap.set(country, currentNumber++);
    }
  });

  shuffleArray(countries); // Shuffle the countries

  countries.forEach((country) => {
 
    const card = document.createElement("div");
    card.classList.add("memory-card");
    card.setAttribute("data-id", countryNumberMap.get(country)); // Use the assigned number as data-id

    const frontFace = document.createElement("img");
    frontFace.classList.add("front-face");
   
    frontFace.alt = `Front image`;
    if(countryExists.has(country)){
      frontFace.src = `./assets/info/Data_of_${country}.jpg`;
    }
    else {
      countryExists.set(country)
      frontFace.src = `./assets/flags/Flag_of_${country}.png`;
    }
    const backFace = document.createElement("div");
    backFace.classList.add("back-face");

    card.appendChild(frontFace);
    card.appendChild(backFace);

    memoryGameSection.appendChild(card);
  });

  // Add event listeners to the newly created cards
  const cards = document.querySelectorAll(".memory-card");
  cards.forEach((card) => card.addEventListener("click", flipCard));
}

// Function to handle grid size change
function changeGridSize() {
  const gridSize = document.getElementById("gridSize").value;
  const [rows, cols] = gridSize.split("x").map(Number);

  createMemoryCards(rows, cols);
}

// Function to generate unique pairs of countries
function generatePairs(numPairs) {
  const countries = [
    "Madagascar", "Kenya", "Japan", "Italy", "Israel", "Ireland", "Iraq", "India", "Greece", "Germany",
    "Georgia", "France", "Ethiopia", "Egypt", "Denmark", "Cyprus", "Cuba", "Croatia", "Colombia", "Chile",
    "Canada", "Bulgaria", "Brazil", "Azerbaijan", "Austria", "Australia", "Argentina", "Albania", "Mexico",
    "Libya", "Namibia", "Morocco", "Togo", "Nepal", "Zimbabwe", "Turkey", "the_United_States", "the_United_Arab_Emirates",
    "the_Republic_of_China", "Thailand", "Sudan", "Spain", "South_Korea", "Russia", "Pakistan", "Nigeria"
  ];

  const selectedCountries = shuffleArray(countries).slice(0, numPairs);

  // Duplicate to create pairs and shuffle again
  const pairs = shuffleArray([...selectedCountries, ...selectedCountries]);

  return pairs;
}

// Function to shuffle an array
function shuffleArray(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;
}

function flipCard() {
  if (lockBoard) return;
  if (this === firstCard) return;
  this.classList.add("flip");

  if (!hasFlippedCard) {
    // first click
    hasFlippedCard = true;
    firstCard = this;
    startTime();
    return;
  }
  //second click
  secondCard = this;
  checkForMatch();
}

function checkForMatch() {
  let isMatch = firstCard.dataset.id === secondCard.dataset.id;
  isMatch ? disableCards() : unFlipCards();
}

function disableCards() {
  //eşleştiğinde
  firstCard.removeEventListener("click", flipCard);
  secondCard.removeEventListener("click", flipCard);
  resetBoard();
  gameWon();
}

function unFlipCards() {
  lockBoard = true;
  //not match
  setTimeout(() => {
    firstCard.classList.remove("flip");
    secondCard.classList.remove("flip");
    resetBoard();
  }, 700);
}

function resetBoard() {
  [hasFlippedCard, lockBoard] = [false, false];
  [firstCard, secondCard] = [null, null];
}

refresh.addEventListener("click", function () {
  confirm("Are you sure that?");
  location.reload();
});

function startTime() {
  if (click === -1) {
    interval = setInterval(function () {
      final.innerHTML = "Μπράβο! Κέρδισες με χρόνο: " + finalTime + "!";
      finalTime = minute.innerHTML + ":" + second.innerHTML;
      totalSeconds++;
      second.innerHTML = pad(totalSeconds % 60);
      minute.innerHTML = pad(parseInt(totalSeconds / 60));
    }, 1000);
  }
  click = 1;
}

function pad(val) {
  const valString = val + "";
  if (valString.length < 2) {
    return "0" + valString;
  } else {
    return valString;
  }
}

//game won
function gameWon() {
  if (click < 1) {
    firstCard = e.target;
  }

  const gridSize = document.getElementById("gridSize").value;
  const [rows, cols] = gridSize.split("x").map(Number);
  const totalPairs = (rows * cols) / 2;

  if (document.getElementsByClassName("flip").length ===  totalPairs * 2) {
    congratsSection.classList.replace("hidden", "show");
    clearInterval(interval);
    finalTime = minute.innerHTML + ":" + second.innerHTML;
    final.innerHTML = "Μπράβο! Κέρδισες με χρόνο: " + finalTime + "!";
    totalTime.innerHTML = finalTime;
  }
  click = 0;
}

//congrats section
again.addEventListener("click", function () {
  congratsSection.classList.replace("show", "hidden");
  location.reload();
});

(function shuffle() {
  cards.forEach((card) => {
    let randomPos = Math.floor(Math.random() * 12);
    card.style.order = randomPos;
  });
})();

cards.forEach((card) => card.addEventListener("click", flipCard));
