"use strict";
(() => {
  // src/ide/web/worksheet-scripts.ts
  var questionsSelector = "input.question, textarea.question, select.question";
  var questions = document.querySelectorAll(questionsSelector);
  var notes = document.querySelectorAll("textarea.notes");
  var hints = document.querySelectorAll("div.hint");
  var doneCheckboxes = document.querySelectorAll("div.step > input.step-complete");
  var snapshots = document.querySelectorAll("div.snapshot");
  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);
    }
    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 questions) {
    addEventListenerToInput(e);
  }
  for (const e of notes) {
    addEventListenerToInput(e);
  }
  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;
      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);
            const hintHelps = content.querySelectorAll("a.help");
            setupHelpLinks(hintHelps);
          }
        }
        hint.classList.add("taken");
        hint.append(getTimestamp());
        updateHintsTaken();
        snapShotCode(hint.id);
      }
    });
  }
  for (const ss of snapshots) {
    ss.classList.add("collapsed");
    ss.addEventListener("click", () => ss.classList.toggle("collapsed"));
  }
  function addEventListenerToInput(e) {
    e.addEventListener("input", async (e2) => {
      const ie = e2;
      const tgt = ie.target;
      if (tgt instanceof HTMLTextAreaElement || tgt instanceof HTMLInputElement) {
        if (tgt.value) {
          tgt.classList.add("answered");
        } else {
          tgt.classList.remove("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 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(questionsSelector);
        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();
      snapShotCode(cb.id);
      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}`;
    }
  }
  function transformHeader(s) {
    if (s.startsWith("#")) {
      const tokens = s.split(" ");
      if (tokens.length === 7 && tokens[0] === "#" && tokens[2] === "Elan") {
        return `${tokens[0]} ${tokens[2]} ${tokens[3]}\r
`;
      }
    }
    return s;
  }
  function fixHeader(s) {
    const firstNL = s.indexOf("\n");
    if (firstNL !== -1) {
      let firstLine = s.slice(0, firstNL);
      firstLine = transformHeader(firstLine);
      return `${firstLine}${s.slice(firstNL + 1)}`;
    }
    return s;
  }
  window.addEventListener("message", async (m) => {
    if (m.data === "hasFocus") {
      scrollToActiveElement();
    }
    if (typeof m.data === "string" && m.data.startsWith("language:")) {
      const l = m.data.slice(9);
      const ws = document.querySelector("#worksheet");
      ws.classList.remove(...ws.classList);
      ws.classList.add(l);
    }
    if (typeof m.data === "string" && m.data.startsWith("code:")) {
      const idPrefixed = m.data.slice(5);
      const indexOfColon = idPrefixed.indexOf(":");
      const id = idPrefixed.slice(0, indexOfColon);
      const newCode = idPrefixed.slice(indexOfColon + 1);
      const oldCode = localStorage.getItem("code_snapshot") ?? "";
      localStorage.setItem("code_snapshot", newCode);
      if (id.startsWith("done") || id.startsWith("hint")) {
        let diff = Diff.diffLines(fixHeader(oldCode), fixHeader(newCode), {
          newLineIsToken: true
        });
        diff = diff.map((d) => {
          if (d.added || d.removed) {
            return d;
          }
          if (d.count > 2) {
            const all = d.value.split("\n").map((s) => s.trimEnd()).filter((s) => s);
            if (all.length > 2) {
              const result = [all[0], "...", all[all.length - 1]];
              return {
                added: false,
                removed: false,
                value: result.join("\n"),
                count: result.length
              };
            }
          }
          return d;
        });
        const text = Diff.convertChangesToXML(diff);
        const diffDiv = document.createElement("div");
        diffDiv.classList.add("diff");
        diffDiv.innerHTML = text;
        const snapshotDiv = document.createElement("div");
        snapshotDiv.classList.add("snapshot");
        snapshotDiv.classList.add("collapsed");
        snapshotDiv.appendChild(diffDiv);
        document.getElementById(id)?.before(snapshotDiv);
        snapshotDiv.addEventListener("click", () => snapshotDiv.classList.toggle("collapsed"));
      }
      await save();
    }
  });
  function setupLoadLinks(loadLinks) {
    for (const b of loadLinks) {
      b.addEventListener("click", (_e) => {
        const code = document.getElementById(`code-${b.id}`)?.textContent ?? "";
        window.parent.postMessage(`code:${code}`, "*");
        snapShotCode("reset");
      });
    }
  }
  function setupHelpLinks(helpLinks) {
    for (const b of helpLinks) {
      b.addEventListener("click", (e) => {
        const link = b.href;
        window.parent.postMessage(`help:${link}`, "*");
        e.preventDefault();
        e.stopPropagation();
      });
    }
  }
  setupLoadLinks(loads);
  setupHelpLinks(helps);
  updateHintsTaken();
  userName.addEventListener("change", () => {
    autosave.disabled = !userName.classList.contains("answered");
  });
  autosave.disabled = !userName.classList.contains("answered");
  function snapShotCode(id) {
    window.parent.postMessage(`snapshot:${id}`, "*");
  }
  snapShotCode("initial");
})();
