var outputs = [];
var simulator = [];
var graph = "";

var textarea = document.getElementById("firstInput");
var editor = CodeMirror.fromTextArea(textarea, {
  mode: "text-x/myLanguage",
  lineNumbers: true,
  autoCloseTags: true,
});

var input2 = document.getElementById("secondInput");
var editor2 = CodeMirror.fromTextArea(input2, {
  mode: "text-x/myLanguage",
  lineNumbers: true,
});
document.addEventListener("DOMContentLoaded", function () {
  // var input = document.createElement("input");
  // input.type = "file";
  // input.classList.add("customInput", "col-3");
  // input.setAttribute("id", "fileInputEditor");
  // const position = { line: 1, ch: 2 };

  // editor.addWidget(position, input, false);

  //Run function
  document.getElementById("runBtn").addEventListener("click", function () {
    var input1 = editor.getValue();
    console.log("CodeMirror input1:", input1);

    var input2 = editor2.getValue();
    console.log("Second input:", input2);
    if (!input1 || !input2) {
      Toastify({
        text: "Input fields cannot be empty!",
        duration: 3000,
        close: true,
        gravity: "top",
      }).showToast();
    } else {
      outputFunction(input1, input2);
      simulatorFunction(input1, input2);
      //graphFunction(input1, input2);

      updateTextarea(getActiveTabContent());

      // Clear the input fields after execution
      document.getElementById("secondInput").value = "";

      // Log checked checkbox values
      let checked = document.querySelectorAll("input[type='checkbox']:checked");
      let checkedValues = Array.from(checked).map((cb) => cb.value);
      console.log(checkedValues);
    }
  });
});

//Functions
function simulatorFunction(input1, input2) {
  var result = input1 + input2;
  simulator.push(result);
}

function outputFunction(input1, input2) {
  var result = input1 + " " + input2;
  outputs.push(result);
}
function graphFunction(svg) {
  graph = svg;
}

function getActiveTabContent() {
  var activeTabId = document.querySelector(".rightNav.active").id;
  switch (activeTabId) {
    case "output":
      return outputs;
    case "simulator":
      return simulator;
    case "graph":
      return graph;
    default:
      return [];
  }
}

function updateTextarea(data) {
  scrollableOutput.innerHTML = "";
  if (data == graph) {
    if (data == "") {
      scrollableOutput.innerHTML = "";
    } else {
      scrollableOutput.appendChild(data);
    }
  } else {
    const formattedData = data.join("\r\n").replace(/(\r\n|\r|\n)/g, "<br>");
    scrollableOutput.innerHTML = formattedData;
  }
}

// Add click event listeners to tab links
document.querySelectorAll(".rightNav").forEach((navLink) => {
  navLink.addEventListener("click", function (event) {
    event.preventDefault();
    document.querySelectorAll(".rightNav").forEach((navLink) => {
      navLink.classList.remove("active");
    });
    this.classList.add("active");
    updateTextarea(getActiveTabContent());
  });
});