document.addEventListener("DOMContentLoaded", loadGames);
let elements = [];
async function loadGames() {
  // taken from mdn
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
  let data = await (await fetch("/resources/apps.json")).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 starredGames = JSON.parse(localStorage.getItem("selenite.starred") || '[]');
  sorted.forEach(element => {
    isStarred = starredGames.indexOf(element.directory) != -1;
    let newElement = document.createElement("game");
    newElement.setAttribute("data-target", element.directory);
    newElement.setAttribute("data-image", element.image);
    let image = document.createElement("img");
    image.src = `/resources/sppa/${element.directory}/${element.image}`
    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";
    newElement.appendChild(image);
    holder.appendChild(title);
    holder.appendChild(star);
    newElement.appendChild(holder);
    gamesElement.appendChild(newElement);
    elements.push(newElement);
    newElement.addEventListener("click", ()=>{
      location.href=`/loader.html?title=${encodeURIComponent(element.name)}&dir=${element.directory}&img=${element.image}&type=a`
    });
    star.addEventListener("click", (e) => {
      e.preventDefault();
	    e.stopPropagation();
      starEvent(e);
    });
  });
  document.getElementById("gameCount").innerText = `${data.length} apps loaded!`;
  document.getElementById("loadingMsg").style.display = "none";
  document.getElementById("allHeader").style.display = "block";
  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 game[data-target='${e}']`);
      let newElement = element.cloneNode(true);
      document.getElementById("starredgames").appendChild(newElement);
      newElement.addEventListener("click", ()=>{
        location.href=`/loader.html?title=${newElement.childNodes[1].childNodes[0].innerText}&dir=${newElement.getAttribute("data-target")}&img=${newElement.getAttribute("data-image")}&type=a`
      });
    });
    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 game[data-target='${e}']`);
      let newElement = element.cloneNode(true);
      document.getElementById("starredgames").appendChild(newElement);
      newElement.addEventListener("click", ()=>{
        location.href=`/loader.html?title=${newElement.childNodes[1].childNodes[0].innerText}&dir=${newElement.getAttribute("data-target")}&img=${newElement.getAttribute("data-image")}&type=a`
      });
    })
  } else {
    starredGames.splice(starredGames.indexOf(game), 1);
    document.querySelectorAll(`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 game[data-target='${e}']`);
      let newElement = element.cloneNode(true);
      document.getElementById("starredgames").appendChild(newElement);
      newElement.addEventListener("click", ()=>{
        location.href=`/loader.html?title=${newElement.childNodes[1].childNodes[0].innerText}&dir=${newElement.getAttribute("data-target")}&img=${newElement.getAttribute("data-image")}&type=a`
      });
    })
  }
  document.querySelectorAll("#starredgames #star").forEach((e) => {
      e.addEventListener("click", (e) => {
        e.preventDefault();
	      e.stopPropagation();
        starEvent(e);
      })
  })
}