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

  const eventNames = [
    "update:queued",
    "update:checking",
    "update:metadata",
    "update:snapshot",
    "update:recovery_marker",
    "update:download",
    "update:apply",
    "update:verify",
    "update:restart_required",
    "update:complete",
    "update:failed",
    "update:revert",
    "recovery:marker_detected",
    "recovery:plugin_disabled",
    "recovery:retry_startup"
  ];
  const destructivePattern = /(?:^|\/)(?:delete|remove|clear|reset|renew|uninstall|cleanup|archive|revoke|unlink|unset|revert)(?:\/|$)/i;

  window.LumiPage.register("update-actions", {
    selector: "main.content",
    mount(pageRoot, { signal }) {
      const timers = new Set();
      const schedule = (callback, delay) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          callback();
        }, delay);
        timers.add(timer);
      };
      const statusFor = (form) => {
        let status = form.querySelector("[data-update-inline-result]") || form.closest(".field, .card")?.querySelector("[data-update-inline-result]");
        if (!status) {
          status = document.createElement("p");
          status.className = "hint";
          status.dataset.updateInlineResult = "";
          status.setAttribute("aria-live", "polite");
          form.insertAdjacentElement("afterend", status);
        }
        return status;
      };
      const monitorRestart = (status, delay = 1000) => {
        let attempts = 0;
        const poll = async () => {
          if (signal.aborted) return;
          attempts += 1;
          status.textContent = `Reconnecting to Lumi… attempt ${attempts} of 45.`;
          try {
            const response = await fetch("/admin/updates/status", { cache: "no-store", headers: { Accept: "application/json" }, signal });
            if (!response.ok) throw new Error("Not ready");
            status.className = "hint status-success";
            status.textContent = "Lumi is available again. You can continue on this page.";
            return;
          } catch (error) {
            if (error.name === "AbortError") return;
          }
          if (attempts >= 45) {
            status.className = "hint status-danger";
            status.setAttribute("role", "alert");
            status.textContent = "Lumi has not reconnected yet. Open Updates or Diagnostics in a new tab when the service is available.";
            return;
          }
          schedule(poll, 1000);
        };
        schedule(poll, Math.max(0, Number(delay) || 0));
      };

      pageRoot.addEventListener("submit", async (event) => {
        const form = event.target;
        const submitter = event.submitter || form?.querySelector?.("button[type='submit']");
        if (!(form instanceof HTMLFormElement) || form.closest("[data-update-management]")) return;
        if (!form.matches("[data-update-action]") && !submitter?.matches?.("[data-update-action]")) return;
        if (!window.LumiRequest) return;
        event.preventDefault();
        event.stopImmediatePropagation();
        const status = statusFor(form);
        const confirmMode = submitter?.dataset.confirmMode || form.dataset.confirmMode;
        if (confirmMode === "modal") {
          const confirmed = await window.LumiConfirm?.destructive?.({
            title: submitter?.dataset.confirmTitle || form.dataset.confirmTitle || "Confirm update",
            text: submitter?.dataset.confirmText || form.dataset.confirmText || "Apply the recommended update and restart Lumi?",
            label: submitter?.dataset.confirmLabel || form.dataset.confirmLabel || "Update Lumi",
            danger: true
          });
          if (!confirmed) {
            window.LumiStateButton?.reset?.(submitter);
            return;
          }
        }
        window.LumiStateButton?.setState?.(submitter, "loading", { busy: true });
        status.className = "hint";
        status.setAttribute("role", "status");
        status.textContent = form.getAttribute("action")?.includes("check") || submitter?.getAttribute("formaction")?.includes("check")
          ? "Checking for updates…"
          : "Applying update…";
        try {
          const result = await window.LumiRequest.form(form, { submitter });
          status.className = "hint status-success";
          status.textContent = result.message || "Update action completed.";
          window.LumiStateButton?.success?.(submitter);
          if (result.restart_required || result.reloadRequired || result.refresh_after_ms) monitorRestart(status, result.refresh_after_ms || 1000);
        } catch (error) {
          status.className = "hint status-danger";
          status.setAttribute("role", "alert");
          status.textContent = error.message || "The update action failed. Your current page is unchanged.";
          window.LumiStateButton?.error?.(submitter);
        }
      }, { signal });

      signal.addEventListener("abort", () => {
        timers.forEach((timer) => window.clearTimeout(timer));
        timers.clear();
      }, { once: true });
    }
  });

  window.LumiPage.register("update-management", {
    selector: "[data-update-management]",
    mount(root, { signal }) {
      const timers = new Set();
      const subscriptions = [];
      let refreshController = null;

      const schedule = (callback, delay) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          callback();
        }, delay);
        timers.add(timer);
        return timer;
      };

      const updateLog = () => root.querySelector("[data-update-progress-log]");
      const noticeRoot = () => root.querySelector("[data-update-notices]");

      const showNotice = (message, tone = "info", { persistent = false } = {}) => {
        const notices = noticeRoot();
        if (!notices) return null;
        const item = document.createElement("div");
        item.className = `update-notice ${tone}`;
        item.setAttribute("role", tone === "danger" ? "alert" : "status");
        const text = document.createElement("span");
        text.textContent = message || "Update status changed.";
        const close = document.createElement("button");
        close.type = "button";
        close.className = "icon-button";
        close.setAttribute("aria-label", "Dismiss notification");
        close.textContent = "×";
        close.addEventListener("click", () => item.remove(), { signal });
        item.append(text, close);
        notices.append(item);
        if (!persistent && !["danger", "warning"].includes(tone)) schedule(() => item.remove(), 6500);
        return { item, text };
      };

      const inlineResult = (form) => {
        const scope = form?.closest(".plugin-update-row, [data-update-target='core'], .card");
        let status = scope?.querySelector("[data-update-inline-result]");
        if (!status && form) {
          status = form.querySelector("[data-update-inline-result]");
          if (!status) {
            status = document.createElement("p");
            status.className = "hint";
            status.dataset.updateInlineResult = "";
            status.setAttribute("aria-live", "polite");
            form.append(status);
          }
        }
        return status;
      };

      const appendLog = (message, level = "info", form = null) => {
        const log = updateLog();
        if (log) {
          log.querySelector(":scope > .hint")?.remove();
          const row = document.createElement("div");
          row.className = `update-progress-entry ${level}`;
          row.textContent = message;
          log.prepend(row);
        }
        const status = inlineResult(form);
        if (status) {
          status.className = `hint ${level === "danger" ? "status-danger" : level === "success" ? "status-success" : ""}`.trim();
          status.setAttribute("role", level === "danger" ? "alert" : "status");
          status.textContent = message;
        }
      };

      const readEvent = (event) => {
        try { return JSON.parse(event.data || "{}"); } catch { return {}; }
      };

      const eventLabel = (eventName, payload) => {
        const stage = eventName.replace("update:", "").replace("recovery:", "recovery ").replaceAll("_", " ");
        const target = payload.plugin_id ? `plugin ${payload.plugin_id}` : payload.target || "recovery";
        return `${stage}: ${target}`;
      };

      if (window.LumiEvents?.subscribe) {
        eventNames.forEach((eventName) => {
          subscriptions.push(window.LumiEvents.subscribe(eventName, (event) => {
            const payload = readEvent(event);
            appendLog(payload.message || eventLabel(eventName, payload), eventName.includes("failed") ? "danger" : eventName.includes("complete") ? "success" : "info");
          }));
        });
      } else {
        appendLog("Live update progress is unavailable. Actions still report their final result.", "danger");
      }

      const fieldError = (form, name, message, index) => {
        const collection = form.elements.namedItem(name);
        const control = collection instanceof RadioNodeList ? collection[0] : collection;
        if (!(control instanceof HTMLElement)) return null;
        const id = `update-error-${Date.now()}-${index}`;
        const error = document.createElement("span");
        error.id = id;
        error.className = "field-error";
        error.dataset.updateFieldError = "";
        error.textContent = String(message);
        control.setAttribute("aria-invalid", "true");
        control.setAttribute("aria-describedby", `${control.getAttribute("aria-describedby") || ""} ${id}`.trim());
        (control.closest("label, .field, fieldset") || control.parentElement)?.append(error);
        return control;
      };

      const clearFieldErrors = (form) => {
        form.querySelectorAll("[data-update-field-error]").forEach((item) => item.remove());
        form.querySelectorAll("[aria-invalid='true']").forEach((control) => {
          control.removeAttribute("aria-invalid");
          const ids = String(control.getAttribute("aria-describedby") || "").split(/\s+/).filter((id) => id && !id.startsWith("update-error-"));
          if (ids.length) control.setAttribute("aria-describedby", ids.join(" "));
          else control.removeAttribute("aria-describedby");
        });
      };

      const applyFieldErrors = (form, errors = {}) => {
        let first = null;
        Object.entries(errors).forEach(([name, message], index) => {
          first ||= fieldError(form, name, message, index);
        });
        first?.focus({ preventScroll: false });
      };

      const buttonState = (button, busy, pendingLabel = "Working…") => {
        if (!button) return;
        if (busy) {
          button.dataset.updateOriginalLabel = button.textContent;
          button.disabled = true;
          button.setAttribute("aria-busy", "true");
          button.textContent = pendingLabel;
        } else {
          button.disabled = false;
          button.removeAttribute("aria-busy");
          button.textContent = button.dataset.updateOriginalLabel || button.textContent;
          delete button.dataset.updateOriginalLabel;
        }
      };

      const setText = (row, selector, value) => {
        const target = row?.querySelector(selector);
        if (target) target.textContent = value || "None";
      };

      const updateRow = (row, item) => {
        if (!row || !item) return;
        const summary = row.querySelector("[data-update-summary]");
        if (summary) {
          const current = item.installed === false ? "Not installed" : item.current_version || "unknown";
          summary.textContent = row.matches("[data-update-target='core']")
            ? `Current ${current} · Recommended ${item.safe_target_version || "none"} · ${item.source_branch || "main"}`
            : `${current} -> ${item.safe_target_version || "none"} · ${item.source_branch || "main"}`;
        }
        const badge = row.querySelector("[data-update-badge]");
        if (badge) {
          const tone = item.blocked ? "danger" : item.update_available ? "warning" : "success";
          badge.className = `badge ${tone}`;
          badge.textContent = item.blocked ? "Blocked" : item.update_available ? "Update available" : "Current";
        }
        setText(row, "[data-update-field='current_version']", item.current_version);
        setText(row, "[data-update-field='safe_target_version']", item.safe_target_version);
        setText(row, "[data-update-field='latest_available_version']", item.latest_available_version);
        setText(row, "[data-update-field='source_branch']", item.source_branch);
        setText(row, "[data-update-description]", item.version_description);
        const apply = row.querySelector("[data-update-apply-button]");
        if (apply) apply.disabled = Boolean(item.blocked || !item.update_available);
      };

      const sourceUrl = () => `/admin/updates?source=${encodeURIComponent(root.dataset.updateSource || "stable")}`;

      const replaceWholePage = async (url = sourceUrl(), focusSelector = "[data-update-source-form] select") => {
        refreshController?.abort();
        refreshController = new AbortController();
        const response = await fetch(url, {
          cache: "no-store",
          headers: { Accept: "text/html", "X-Lumi-Partial": "update-management" },
          signal: refreshController.signal
        });
        if (!response.ok || response.redirected) throw new Error("The update workspace could not be refreshed.");
        const html = await response.text();
        const nextDocument = new DOMParser().parseFromString(html, "text/html");
        const next = nextDocument.querySelector("[data-update-management]");
        if (!next) throw new Error("The refreshed update workspace was incomplete.");
        const nextUrl = new URL(url, window.location.href);
        window.LumiPage?.unmount?.();
        root.replaceWith(next);
        history.replaceState(history.state, "", nextUrl.pathname + nextUrl.search);
        window.LumiInteractions?.init?.(next);
        window.LumiPage?.mount?.(document.querySelector("main.content") || document);
        next.querySelector(focusSelector)?.focus({ preventScroll: true });
      };

      const refreshRecovery = async () => {
        const current = root.querySelector("[data-update-recovery-region]");
        if (!current) return;
        const response = await fetch(sourceUrl(), { cache: "no-store", headers: { Accept: "text/html", "X-Lumi-Partial": "update-recovery" }, signal });
        if (!response.ok || response.redirected) throw new Error("Recovery status could not be refreshed.");
        const html = await response.text();
        const next = new DOMParser().parseFromString(html, "text/html").querySelector("[data-update-recovery-region]");
        if (!next) throw new Error("The refreshed recovery status was incomplete.");
        current.replaceWith(next);
        window.LumiInteractions?.init?.(next);
      };

      const reconnect = (delay, message) => {
        const notice = showNotice(message || "Lumi is restarting. This page will reconnect automatically.", "warning", { persistent: true });
        appendLog("Waiting for Lumi to restart; the current page remains available.", "info");
        let attempts = 0;
        const poll = async () => {
          if (signal.aborted) return;
          attempts += 1;
          if (notice?.text) notice.text.textContent = `Reconnecting to Lumi… attempt ${attempts} of 45.`;
          try {
            const response = await fetch(`/admin/updates/status?source=${encodeURIComponent(root.dataset.updateSource || "stable")}`, {
              cache: "no-store",
              headers: { Accept: "application/json" },
              signal
            });
            if (!response.ok) throw new Error("Not ready");
            appendLog("Lumi is available again. Refreshing update status in place.", "success");
            notice?.item.remove();
            await replaceWholePage(sourceUrl(), "[data-update-progress-log]");
            return;
          } catch (error) {
            if (error.name === "AbortError") return;
          }
          if (attempts >= 45) {
            if (notice?.text) notice.text.textContent = "Lumi has not reconnected yet. Your current page is preserved; retry the connection or open Diagnostics in a new tab.";
            notice?.item.classList.remove("warning");
            notice?.item.classList.add("danger");
            notice?.item.setAttribute("role", "alert");
            appendLog("Lumi did not reconnect within 45 seconds.", "danger");
            return;
          }
          schedule(poll, 1000);
        };
        schedule(poll, Math.max(0, Number(delay) || 0));
      };

      const confirmAction = async (form, submitter, action) => {
        if (form.dataset.confirmMode !== "modal") return true;
        const options = {
          title: form.dataset.confirmTitle || "Confirm update action",
          text: form.dataset.confirmText || "This update action will change local files.",
          label: form.dataset.confirmLabel || submitter?.textContent || "Confirm",
          danger: true
        };
        const pathname = new URL(action, window.location.href).pathname;
        if (destructivePattern.test(pathname)) {
          const token = await window.LumiConfirm?.destructiveToken?.({ ...options, action: pathname });
          if (!token) return false;
          let field = form.querySelector('input[name="confirmation_token"]');
          if (!field) {
            field = document.createElement("input");
            field.type = "hidden";
            field.name = "confirmation_token";
            form.append(field);
          }
          field.value = token;
          return true;
        }
        return Boolean(await window.LumiConfirm?.destructive?.(options));
      };

      root.addEventListener("submit", async (event) => {
        const form = event.target;
        if (!(form instanceof HTMLFormElement)) return;
        if (form.matches("[data-update-source-form]")) {
          event.preventDefault();
          const submitter = event.submitter || form.querySelector("button[type='submit']");
          buttonState(submitter, true, "Loading…");
          const url = new URL(form.getAttribute("action") || "/admin/updates", window.location.href);
          new FormData(form).forEach((value, name) => {
            if (typeof value === "string") url.searchParams.set(name, value);
          });
          try {
            await replaceWholePage(url.href);
          } catch (error) {
            if (error.name !== "AbortError") showNotice(error.message, "danger", { persistent: true });
            buttonState(submitter, false);
          }
          return;
        }
        if (!form.matches("[data-update-action]") || !window.LumiRequest) return;
        event.preventDefault();
        event.stopImmediatePropagation();
        if (!form.checkValidity()) {
          form.reportValidity();
          return;
        }
        clearFieldErrors(form);
        const submitter = event.submitter || form.querySelector("button[type='submit']");
        const action = window.LumiForms?.action?.(form, submitter) || form.getAttribute("action") || window.location.href;
        let confirmed = false;
        try {
          confirmed = await confirmAction(form, submitter, action);
        } catch (error) {
          showNotice(error.message || "Confirmation could not be prepared.", "danger", { persistent: true });
          return;
        }
        if (!confirmed) return;
        const label = submitter?.textContent?.trim() || "Update action";
        buttonState(submitter, true, form.matches("[data-update-check-form]") ? "Checking…" : "Working…");
        form.setAttribute("aria-busy", "true");
        appendLog(`Started ${label}.`, "info", form);
        try {
          const result = await window.LumiRequest.form(form, { submitter });
          const data = result.data || {};
          const item = data.plugin || result.plugin || data.status?.core || result.status?.core;
          if (item) updateRow(form.closest(".plugin-update-row, [data-update-target='core']"), item);
          if (data.retention) {
            const age = form.elements.namedItem("max_age_days");
            const count = form.elements.namedItem("max_per_target");
            if (age) age.value = data.retention.max_age_days;
            if (count) count.value = data.retention.max_per_target;
          }
          appendLog(result.message || "Update action completed.", "success", form);
          const tone = item?.blocked ? "danger" : item?.update_available ? "warning" : "success";
          showNotice(result.message || "Update action completed.", tone, { persistent: tone !== "success" });
          if (action.includes("/recovery/clear-marker")) await refreshRecovery();
          if (result.restart_required || result.reloadRequired || result.refresh_after_ms) {
            reconnect(result.refresh_after_ms || 1000, result.message);
          }
        } catch (error) {
          applyFieldErrors(form, error.fieldErrors);
          appendLog(error.message || "Update action failed. Your current page and input are unchanged.", "danger", form);
          showNotice(error.message || "Update action failed. Your current page and input are unchanged.", "danger", { persistent: true });
        } finally {
          form.removeAttribute("aria-busy");
          form.querySelector('input[name="confirmation_token"]')?.remove();
          buttonState(submitter, false);
        }
      }, { signal });

      window.addEventListener("lumi:event-status", (event) => {
        if (event.detail?.status === "disconnected") appendLog("Live progress disconnected. The page will keep trying through the shared connection.", "danger");
      }, { signal });

      signal.addEventListener("abort", () => {
        refreshController?.abort();
        subscriptions.splice(0).forEach((unsubscribe) => unsubscribe());
        timers.forEach((timer) => window.clearTimeout(timer));
        timers.clear();
      }, { once: true });
    }
  });
})();
