var animals = [
  { count: 0, maxcount: 0, name: "Αμπερόμετρο" },
  { count: 0, maxcount: 1, name: "Αντίσταση" },
  { count: 0, maxcount: 0, name: "Ένταση ρεύματος" },
  {
    count: 0,
    maxcount: 1,
    name: "Η μαθηματική σχέση που μας δίνει την αντίσταση",
  },
  { count: 0, maxcount: 0, name: "Κύκλωμα" },
  { count: 0, maxcount: 1, name: "Μετριέται σε" },
  { count: 0, maxcount: 1, name: "Ωμική Αντίσταση" },
];

shuffleArray(animals);

const message = document.getElementById("message");
const parentDiv = document.getElementById("confettis");
const confettis = Array.from(document.querySelectorAll(".confetti"));
const wrapper = document.getElementById("image-container");
var regions = Array.from(document.getElementsByClassName("region"));
var left_animals = document.getElementById("left-animals");
var right_animals = document.getElementById("right-animals");
left_animals.innerHTML = "";
right_animals.innerHTML = "";
let isOverlapping, overlappingRegion, newElement;
let answersCounter = 0;
let images = [];

animals.forEach((animal, index) => {
  var imgElement = document.createElement("img");
  var filename = animal.name + ".jpg"; // Add file extension
  imgElement.src = "./resources/" + filename; // Set source
  imgElement.alt = animal.name; // Set alt attribute
  imgElement.setAttribute("draggable", true); // Make it draggable
  imgElement.addEventListener("dragstart", dragStart);
  imgElement.addEventListener("touchstart", touchStart);
  imgElement.addEventListener("touchmove", touchMove);
  imgElement.addEventListener("touchend", touchEnd);
  imgElement.addEventListener("contextmenu", function (event) {
    event.preventDefault();
  });

  if (index < 4) {
    left_animals.appendChild(imgElement);
  } else {
    right_animals.appendChild(imgElement);
  }
});

images = Array.from(document.querySelectorAll(".side img"));

regions.forEach((region) => {
  region.addEventListener("dragover", dragOver);
  region.addEventListener("drop", drop);
});

function dragStart(event) {
  event.dataTransfer.setData("text/html", event.target.outerHTML);
  regions.forEach((region) => {
    region.style.boxShadow = "0px 0px 5px 0px rgba(0,0,0,0.5)";
  });
}

function dragOver(event) {
  event.preventDefault();
}

function drop(event) {
  event.preventDefault();
  regions.forEach((region) => {
    region.style.boxShadow = "none";
  });
  const data = event.dataTransfer.getData("text/html");
  console.log(data);
  const tempElement = document.createElement("div");
  tempElement.innerHTML = data;
  const element = tempElement.firstChild; // This gets the first child, assuming there's only one element in the HTML string

  if (!element) {
    console.error("No element found in the transferred data");
    return;
  }

  const animalName = element.getAttribute("alt");
  const animals_habitat = event.target.innerText.split(",");
  const appendedChildren = Array.from(event.target.children).map((child) =>
    child.getAttribute("alt")
  );

  //checks if the animal is included in the regions habitat and if its already dropped in the region
  if (
    animals_habitat.includes(animalName) &&
    !appendedChildren.includes(animalName)
  ) {
    event.target.appendChild(element);
    //checking if the animal has been appeared in all of his possible regions
    var foundAnimal = animals.find(function (element) {
      return element.name === animalName;
    });

    if (foundAnimal) {
      foundAnimal.count++; // Increment the count by 1

      if (foundAnimal.count == foundAnimal.maxcount) {
        var foundImage = images.find((element) => {
          if (element.getAttribute("alt") === foundAnimal.name) {
            return element;
          }
        });
        foundImage.style.opacity = "0.4";
        foundImage.style.pointerEvents = "none";
        answersCounter = answersCounter + 1;
      }
    }
  }
  checkIfSuccess();
  event.preventDefault();
}

function touchStart(event) {
  regions.forEach((region) => {
    region.style.boxShadow = "0px 0px 5px 0px rgba(0,0,0,0.25)";
  });

  element = document.createElement("img");
  element.setAttribute("draggable", "true");
  element.src = event.target.getAttribute("src");
  element.alt = event.target.getAttribute("alt");

  element.style.position = "absolute";
  element.style.left = `calc(${event.changedTouches[0].clientX}px - ${
    element.offsetWidth / 2
  }px)`;
  element.style.top = `calc(${event.changedTouches[0].clientY}px - 25svw)`;

  // Append the clone to the document
  wrapper.appendChild(element);
}

function touchMove(event) {
  element.style.left = `calc(${event.changedTouches[0].clientX}px - 5svw)`;
  element.style.top = `calc(${event.changedTouches[0].clientY}px - 25svw)`;

  // Iterate over each region to check for overlap
  regions.forEach((region) => {
    const regionRect = region.getBoundingClientRect();

    isOverlapping =
      event.touches[0].clientX >= regionRect.left &&
      event.touches[0].clientX <= regionRect.right &&
      event.touches[0].clientY >= regionRect.top &&
      event.touches[0].clientY <= regionRect.bottom;

    if (isOverlapping) {
      region.style.boxShadow = "0px 0px 5px 0px rgba(0,0,0,0.75)";
      overlappingRegion = region;
    } else {
      region.style.boxShadow = "0px 0px 5px 0px rgba(0,0,0,0.25)";
    }
  });

  event.preventDefault();
}

function touchEnd(event) {
  regions.forEach((region) => {
    region.style.boxShadow = "none";
  });

  // Create a clone of the target element
  newElement = document.createElement("img");
  newElement.setAttribute("draggable", "true");
  newElement.src = element.getAttribute("src");
  newElement.alt = element.getAttribute("alt");
  newElement.style.position = "relative";
  newElement.style.maxHeight = "100%";
  newElement.style.minHeight = "40%";
  let dropable = document.getElementById(overlappingRegion.getAttribute("id"));

  const animalName = newElement.getAttribute("alt");
  const animals_habitat = overlappingRegion.innerText.split(",");
  const appendedChildren = Array.from(overlappingRegion.children).map((child) =>
    child.getAttribute("alt")
  );

  if (
    animals_habitat.includes(animalName) &&
    !appendedChildren.includes(animalName)
  ) {
    dropable.appendChild(newElement);
    var foundAnimal = animals.find(function (element) {
      return element.name === newElement.getAttribute("alt");
    });
    if (foundAnimal) {
      foundAnimal.count++; // Increment the count by 1
      if (foundAnimal.count == foundAnimal.maxcount) {
        var foundImage = images.find((element) => {
          if (element.getAttribute("alt") === foundAnimal.name) {
            return element;
          }
        });
        foundImage.style.opacity = "0.4";
        foundImage.style.pointerEvents = "none";
        answersCounter = answersCounter + 1;
      }
    }
  } else {
    newElement.remove();
  }
  element.remove();
  checkIfSuccess();
  event.preventDefault();
}

function shuffleArray(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

function checkIfSuccess() {
  if (answersCounter > 3) {
    wrapper.style.transition = "0.2s ease-in";
    wrapper.style.opacity = "0.2";
    message.style.transform = "scale(1.6)";
    parentDiv.style.zIndex = 10;
    confettis.forEach((confetti) => {
      confetti.style.display = "block";
    });
  }
}
