$(document).ready(function () {
  const inner_container = document.getElementById("inner_container");
  const container = document.getElementById("container_wrapper");
  const canvas = document.getElementById("linesCanvas");
  const context = canvas.getContext("2d");
  const addInput = document.getElementById("addInput");
  const errMessage = document.getElementById("errMessage");
  const centralMeaning = document.getElementById("central");
  const colors = [
  "#b8b8b8",
  "#ffd452",
  "#ee9254"
];
  let counter = 0;
  let editedBoxContent;
  let isResizing = false, isDeleting = false;
  let dragMoved = false; // Add this variable for Safari Fix and remove "isDragging". !IMPORTANT

  resizeCanvas();
  window.addEventListener("resize", () => {
  setTimeout(() => {
    resizeCanvas();
    positionBoxesInCircle();
  }, 300);
});

  // Θέτουμε την βασική έννοια
  centralMeaning.innerText = central_meaning;

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

  function initMeanings() {

    
    counter = meanings.length;
    if(counter > 0) {
      const half = Math.ceil(counter / 2);

      meanings.forEach((meaning, index) => {
        const box = document.createElement("div");
        box.className = "box";
        box.classList.add("box_"+index);
        if (index === 0) {
          box.classList.add("first-box");  // Add a unique class to the first box
          box.setAttribute("id", "first-box");
        }

        box.classList.add("unselectable"); // For not be able to select the content
        box.setAttribute("tabindex", "0");

        box.innerHTML = '<div class="text-content box-inner">'+meaning+'</div>';
        const span = document.createElement("span");
        span.classList.add("box-close-btn");
        span.ariaLabel = "Αφαίρεση πεδίου";
        span.setAttribute("tabindex", "0");
        span.innerHTML = "&times;";
        box.appendChild(span);
        
        // Remove box.addEventListener('contextmenu', function(e) { e.preventDefault(); }); !IMPORTANT
        // Remove box.addEventListener('touchstart', function(e) { e.preventDefault(); }, { passive: false }); !IMPORTANT
       
        container.appendChild(box);

       

        // Make draggable + resizable
        const $box = $(box);
        $box.resizable(
          {
            handles: "n, e, s, w, ne, se, sw, nw",
            start: function( event, ui ) {
              isResizing = true;
            },
            stop: function( event, ui ) {
              isResizing = false;
            },
            resize: function( event, ui ) {
              drawLines();
            }
          }
        );
    $box.draggable({ //Update draggable logic to include Safari fix. !IMPORTANT
          start: function () {
            dragMoved = false;
            document.getSelection().removeAllRanges();
          },
          drag: function () {
            dragMoved = true;

            if ($(this).hasClass("box-right")) {
              $(this).css("right", "auto");
            }
            if ($(this).hasClass("box-bottom")) {
              $(this).css("bottom", "auto");
            }

            drawLines();
          }
        });
            });
    }

    
    const boxes = document.querySelectorAll(".box");  

    boxes.forEach((box, index) => {
    box.style.backgroundColor = colors[index];
});
  positionBoxesInCircle();
  }

  $("#addButton").on("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.classList.add("unselectable"); // For not be able to select the content
      box.setAttribute("tabindex", "0");
      box.innerHTML = '<div class="text-content box-inner">'+input+'</div>';
      const span = document.createElement("span");
      span.classList.add("box-close-btn");
      span.ariaLabel = "Αφαίρεση πεδίου";
      span.setAttribute("tabindex", "0");
      span.innerHTML = "&times;";
      box.appendChild(span);
      
      
      //Remove box.addEventListener('contextmenu', function(e) { e.preventDefault(); }); !IMPORTANT
      //Remove box.addEventListener('touchstart', function(e) { e.preventDefault(); }, { passive: false }); !IMPORTANT

      container.appendChild(box);
      box.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];

      const $box = $(box);

      // Make draggable + resizable
      $box.resizable({
        handles: "n, e, s, w, ne, se, sw, nw",
        start: function (event, ui) {
          isResizing = true;
        },
        resize: function (event, ui) {
          drawLines();
        }
      });

      $box.draggable({
        start: function (event, ui) {
          dragMoved = false; //Change "isDragging" to this variable and set it to false. !IMPORTANT
          document.getSelection().removeAllRanges();
        },
        drag: function (event, ui) {
          dragMoved = true; //Add this line for Safari fix. !IMPORTANT
          if ($(this).hasClass("box-right")) {
            $(this).css("right", "auto");
            $(this).css("bottom", "auto");
          }
          drawLines();
        }
      });

      drawLines();

      counter++;
      $('#addModal').modal('hide');
    }

  });

  $(document).on("click", ".box-close-btn", function (e) {
    e.stopPropagation(); //Add this line for Safari fix !IMPORTANT
    let elTitle = $(this).siblings(".text-content").text().trim();
    isDeleting = true;
    if (confirm('Θέλετε σίγουρα να αφαιρέσετε τη συγκεκριμένη έννοια με τίτλο "'+elTitle+'"')) {
      $(this).parent(".box").remove();
      counter = counter - 1;
      drawLines();
    }
    isDeleting = false; //Add this line !IMPORTANT
  });

  document.getElementById("captureBtn").addEventListener("click", function () {
    $(".box .box-close-btn").hide();
    hasDarkMode = $('body').hasClass('dark-mode');
    if (hasDarkMode){
      $('body').removeClass('dark-mode');
    }
    drawLines();

    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_"+ Math.floor(new Date().getTime() / 1000) + ".jpg";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch((error) => {
        console.error("Error capturing screenshot:", error);
      });
    $(".box .box-close-btn").show();
    if (hasDarkMode){
      $('body').addClass('dark-mode');
    }
    drawLines();
  });

  function positionBoxesInCircle() {

  const boxes = document.querySelectorAll(".box");
  const total = boxes.length;

  const centerX = container.offsetWidth / 2;
  const centerY = container.offsetHeight / 2;

  const radius = Math.min(container.offsetWidth, container.offsetHeight) * 0.35;

  boxes.forEach((box, index) => {

    const angle = (index / total) * (2 * Math.PI);

    const x = centerX + radius * Math.cos(angle) - box.offsetWidth / 2;
    const y = centerY + radius * Math.sin(angle) - box.offsetHeight / 2;

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

  });

  drawLines();
}

  

  function resizeCanvas() {
    container.style.height = `${inner_container.offsetHeight}px`;
    canvas.width = container.offsetWidth;
    canvas.height = container.offsetHeight;

    drawLines();
  }

  function drawLines() {

    const boxes = document.querySelectorAll(".box");

    const centerX = container.offsetWidth / 2;
    const centerY = container.offsetHeight / 2;

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

    boxes.forEach((box, index) => {

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

      context.beginPath();
      context.moveTo(centerX, centerY);
      context.lineTo(boxCenterX, boxCenterY);
      lineColor = "#000";
      if($('body').hasClass('dark-mode')){
        lineColor = "#fff";
      }
      context.strokeStyle = lineColor;
      context.stroke();
    });
  }

  $('#addModal').on('hidden.bs.modal', function (e) {
    addInput.value = "";
  });

  //Update click event logic of box for Safari FIx. !IMPORTANT
  $(document).on("click", ".box", function () {

    if (dragMoved) {
      dragMoved = false;
      return;
    }

    if (isResizing) {
      isResizing = false;
      return;
    }

    if (isDeleting) {
      isDeleting = false;
      return;
    }

    editedBoxContent = $(this).find(".text-content");
    $("#editInput").val(editedBoxContent.text().trim());
    $("#editModal").modal("show");
    drawLines();
  });
  

  $("#editButton").on("click", function () {
    htmlContent = "";
    edInput = $("#editInput").val().trim();
    
    if (edInput !== "" ){
      editedBoxContent.html(edInput);
    }

    $('#editModal').modal('hide');
    drawLines(); //Add this to redraw lines after edit !IMPORTANT
  });

  $('#editModal').on('hidden.bs.modal', function (e) {
    $("#editInput").val("");
    $("#editList").val("");
    editedBoxContent = null; // Rename to editedBoxContent !IMPORTANT
  });

  $("#deleteButton").on("click", function () {
    let elTitle = editedBoxContent.text().trim();
    if (confirm('Θέλετε σίγουρα να αφαιρέσετε τη συγκεκριμένη έννοια με τίτλο "'+elTitle+'"')) {
      editedBoxContent.parent(".box").remove();
      counter = counter - 1;
      drawLines();
      $('#editModal').modal('hide');
    }
  });

  $("#themeToggle").click(function() {
    drawLines();
  });
});  