//Countdown-timer
const minEl= document.getElementById("min");
const secondsEl = document.getElementById("seconds");

var defaultTime = 180;
var time = defaultTime;
var intervID;
var score = 0;
var allowClick = true;

if (screen.width < 576 || screen.height < 599) {
  document.getElementById("error-page").style.display = "block";
  document.getElementById("game-page").style.display = "none";
}
//list question with options
const question = document.getElementById("question");
const options = document.getElementById("choices");
const scoreText = document.getElementById("score");
const hintContainer = document.getElementById("hint-container");

function updateCountdown() {
  let min = Math.floor(time/60);
  let seconds = time % 60;
  min =  min < 10 ? "0" + min : min;
  seconds = seconds < 10 ? "0" + seconds : seconds;
 
  minEl.innerHTML = `${min}`
  secondsEl.innerHTML = `${seconds}`
 
  time -= 1;
  if (time < 0) {
    clearInterval(intervID);
    removeQuestion();
    document.getElementById("game-container").style.display = "none";
    document.getElementById("modal-save-score").style.display = "block";
    document.getElementById("last-score").innerHTML =
      " <h2 class='fw-lighter'> Dein Ergebnis: <h1><strong> " +
      score * 10 +
      " </strong></h1></h2> ";
    completed.play();
  }

  if(time<10){
    secondsEl.style.display = "none"
    minEl.style.display = "none"
    setTimeout(function() { 
      secondsEl.style.display = "block"
      minEl.style.display = "block"
    }, 100);
  }
}

async function getJson() {
  const game = await fetch("/public/game.json");
  const gameJson = await game.json();
  return gameJson;
}

function removeQuestion() {
  const elements = document.querySelectorAll(".choice-content");
  question.removeAttribute("src");
  elements.forEach((e) => {
    e.remove();
  });
}

function removeHint() {
  const hintElements = document.querySelectorAll(".hint");
  hintElements.forEach((e) => {
    e.remove();
  });
}

function getNewQuestion() {
  //radom question
  const qIndex = Math.floor(Math.random() * allData.length);
  question.querySelector("img").setAttribute("src", allData[qIndex].question);

  //random options of question with no order
  //never change input Data => copy an Input Data for usage
  const allOptions = Object.assign([], allData[qIndex].choices);
  var optionsLength = allOptions.length;
  const allHints = [];
  while (optionsLength--) {
    const optionRandom = Math.floor(Math.random() * (optionsLength + 1));
    const choiceSrc = `src='` + allOptions[optionRandom].img + `'`;
    //add hintAttribute for later usage (2.method)
    options.innerHTML +=
      `<div class="col-md-6 col-lg-3 justify-content-center mb-lg-0 p-0 choice-content"> <img class='choice
      cursor-pointer' alt='Choice Image' hint='` +
      allOptions[optionRandom].hint +
      `'` +
      choiceSrc +
      `></img> </div>`;

    allHints.push(allOptions[optionRandom].hint);
    const hintAttribute =
      `src='` +
      allOptions[optionRandom].hint +
      `' id='` +
      allHints.indexOf(allOptions[optionRandom].hint) +
      `'  class='hint'`;
    hintContainer.innerHTML += `<img ` + hintAttribute + `></img>`;
    const hints = document.querySelectorAll(".hint");
    hints.forEach((e) => {
      e.style.display = "none";
    });

    allOptions.splice(optionRandom, 1);
  }
  handleClick(qIndex, allHints);
}

function handleClick(qIndex, allHints) {
  // const questionIndex = getNewQuestion();
  const choices = document.querySelectorAll(".choice-content");

  choices.forEach((choice) => {
    choice.addEventListener("click", async (e) => {
      if(!allowClick) return;
      allowClick = false;
      //other method for hint with getAttribute
      // console.log(choice.getAttribute("hint"))

      //1.method
      // console.log( choice.getAttribute("src"))
      //find src of choice in json choices
      const src = choice.children[0].getAttribute("src");
      // console.log(choice.children[0]);
      const result = allData[qIndex].choices.find((e) => e.img === src);

      //hint appear
      document.getElementById(allHints.indexOf(result.hint)).style.display = "block";

      // if ( == answer)
      // if (questionChoice == answer)
      if (src.localeCompare(allData[qIndex].answer) == 0) {
        score++;
        scoreText.innerText = score * 10;
        choice.children[0].src = "/public/images/Check.png";
        correct.play().then(() => {
          setTimeout(() => {
            allowClick = true
            removeQuestion();
            removeHint();
            getNewQuestion();
          }, 1000);
        });
      } else {
        choice.children[0].src = "/public/images/X.png";
        //wait for hint's appearance
        fail.play().then(() => {
          setTimeout(() => {
            allowClick = true;
            removeQuestion();
            removeHint();
            getNewQuestion();
          }, 2500);
        });
      }
    });
  });
}


