const inner_container = document.getElementById("inner_container");
const container = document.getElementById("container_wrapper");
const canvas = document.getElementById("linesCanvas");
const context = canvas.getContext("2d");
const addBoxButton = document.getElementById("addBoxButton");
const addInput = document.getElementById("addInput");
const header = document.getElementsByTagName("header")[0];
const errMessage = document.getElementById("errMessage");
const centralMeaning = document.getElementById("central");
const plusMeaning = document.getElementById("plus");
const minusMeaning = document.getElementById("minus");

// container.style.height = `${inner_container.offsetHeight}px`;
let counter = 0;

resizeCanvas();
window.addEventListener("resize", resizeCanvas);

// Θέτουμε την βασική έννοια
plusMeaning.innerText = "Έχω ανάγκη να...";
plusMeaning.style.display = "none";
minusMeaning.innerText = "Επιθυμώ να...";
minusMeaning.style.display = "none";
centralMeaning.innerText = "Επιθυμίες / Ανάγκες";

centralMeaning.style.display = "none";

// Αν θέλουμε έννοιες να υπάρχουν ήδη, προσθέτουμε εδώ
// αλλιώς κάνουμε comment out τις 2 παρακάτω γραμμές

/*function initMeanings() {
  const meanings = [`Ως παιδιά των γονέων τους μέσα στην</br> οικογένεια`, `Ως αδέλφια</br> μέσα στην οικογένεια`, `Ως μαθήτριες ή μαθητές μέσα στο σχολείο`,`Ως φίλες ή φίλοι </br>μεταξύ τους`,`Ως ενεργοί πολίτες </br>μέσα  στην κοινωνία`,`Ως μέλη σε ομαδικές </br>δραστηριότητες`];

  counter = meanings.length;
  meanings.forEach((meaning, index) => {
    const box = document.createElement("div");
    box.className = "box";
    if (index === 0) {
      box.classList.add("first-box");  // Add a unique class to the first box
    }
    $(".first-box").css("margin-left", "20px");
    box.setAttribute("tabindex", "0");
    box.innerHTML = meaning;
    const span = document.createElement("span");
    span.ariaLabel = "Αφαίρεση πεδίου";
    span.setAttribute("tabindex", "0");
    box.appendChild(span);
    container.appendChild(box);
    makeBoxDraggable(box);
    positionBoxes();
  });
}*/

//initMeanings();

addBoxButton.addEventListener("click", function () {
  if (counter > 11) {
    errMessage.innerHTML = '<i class="bi bi-x"></i> Φτάσατε το όριο εννοιών';
    setTimeout(() => {
      errMessage.innerHTML = "";
    }, 2000);
    return;
  }

  let input = addInput.value;
  if (input !== "") {
    const box = document.createElement("div");
    box.className = "box";
    box.setAttribute("tabindex", "0");
    box.innerText = input;
    const span = document.createElement("span");
    span.ariaLabel = "Αφαίρεση πεδίου";
    span.setAttribute("tabindex", "0");
    box.appendChild(span);
    container.appendChild(box);
    makeBoxDraggable(box);
    positionBoxes();
    addInput.value = "";
  }
  counter++;
});

function removeBox(event) {
  container.removeChild(event.target.parentNode);
  counter = counter - 1;
  positionBoxes();
}

document.getElementById("captureBtn").addEventListener("click", function () {
  const spans = document.querySelectorAll("span");
  spans.forEach((span) => (span.style.display = "none"));
  html2canvas(document.getElementById("container_wrapper"))
    .then((canvas) => {
      var img = canvas.toDataURL("image/jpeg");
      document.getElementById("screenshot").src = img;
      var link = document.createElement("a");
      link.href = img;
      link.download = "conceptual_map.jpg";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      spans.forEach((span) => (span.style.display = "inline"));
    })
    .catch((error) => {
      console.error("Error capturing screenshot:", error);
      spans.forEach((span) => (span.style.display = "inline"));
    });
});

function resizeCanvas() {
  positionBoxes();
}

function positionBoxes() {
  let multiplier = 0;

  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight - header.offsetHeight;
  // container.style.height = `${inner_container.offsetHeight}px`;
  canvas.width = container.offsetWidth;
  canvas.height = container.offsetHeight;

  if (windowWidth > windowHeight) {
    multiplier = 0.8;
  } else {
    multiplier = 0.45;
  }

  const boxes = document.querySelectorAll(".box");
  const horizontalRadius =
    Math.min(container.offsetWidth, container.offsetHeight * multiplier) / 2;
  const verticalRadius =
    Math.min(container.offsetWidth, container.offsetHeight * multiplier) / 2;
  const centerX = container.offsetWidth / 2;
  const centerY = container.offsetHeight / 2;

  context.clearRect(0, 0, canvas.width, canvas.height);

  boxes.forEach((box, index) => {
    box.addEventListener("click", () => {
      box.style.zIndex = 100;
      boxes.forEach((otherBox, i) => {
        if (i != index) {
          otherBox.style.zIndex = 1;
        }
      });
    });

    if (!box.hasAttribute("data-dragged")) {
      const angle = (index / boxes.length) * (2 * Math.PI);
      const x =
        centerX + horizontalRadius * Math.cos(angle) - box.offsetWidth / 2;
      const y =
        centerY + verticalRadius * Math.sin(angle) - box.offsetHeight / 2;

      box.style.left = `${x}px`;
      box.style.top = `${y}px`;
    }

    const boxCenterX = box.offsetLeft + box.offsetWidth / 2;
    const boxCenterY = box.offsetTop + box.offsetHeight / 2;

    context.beginPath();
    context.moveTo(centerX, centerY);
    context.lineTo(boxCenterX, boxCenterY);
    context.strokeStyle = "#000"; // Line color
    context.stroke();

    // Position the span inside the box
    const span = box.querySelector("span");
    span.addEventListener("click", removeBox);

    if (boxCenterX > windowWidth / 2) {
      span.style.left = "-10%";
    } else {
      span.style.left = "90%";
    }
  });
}

function makeBoxDraggable(box) {
  let offsetX, offsetY;
  let isDragging = false;

  const startDrag = (e) => {
    isDragging = true;
    const event = e.type === "touchstart" ? e.touches[0] : e;
    offsetX = event.clientX - box.offsetLeft;
    offsetY = event.clientY - box.offsetTop;
    box.style.zIndex = 100;
  };

  const duringDrag = (e) => {
    if (isDragging) {
      const event = e.type === "touchmove" ? e.touches[0] : e;
      box.style.left = `${event.clientX - offsetX}px`;
      box.style.top = `${event.clientY - offsetY}px`;
      box.setAttribute("data-dragged", "true");
      positionBoxes();
    }
  };

  const endDrag = () => {
    if (isDragging) {
      isDragging = false;
      box.style.zIndex = 1;
    }
  };

  box.addEventListener("mousedown", startDrag);
  box.addEventListener("touchstart", startDrag);

  document.addEventListener("mousemove", duringDrag);
  document.addEventListener("touchmove", duringDrag);

  document.addEventListener("mouseup", endDrag);
  document.addEventListener("touchend", endDrag);
}
