(() => {
  if (!window.LumiPage) return;

  window.LumiPage.register("command-management", {
    selector: "[data-command-management]",
    mount(root, { signal }) {
      const forms = () => Array.from(root.querySelectorAll(".command-form"));
      let refreshController = null;

      const toggleFields = (form) => {
        const mode = form.querySelector(".js-command-mode")?.value || "plain";
        const response = form.querySelector(".js-field-response")?.closest(".field");
        const code = form.querySelector(".js-field-code");
        const language = form.querySelector(".js-field-language");
        const random = form.querySelector(".js-field-random");
        const conditional = form.querySelector(".js-field-conditional");
        if (response) response.hidden = !["plain", "conditional"].includes(mode);
        if (code) code.hidden = mode !== "advanced";
        if (language) language.hidden = mode !== "advanced";
        if (random) random.hidden = mode !== "random";
        if (conditional) conditional.hidden = mode !== "conditional";
      };

      const toggleRngFields = (form) => {
        const range = form.querySelector("[data-rng-range]");
        if (range) range.hidden = form.querySelector(".js-rng-enabled")?.checked !== true;
      };

      const removeButton = (kind) => {
        const button = document.createElement("button");
        button.type = "button";
        button.className = "button subtle";
        button.dataset[kind] = "";
        button.textContent = "Remove";
        return button;
      };

      const addConditionalReply = (form) => {
        const list = form.querySelector("[data-conditional-replies]");
        if (!list) return;
        const row = document.createElement("div");
        row.className = "command-random-row command-conditional-row";
        row.dataset.conditionalReplyRow = "";
        const keyword = document.createElement("input");
        keyword.name = "conditional_keyword";
        keyword.placeholder = "keyword, alias";
        keyword.setAttribute("aria-label", "Keywords, separated with commas");
        const response = document.createElement("input");
        response.name = "conditional_response";
        response.placeholder = "The reply for this keyword";
        response.setAttribute("aria-label", "Reply");
        response.dataset.placeholderField = "core.custom_commands.static_response";
        response.dataset.placeholderOutputAudience = "user";
        row.append(keyword, response, removeButton("conditionalRemove"));
        list.append(row);
        keyword.focus();
      };

      const addRandomReply = (form) => {
        const list = form.querySelector("[data-random-replies]");
        if (!list) return;
        const row = document.createElement("div");
        row.className = "command-random-row";
        row.dataset.randomReplyRow = "";
        const text = document.createElement("input");
        text.name = "random_text";
        text.placeholder = "Message to send";
        text.dataset.placeholderField = "core.custom_commands.static_response";
        text.dataset.placeholderOutputAudience = "user";
        const weight = document.createElement("input");
        weight.name = "random_weight";
        weight.type = "number";
        weight.min = "1";
        weight.max = "999";
        weight.step = "1";
        weight.value = "1";
        weight.setAttribute("aria-label", "Selection weight");
        const condition = document.createElement("input");
        condition.name = "random_condition";
        condition.placeholder = "Optional: <20";
        condition.setAttribute("aria-label", "RNG condition");
        row.append(text, weight, condition, removeButton("randomRemove"));
        list.append(row);
        text.focus();
      };

      const initializeForms = (scope = root) => {
        scope.querySelectorAll(".command-form").forEach((form) => {
          toggleFields(form);
          toggleRngFields(form);
        });
      };
      initializeForms();

      const refreshCommandList = async (message) => {
        const current = root.querySelector("[data-command-list-section]");
        if (!current) return;
        refreshController?.abort();
        refreshController = new AbortController();
        current.setAttribute("aria-busy", "true");
        try {
          const response = await fetch("/admin/commands", {
            cache: "no-store",
            headers: { Accept: "text/html", "X-Lumi-Partial": "command-list" },
            signal: refreshController.signal
          });
          if (!response.ok || response.redirected) throw new Error("The command list could not be refreshed.");
          const html = await response.text();
          const nextDocument = new DOMParser().parseFromString(html, "text/html");
          const next = nextDocument.querySelector("[data-command-list-section]");
          if (!next) throw new Error("The refreshed command list was incomplete.");
          current.replaceWith(next);
          const status = next.querySelector("[data-command-management-status]");
          if (status) status.textContent = message || "Command list updated.";
          initializeForms(next);
          window.LumiInteractions?.init?.(next);
        } catch (error) {
          if (error.name === "AbortError") return;
          current.removeAttribute("aria-busy");
          const status = current.querySelector("[data-command-management-status]");
          if (status) {
            status.setAttribute("role", "alert");
            status.textContent = `${message || "The command was saved"} The list could not refresh; reload this page to see the latest state.`;
          }
        }
      };
      signal.addEventListener("abort", () => refreshController?.abort(), { once: true });

      root.addEventListener("change", (event) => {
        const form = event.target.closest(".command-form");
        if (!form) return;
        if (event.target.matches(".js-command-mode")) toggleFields(form);
        if (event.target.matches(".js-rng-enabled")) toggleRngFields(form);
      }, { signal });

      root.addEventListener("click", (event) => {
        const form = event.target.closest(".command-form");
        if (!form) return;
        if (event.target.closest("[data-random-add]")) addRandomReply(form);
        else if (event.target.closest("[data-conditional-add]")) addConditionalReply(form);
        else event.target.closest("[data-random-remove]")?.closest("[data-random-reply-row]")?.remove();
        if (event.target.closest("[data-conditional-remove]")) {
          event.target.closest("[data-conditional-remove]").closest("[data-conditional-reply-row]")?.remove();
        }
      }, { signal });

      root.addEventListener("lumi:form-saved", (event) => {
        const form = event.target;
        if (!(form instanceof HTMLFormElement)) return;
        if (form.matches("[data-command-create-form]")) {
          form.reset();
          toggleFields(form);
          toggleRngFields(form);
        }
        if (form.matches("[data-command-create-form], [data-command-list-action]")) {
          refreshCommandList(event.detail?.message);
        }
      }, { signal });
    }
  });
})();