async function startGame() {
  scoreText.innerText = score;
  allData = await getJson();
  getNewQuestion();
}

function playGame() {
  removeQuestion();
  intervID = setInterval(updateCountdown, 1000);
  document.getElementById("game-container").style.display = "block";
  document.getElementById("end-container").style.display = "none";
  document.getElementById("introduction-page").style.display = "none";
  time = defaultTime;
  // intervID = setInterval(updateCountdown, 1000);
  score = 0;
  startGame();
}

function playAgain() {
  removeQuestion();
  document.getElementById("ranking-row").innerHTML= "";
  document.getElementById("game-container").style.display = "block";
  document.getElementById("end-container").style.display = "none";
  document.getElementById("introduction-page").style.display = "none";
  time = defaultTime;
  intervID = setInterval(updateCountdown, 1000);
  score = 0;
  startGame();
}


var correct = new Audio("/public/audio/correct-notification.wav");
var fail = new Audio("/public/audio/failure-notification.wav");
var completed = new Audio("/public/audio/game-completed.wav");

// Backend
async function saveScore() {
  const playerName = document.getElementById("player-name").value;
  const validationName = document.getElementById("validation-player-name");
  if (playerName == "") {
    validationName.style.display = "block";
    document.getElementById("player-name").classList.add("border-warning");
    return false;
  } else {
    document.getElementById("player-name").classList.add("border-0");
    validationName.style.display = "none";
    document.getElementById("end-container").style.display = "block";
    document.getElementById("modal-save-score").style.display = "none";

    const data = {
      name: playerName,
      score: Number(document.getElementById("score").innerText),
    };
    // console.log(data);
    const appwriteData = { data: JSON.stringify(data) };
    const response = await fetch(
      "https://baas.vibentec-it.io/v1/functions/6466b6d587ca2a959fb9/executions",
      {
        method: "POST",
        headers: {
          "X-Appwrite-Project": "6466b683b00bf586977c",
          "Content-Type": "application/json",
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: JSON.stringify(appwriteData),
      }
    );
    const appwriteRes = await response.json();
    console.log(appwriteRes.response);
    const rankData = JSON.parse(appwriteRes.response);
    console.log(rankData);

    if (rankData.currentRank > 5) {
      document.getElementById("end-score").innerHTML =
        "<h1 class='fw-bold'> Du bist am " + rankData.currentRank + ". Platz </h1> <h5>Übung macht den Meister. Toi Toi Toi <i class='bi bi-emoji-smile-fill'></i></h5>";
    } else {
      document.getElementById("end-score").innerHTML = "<h1 class='fw-bold'> Du bist am " + rankData.currentRank + ". Platz <i class='bi bi-trophy-fill'></i> </h1> <h4> Prima !!! </h4>";
    }

    const rankingRow = document.getElementById("ranking-row");

    const bgColor = [
      "bg-pink1",
      "bg-pink2",
      "bg-pink3",
      "bg-green1",
      "bg-green2",
    ];

    rankData.higherRank.forEach((i, index) => {
      console.log(i);
      console.log(index)
      const j = bgColor[index];
      // console.log(i.name, j)
      rankingRow.innerHTML +=
        " <tr class='" +
        j +
        "'> <th scope='row'>" +
        (index + 1) +
        "</th> <td>" +
        i.name +
        "</td><td>" +
        i.score +
        "</td></tr>";
    });
  }
}

function goToIntroductionPage() {
  document.getElementById("ranking-row").innerHTML= "";
  document.getElementById("introduction-page").style.display = "block";
  document.getElementById("modal-save-score").style.display = "none";
  document.getElementById("end-container").style.display = "none";
}
