"use strict";
(() => {
  // src/ide/web/worksheet-scripts.ts
  var answersSelector = "input.question, textarea.question, select.question";
  var answers = document.querySelectorAll(answersSelector);
  var hints = document.querySelectorAll("div.hint");
  var doneCheckboxes = document.querySelectorAll("div.step > input.step-complete");
  var autoSaveButton = document.getElementById("auto-save");
  var helps = document.querySelectorAll("a.help");
  var loads = document.querySelectorAll("button.load");
  var userName = document.getElementById("username");
  var autosave = document.getElementById("auto-save");
  var fh;
  if (fh) {
    document.getElementById("worksheet")?.classList.add("saved");
    userName.disabled = true;
  } else {
    document.getElementById("worksheet")?.classList.remove("saved");
  }
  if (userName.value) {
    userName.disabled = true;
  }
  async function write(code, fh2) {
    const writeable = await fh2.createWritable();
    await writeable.write(code);
    await writeable.close();
    document.getElementById("worksheet")?.classList.add("saved");
  }
  async function chromeSave(code, newName) {
    try {
      const fh2 = await showSaveFilePicker({
        suggestedName: newName,
        startIn: "documents",
        types: [{ accept: { "text/html": ".html" } }],
        id: ""
      });
      await write(code, fh2);
      userName.disabled = true;
      return fh2;
    } catch {
      return void 0;
    }
  }
  function getUpdatedDocument() {
    for (const e of document.querySelectorAll("input[type=text]")) {
      const v = e.value;
      e.setAttribute("value", v);
    }
    for (const e of document.querySelectorAll("input[type=radio]")) {
      const v = e.checked ? "true" : "false";
      e.setAttribute("checked", v);
    }
    for (const e of document.querySelectorAll(
      "input[type=checkbox]"
    )) {
      if (e.checked) {
        e.setAttribute("checked", "true");
      }
    }
    for (const e of document.getElementsByTagName("textarea")) {
      const v = e.value;
      e.innerText = v;
    }
    for (const e of document.getElementsByTagName("select")) {
      const options = e.options;
      const index = options.selectedIndex;
      options[index].setAttribute("selected", "");
    }
    const code = new XMLSerializer().serializeToString(document);
    return code;
  }
  function scrollToActiveElement() {
    const activeAndCompleteSteps = document.querySelectorAll("div.complete, div.active");
    if (activeAndCompleteSteps.length === 0) {
      const firstStep = document.querySelector("div.step");
      firstStep?.classList.add("active");
      firstStep?.scrollIntoView(false);
    } else {
      const arr = Array.from(activeAndCompleteSteps);
      const lastElement = arr[arr.length - 1];
      lastElement.scrollIntoView(false);
    }
  }
  autoSaveButton.addEventListener("click", async () => {
    const code = getUpdatedDocument();
    if (autoSaveButton?.classList.contains("test-only")) {
      document.getElementById("worksheet")?.classList.add("saved");
    } else {
      const suggestedName = document.getElementsByClassName("docTitle")[0].innerHTML;
      fh = await chromeSave(code, suggestedName);
      if (fh) {
      }
    }
    scrollToActiveElement();
  });
  function clearTempMsgs() {
    const allMsgs = document.querySelectorAll(`.temp-msg`);
    for (const m of allMsgs) {
      m.remove();
    }
  }
  async function save() {
    if (fh) {
      const code = getUpdatedDocument();
      await write(code, fh);
    }
  }
  for (const e of answers) {
    e.addEventListener("input", async (e2) => {
      const ie = e2;
      const tgt = ie.target;
      tgt.classList.add("answered");
      if (tgt.type === "radio") {
        const name = tgt.name;
        const allradio = document.querySelectorAll(`input[name=${name}]`);
        for (const e3 of allradio) {
          e3.classList.add("answered");
        }
      }
      clearTempMsgs();
      await save();
    });
  }
  function updateHintsTaken() {
    let hintsSoFar = 0;
    let hintsTaken = 0;
    for (const step of document.querySelectorAll(
      "div.complete, div.active"
    )) {
      hintsTaken = hintsTaken + step.querySelectorAll(".taken").length;
      hintsSoFar = hintsSoFar + step.querySelectorAll("div.hint").length;
    }
    for (const step of document.querySelectorAll("div.active")) {
      const taken = step.querySelectorAll("span.hints-taken");
      const total = step.querySelectorAll("span.hints-total");
      for (const ht of taken) {
        ht.innerText = `${hintsTaken}`;
      }
      for (const ht of total) {
        ht.innerText = `${hintsSoFar}`;
      }
    }
  }
  for (const hint of hints) {
    hint.addEventListener("click", async (_e) => {
      if (!hint.classList.contains("taken")) {
        const encryptedText = hint.dataset.hint || "";
        if (encryptedText !== "") {
          const content = document.getElementById(`${hint.id}content`);
          if (content) {
            content.innerHTML = atob(encryptedText);
          }
        }
        hint.classList.add("taken");
        hint.append(getTimestamp());
        updateHintsTaken();
        await save();
      }
    });
  }
  function getTimestamp() {
    const dt = /* @__PURE__ */ new Date();
    const sp = document.createElement("span");
    sp.classList.add("timestamp");
    sp.innerText = `${dt.toLocaleTimeString()} ${dt.toLocaleDateString()}`;
    return sp;
  }
  for (const cb of doneCheckboxes) {
    cb.addEventListener("click", async (e) => {
      clearTempMsgs();
      const step = cb.parentElement;
      const id = cb.id.slice(4);
      if (step) {
        const allInputs = step.querySelectorAll(answersSelector);
        const answeredInputs = step.querySelectorAll(
          "input.question.answered, textarea.question.answered, select.question.answered"
        );
        if (allInputs.length !== answeredInputs.length) {
          const msg = document.createElement("div");
          msg.classList.add("temp-msg");
          msg.innerText = "All required inputs must be completed to continue";
          cb.after(msg);
          e.preventDefault();
          return;
        }
        cb.disabled = true;
        cb.setAttribute("checked", "true");
        step.classList.remove("active");
        step.classList.add("complete");
        for (const inp of allInputs) {
          inp.disabled = true;
        }
        const nextId = parseInt(id) + 1;
        const nextStep = document.getElementById(`step${nextId}`);
        if (nextStep) {
          nextStep.classList.add("active");
        }
      }
      cb.after(getTimestamp());
      updateHintsTaken();
      await save();
    });
  }
  for (const step of document.querySelectorAll("div.step")) {
    const hintsTaken = step.querySelectorAll("span.hints-taken");
    const total = step.querySelectorAll("span.hints-total");
    for (const ht of hintsTaken) {
      ht.innerText = `${0}`;
    }
    for (const ht of total) {
      ht.innerText = `${0}`;
    }
  }
  window.addEventListener("message", (m) => {
    if (m.data === "hasFocus") {
      scrollToActiveElement();
    }
  });
  for (const b of loads) {
    b.addEventListener("click", (_e) => {
      const code = b.nextElementSibling?.textContent;
      window.parent.postMessage(`code:${code}`, "*");
    });
  }
  for (const b of helps) {
    b.addEventListener("click", (e) => {
      const link = b.href;
      window.parent.postMessage(`help:${link}`, "*");
      e.preventDefault();
      e.stopPropagation();
    });
  }
  userName.addEventListener("change", () => {
    autosave.disabled = !userName.classList.contains("answered");
  });
  autosave.disabled = !userName.classList.contains("answered");
})();
