// Un-bundled. Driven by data-editor-language attrs on <textarea>.
// Mounts cm6 (from editor.bundle.js exporting window.__editor),
// installs one capture-phase submit handler per <form>, and exposes
// a named alias for the files-editor modal.
(function () {
  "use strict";

  // editor.css pre-hides every textarea[data-editor-language] so the
  // page never paints the raw textarea before cm6 takes over. Both
  // failure paths below restore the textarea by clearing the CSS rule
  // with an inline display:revert.
  function unhideTextarea(ta) {
    ta.style.display = "revert";
  }

  if (!window.__editor || typeof window.__editor.mount !== "function") {
    // Bundle didn't load — un-hide every editor textarea so the form
    // is still usable. Mirrors the <noscript> override for the
    // JS-disabled case.
    for (const ta of document.querySelectorAll("textarea[data-editor-language]")) {
      unhideTextarea(ta);
    }
    return;
  }

  let vocabPromise = null;
  function loadSrccfgVocab() {
    if (!vocabPromise) {
      vocabPromise = fetch("/static/data/srccfg-vocab.json", { credentials: "same-origin" })
        .then(r => r.ok ? r.json() : Promise.reject(new Error("vocab fetch failed: " + r.status)))
        .catch(err => { console.warn("[editor] vocab load failed", err); return null; });
    }
    return vocabPromise;
  }

  function resolveAutoLanguage(filenameInput) {
    const name = (filenameInput && filenameInput.value || "").toLowerCase();
    if (name.endsWith(".cfg")) return "srccfg";
    if (name.endsWith(".sh"))  return "bash";
    return "plain";
  }

  async function mountOne(textarea) {
    if (textarea.__editorController) return;  // idempotency: don't double-mount
    let lang = textarea.getAttribute("data-editor-language") || "plain";
    let filenameInput = null;
    let dropdown = null;
    if (lang === "auto") {
      const modal = textarea.closest("#files-editor-modal, #files-editor-fragment") || document;
      filenameInput = modal.querySelector("[data-editor-filename]");
      dropdown = modal.querySelector("[data-editor-language-select]");
      lang = resolveAutoLanguage(filenameInput);
    }

    const vocab = (lang === "srccfg") ? await loadSrccfgVocab() : null;
    const rows = parseInt(textarea.getAttribute("rows") || "0", 10) || 0;
    const controller = window.__editor.mount(textarea, { language: lang, vocab, rows });

    // Submit-time copy bridge
    const form = textarea.closest("form");
    if (form && !form.__editorSubmitBound) {
      form.__editorSubmitBound = true;
      form.addEventListener("submit", () => {
        for (const ta of form.querySelectorAll("textarea[data-editor-language]")) {
          if (ta.__editorController) ta.value = ta.__editorController.getValue();
        }
      }, true /* capture phase */);
    }
    textarea.__editorController = controller;

    // Files-modal hooks
    if (textarea.classList.contains("files-editor-content")) {
      window.__filesEditor = controller;
      if (dropdown) {
        dropdown.addEventListener("change", () => {
          const v = dropdown.value;
          controller.setLanguage(v === "auto" ? resolveAutoLanguage(filenameInput) : v);
        });
      }
      if (filenameInput) {
        filenameInput.addEventListener("input", () => {
          if (!dropdown || dropdown.value === "auto") {
            controller.setLanguage(resolveAutoLanguage(filenameInput));
          }
        });
      }
    }
  }

  function initEditors(root) {
    const scope = root || document;
    for (const ta of scope.querySelectorAll("textarea[data-editor-language]")) {
      mountOne(ta).catch(err => {
        console.error("[editor] mount failed", err);
        unhideTextarea(ta);
      });
    }
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => initEditors(document));
  } else {
    initEditors(document);
  }

  // Re-init editors that arrive via HTMX swap (modal content, etc.).
  document.body.addEventListener("htmx:afterSwap", (event) => {
    if (event.target && event.target.id === "modal-content") {
      initEditors(event.target);
    }
  });

  // Expose for callers that need to re-mount imperatively.
  if (window.__editor) {
    window.__editor.initEditors = initEditors;
  }
})();
