document.addEventListener("DOMContentLoaded", loadGames);
let elements = [];
let isDev = [];
let pageData;
async function loadGames() {
  if(type == "g") pageData = {path: "/resources/games.json", prefix: "semag"}
  else if(type == "a") pageData = {path: "/resources/apps.json", prefix: "sppa"}
  else sAlert("this is not valid");
  // taken from mdn
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
  let data = await (await fetch(pageData.path)).json();
  let sorted = data.sort((a, b) => {
    const n1 = a.name.toUpperCase();
    const n2 = b.name.toUpperCase();
    if (n1 < n2) {
      return -1;
    }
    if (n1 > n2) {
      return 1;
    }
    // shouldnt happen but just incase
    return 0;
  });
  let gamesElement = document.getElementById("games");
  let topGElement = document.getElementById("topGames");

  let gamesFragment = document.createDocumentFragment();
  let topFragment = document.createDocumentFragment();
  let starredGames = JSON.parse(localStorage.getItem("selenite.starred") || '[]');
  sorted.forEach(element => {
    isStarred = starredGames.indexOf(element.directory) != -1;
    let newElement = document.createElement("a");
    newElement.setAttribute("data-target", element.directory);
    newElement.setAttribute("data-image", element.image);
    newElement.setAttribute("class", "game");
    newElement.setAttribute("href", `/loader.html?title=${encodeURIComponent(element.name)}&dir=${element.directory}&img=${element.image}&type=g`);
    let image = document.createElement("img");
    image.src = `/resources/${pageData.prefix}/${element.directory}/${element.image}`;
    image.loading = `lazy`;
    image.onerror = function() {this.src="/img/missing.svg"};
    let holder = document.createElement("div");
    holder.id = "holder";
    let title = document.createElement("h1");
    title.innerText = element.name;
    let star = document.createElement("img");
    star.id = "star";
    star.classList = "star";
    star.src = isStarred ? "/img/star-fill.svg" : "/img/star.svg";
    let warnings = document.createElement("warnings");
    newElement.appendChild(image);
    holder.appendChild(title);
    newElement.appendChild(holder);
    newElement.appendChild(warnings);
    if(element.tags) {
      if(element.tags.includes("18+")) {
        let thirteenplus = document.createElement("warning");
        thirteenplus.innerText = "18+";
        thirteenplus.classList = "thirteen";
        warnings.appendChild(thirteenplus);
      }
      if(element.tags.includes("13+")) {
        let thirteenplus = document.createElement("warning");
        thirteenplus.innerText = "13+";
        thirteenplus.classList = "thirteen";
        warnings.appendChild(thirteenplus);
      }
      if(element.tags.includes("horror")) {
        let horror = document.createElement("warning");
        horror.innerText = "😱";
        horror.classList = "horror";
        warnings.appendChild(horror);
      }
      if(element.tags.includes("gore")) {
        let gore = document.createElement("warning");
        gore.innerText = "🩸";
        gore.classList = "gore";
        warnings.appendChild(gore);
      }
      if(element.tags.includes("top") && localStorage.getItem("selenite.disableTopGames") != "false") {
        topFragment.appendChild(newElement);
      } else {
        gamesFragment.appendChild(newElement);
        holder.appendChild(star);
      }
      if(element.tags.includes("tofinish")) isDev.push(element.directory);
    } else {
      gamesFragment.appendChild(newElement);
      holder.appendChild(star);
    }
    elements.push(newElement);
    star.addEventListener("click", (e) => {
      e.preventDefault();
	    e.stopPropagation();
      starEvent(e);
    });
  });
  gamesElement.appendChild(gamesFragment);
  topGElement.appendChild(topFragment);
  document.getElementById("gameCount").innerText = `${data.length} games loaded!`;
  document.getElementById("loadingMsg").style.display = "none";
  document.getElementById("allHeader").style.display = "block";
  if(localStorage.getItem("selenite.disableTopGames") != "false") {
    document.getElementById("topHeader").style.display = "block";
  }
  if(isDev.length > 0) {sAlert("wip games", "dev message, shouldnt be seen");console.log(isDev.join(","))};
  starredGames = JSON.parse(localStorage.getItem("selenite.starred") || '[]');
  if(starredGames.length > 0) {
    document.getElementById("starredHeader").style.display = "block";
    starredGames.forEach((e) => {
      let element = document.querySelector(`#games a.game[data-target='${e}']`);
      let newElement = element.cloneNode(true);
      document.getElementById("starredgames").appendChild(newElement);
    });
    document.querySelectorAll("#starredgames #star").forEach((e) => {
      e.addEventListener("click", (e) => {
        e.preventDefault();
	      e.stopPropagation();
        starEvent(e);
      })
    })
  }
}
document.addEventListener("DOMContentLoaded", ()=>{
  document.getElementById("gamesearch").addEventListener("input", ()=>{
    let input = document.getElementById("gamesearch").value.toUpperCase();
    let total = 0;
    if(elements.length > 0) {
      elements.forEach((element) => {
        let title = element.childNodes[1].childNodes[0].innerText.toUpperCase();
        if(title.includes(input)) {
          element.style.display = "flex";
        } else {
          element.style.display = "none";
          total++;
        }
      })
    }
    document.getElementById("noResults").style.display = total >= elements.length ?  "flex" : "none"
  })
});

function starEvent(e) {
  let game = e.target.parentNode.parentNode.getAttribute("data-target");
  starredGames = JSON.parse(localStorage.getItem("selenite.starred") || '[]');
  if(starredGames.indexOf(game) == -1) {
    starredGames.push(game);
    starredGames.sort();
    if(starredGames.length > 0) {
      document.getElementById("starredHeader").style.display = "block";
    } else {
      document.getElementById("starredHeader").style.display = "none";
    }
    localStorage.setItem("selenite.starred", JSON.stringify(starredGames));
    e.target.src = "/img/star-fill.svg";
    starredgames.innerHTML = "";
    starredGames.forEach((e) => {
      let element = document.querySelector(`#games a.game[data-target='${e}']`);
      let newElement = element.cloneNode(true);
      document.getElementById("starredgames").appendChild(newElement);
    })
  } else {
    starredGames.splice(starredGames.indexOf(game), 1);
    document.querySelectorAll(`a.game[data-target='${game}'] #star`).forEach((e) => {
      e.src = "/img/star.svg";
    })
    if(starredGames.length > 0) {
      document.getElementById("starredHeader").style.display = "block";
    } else {
      document.getElementById("starredHeader").style.display = "none";
    }
    localStorage.setItem("selenite.starred", JSON.stringify(starredGames));
    starredgames.innerHTML = "";
    starredGames.forEach((e) => {
      let element = document.querySelector(`#games a.game[data-target='${e}']`);
      let newElement = element.cloneNode(true);
      document.getElementById("starredgames").appendChild(newElement);
    })
  }
  document.querySelectorAll("#starredgames #star").forEach((e) => {
      e.addEventListener("click", (e) => {
        e.preventDefault();
	      e.stopPropagation();
        starEvent(e);
      })
  })
}