(() => {
  const body = document.body;
  const media = window.matchMedia("(max-width: 900px)");
  const sidebarPreferenceKey = "lumi-sidebar-collapsed";
  const sidebar = document.getElementById("lumi-sidebar");
  const page = document.querySelector(".page");
  const sidebarToggles = Array.from(document.querySelectorAll("[data-sidebar-toggle]"));
  let sidebarOpener = null;

  const sidebarFocusable = () => Array.from(sidebar?.querySelectorAll("a[href], button:not([disabled]), summary, [tabindex]:not([tabindex='-1'])") || [])
    .filter((item) => !item.hidden && item.offsetParent !== null);

  const updateSidebarState = () => {
    const open = body.classList.contains("sidebar-open");
    const collapsed = body.classList.contains("sidebar-collapsed");
    sidebarToggles.forEach((button) => {
      const expanded = media.matches ? open : !collapsed;
      button.setAttribute("aria-expanded", expanded ? "true" : "false");
      button.setAttribute("aria-label", media.matches
        ? `${open ? "Close" : "Open"} navigation`
        : `${collapsed ? "Expand" : "Collapse"} navigation`);
    });
  };

  const closeSidebar = ({ restoreFocus = true } = {}) => {
    if (!body.classList.contains("sidebar-open")) return;
    body.classList.remove("sidebar-open");
    if (page) page.inert = false;
    if (sidebar && media.matches) {
      sidebar.inert = true;
      sidebar.setAttribute("aria-hidden", "true");
    }
    sidebar?.removeAttribute("role");
    sidebar?.removeAttribute("aria-modal");
    updateSidebarState();
    if (restoreFocus && sidebarOpener?.isConnected) sidebarOpener.focus({ preventScroll: true });
    sidebarOpener = null;
  };

  const openSidebar = (opener) => {
    if (!sidebar) return;
    sidebarOpener = opener;
    sidebar.inert = false;
    sidebar.removeAttribute("aria-hidden");
    body.classList.add("sidebar-open");
    if (page) page.inert = true;
    sidebar.setAttribute("role", "dialog");
    sidebar.setAttribute("aria-modal", "true");
    updateSidebarState();
    window.setTimeout(() => (sidebarFocusable()[0] || sidebar).focus({ preventScroll: true }), 0);
  };

  if (!media.matches && window.localStorage.getItem(sidebarPreferenceKey) === "true") {
    body.classList.add("sidebar-collapsed");
  }

  sidebarToggles.forEach((button) => {
    button.addEventListener("click", () => {
      if (media.matches) {
        if (body.classList.contains("sidebar-open")) closeSidebar();
        else openSidebar(button);
      } else {
        body.classList.toggle("sidebar-collapsed");
        window.localStorage.setItem(
          sidebarPreferenceKey,
          body.classList.contains("sidebar-collapsed") ? "true" : "false"
        );
        updateSidebarState();
      }
    });
  });

  document.querySelector("[data-sidebar-dismiss]")?.addEventListener("click", () => {
    closeSidebar();
  });

  document.addEventListener("keydown", (event) => {
    if (!media.matches || !body.classList.contains("sidebar-open")) return;
    if (event.key === "Escape") {
      event.preventDefault();
      closeSidebar();
      return;
    }
    if (event.key !== "Tab") return;
    const items = sidebarFocusable();
    if (!items.length) return;
    const first = items[0];
    const last = items[items.length - 1];
    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  });

  document.addEventListener("click", (event) => {
    const button = event.target.closest("[data-expand-text]");
    if (!button) return;
    const target = document.getElementById(button.dataset.expandText || "");
    if (!target) return;
    const expanded = button.getAttribute("aria-expanded") !== "true";
    target.classList.toggle("is-collapsed", !expanded);
    target.classList.toggle("is-expanded", expanded);
    button.setAttribute("aria-expanded", expanded ? "true" : "false");
    button.textContent = expanded
      ? button.dataset.expandedLabel || "Read less"
      : button.dataset.collapsedLabel || "Read more";
  });

  document.querySelectorAll("[data-command-content-toggle]").forEach((controls) => {
    const buttons = Array.from(controls.querySelectorAll("[data-command-content-mode]"));
    const applyMode = (mode) => {
      const showDescriptions = mode === "description";
      document.querySelectorAll("[data-command-list-content]").forEach((content) => {
        const preview = content.querySelector("[data-command-content-preview]");
        const description = content.querySelector("[data-command-content-description]");
        if (preview) preview.hidden = showDescriptions;
        if (description) description.hidden = !showDescriptions;
      });
      buttons.forEach((button) => {
        const active = button.dataset.commandContentMode === mode;
        button.classList.toggle("is-active", active);
        button.setAttribute("aria-pressed", active ? "true" : "false");
      });
    };
    buttons.forEach((button) => {
      button.addEventListener("click", () => applyMode(button.dataset.commandContentMode || "preview"));
    });
    applyMode("preview");
  });

  document.querySelectorAll(".nav-link").forEach((link) => {
    link.addEventListener("click", () => {
      if (body.classList.contains("sidebar-open")) {
        closeSidebar({ restoreFocus: false });
      }
    });
  });

  document.querySelectorAll(".nav-section").forEach((section) => {
    const summary = section.querySelector("summary");
    summary?.setAttribute("aria-expanded", section.open ? "true" : "false");
    section.addEventListener("toggle", () => {
      summary?.setAttribute("aria-expanded", section.open ? "true" : "false");
      if (!section.open) return;
      document.querySelectorAll(".nav-section[open]").forEach((other) => {
        if (other !== section) {
          other.open = false;
          other.querySelector("summary")?.setAttribute("aria-expanded", "false");
        }
      });
    });
  });

  document.querySelectorAll("[data-user-lookup]").forEach((lookup) => {
    const search = lookup.querySelector("[data-user-lookup-search]");
    const userId = lookup.querySelector("[data-user-lookup-id]");
    const results = lookup.querySelector("[data-user-lookup-results]");
    const preview = lookup.querySelector("[data-user-lookup-preview]");
    const endpoint = lookup.dataset.userLookupEndpoint || "/api/users/search";
    const fillSelector = lookup.dataset.userLookupFill || "";
    const fillInput = fillSelector ? lookup.closest("form")?.querySelector(fillSelector) || document.querySelector(fillSelector) : null;
    let timer = null;
    let controller = null;

    if (!search || !userId || !results) return;

    const identityLabel = (identity) => {
      if (!identity) return "";
      const provider = identity.provider || "account";
      return `${provider}: ${identity.display_name || identity.provider_user_id || ""}`.trim();
    };
    const selectUser = (user) => {
      const username = user.username || user.internal_username || user.id;
      userId.value = user.id || "";
      search.value = username;
      if (fillInput && fillInput !== userId) fillInput.value = username;
      const identities = (user.identities || []).map(identityLabel).filter(Boolean).join(" | ");
      if (preview) {
        preview.textContent = `${username} | ${user.id}${identities ? ` | ${identities}` : ""}`;
        preview.hidden = false;
      }
      results.hidden = true;
      results.replaceChildren();
      search.setCustomValidity("");
      lookup.dispatchEvent(new CustomEvent("lumi:user-selected", { bubbles: true, detail: { user } }));
    };
    const renderUsers = (users) => {
      results.replaceChildren();
      users.forEach((user) => {
        const username = user.username || user.internal_username || user.id;
        const identity = (user.identities || [])[0];
        const button = document.createElement("button");
        button.type = "button";
        button.className = "lumi-user-lookup-result";
        button.textContent = identity
          ? `${username} | ${identity.display_name || identity.provider_user_id} (${identity.provider})`
          : `${username} | ${user.id}`;
        button.addEventListener("click", () => selectUser(user));
        results.append(button);
      });
      results.hidden = !users.length;
    };
    const clearSelection = () => {
      userId.value = "";
      if (preview) preview.hidden = true;
      search.setCustomValidity("");
    };

    search.addEventListener("input", () => {
      clearSelection();
      window.clearTimeout(timer);
      controller?.abort();
      const query = search.value.trim();
      if (query.length < 2) {
        results.hidden = true;
        results.replaceChildren();
        return;
      }
      timer = window.setTimeout(async () => {
        controller = new AbortController();
        try {
          const response = await fetch(`${endpoint}?q=${encodeURIComponent(query)}`, {
            cache: "no-store",
            signal: controller.signal
          });
          const payload = await response.json();
          renderUsers(response.ok ? payload.users || [] : []);
        } catch (error) {
          if (error.name !== "AbortError") renderUsers([]);
        }
      }, 180);
    });

    lookup.closest("form")?.addEventListener("submit", (event) => {
      if (userId.required && !userId.value) {
        event.preventDefault();
        search.setCustomValidity("Select a known Lumi user from the search results.");
        search.reportValidity();
      }
    });
    document.addEventListener("click", (event) => {
      if (!lookup.contains(event.target)) results.hidden = true;
    });
  });

  media.addEventListener?.("change", () => {
    closeSidebar({ restoreFocus: false });
    if (media.matches) {
      body.classList.remove("sidebar-collapsed");
      if (sidebar) {
        sidebar.inert = true;
        sidebar.setAttribute("aria-hidden", "true");
      }
    } else if (window.localStorage.getItem(sidebarPreferenceKey) === "true") {
      if (sidebar) {
        sidebar.inert = false;
        sidebar.removeAttribute("aria-hidden");
      }
      body.classList.add("sidebar-collapsed");
    } else if (sidebar) {
      sidebar.inert = false;
      sidebar.removeAttribute("aria-hidden");
    }
    updateSidebarState();
  });
  if (sidebar) {
    sidebar.inert = media.matches;
    if (media.matches) sidebar.setAttribute("aria-hidden", "true");
    else sidebar.removeAttribute("aria-hidden");
  }
  updateSidebarState();

  const placeholderOptionCache = new Map();
  const placeholderFetchPromises = new Map();
  const placeholderSuggestBox = document.createElement("div");
  placeholderSuggestBox.className = "lumi-placeholder-suggest";
  placeholderSuggestBox.hidden = true;
  document.body.append(placeholderSuggestBox);
  const placeholderTreeModal = document.createElement("div");
  placeholderTreeModal.className = "modal-backdrop lumi-placeholder-tree-modal";
  placeholderTreeModal.hidden = true;
  placeholderTreeModal.setAttribute("aria-hidden", "true");
  placeholderTreeModal.innerHTML = `
    <div class="modal lumi-placeholder-tree-dialog" role="dialog" aria-modal="true" aria-labelledby="placeholder-tree-title">
      <div class="modal-header">
        <div>
          <h2 id="placeholder-tree-title">Available placeholders</h2>
          <p class="hint">Search the placeholder tree, then select a full placeholder to insert it.</p>
        </div>
        <button class="button subtle" type="button" data-placeholder-tree-close>Close</button>
      </div>
      <label class="field full">
        <span>Search placeholders</span>
        <input type="search" data-placeholder-tree-search placeholder="Search by scope, entry, or field" />
      </label>
      <div class="lumi-placeholder-tree" data-placeholder-tree></div>
    </div>
  `;
  document.body.append(placeholderTreeModal);
  let activePlaceholderField = null;
  let activePlaceholderToken = null;
  let activePlaceholderSuggestions = [];
  let activePlaceholderIndex = 0;
  let activePlaceholderTreeOptions = [];

  const normalizePlaceholderValue = (value) => {
    const raw = typeof value === "string" ? value : value?.token || value?.value || value?.placeholder || "";
    const text = String(raw || "").trim();
    if (!text) return "";
    return text.startsWith("{{") ? text : `{{${text.replace(/^\{+|\}+$/g, "")}}}`;
  };
  const placeholderSourceKeyFor = (field) => {
    const fieldId = field?.dataset.placeholderField || "";
    if (fieldId) {
      return `field:${fieldId}:${field.dataset.placeholderOutputAudience || ""}`;
    }
    const sourceId = field?.dataset.placeholderOptions || "";
    return sourceId ? `inline:${sourceId}` : "";
  };
  const placeholderOptionsFor = (field) => {
    const sourceKey = placeholderSourceKeyFor(field);
    if (!sourceKey) return [];
    if (placeholderOptionCache.has(sourceKey)) return placeholderOptionCache.get(sourceKey);
    const fieldId = field?.dataset.placeholderField || "";
    if (fieldId) return [];
    const sourceId = field?.dataset.placeholderOptions || "";
    const source = document.getElementById(sourceId);
    let options = [];
    try {
      const parsed = JSON.parse(source?.textContent || "[]");
      options = Array.isArray(parsed)
        ? parsed.map(normalizePlaceholderValue).filter(Boolean)
        : [];
    } catch {
      options = [];
    }
    options = Array.from(new Set(options)).sort((a, b) => a.localeCompare(b));
    placeholderOptionCache.set(sourceKey, options);
    return options;
  };
  const ensurePlaceholderOptions = (field) => {
    const fieldId = field?.dataset.placeholderField || "";
    if (!fieldId) return Promise.resolve(placeholderOptionsFor(field));
    const sourceKey = placeholderSourceKeyFor(field);
    if (placeholderOptionCache.has(sourceKey)) {
      return Promise.resolve(placeholderOptionCache.get(sourceKey));
    }
    if (placeholderFetchPromises.has(sourceKey)) {
      return placeholderFetchPromises.get(sourceKey);
    }
    const params = new URLSearchParams({ field_id: fieldId });
    const outputAudience = field.dataset.placeholderOutputAudience || "";
    if (outputAudience) params.set("output_audience", outputAudience);
    const request = fetch(`/api/placeholders/catalog?${params.toString()}`, { cache: "no-store" })
      .then((response) => response.ok ? response.json() : Promise.reject(new Error("Placeholder catalog unavailable.")))
      .then((payload) => {
        const options = Array.from(new Set((payload.placeholders || [])
          .map(normalizePlaceholderValue)
          .filter(Boolean)))
          .sort((a, b) => a.localeCompare(b));
        placeholderOptionCache.set(sourceKey, options);
        placeholderFetchPromises.delete(sourceKey);
        return options;
      })
      .catch(() => {
        placeholderFetchPromises.delete(sourceKey);
        placeholderOptionCache.set(sourceKey, []);
        return [];
      });
    placeholderFetchPromises.set(sourceKey, request);
    return request;
  };
  const placeholderCandidatesFor = (options) => {
    const candidates = new Set(options);
    return Array.from(candidates).sort((a, b) => a.localeCompare(b));
  };
  const currentLevelPlaceholderSuggestions = (tokenValue, options, limit = 9) => {
    const rawToken = String(tokenValue || "").replace(/^\{\{/, "").replace(/\}\}$/, "");
    const rawParts = rawToken.split(".");
    const endsAtLevelBoundary = rawToken.endsWith(".");
    const baseParts = endsAtLevelBoundary ? rawParts.filter(Boolean) : rawParts.slice(0, -1).filter(Boolean);
    const segmentPrefix = endsAtLevelBoundary ? "" : rawParts[rawParts.length - 1] || "";
    const matchesBase = (parts) => baseParts.every((part, index) => parts[index]?.toLowerCase() === part.toLowerCase());
    const suggestions = new Map();
    options.forEach((option) => {
      const inner = option.replace(/^\{\{|\}\}$/g, "");
      const parts = inner.split(".").filter(Boolean);
      if (parts.length <= baseParts.length || !matchesBase(parts)) return;
      const next = parts[baseParts.length];
      if (!next || !next.toLowerCase().startsWith(segmentPrefix.toLowerCase())) return;
      const pathParts = [...baseParts, next];
      const suggestion = parts.length === pathParts.length
        ? `{{${pathParts.join(".")}}}`
        : `{{${pathParts.join(".")}.`;
      suggestions.set(suggestion, suggestion);
    });
    return Array.from(suggestions.values())
      .filter((suggestion) => suggestion !== tokenValue)
      .sort((a, b) => a.localeCompare(b))
      .slice(0, limit);
  };
  const placeholderTokenAtCaret = (field) => {
    if (!field || !("selectionStart" in field)) return null;
    const caret = field.selectionStart || 0;
    const before = field.value.slice(0, caret);
    const match = before.match(/(^|\s)(\{\{[^\s]*)$/);
    if (!match) return null;
    const token = match[2];
    return {
      value: token,
      start: caret - token.length,
      end: caret
    };
  };
  const placeholderTokensIn = (value) => {
    const tokens = [];
    const matcher = /(^|\s)(\{\{[^\s]+)/g;
    let match = null;
    while ((match = matcher.exec(String(value || "")))) {
      const start = match.index + match[1].length;
      tokens.push({
        value: match[2],
        start,
        end: start + match[2].length
      });
    }
    return tokens;
  };
  const isValidPlaceholderToken = (token, options) => {
    if (!token || !token.startsWith("{{")) return true;
    if (!/^\{\{[A-Za-z0-9_.-]+\}\}$/.test(token)) return false;
    return options.includes(token);
  };
  const isCaretNearPlaceholder = (range, caret) => {
    return caret >= range.start - 1 && caret <= range.end + 1;
  };
  const updatePlaceholderValidity = (field, force = false) => {
    const options = placeholderOptionsFor(field);
    if (!field || !options.length) {
      field?.classList?.remove("placeholder-invalid");
      return;
    }
    const caret = force || document.activeElement !== field
      ? -1
      : "selectionStart" in field ? field.selectionStart || 0 : -1;
    const invalid = placeholderTokensIn(field.value)
      .some((token) => !isValidPlaceholderToken(token.value, options) && !isCaretNearPlaceholder(token, caret));
    field.classList.toggle("placeholder-invalid", invalid);
  };
  const hidePlaceholderSuggest = () => {
    placeholderSuggestBox.hidden = true;
    placeholderSuggestBox.replaceChildren();
    activePlaceholderField = null;
    activePlaceholderToken = null;
    activePlaceholderSuggestions = [];
    activePlaceholderIndex = 0;
  };
  const positionPlaceholderSuggest = (field) => {
    const rect = field.getBoundingClientRect();
    const width = Math.min(Math.max(rect.width, 260), window.innerWidth - 16);
    placeholderSuggestBox.style.width = `${width}px`;
    const boxRect = placeholderSuggestBox.getBoundingClientRect();
    const left = Math.min(Math.max(8, rect.left), Math.max(8, window.innerWidth - width - 8));
    const below = rect.bottom + 6;
    const top = below + boxRect.height < window.innerHeight - 8
      ? below
      : Math.max(8, rect.top - boxRect.height - 6);
    placeholderSuggestBox.style.left = `${left}px`;
    placeholderSuggestBox.style.top = `${top}px`;
  };
  const renderPlaceholderSuggest = () => {
    placeholderSuggestBox.replaceChildren();
    activePlaceholderSuggestions.forEach((suggestion, index) => {
      const button = document.createElement("button");
      button.type = "button";
      button.className = suggestion.type === "expand"
        ? "lumi-placeholder-suggest-item lumi-placeholder-suggest-expand"
        : "lumi-placeholder-suggest-item";
      button.textContent = suggestion.type === "expand" ? "Expand" : suggestion.value;
      button.setAttribute("aria-selected", index === activePlaceholderIndex ? "true" : "false");
      button.addEventListener("mousedown", (event) => {
        event.preventDefault();
        insertPlaceholderSuggestion(index);
      });
      placeholderSuggestBox.append(button);
    });
    placeholderSuggestBox.hidden = !activePlaceholderSuggestions.length;
    if (activePlaceholderField && activePlaceholderSuggestions.length) {
      positionPlaceholderSuggest(activePlaceholderField);
    }
  };
  function insertPlaceholderSuggestion(index = activePlaceholderIndex) {
    if (!activePlaceholderField || !activePlaceholderToken) return;
    const suggestion = activePlaceholderSuggestions[index];
    if (!suggestion) return;
    if (suggestion.type === "expand") {
      openPlaceholderTree(activePlaceholderField, activePlaceholderToken);
      return;
    }
    const field = activePlaceholderField;
    const before = field.value.slice(0, activePlaceholderToken.start);
    const after = field.value.slice(activePlaceholderToken.end);
    field.value = `${before}${suggestion.value}${after}`;
    const caret = before.length + suggestion.value.length;
    field.setSelectionRange?.(caret, caret);
    field.dispatchEvent(new Event("input", { bubbles: true }));
    updatePlaceholderValidity(field);
    field.focus();
    if (suggestion.value.endsWith(".")) {
      window.setTimeout(() => updatePlaceholderSuggest(field), 0);
    } else {
      hidePlaceholderSuggest();
    }
  }
  const updatePlaceholderSuggest = (field) => {
    const sourceKey = placeholderSourceKeyFor(field);
    if (field?.dataset.placeholderField && sourceKey && !placeholderOptionCache.has(sourceKey)) {
      ensurePlaceholderOptions(field).then(() => {
        if (document.activeElement === field || activePlaceholderField === field) {
          updatePlaceholderSuggest(field);
        }
      });
    }
    const options = placeholderOptionsFor(field);
    updatePlaceholderValidity(field);
    if (!options.length) {
      hidePlaceholderSuggest();
      return;
    }
    const token = placeholderTokenAtCaret(field);
    if (!token) {
      hidePlaceholderSuggest();
      return;
    }
    const suggestions = currentLevelPlaceholderSuggestions(token.value, options, 9)
      .map((value) => ({ type: "placeholder", value }));
    suggestions.push({ type: "expand" });
    activePlaceholderField = field;
    activePlaceholderToken = token;
    activePlaceholderSuggestions = suggestions;
    activePlaceholderIndex = 0;
    renderPlaceholderSuggest();
  };
  document.querySelectorAll("[data-placeholder-options], [data-placeholder-field]").forEach((field) => {
    ensurePlaceholderOptions(field).then(() => updatePlaceholderValidity(field));
    updatePlaceholderValidity(field);
    field.addEventListener("input", () => updatePlaceholderSuggest(field));
    field.addEventListener("keyup", () => updatePlaceholderSuggest(field));
    field.addEventListener("click", () => updatePlaceholderSuggest(field));
    field.addEventListener("blur", () => {
      updatePlaceholderValidity(field, true);
      window.setTimeout(() => {
        if (!placeholderSuggestBox.matches(":hover")) hidePlaceholderSuggest();
      }, 120);
    });
    field.addEventListener("keydown", (event) => {
      if (activePlaceholderField !== field || placeholderSuggestBox.hidden) return;
      if (event.key === "ArrowDown") {
        event.preventDefault();
        activePlaceholderIndex = (activePlaceholderIndex + 1) % activePlaceholderSuggestions.length;
        renderPlaceholderSuggest();
      } else if (event.key === "ArrowUp") {
        event.preventDefault();
        activePlaceholderIndex = (activePlaceholderIndex - 1 + activePlaceholderSuggestions.length) % activePlaceholderSuggestions.length;
        renderPlaceholderSuggest();
      } else if (event.key === "Enter" || event.key === "Tab") {
        event.preventDefault();
        insertPlaceholderSuggestion();
      } else if (event.key === "Escape") {
        event.preventDefault();
        hidePlaceholderSuggest();
      }
    });
  });
  const buildPlaceholderTree = (options) => {
    const root = { children: new Map(), placeholder: "" };
    options.forEach((option) => {
      const parts = option.replace(/^\{\{|\}\}$/g, "").split(".").filter(Boolean);
      let node = root;
      parts.forEach((part) => {
        if (!node.children.has(part)) node.children.set(part, { label: part, children: new Map(), placeholder: "" });
        node = node.children.get(part);
      });
      node.placeholder = option;
    });
    return root;
  };
  const nodeMatchesPlaceholderFilter = (node, filter) => {
    if (!filter) return true;
    const labelMatch = String(node.label || "").toLowerCase().includes(filter);
    const placeholderMatch = String(node.placeholder || "").toLowerCase().includes(filter);
    if (labelMatch || placeholderMatch) return true;
    return Array.from(node.children.values()).some((child) => nodeMatchesPlaceholderFilter(child, filter));
  };
  const renderPlaceholderTreeNode = (node, filter, depth = 0) => {
    const hasChildren = node.children.size > 0;
    const matches = nodeMatchesPlaceholderFilter(node, filter);
    const selfMatches = !filter ||
      String(node.label || "").toLowerCase().includes(filter) ||
      String(node.placeholder || "").toLowerCase().includes(filter);
    if (node.placeholder && !hasChildren) {
      const button = document.createElement("button");
      button.type = "button";
      button.className = "lumi-placeholder-tree-leaf";
      if (filter && !selfMatches) button.classList.add("is-muted");
      button.style.setProperty("--placeholder-depth", depth);
      button.append(renderPlaceholderTreeLabel(node, { depth, leaf: true }));
      button.addEventListener("click", () => {
        insertPlaceholderValueFromTree(node.placeholder);
      });
      return button;
    }
    const details = document.createElement("details");
    details.className = "lumi-placeholder-tree-branch";
    if (filter && !matches) details.classList.add("is-muted");
    details.open = !filter || matches;
    const summary = document.createElement("summary");
    summary.style.setProperty("--placeholder-depth", depth);
    summary.append(renderPlaceholderTreeLabel(node, { depth, leaf: false }));
    details.append(summary);
    if (!filter || matches) {
      Array.from(node.children.entries())
        .sort(([a], [b]) => a.localeCompare(b))
        .forEach(([, child]) => details.append(renderPlaceholderTreeNode(child, filter, depth + 1)));
    }
    return details;
  };
  const renderPlaceholderTreeLabel = (node, { depth = 0, leaf = false } = {}) => {
    const fragment = document.createDocumentFragment();
    const appendMuted = (text) => {
      if (!text) return;
      const span = document.createElement("span");
      span.className = "lumi-placeholder-tree-muted-token";
      span.textContent = text;
      fragment.append(span);
    };
    const appendMain = (text) => {
      const span = document.createElement("span");
      span.className = "lumi-placeholder-tree-token";
      span.textContent = text || "Placeholders";
      fragment.append(span);
    };
    if (depth === 0) appendMuted("{{");
    appendMain(node.label || "Placeholders");
    if (leaf) {
      appendMuted("}}");
    } else {
      appendMuted(".");
    }
    return fragment;
  };
  const renderPlaceholderTree = () => {
    const tree = placeholderTreeModal.querySelector("[data-placeholder-tree]");
    const search = placeholderTreeModal.querySelector("[data-placeholder-tree-search]");
    if (!tree || !search) return;
    tree.replaceChildren();
    const filter = search.value.trim().toLowerCase();
    const root = buildPlaceholderTree(activePlaceholderTreeOptions);
    Array.from(root.children.entries())
      .sort(([a], [b]) => a.localeCompare(b))
      .forEach(([, child]) => tree.append(renderPlaceholderTreeNode(child, filter, 0)));
  };
  const openPlaceholderTree = (field, token) => {
    const options = placeholderOptionsFor(field);
    if (!options.length) return;
    hidePlaceholderSuggest();
    activePlaceholderField = field;
    activePlaceholderToken = token || placeholderTokenAtCaret(field) || {
      value: "",
      start: field.selectionStart || 0,
      end: field.selectionEnd || field.selectionStart || 0
    };
    activePlaceholderTreeOptions = options;
    placeholderTreeModal.hidden = false;
    placeholderTreeModal.classList.add("is-open");
    placeholderTreeModal.setAttribute("aria-hidden", "false");
    const search = placeholderTreeModal.querySelector("[data-placeholder-tree-search]");
    if (search) {
      search.value = "";
      search.oninput = renderPlaceholderTree;
    }
    renderPlaceholderTree();
    window.setTimeout(() => search?.focus(), 0);
  };
  const closePlaceholderTree = () => {
    placeholderTreeModal.classList.remove("is-open");
    placeholderTreeModal.setAttribute("aria-hidden", "true");
    placeholderTreeModal.hidden = true;
    activePlaceholderTreeOptions = [];
  };
  function insertPlaceholderValueFromTree(value) {
    if (!activePlaceholderField || !activePlaceholderToken || !value) return;
    const field = activePlaceholderField;
    const before = field.value.slice(0, activePlaceholderToken.start);
    const after = field.value.slice(activePlaceholderToken.end);
    field.value = `${before}${value}${after}`;
    const caret = before.length + value.length;
    field.setSelectionRange?.(caret, caret);
    field.dispatchEvent(new Event("input", { bubbles: true }));
    updatePlaceholderValidity(field);
    closePlaceholderTree();
    field.focus();
  }
  placeholderTreeModal.querySelectorAll("[data-placeholder-tree-close]").forEach((button) => {
    button.addEventListener("click", closePlaceholderTree);
  });
  placeholderTreeModal.addEventListener("click", (event) => {
    if (event.target === placeholderTreeModal) closePlaceholderTree();
  });
  window.addEventListener("scroll", () => {
    if (activePlaceholderField && !placeholderSuggestBox.hidden) positionPlaceholderSuggest(activePlaceholderField);
  }, true);
  window.addEventListener("resize", () => {
    if (activePlaceholderField && !placeholderSuggestBox.hidden) positionPlaceholderSuggest(activePlaceholderField);
  });
  document.addEventListener("click", (event) => {
    if (!placeholderSuggestBox.contains(event.target) && !event.target.closest?.("[data-placeholder-options], [data-placeholder-field]")) {
      hidePlaceholderSuggest();
    }
  });

  const selectorEscape = (value) => {
    if (window.CSS?.escape) return CSS.escape(value);
    return String(value || "").replace(/["\\]/g, "\\$&");
  };

  const updateEditToggleStates = () => {
    document.querySelectorAll("[data-edit-toggle]").forEach((button) => {
      const key = button.dataset.editToggle;
      const row = key ? document.querySelector(`[data-edit-row="${selectorEscape(key)}"]`) : null;
      const isOpen = row?.classList.contains("is-open");
      button.setAttribute("aria-expanded", isOpen ? "true" : "false");
    });
  };

  document.addEventListener("click", (event) => {
    const button = event.target.closest("[data-edit-toggle]");
    if (!button) return;
    event.preventDefault();
    const key = button.dataset.editToggle;
    const target = key ? document.querySelector(`[data-edit-row="${selectorEscape(key)}"]`) : null;
    const willOpen = target ? !target.classList.contains("is-open") : false;
    document.querySelectorAll("[data-edit-row].is-open").forEach((row) => {
      row.classList.remove("is-open");
    });
    if (target && willOpen) {
      target.classList.add("is-open");
    }
    updateEditToggleStates();
  });
  updateEditToggleStates();

  document.querySelectorAll("[data-table]").forEach((table) => {
    const tbody = table.tBodies[0];
    if (!tbody) {
      return;
    }
    let rows = Array.from(tbody.rows);
    const tableId = table.getAttribute("data-table");
    const isCommandTable = tableId === "commands";
    const isPageable =
      table.dataset.pageable !== undefined && table.dataset.pageable !== "false";
    const pageSizes = (table.dataset.pageSizes || "25,50,100,250")
      .split(",")
      .map((value) => Number(value.trim()))
      .filter((value) => Number.isFinite(value) && value > 0);
    const defaultSize = Number(table.dataset.pageSize) || pageSizes[0] || 25;
    const sizeSelect = document.querySelector(`[data-table-size="${tableId}"]`);
    const pagination = document.querySelector(
      `[data-table-pagination="${tableId}"]`
    );
    const prevButton = pagination?.querySelector("[data-page-prev]");
    const nextButton = pagination?.querySelector("[data-page-next]");
    const pageLabel = pagination?.querySelector("[data-page-label]");
    let currentPage = 1;
    let currentPageSize = defaultSize;

    const buildCommandGroups = () => {
      const groupMap = new Map();
      rows.forEach((row) => {
        const key = row.dataset.commandRoot;
        if (!key) {
          return;
        }
        groupMap.set(key, { root: row, subRows: [] });
      });
      rows.forEach((row) => {
        const parent = row.dataset.commandParent;
        if (!parent) {
          return;
        }
        const group = groupMap.get(parent);
        if (group) {
          group.subRows.push(row);
        }
      });
      return groupMap;
    };

    const commandGroups = isCommandTable ? buildCommandGroups() : null;
    let highlightTimeout = null;

    const setGroupExpanded = (group, expanded) => {
      if (!group || !group.root) {
        return;
      }
      group.root.dataset.expanded = expanded ? "true" : "false";
      group.root.classList.toggle("is-expanded", expanded);
      group.subRows.forEach((row) => {
        row.classList.toggle("is-visible", expanded);
        row.style.display = expanded ? "table-row" : "none";
      });
      const toggle = group.root.querySelector("[data-command-toggle]");
      if (toggle) {
        toggle.setAttribute("aria-expanded", expanded ? "true" : "false");
      }
    };

    const clearCommandHighlights = () => {
      tbody.querySelectorAll(".command-highlight").forEach((row) => {
        row.classList.remove("command-highlight");
      });
    };

    const highlightCommandRow = (row) => {
      if (!row || !tbody.contains(row)) {
        return;
      }
      clearCommandHighlights();
      row.classList.add("command-highlight");
      if (highlightTimeout) {
        window.clearTimeout(highlightTimeout);
      }
      highlightTimeout = window.setTimeout(() => {
        row.classList.remove("command-highlight");
      }, 2200);
    };

    const revealAnchorRow = () => {
      if (!isCommandTable || !commandGroups) {
        return;
      }
      const anchor = window.location.hash.slice(1);
      if (!anchor) {
        return;
      }
      const target = document.getElementById(anchor);
      if (!target || !tbody.contains(target)) {
        return;
      }
      if (target.dataset.commandParent) {
        const group = commandGroups.get(target.dataset.commandParent);
        if (group) {
          setGroupExpanded(group, true);
        }
      }
      highlightCommandRow(target);
    };

    if (isCommandTable && commandGroups) {
      commandGroups.forEach((group) => {
        setGroupExpanded(group, false);
      });

      tbody.addEventListener("click", (event) => {
        const button = event.target.closest("[data-command-toggle]");
        if (!button || !tbody.contains(button)) {
          return;
        }
        event.preventDefault();
        const rootRow = button.closest("tr");
        if (!rootRow) {
          return;
        }
        const key = rootRow.dataset.commandRoot;
        const group = key ? commandGroups.get(key) : null;
        if (!group) {
          return;
        }
        const expanded = rootRow.dataset.expanded === "true";
        setGroupExpanded(group, !expanded);
      });

      revealAnchorRow();
      window.addEventListener("hashchange", () => {
        revealAnchorRow();
      });
    }

    const filterInput = document.querySelector(
      `[data-table-filter="${tableId}"]`
    );
    const filterSelect = document.querySelector(
      `[data-table-filter-select="${tableId}"]`
    );
    const filterKey = filterSelect?.dataset.filterKey || "filter";

    const refreshRows = () => {
      rows = Array.from(tbody.rows);
    };

    const getFilteredRows = () => {
      const term = (filterInput?.value || "").trim().toLowerCase();
      const filterValue = (filterSelect?.value || "").trim().toLowerCase();
      return rows.filter((row) => {
        const haystack = (row.dataset.search || row.textContent || "")
          .toLowerCase()
          .trim();
        const matchesTerm = !term || haystack.includes(term);
        const rowFilter = (row.dataset[filterKey] || "").toLowerCase();
        const matchesFilter = !filterValue || rowFilter === filterValue;
        return matchesTerm && matchesFilter;
      });
    };

    const applyPagination = () => {
      if (!isPageable || isCommandTable) {
        return;
      }
      refreshRows();
      const filtered = getFilteredRows();
      const totalPages = Math.max(
        1,
        Math.ceil(filtered.length / currentPageSize)
      );
      currentPage = Math.min(currentPage, totalPages);
      const start = (currentPage - 1) * currentPageSize;
      const end = start + currentPageSize;
      const visible = new Set(filtered.slice(start, end));

      rows.forEach((row) => {
        row.style.display = visible.has(row) ? "" : "none";
      });

      if (pageLabel) {
        pageLabel.textContent = `Page ${currentPage} of ${totalPages}`;
      }
      if (prevButton) {
        prevButton.disabled = currentPage <= 1;
      }
      if (nextButton) {
        nextButton.disabled = currentPage >= totalPages;
      }
    };
    if (filterInput) {
      filterInput.addEventListener("input", () => {
        const term = filterInput.value.trim().toLowerCase();
        const filterValue = (filterSelect?.value || "").trim().toLowerCase();
        if (!isCommandTable || !commandGroups) {
          if (isPageable) {
            currentPage = 1;
            applyPagination();
            return;
          }
          rows.forEach((row) => {
            const haystack = (row.dataset.search || row.textContent || "")
              .toLowerCase()
              .trim();
            const rowFilter = (row.dataset[filterKey] || "").toLowerCase();
            const matchesTerm = !term || haystack.includes(term);
            const matchesFilter = !filterValue || rowFilter === filterValue;
            row.style.display = matchesTerm && matchesFilter ? "" : "none";
          });
          return;
        }

        commandGroups.forEach((group) => {
          const root = group.root;
          const rootHaystack = (root.dataset.search || root.textContent || "")
            .toLowerCase()
            .trim();
          const rootMatches = rootHaystack.includes(term);
          const subMatches = group.subRows.filter((row) => {
            const haystack = (row.dataset.search || row.textContent || "")
              .toLowerCase()
              .trim();
            return haystack.includes(term);
          });

          const showGroup = !term || rootMatches || subMatches.length > 0;
          root.style.display = showGroup ? "" : "none";
          if (!term) {
            const expanded = root.dataset.expanded === "true";
            group.subRows.forEach((row) => {
              row.style.display = expanded ? "" : "none";
            });
            return;
          }
          if (subMatches.length > 0) {
            setGroupExpanded(group, true);
          }
          group.subRows.forEach((row) => {
            row.style.display = subMatches.includes(row) ? "" : "none";
          });
        });
      });
    }
    if (filterSelect) {
      filterSelect.addEventListener("change", () => {
        if (isPageable) {
          currentPage = 1;
          applyPagination();
        } else if (filterInput) {
          filterInput.dispatchEvent(new Event("input"));
        }
      });
    }

    const headers = table.querySelectorAll("th[data-sort]");
    headers.forEach((header) => {
      header.setAttribute("aria-sort", "none");
      const sortControl = header.querySelector("[data-table-sort-control]") || header;
      if (sortControl === header) {
        if (!header.hasAttribute("tabindex")) header.tabIndex = 0;
        if (!header.hasAttribute("role")) header.setAttribute("role", "button");
        header.addEventListener("keydown", (event) => {
          if (event.key !== "Enter" && event.key !== " ") return;
          event.preventDefault();
          header.click();
        });
      }
      sortControl.addEventListener("click", () => {
        const key = header.dataset.sort;
        const currentKey = table.dataset.sortKey;
        const currentDir = table.dataset.sortDir || "asc";
        const nextDir = currentKey === key && currentDir === "asc" ? "desc" : "asc";
        table.dataset.sortKey = key;
        table.dataset.sortDir = nextDir;
        headers.forEach((item) => item.setAttribute("aria-sort", item === header ? (nextDir === "asc" ? "ascending" : "descending") : "none"));

        const compare = (a, b) => {
          const aValue = (a.dataset[key] || "").toString();
          const bValue = (b.dataset[key] || "").toString();
          const aNumber = Number(aValue);
          const bNumber = Number(bValue);
          if (!Number.isNaN(aNumber) && !Number.isNaN(bNumber)) {
            return aNumber - bNumber;
          }
          return aValue.localeCompare(bValue);
        };

        if (isCommandTable && commandGroups) {
          const roots = Array.from(commandGroups.values()).map((group) => group.root);
          const sorted = roots.slice().sort(compare);
          if (nextDir === "desc") {
            sorted.reverse();
          }
          sorted.forEach((root) => {
            const group = commandGroups.get(root.dataset.commandRoot);
            tbody.appendChild(root);
            group?.subRows.forEach((row) => tbody.appendChild(row));
          });
          return;
        }

        const sorted = rows.slice().sort(compare);
        if (nextDir === "desc") {
          sorted.reverse();
        }
        sorted.forEach((row) => tbody.appendChild(row));
        refreshRows();
        if (isPageable) {
          currentPage = 1;
          applyPagination();
        }
      });
    });

    if (isPageable && sizeSelect) {
      sizeSelect.value = currentPageSize.toString();
      sizeSelect.addEventListener("change", () => {
        const nextSize = Number(sizeSelect.value);
        if (Number.isFinite(nextSize) && nextSize > 0) {
          currentPageSize = nextSize;
          currentPage = 1;
          applyPagination();
        }
      });
    }

    if (isPageable && prevButton && nextButton) {
      prevButton.addEventListener("click", () => {
        if (currentPage > 1) {
          currentPage -= 1;
          applyPagination();
        }
      });
      nextButton.addEventListener("click", () => {
        currentPage += 1;
        applyPagination();
      });
    }

    if (isPageable) {
      applyPagination();
    }
  });

  const logList = document.querySelector("[data-log-list]");
  if (logList) {
    const searchInput = document.querySelector("[data-log-search]");
    const levelSelect = document.querySelector("[data-log-level]");
    const sourceSelect = document.querySelector("[data-log-source]");
    const categorySelect = document.querySelector("[data-log-category]");
    const rangeSelect = document.querySelector("[data-log-range]");
    const limitSelect = document.querySelector("[data-log-limit]");
    const liveStatus = document.querySelector("[data-log-live-status] .status-indicator");

    const applyLogFilters = () => {
      const term = (searchInput?.value || "").trim().toLowerCase();

      Array.from(logList.querySelectorAll("[data-log-entry]")).forEach((entry) => {
        const haystack = (entry.dataset.search || entry.textContent || "")
          .toLowerCase()
          .trim();

        const matchesTerm = !term || haystack.includes(term);
        entry.style.display = matchesTerm ? "" : "none";
      });
    };

    searchInput?.addEventListener("input", applyLogFilters);

    applyLogFilters();

    const reloadLogView = () => {
      document.querySelector("[data-log-filter-form]")?.requestSubmit();
    };

    levelSelect?.addEventListener("change", reloadLogView);
    sourceSelect?.addEventListener("change", reloadLogView);
    categorySelect?.addEventListener("change", reloadLogView);
    rangeSelect?.addEventListener("change", reloadLogView);
    limitSelect?.addEventListener("change", reloadLogView);

    const matchesLiveFilters = (entry) => {
      if (levelSelect?.value !== "all" && entry.level !== levelSelect?.value) return false;
      if (sourceSelect?.value !== "all" && entry.source !== sourceSelect?.value) return false;
      if (categorySelect?.value !== "all" && entry.category !== categorySelect?.value) return false;
      const range = rangeSelect?.value || "all";
      if (range !== "all" && Number(entry.created_at) < Date.now() - Number(range)) return false;
      const term = (searchInput?.value || "").trim().toLowerCase();
      const haystack = [entry.message, entry.details, entry.source, entry.category, entry.event, entry.request_id]
        .filter(Boolean).join(" ").toLowerCase();
      return !term || haystack.includes(term);
    };

    const createLiveLogEntry = (entry) => {
      const details = document.createElement("details");
      details.className = `log-entry level-${entry.level}`;
      details.dataset.logEntry = "";
      details.dataset.level = entry.level;
      details.dataset.source = entry.source || "core";
      details.dataset.category = entry.category || "general";
      details.dataset.timestamp = String(entry.created_at || Date.now());
      details.dataset.search = [entry.message, entry.details, entry.source, entry.category, entry.event, entry.request_id]
        .filter(Boolean).join(" ").toLowerCase();
      const summary = document.createElement("summary");
      const marker = document.createElement("span");
      marker.className = "log-marker";
      marker.setAttribute("aria-hidden", "true");
      const message = document.createElement("span");
      message.className = "log-message";
      message.textContent = entry.message || "Log entry";
      const scope = document.createElement("span");
      scope.className = "log-scope-pill";
      scope.textContent = entry.source || "core";
      const level = document.createElement("span");
      level.className = "log-level-pill";
      level.textContent = entry.level || "info";
      const time = document.createElement("span");
      time.className = "log-time";
      time.textContent = new Date(entry.created_at || Date.now()).toLocaleString();
      summary.append(marker, message, scope, level, time);
      const meta = document.createElement("div");
      meta.className = "log-entry-meta";
      const values = [
        ["Activity", entry.category || "general"],
        ["Event", entry.event],
        ["Request ID", entry.request_id]
      ];
      values.forEach(([label, value]) => {
        if (!value) return;
        const item = document.createElement("span");
        const strong = document.createElement("strong");
        strong.textContent = `${label}:`;
        item.append(strong, ` ${value}`);
        meta.append(item);
      });
      const body = entry.details ? document.createElement("pre") : document.createElement("div");
      body.className = entry.details ? "log-details" : "log-details empty";
      body.textContent = entry.details || "No additional details.";
      details.append(summary, meta, body);
      return details;
    };

    window.addEventListener("lumi:log-created", (event) => {
      const entry = event.detail || {};
      if (!entry.id || !matchesLiveFilters(entry)) return;
      logList.querySelector("[data-log-empty]")?.remove();
      logList.prepend(createLiveLogEntry(entry));
      const limit = Number(logList.dataset.logLimitValue || 50);
      const entries = Array.from(logList.querySelectorAll("[data-log-entry]"));
      entries.slice(limit).forEach((item) => item.remove());
      const total = document.querySelector("[data-log-total]");
      if (total) total.textContent = String(Number(total.textContent || 0) + 1);
      const levelCount = document.querySelector(`[data-log-count="${entry.level}"]`);
      if (levelCount) levelCount.textContent = String(Number(levelCount.textContent || 0) + 1);
      if (liveStatus) liveStatus.textContent = "Live · newest entry added";
    });
    window.addEventListener("lumi:event-status", (event) => {
      if (!liveStatus) return;
      const connected = event.detail?.status === "connected";
      liveStatus.textContent = connected ? "Live updates connected" : "Live updates reconnecting";
      liveStatus.classList.toggle("status-success", connected);
      liveStatus.classList.toggle("status-warning", !connected);
    });
  }

  const logModal = document.querySelector("[data-log-modal]");
  const logModalOpen = document.querySelector("[data-log-download]");
  if (logModal && logModalOpen) {
    const closeButtons = logModal.querySelectorAll("[data-modal-close]");
    const closeModal = () => {
      logModal.classList.remove("is-open");
      logModal.setAttribute("aria-hidden", "true");
    };
    const openModal = () => {
      logModal.classList.add("is-open");
      logModal.setAttribute("aria-hidden", "false");
    };
    logModalOpen.addEventListener("click", openModal);
    closeButtons.forEach((button) => {
      button.addEventListener("click", closeModal);
    });
    logModal.addEventListener("click", (event) => {
      if (event.target === logModal) {
        closeModal();
      }
    });
    window.addEventListener("keydown", (event) => {
      if (event.key === "Escape" && logModal.classList.contains("is-open")) {
        closeModal();
      }
    });
  }

  const compareToggles = document.querySelectorAll("[data-compare-toggle]");
  if (compareToggles.length) {
    const defaultStats = document.querySelector("[data-stats-default]");
    const compareStats = document.querySelector("[data-stats-compare]");
    const setCompareMode = (active) => {
      document.body.classList.toggle("stats-compare-mode", active);
      if (defaultStats) {
        defaultStats.hidden = active;
        defaultStats.setAttribute("aria-hidden", active ? "true" : "false");
      }
      if (compareStats) {
        compareStats.hidden = !active;
        compareStats.setAttribute("aria-hidden", active ? "false" : "true");
      }
      compareToggles.forEach((button) => {
        if (!button.dataset.compareDefaultLabel) {
          button.dataset.compareDefaultLabel = button.textContent.trim();
        }
        const defaultLabel = button.dataset.compareDefaultLabel || "Compare";
        const altLabel = button.getAttribute("data-compare-label") || "Back";
        button.textContent = active ? altLabel : defaultLabel;
        button.setAttribute("aria-expanded", active ? "true" : "false");
      });
    };

    setCompareMode(false);
    document.addEventListener("click", (event) => {
      const toggle = event.target.closest("[data-compare-toggle]");
      if (!toggle) {
        return;
      }
      event.preventDefault();
      setCompareMode(!document.body.classList.contains("stats-compare-mode"));
    });
  }

  const healthEndpoint = "/health";
  let connectionLost = false;
  const checkConnection = async () => {
    try {
      const response = await fetch(healthEndpoint, { cache: "no-store" });
      if (response.ok) {
        if (connectionLost) {
          window.LumiInteractions?.showEventNotice?.({
            message: "Connection restored. Refresh manually if you need newer page data."
          }, "info");
        }
        connectionLost = false;
      } else {
        connectionLost = true;
      }
    } catch {
      connectionLost = true;
    }
  };

  window.addEventListener("online", () => {
    checkConnection();
  });

  window.addEventListener("offline", () => {
    connectionLost = true;
  });

  window.setInterval(checkConnection, 5000);

  const destructivePattern =
    /(?:^|\/)(?:delete|remove|clear|reset|renew|uninstall|cleanup|archive|revoke|unlink|unset|revert)(?:\/|$)/i;
  const highImpactPattern =
    /(?:\/plugins\/[^/]+\/uninstall|\/models\/[^/]+\/delete|\/storage\/cleanup|\/navigation\/reset|\/updates\/|\/remove-data)/i;
  const destructiveModal = document.querySelector("[data-destructive-modal]");
  const destructiveTitle = destructiveModal?.querySelector("[data-destructive-title]");
  const destructiveDescription = destructiveModal?.querySelector("[data-destructive-description]");
  const destructiveConfirm = destructiveModal?.querySelector("[data-destructive-confirm]");
  const destructiveStates = new WeakMap();
  let activeDestructive = null;
  let activeCallbackConfirm = null;

  // Read authored attributes instead of form.action/form.method. Controls named
  // "action" or "method" can shadow those DOM properties and turn the endpoint
  // into an HTML element rather than a URL.
  const effectiveFormAction = (form, submitter = null) =>
    submitter?.getAttribute?.("formaction") || form?.getAttribute?.("action") || window.location.href;

  const effectiveFormMethod = (form, submitter = null) =>
    submitter?.getAttribute?.("formmethod") || form?.getAttribute?.("method") || "get";

  window.LumiForms = Object.freeze({
    action: effectiveFormAction,
    method: effectiveFormMethod
  });

  const destructiveAction = (form, submitter = null) => {
    try {
      const action = effectiveFormAction(form, submitter);
      return new URL(action, window.location.origin).pathname;
    } catch {
      return "";
    }
  };

  const actionCopy = (action) => {
    const normalized = String(action || "").toLowerCase();
    if (normalized.includes("/delete")) return { title: "Confirm deletion", label: "Delete" };
    if (normalized.includes("/uninstall")) return { title: "Confirm uninstall", label: "Uninstall" };
    if (normalized.includes("/cleanup")) return { title: "Confirm cleanup", label: "Clean selected" };
    if (normalized.includes("/reset")) return { title: "Confirm reset", label: "Reset" };
    if (normalized.includes("/revert")) return { title: "Confirm restore", label: "Restore" };
    if (normalized.includes("/remove")) return { title: "Confirm removal", label: "Remove" };
    if (normalized.includes("/update")) return { title: "Confirm update", label: "Update" };
    if (normalized.includes("/restart")) return { title: "Confirm restart", label: "Restart" };
    return { title: "Confirm action", label: "Confirm" };
  };

  const isDestructiveForm = (form, submitter = null) => {
    if (!form || form.dataset.noDestructiveConfirm !== undefined) return false;
    if (form.dataset.updateAction !== undefined) return false;
    return String(form.method || "get").toLowerCase() === "post" &&
      destructivePattern.test(destructiveAction(form, submitter));
  };

  const resetDestructive = (form) => {
    const state = destructiveStates.get(form);
    if (state?.timer) window.clearInterval(state.timer);
    if (state?.expiryTimer) window.clearTimeout(state.expiryTimer);
    if (state?.confirmButton && state?.onConfirm) {
      state.confirmButton.removeEventListener("click", state.onConfirm);
    }
    state?.inline?.remove();
    form.querySelector('input[name="confirmation_token"]')?.remove();
    destructiveStates.delete(form);
    if (activeDestructive?.form === form) {
      destructiveModal?.classList.remove("is-open");
      destructiveModal?.setAttribute("aria-hidden", "true");
      activeDestructive = null;
    }
    if (form.dataset.syntheticConfirmation === "true") form.remove();
  };

  const resetCallbackConfirm = (result = false) => {
    const active = activeCallbackConfirm;
    if (!active) return;
    activeCallbackConfirm = null;
    if (active.timer) window.clearInterval(active.timer);
    if (active.expiryTimer) window.clearTimeout(active.expiryTimer);
    destructiveModal?.classList.remove("is-open");
    destructiveModal?.setAttribute("aria-hidden", "true");
    destructiveConfirm?.removeEventListener("click", active.onConfirm);
    active.resolve(result);
    active.returnFocus?.focus?.();
  };

  const requestDestructiveToken = async (action) => {
    const response = await fetch("/api/destructive-confirmations", {
      method: "POST",
      headers: { "Content-Type": "application/json", "Accept": "application/json" },
      body: JSON.stringify({ action })
    });
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(payload.error || "Unable to prepare confirmation.");
    return payload;
  };

  const normalizeDestructiveAction = (action) => {
    try {
      return new URL(action, window.location.origin).pathname;
    } catch {
      return "";
    }
  };

  const timedDestructiveToken = async ({
    action,
    title = "Confirm action",
    text = "This action cannot be undone.",
    label = "Confirm",
    danger = true
  } = {}) => {
    const normalizedAction = normalizeDestructiveAction(action);
    if (!destructivePattern.test(normalizedAction)) {
      throw new Error("This action is not registered as destructive.");
    }
    const payload = await requestDestructiveToken(normalizedAction);
    const waitMs = Math.max(0, Number(payload.not_before || 0) - Date.now());
    if (!destructiveModal || !destructiveConfirm) {
      if (!window.confirm(text)) return null;
      if (waitMs > 0) await new Promise((resolve) => window.setTimeout(resolve, waitMs));
      return payload.token;
    }
    if (activeDestructive?.form) resetDestructive(activeDestructive.form);
    if (activeCallbackConfirm) resetCallbackConfirm(false);
    return new Promise((resolve) => {
      const returnFocus = document.activeElement;
      destructiveTitle.textContent = title;
      destructiveDescription.textContent = text;
      destructiveConfirm.disabled = true;
      destructiveConfirm.classList.toggle("danger", danger);
      destructiveModal.classList.add("is-open");
      destructiveModal.setAttribute("aria-hidden", "false");
      const update = () => {
        const remaining = Math.max(0, Math.ceil((Number(payload.not_before || 0) - Date.now()) / 1000));
        destructiveConfirm.disabled = remaining > 0;
        destructiveConfirm.textContent = remaining > 0 ? `${label} in ${remaining}` : label;
        if (!remaining && activeCallbackConfirm?.timer) {
          window.clearInterval(activeCallbackConfirm.timer);
          activeCallbackConfirm.timer = null;
        }
      };
      const onConfirm = () => resetCallbackConfirm(payload.token);
      activeCallbackConfirm = {
        resolve,
        returnFocus,
        onConfirm,
        timer: window.setInterval(update, 200),
        expiryTimer: window.setTimeout(() => resetCallbackConfirm(null), Math.max(0, Number(payload.expires_at || 0) - Date.now()))
      };
      destructiveConfirm.addEventListener("click", onConfirm);
      update();
      destructiveConfirm.focus();
    });
  };

  window.LumiConfirm = {
    destructive({ title = "Confirm action", text = "This action cannot be undone.", label = "Confirm", danger = true } = {}) {
      if (!destructiveModal || !destructiveConfirm) {
        return Promise.resolve(window.confirm(text));
      }
      if (activeDestructive?.form) resetDestructive(activeDestructive.form);
      if (activeCallbackConfirm) resetCallbackConfirm(false);
      return new Promise((resolve) => {
        const returnFocus = document.activeElement;
        destructiveTitle.textContent = title;
        destructiveDescription.textContent = text;
        destructiveConfirm.disabled = false;
        destructiveConfirm.textContent = label;
        destructiveConfirm.classList.toggle("danger", danger);
        destructiveModal.classList.add("is-open");
        destructiveModal.setAttribute("aria-hidden", "false");
        const onConfirm = () => resetCallbackConfirm(true);
        activeCallbackConfirm = { resolve, returnFocus, onConfirm };
        destructiveConfirm.addEventListener("click", onConfirm);
        destructiveConfirm.focus();
      });
    },
    destructiveToken: timedDestructiveToken,
    async destructiveFetch(action, options = {}, confirmOptions = {}) {
      const token = await timedDestructiveToken({ ...confirmOptions, action });
      if (!token) return null;
      const headers = new Headers(options.headers || {});
      headers.set("X-Confirmation-Token", token);
      if (!headers.has("Accept")) headers.set("Accept", "application/json");
      return fetch(action, { ...options, method: options.method || "POST", headers });
    }
  };

  const submitDestructive = (form, submitter, token) => {
    let tokenField = form.querySelector('input[name="confirmation_token"]');
    if (!tokenField) {
      tokenField = document.createElement("input");
      tokenField.type = "hidden";
      tokenField.name = "confirmation_token";
      form.append(tokenField);
    }
    tokenField.value = token;
    const state = destructiveStates.get(form) || {};
    state.confirmed = true;
    destructiveStates.set(form, state);
    form.requestSubmit(submitter?.form === form ? submitter : undefined);
  };

  const confirmLabel = (form, submitter = null) => submitter?.dataset?.confirmLabel || form.dataset.confirmLabel || actionCopy(destructiveAction(form, submitter)).label;

  const startCountdown = ({ form, button, token, notBefore, expiresAt, submitter }) => {
    const state = destructiveStates.get(form) || {};
    const update = () => {
      const remaining = Math.max(0, Math.ceil((notBefore - Date.now()) / 1000));
      button.disabled = remaining > 0;
      button.textContent = remaining > 0 ? `${confirmLabel(form, submitter)} in ${remaining}` : confirmLabel(form, submitter);
      if (!remaining && state.timer) {
        window.clearInterval(state.timer);
        state.timer = null;
      }
    };
    update();
    state.timer = window.setInterval(update, 200);
    state.expiryTimer = window.setTimeout(() => resetDestructive(form), Math.max(0, expiresAt - Date.now()));
    const onConfirm = () => {
      if (!button.disabled) submitDestructive(form, submitter, token);
    };
    state.confirmButton = button;
    state.onConfirm = onConfirm;
    button.addEventListener("click", onConfirm, { once: true });
    destructiveStates.set(form, state);
  };

  const issueDestructiveConfirmation = async (form, submitter) => {
    if (destructiveStates.has(form)) return;
    const action = destructiveAction(form, submitter);
    const state = { confirmed: false, inline: null, timer: null, expiryTimer: null };
    destructiveStates.set(form, state);
    const copy = actionCopy(action);
    const message = submitter?.dataset?.confirmText || form.dataset.confirmText || form.dataset.confirmForm || "This action cannot be undone.";
    const mode = submitter?.dataset?.confirmMode || form.dataset.confirmMode || (highImpactPattern.test(action) ? "modal" : "inline");
    let confirmButton;

    if (mode === "modal" && destructiveModal && destructiveConfirm) {
      if (activeDestructive?.form) resetDestructive(activeDestructive.form);
      activeDestructive = { form };
      destructiveTitle.textContent = submitter?.dataset?.confirmTitle || form.dataset.confirmTitle || copy.title;
      destructiveDescription.textContent = message;
      destructiveConfirm.disabled = true;
      destructiveConfirm.classList.add("danger");
      destructiveConfirm.textContent = "Preparing...";
      destructiveModal.classList.add("is-open");
      destructiveModal.setAttribute("aria-hidden", "false");
      confirmButton = destructiveConfirm;
    } else {
      const inline = document.createElement("span");
      inline.className = "destructive-inline-confirm";
      const label = document.createElement("span");
      label.textContent = message;
      const cancel = document.createElement("button");
      cancel.type = "button";
      cancel.className = "button subtle";
      cancel.textContent = "Cancel";
      cancel.addEventListener("click", () => resetDestructive(form));
      confirmButton = document.createElement("button");
      confirmButton.type = "button";
      confirmButton.className = "button danger";
      confirmButton.disabled = true;
      confirmButton.textContent = "Preparing...";
      inline.append(label, cancel, confirmButton);
      form.insertAdjacentElement("afterend", inline);
      state.inline = inline;
    }

    try {
      const payload = await requestDestructiveToken(action);
      if (destructiveStates.get(form) !== state) return;
      startCountdown({
        form,
        button: confirmButton,
        token: payload.token,
        notBefore: payload.not_before,
        expiresAt: payload.expires_at,
        submitter
      });
    } catch (error) {
      if (destructiveStates.get(form) !== state) return;
      confirmButton.disabled = true;
      confirmButton.textContent = "Confirmation unavailable";
      confirmButton.title = error.message;
    }
  };

  document.addEventListener("submit", (event) => {
    const form = event.target;
    if (!(form instanceof HTMLFormElement) || !isDestructiveForm(form, event.submitter)) return;
    const state = destructiveStates.get(form);
    if (state?.confirmed) {
      state.confirmed = false;
      return;
    }
    event.preventDefault();
    issueDestructiveConfirmation(form, event.submitter);
  }, true);

  document.addEventListener("click", (event) => {
    const button = event.target.closest("[data-confirm-action]");
    if (!button) return;
    const action = button.dataset.confirmAction || "";
    if (!destructivePattern.test(normalizeDestructiveAction(action))) return;
    event.preventDefault();
    event.stopImmediatePropagation();
    const form = document.createElement("form");
    form.method = "post";
    form.action = action;
    form.hidden = true;
    form.dataset.confirmMode = "modal";
    form.dataset.syntheticConfirmation = "true";
    form.dataset.confirmTitle = button.dataset.confirmTitle || "Confirm destructive action";
    form.dataset.confirmText = button.dataset.confirmText || "This action cannot be undone.";
    form.dataset.confirmLabel = button.dataset.confirmLabel || "Confirm";
    document.body.append(form);
    issueDestructiveConfirmation(form, null);
  }, true);

  document.querySelectorAll("[data-destructive-cancel]").forEach((button) => {
    button.addEventListener("click", () => {
      if (activeDestructive?.form) resetDestructive(activeDestructive.form);
      else resetCallbackConfirm(false);
    });
  });
  destructiveModal?.addEventListener("click", (event) => {
    if (event.target === destructiveModal && activeDestructive?.form) {
      resetDestructive(activeDestructive.form);
    } else if (event.target === destructiveModal) {
      resetCallbackConfirm(false);
    }
  });
  window.addEventListener("keydown", (event) => {
    if (event.key === "Escape" && activeDestructive?.form) {
      resetDestructive(activeDestructive.form);
    } else if (event.key === "Escape") {
      resetCallbackConfirm(false);
    }
  });

  const copyText = async (text) => {
    if (navigator.clipboard?.writeText && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    }
    const tempInput = document.createElement("textarea");
    tempInput.value = text;
    tempInput.setAttribute("readonly", "");
    tempInput.style.position = "fixed";
    tempInput.style.left = "-9999px";
    tempInput.style.top = "0";
    document.body.appendChild(tempInput);
    tempInput.focus();
    tempInput.select();
    try {
      return document.execCommand("copy");
    } finally {
      tempInput.remove();
    }
  };

  document.addEventListener("click", async (event) => {
    const button = event.target.closest("[data-copy]");
    if (!button) return;
    event.preventDefault();
    const text = button.getAttribute("data-copy") || "";
    if (!text) {
      return;
    }
    const label = button.querySelector("[data-copy-label]");
    const originalLabel = label ? label.textContent : "";

    const markCopyResult = (copied) => {
      button.classList.toggle("copied", copied);
      button.classList.toggle("copy-failed", !copied);
      if (label) {
        label.textContent = copied ? "Copied" : "Copy failed";
      }
      window.setTimeout(() => {
        button.classList.remove("copied", "copy-failed");
        if (label) {
          label.textContent = originalLabel;
        }
      }, copied ? 1200 : 1800);
    };

    try {
      markCopyResult(await copyText(text));
    } catch {
      markCopyResult(false);
    }
  });

  const feedbackModal = document.querySelector("[data-feedback-modal]");
  const feedbackForm = document.querySelector("[data-feedback-form]");
  const contextMenu = document.querySelector("[data-lumi-context-menu]");
  let contextTarget = null;
  let highlightedFeedbackTarget = null;
  let contextClipboardText = "";
  let contextTooltipTimer = null;
  let contextTooltip = null;
  let activeFeedbackTarget = null;
  let activeFeedbackMetadata = {};
  let attachedScreenshotBlob = null;
  let attachedScreenshotUrl = "";
  let attachedScreenshotSource = "";
  let attachedScreenshotName = "feedback-screenshot.png";
  let feedbackSimilarTimer = null;
  let feedbackSimilarController = null;
  let feedbackSimilarMatches = [];
  const feedbackDraftStorageKey = "lumi.feedback.draft";

  const parseJson = (value, fallback = {}) => {
    try {
      return JSON.parse(value || "");
    } catch {
      return fallback;
    }
  };

  const feedbackOptions = parseJson(feedbackModal?.dataset.feedbackOptions, {});

  const setSelectOptions = (select, entries, preferred) => {
    if (!select || !Array.isArray(entries)) return;
    select.replaceChildren();
    entries.forEach((entry) => {
      const option = document.createElement("option");
      option.value = entry.value;
      option.textContent = entry.label;
      if (entry.value === preferred) option.selected = true;
      select.append(option);
    });
  };

  if (feedbackForm) {
    setSelectOptions(feedbackForm.querySelector("[data-feedback-category]"), feedbackOptions.categories, "bug");
    setSelectOptions(feedbackForm.querySelector("[data-feedback-severity]"), feedbackOptions.severities, "minor");
    setSelectOptions(feedbackForm.querySelector("[data-feedback-scope-type]"), feedbackOptions.scopes, "page");
  }

  const scopeLabelForValue = (value) => {
    const option = (feedbackOptions.scopes || []).find((entry) => entry.value === value);
    return option?.label || value;
  };

  const screenshotShortcutHint = () => {
    const platform = `${navigator.userAgentData?.platform || navigator.platform || ""}`.toLowerCase();
    if (platform.includes("mac")) {
      return "Press Shift + Command + 4 to take a selected-area screenshot";
    }
    if (platform.includes("linux")) {
      return "Press Print Screen or Shift + Print Screen to take a screenshot";
    }
    if (platform.includes("iphone") || platform.includes("ipad")) {
      return "Use your device screenshot buttons, then choose the saved image";
    }
    if (platform.includes("android")) {
      return "Use your device screenshot buttons, then choose the saved image";
    }
    return "Press Win + Shift + S to take a snippet screenshot";
  };

  if (feedbackForm) {
    const keybindHint = feedbackForm.querySelector("[data-feedback-screenshot-keybind]");
    if (keybindHint) {
      keybindHint.textContent = screenshotShortcutHint();
    }
    const pasteButton = feedbackForm.querySelector("[data-feedback-paste-screenshot]");
    const screenshotStatus = feedbackForm.querySelector("[data-feedback-screenshot-status]");
    if (pasteButton && (!navigator.clipboard?.read || !window.isSecureContext)) {
      pasteButton.textContent = "Paste with Ctrl+V";
      pasteButton.title = "Button-based clipboard image access is unavailable here. Copy an image, focus this dialog, and press Ctrl+V, or choose an image file.";
      if (screenshotStatus) screenshotStatus.textContent = "This browser restricts button-based clipboard access. Ctrl+V and Choose image still work.";
    }
  }

  const feedbackDraftFieldNames = [
    "summary",
    "category",
    "severity",
    "scope_type",
    "description",
    "steps_to_reproduce",
    "expected_behavior",
    "actual_behavior"
  ];

  function saveFeedbackDraft() {
    if (!feedbackForm) return;
    const draft = {};
    feedbackDraftFieldNames.forEach((name) => {
      const field = feedbackForm.elements[name];
      if (field) draft[name] = field.value || "";
    });
    draft.include_browser = Boolean(feedbackForm.querySelector("[data-feedback-include-browser]")?.checked);
    draft.include_dom = Boolean(feedbackForm.querySelector("[data-feedback-include-dom]")?.checked);
    draft.target_metadata = feedbackForm.querySelector("[data-feedback-target-metadata]")?.value || "{}";
    draft.current_url = feedbackForm.querySelector("[data-feedback-current-url]")?.value || "";
    draft.page_title = feedbackForm.querySelector("[data-feedback-page-title]")?.value || "";
    try {
      window.sessionStorage?.setItem(feedbackDraftStorageKey, JSON.stringify(draft));
    } catch {}
  }

  function loadFeedbackDraft() {
    try {
      return JSON.parse(window.sessionStorage?.getItem(feedbackDraftStorageKey) || "null") || null;
    } catch {
      return null;
    }
  }

  function restoreFeedbackDraft(draft) {
    if (!feedbackForm || !draft) return false;
    feedbackDraftFieldNames.forEach((name) => {
      const field = feedbackForm.elements[name];
      if (field && draft[name] !== undefined) field.value = draft[name];
    });
    const includeBrowser = feedbackForm.querySelector("[data-feedback-include-browser]");
    const includeDom = feedbackForm.querySelector("[data-feedback-include-dom]");
    if (includeBrowser) includeBrowser.checked = Boolean(draft.include_browser);
    if (includeDom) includeDom.checked = Boolean(draft.include_dom);
    const targetInput = feedbackForm.querySelector("[data-feedback-target-metadata]");
    const urlInput = feedbackForm.querySelector("[data-feedback-current-url]");
    const titleInput = feedbackForm.querySelector("[data-feedback-page-title]");
    if (targetInput && draft.target_metadata) targetInput.value = draft.target_metadata;
    if (urlInput && draft.current_url) urlInput.value = draft.current_url;
    if (titleInput && draft.page_title) titleInput.value = draft.page_title;
    activeFeedbackMetadata = parseJson(draft.target_metadata, activeFeedbackMetadata);
    updateGeneratedScopeLabel();
    return true;
  }

  function clearFeedbackDraft() {
    try {
      window.sessionStorage?.removeItem(feedbackDraftStorageKey);
    } catch {}
  }

  function hasMeaningfulFeedbackDraft(draft) {
    if (!draft) return false;
    const hasText = feedbackDraftFieldNames.some((name) => String(draft[name] || "").trim());
    const hasTarget = draft.target_metadata && draft.target_metadata !== "{}";
    return Boolean(hasText || hasTarget || draft.include_browser || draft.include_dom);
  }

  const sensitiveSelector = [
    "input[type='password']",
    "input[type='hidden']",
    "input[name*='token' i]",
    "input[name*='secret' i]",
    "input[name*='password' i]",
    "textarea[name*='token' i]",
    "textarea[name*='secret' i]",
    "textarea[name*='password' i]"
  ].join(",");

  const safeText = (value, max = 300) => String(value || "").replace(/\s+/g, " ").trim().slice(0, max);

  const cssPath = (element) => {
    if (!element || element === document.body || element === document.documentElement) return "body";
    if (element.id) return `#${selectorEscape(element.id)}`;
    const parts = [];
    let node = element;
    while (node && node.nodeType === 1 && node !== document.body && parts.length < 5) {
      let part = node.tagName.toLowerCase();
      if (node.classList.length) {
        part += `.${Array.from(node.classList).slice(0, 2).map(selectorEscape).join(".")}`;
      }
      const parent = node.parentElement;
      if (parent) {
        const siblings = Array.from(parent.children).filter((child) => child.tagName === node.tagName);
        if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(node) + 1})`;
      }
      parts.unshift(part);
      node = parent;
    }
    return parts.join(" > ") || "body";
  };

  const nearestText = (element, selector) => {
    const match = element?.closest?.(selector);
    return safeText(match?.innerText || match?.textContent || "", 200);
  };

  const directChildText = (element, selector, max = 120) => {
    const match = element?.querySelector?.(selector);
    if (!match) return "";
    return safeText(Array.from(match.childNodes || [])
      .filter((node) => node.nodeType === Node.TEXT_NODE)
      .map((node) => node.textContent || "")
      .join(" "), max);
  };

  const elementOwnLabel = (element, max = 120) => {
    if (!element || element.matches?.(sensitiveSelector)) return "";
    const explicit =
      element.getAttribute?.("aria-label") ||
      element.getAttribute?.("title") ||
      element.getAttribute?.("data-feedback-label") ||
      element.getAttribute?.("data-label");
    if (explicit) return safeText(explicit, max);
    if (["INPUT", "TEXTAREA", "SELECT"].includes(element.tagName)) {
      const label = element.id ? document.querySelector(`label[for="${selectorEscape(element.id)}"]`) : element.closest?.("label");
      return safeText(label?.innerText || element.getAttribute?.("placeholder") || element.name || element.tagName.toLowerCase(), max);
    }
    if (["BUTTON", "A", "SUMMARY", "LABEL"].includes(element.tagName)) {
      return safeText(element.innerText || element.textContent || "", max);
    }
    return "";
  };

  const semanticSectionLabel = (element) => {
    if (!element) return "";
    const heading =
      directChildText(element, ":scope > .section-header h1, :scope > .section-header h2, :scope > .section-header h3", 140) ||
      directChildText(element, ":scope > header h1, :scope > header h2, :scope > header h3", 140) ||
      directChildText(element, ":scope > h1, :scope > h2, :scope > h3", 140);
    if (heading) return heading;
    return element.id ? idToLabel(element.id) : "";
  };

  const idToLabel = (value) => safeText(String(value || "").replace(/^okf-/, "OKF ").replace(/[-_]+/g, " "), 120)
    .replace(/\b\w/g, (match) => match.toUpperCase());

  const semanticContextLabel = (target) => {
    const adminFeedbackItem = target?.closest?.(".feedback-admin-item");
    if (adminFeedbackItem) return "Feedback entry metadata";
    const details = target?.closest?.("details");
    if (details) {
      const summary = elementOwnLabel(details.querySelector(":scope > summary"), 140);
      if (summary) return summary;
    }
    const table = target?.closest?.("table");
    if (table) {
      const header = target.closest("th");
      if (header) return safeText(header.textContent, 120);
      const cell = target.closest("td");
      if (cell?.cellIndex >= 0) {
        const heading = table.querySelectorAll("thead th")[cell.cellIndex];
        if (heading) return safeText(heading.textContent, 120);
      }
      return "Table row";
    }
    const form = target?.closest?.("form");
    if (form) {
      const field = target.closest(".field");
      const fieldLabel = field ? safeText(field.querySelector("label")?.innerText, 120) : "";
      if (fieldLabel) return fieldLabel;
      const submit = form.querySelector("button[type='submit'], input[type='submit']");
      const submitLabel = safeText(submit?.innerText || submit?.value, 120);
      if (submitLabel) return `${submitLabel} form`;
    }
    return elementOwnLabel(target, 120);
  };

  const semanticTargetPath = (target) => {
    const segments = [window.location.pathname || "/"];
    const section = target?.closest?.("section.card, section, .card, main");
    const sectionLabel = semanticSectionLabel(section);
    if (sectionLabel && !segments.includes(sectionLabel)) segments.push(sectionLabel);
    const contextLabel = semanticContextLabel(target);
    if (contextLabel && !segments.includes(contextLabel)) segments.push(contextLabel);
    if (segments.length === 1) {
      const fallback = elementOwnLabel(target, 120) || cssPath(target);
      if (fallback) segments.push(fallback);
    }
    return segments.map((segment) => safeText(segment, 140)).filter(Boolean).join(";");
  };

  const safeElementText = (element) => {
    if (!element || element.matches?.(sensitiveSelector)) return "";
    if (["INPUT", "TEXTAREA", "SELECT"].includes(element.tagName)) {
      return "";
    }
    return elementOwnLabel(element, 120);
  };

  const feedbackTargetMetadata = (element) => {
    const target = element?.closest?.("button, a, input, textarea, select, label, summary, [role], td, th, details, .card, section, main") || element || document.body;
    const path = semanticTargetPath(target);
    return {
      selector: cssPath(target),
      path,
      tag: target?.tagName?.toLowerCase?.() || "",
      text: safeElementText(target),
      aria_label: safeText(target?.getAttribute?.("aria-label"), 200),
      title: safeText(target?.getAttribute?.("title"), 200),
      role: safeText(target?.getAttribute?.("role"), 80),
      label: elementOwnLabel(target, 120),
      heading: path,
      page_url: window.location.href,
      page_title: document.title,
      viewport: `${window.innerWidth}x${window.innerHeight}`
    };
  };

  const currentPageLabel = () => {
    const h1 = document.querySelector("h1");
    return safeText(h1?.innerText || document.title, 180);
  };

  const generatedScopeLabel = (scope, metadata = {}) => {
    const pageLabel = currentPageLabel() || "this page";
    const elementLabel = metadata.path || metadata.label || metadata.aria_label || metadata.title || metadata.selector;
    if (scope === "element") return elementLabel || `Clicked element on ${pageLabel}`;
    if (scope === "feature") return `Feature/page: ${pageLabel}`;
    if (scope === "plugin") {
      const pluginMatch = window.location.pathname.match(/\/plugins\/([^/]+)/);
      return pluginMatch ? `Plugin: ${pluginMatch[1].replaceAll("_", " ")}` : `Plugin-related feedback on ${pageLabel}`;
    }
    if (scope === "system") return `System area: ${pageLabel}`;
    if (scope === "other") return `Other feedback on ${pageLabel}`;
    return `Whole page: ${pageLabel}`;
  };

  const updateGeneratedScopeLabel = () => {
    if (!feedbackForm) return;
    const scopeSelect = feedbackForm.querySelector("[data-feedback-scope-type]");
    const scopeLabel = feedbackForm.querySelector("[data-feedback-scope-label]");
    if (!scopeSelect || !scopeLabel) return;
    scopeLabel.value = generatedScopeLabel(scopeSelect.value, activeFeedbackMetadata);
  };

  const clearFeedbackHighlight = () => {
    highlightedFeedbackTarget?.classList?.remove("feedback-target-highlight");
    highlightedFeedbackTarget = null;
  };

  const performFeedbackReset = () => {
    if (!feedbackForm) return;
    clearFeedbackDraft();
    clearAttachedScreenshot();
    feedbackForm.reset();
    setSelectOptions(feedbackForm.querySelector("[data-feedback-category]"), feedbackOptions.categories, "bug");
    setSelectOptions(feedbackForm.querySelector("[data-feedback-severity]"), feedbackOptions.severities, "minor");
    setSelectOptions(feedbackForm.querySelector("[data-feedback-scope-type]"), feedbackOptions.scopes, "page");
    activeFeedbackTarget = null;
    activeFeedbackMetadata = {};
    const targetInput = feedbackForm.querySelector("[data-feedback-target-metadata]");
    const urlInput = feedbackForm.querySelector("[data-feedback-current-url]");
    const titleInput = feedbackForm.querySelector("[data-feedback-page-title]");
    const diagnosticsInput = feedbackForm.querySelector("[data-feedback-diagnostics]");
    const status = feedbackForm.querySelector("[data-feedback-status]");
    if (targetInput) targetInput.value = "{}";
    if (urlInput) urlInput.value = window.location.href;
    if (titleInput) titleInput.value = document.title;
    if (diagnosticsInput) diagnosticsInput.value = "{}";
    clearFeedbackHighlight();
    clearSimilarFeedback();
    updateGeneratedScopeLabel();
    if (status) status.textContent = "Feedback draft reset.";
    feedbackForm.querySelector("input[name='summary']")?.focus();
  };

  const openFeedbackModal = ({ scope = "page", target = null } = {}) => {
    if (!feedbackModal || !feedbackForm) return;
    hideContextMenu();
    clearFeedbackHighlight();
    const draft = loadFeedbackDraft();
    const restoreDraft = hasMeaningfulFeedbackDraft(draft);
    feedbackForm.reset();
    if (!restoreDraft && !attachedScreenshotBlob) {
      clearAttachedScreenshot();
    }
    setSelectOptions(feedbackForm.querySelector("[data-feedback-category]"), feedbackOptions.categories, "bug");
    setSelectOptions(feedbackForm.querySelector("[data-feedback-severity]"), feedbackOptions.severities, "minor");
    setSelectOptions(feedbackForm.querySelector("[data-feedback-scope-type]"), feedbackOptions.scopes, scope);
    const metadata = restoreDraft ? parseJson(draft.target_metadata, target ? feedbackTargetMetadata(target) : {}) : target ? feedbackTargetMetadata(target) : {};
    activeFeedbackTarget = target;
    activeFeedbackMetadata = metadata;
    const targetInput = feedbackForm.querySelector("[data-feedback-target-metadata]");
    const urlInput = feedbackForm.querySelector("[data-feedback-current-url]");
    const titleInput = feedbackForm.querySelector("[data-feedback-page-title]");
    const diagnosticsInput = feedbackForm.querySelector("[data-feedback-diagnostics]");
    const status = feedbackForm.querySelector("[data-feedback-status]");
    if (targetInput) targetInput.value = JSON.stringify(metadata);
    if (urlInput) urlInput.value = window.location.href;
    if (titleInput) titleInput.value = document.title;
    if (diagnosticsInput) diagnosticsInput.value = "{}";
    if (restoreDraft) {
      restoreFeedbackDraft(draft);
    }
    updateGeneratedScopeLabel();
    clearSimilarFeedback();
    if (status) status.textContent = "";
    if (target && scope === "element" && !restoreDraft) {
      highlightedFeedbackTarget = target;
      highlightedFeedbackTarget.classList.add("feedback-target-highlight");
    }
    feedbackModal.classList.add("is-open");
    feedbackModal.setAttribute("aria-hidden", "false");
    feedbackForm.querySelector("input[name='summary']")?.focus();
  };

  const closeFeedbackModal = ({ preserveDraft = true } = {}) => {
    if (!feedbackModal) return;
    if (preserveDraft) saveFeedbackDraft();
    feedbackModal.classList.remove("is-open");
    feedbackModal.setAttribute("aria-hidden", "true");
    clearFeedbackHighlight();
    activeFeedbackTarget = null;
    activeFeedbackMetadata = {};
  };

  document.addEventListener("click", (event) => {
    const openButton = event.target.closest("[data-feedback-open]");
    if (openButton) {
      event.preventDefault();
      openFeedbackModal({ scope: openButton.dataset.feedbackScope || "page" });
      return;
    }
    if (event.target.closest("[data-feedback-close]")) {
      event.preventDefault();
      closeFeedbackModal();
    }
  });

  feedbackForm?.querySelector("[data-feedback-scope-type]")?.addEventListener("change", updateGeneratedScopeLabel);
  ["input", "change"].forEach((eventName) => {
    feedbackForm?.addEventListener(eventName, (event) => {
      const draftSelector = [
        "input[name='summary']",
        "textarea[name='description']",
        "textarea[name='steps_to_reproduce']",
        "textarea[name='expected_behavior']",
        "textarea[name='actual_behavior']",
        "select[name='category']",
        "select[name='severity']",
        "select[name='scope_type']",
        "[data-feedback-include-browser]",
        "[data-feedback-include-dom]"
      ].join(",");
      if (event.target.matches?.(draftSelector)) {
        saveFeedbackDraft();
      }
      if (event.target.matches?.("input[name='summary'], textarea[name='description'], select[name='category'], select[name='scope_type']")) {
        scheduleSimilarFeedbackLookup();
      }
    });
  });

  feedbackForm?.addEventListener("click", async (event) => {
    const resetButton = event.target.closest("[data-feedback-reset]");
    if (resetButton) {
      event.preventDefault();
      performFeedbackReset();
      return;
    }
    const supportButton = event.target.closest("[data-feedback-support-similar]");
    if (!supportButton) return;
    event.preventDefault();
    supportButton.disabled = true;
    try {
      const response = await fetch(`/api/feedback/${encodeURIComponent(supportButton.dataset.feedbackSupportSimilar)}/support`, {
        method: "POST",
        headers: { Accept: "application/json" }
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.error || "Could not mark this as affecting you.");
      supportButton.textContent = `Affects me too (${result.support_count})`;
    } catch (error) {
      supportButton.disabled = false;
      supportButton.textContent = error.message || "Could not mark";
    }
  });

  feedbackForm?.querySelector("[data-feedback-screenshot-file]")?.addEventListener("change", (event) => {
    const file = event.target.files?.[0];
    if (file) {
      setAttachedScreenshot(file, "upload", file.name || "feedback-screenshot.png");
    }
    event.target.value = "";
  });

  feedbackForm?.querySelector("[data-feedback-paste-screenshot]")?.addEventListener("click", async () => {
    await pasteFeedbackScreenshot();
  });

  feedbackModal?.addEventListener("paste", (event) => {
    const file = imageFileFromClipboardData(event.clipboardData);
    if (!file) return;
    event.preventDefault();
    setAttachedScreenshot(file, "paste", file.name || "feedback-screenshot.png");
  });

  feedbackForm?.querySelector("[data-feedback-remove-screenshot]")?.addEventListener("click", clearAttachedScreenshot);

  function clearSimilarFeedback() {
    feedbackSimilarController?.abort?.();
    feedbackSimilarController = null;
    window.clearTimeout(feedbackSimilarTimer);
    const box = feedbackForm?.querySelector("[data-feedback-similar]");
    const list = feedbackForm?.querySelector("[data-feedback-similar-list]");
    if (box) box.hidden = true;
    if (list) list.replaceChildren();
    feedbackSimilarMatches = [];
    const confirmation = feedbackForm?.querySelector("[data-feedback-similar-confirm-input]");
    if (confirmation) confirmation.checked = false;
  }

  function scheduleSimilarFeedbackLookup() {
    window.clearTimeout(feedbackSimilarTimer);
    feedbackSimilarTimer = window.setTimeout(loadSimilarFeedback, 450);
  }

  async function loadSimilarFeedback() {
    if (!feedbackForm) return [];
    const summary = feedbackForm.querySelector("input[name='summary']")?.value || "";
    const description = feedbackForm.querySelector("textarea[name='description']")?.value || "";
    if (summary.trim().length < 6 && description.trim().length < 12) {
      clearSimilarFeedback();
      return [];
    }
    feedbackSimilarController?.abort?.();
    feedbackSimilarController = new AbortController();
    const params = new URLSearchParams({
      summary,
      description,
      category: feedbackForm.querySelector("select[name='category']")?.value || "",
      scope_type: feedbackForm.querySelector("select[name='scope_type']")?.value || "",
      current_url: window.location.href,
      limit: "4"
    });
    try {
      const response = await fetch(`/api/feedback/similar?${params.toString()}`, {
        headers: { Accept: "application/json" },
        signal: feedbackSimilarController.signal
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.error || "Could not load similar feedback.");
      const matches = result.matches || [];
      renderSimilarFeedback(matches);
      return matches;
    } catch (error) {
      if (error.name !== "AbortError") {
        renderSimilarFeedback([]);
      }
      return [];
    }
  }

  function renderSimilarFeedback(matches) {
    const box = feedbackForm?.querySelector("[data-feedback-similar]");
    const list = feedbackForm?.querySelector("[data-feedback-similar-list]");
    const confirmation = feedbackForm?.querySelector("[data-feedback-similar-confirm-input]");
    if (!box || !list) return;
    const previousIds = feedbackSimilarMatches.map((item) => item.id).join(",");
    const wasConfirmed = confirmation?.checked === true;
    list.replaceChildren();
    if (!matches.length) {
      feedbackSimilarMatches = [];
      if (confirmation) confirmation.checked = false;
      box.hidden = true;
      return;
    }
    feedbackSimilarMatches = matches;
    const nextIds = matches.map((item) => item.id).join(",");
    if (confirmation) confirmation.checked = wasConfirmed && previousIds === nextIds;
    matches.forEach((item) => {
      const row = document.createElement("article");
      row.className = "feedback-similar-item";
      const title = document.createElement("strong");
      title.textContent = item.summary;
      const meta = document.createElement("span");
      meta.className = "hint";
      meta.textContent = `${item.category_label} · ${item.scope_label_display} · ${item.status_label} · ${item.support_count || 0} also affected`;
      const actions = document.createElement("div");
      actions.className = "button-group";
      const open = document.createElement("a");
      open.className = "button subtle";
      open.href = `/feedback?id=${encodeURIComponent(item.id)}`;
      open.textContent = "Open";
      const support = document.createElement("button");
      support.type = "button";
      support.className = "button subtle";
      support.dataset.feedbackSupportSimilar = item.id;
      support.disabled = Boolean(item.supported_by_me);
      support.textContent = item.supported_by_me ? "Affects me too" : "This affects me too";
      actions.append(open, support);
      row.append(title, meta, actions);
      list.append(row);
    });
    box.hidden = false;
  }

  feedbackForm?.addEventListener("submit", async (event) => {
    event.preventDefault();
    const submitter = feedbackForm.querySelector("button[type='submit']");
    const status = feedbackForm.querySelector("[data-feedback-status]");
    const includeBrowser = feedbackForm.querySelector("[data-feedback-include-browser]")?.checked;
    const includeDom = feedbackForm.querySelector("[data-feedback-include-dom]")?.checked;
    const matches = await loadSimilarFeedback();
    const similarConfirmation = feedbackForm.querySelector("[data-feedback-similar-confirm-input]");
    if (matches.length && !similarConfirmation?.checked) {
      if (status) status.textContent = "Review the related feedback above, then confirm that this report is distinct or adds useful context.";
      similarConfirmation?.focus();
      return;
    }
    const formData = new FormData(feedbackForm);
    formData.set("target_metadata", JSON.stringify(parseJson(formData.get("target_metadata"), {})));
    formData.set("diagnostics", JSON.stringify({
      ...(includeBrowser
        ? {
            user_agent: navigator.userAgent,
            viewport: `${window.innerWidth}x${window.innerHeight}`,
            language: navigator.language || ""
          }
        : {}),
      ...(includeDom
        ? { dom_snapshot: sanitizedDomSnapshot(activeFeedbackTarget || document.querySelector("main") || document.body) }
        : {}),
      ...(attachedScreenshotBlob
        ? {
            screenshot_mode: "user_attached",
            screenshot_source: attachedScreenshotSource
          }
        : {}),
      ...(matches.length && similarConfirmation?.checked
        ? {
            similar_feedback_confirmation: "distinct_or_additional_context",
            similar_feedback_ids: feedbackSimilarMatches.map((item) => item.id).slice(0, 5).join(",")
          }
        : {})
    }));
    if (attachedScreenshotBlob) {
      formData.set("screenshot", attachedScreenshotBlob, attachedScreenshotName);
    }
    submitter.disabled = true;
    if (status) status.textContent = "Submitting feedback...";
    try {
      const response = await fetch("/api/feedback", {
        method: "POST",
        headers: { Accept: "application/json" },
        body: formData
      });
      const result = await response.json();
      if (response.status === 409 && result.reason === "similar_feedback_confirmation_required") {
        renderSimilarFeedback(result.matches || []);
      }
      if (!response.ok) throw new Error(result.error || "Feedback could not be submitted.");
      if (status) status.textContent = result.message || "Feedback submitted.";
      clearFeedbackDraft();
      clearAttachedScreenshot();
      feedbackForm.reset();
      window.setTimeout(() => {
        closeFeedbackModal({ preserveDraft: false });
        window.location.href = `/feedback?id=${encodeURIComponent(result.id)}`;
      }, 700);
    } catch (error) {
      if (status) status.textContent = error.message;
      submitter.disabled = false;
    }
  });

  function sanitizedDomSnapshot(root) {
    const lines = [];
    const maxNodes = 80;
    const maxDepth = 4;
    const skipTags = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "SVG"]);
    const walk = (node, depth = 0) => {
      if (!node || lines.length >= maxNodes || depth > maxDepth) return;
      if (node.nodeType !== 1 || skipTags.has(node.tagName)) return;
      const indent = "  ".repeat(depth);
      const tag = node.tagName.toLowerCase();
      const attrs = [];
      if (node.id) attrs.push(`#${node.id.slice(0, 60)}`);
      if (node.classList?.length) attrs.push(`.${Array.from(node.classList).slice(0, 3).join(".").slice(0, 80)}`);
      const role = node.getAttribute?.("role");
      const label = node.getAttribute?.("aria-label") || node.getAttribute?.("title");
      if (role) attrs.push(`role=${role.slice(0, 40)}`);
      if (label) attrs.push(`label="${safeText(label, 80)}"`);
      const sensitive = node.matches?.(sensitiveSelector) || ["INPUT", "TEXTAREA", "SELECT"].includes(node.tagName);
      const text = sensitive ? "" : safeElementText(node);
      lines.push(`${indent}<${tag}${attrs.length ? ` ${attrs.join(" ")}` : ""}>${text ? ` ${safeText(text, 120)}` : ""}`);
      Array.from(node.children || []).slice(0, 10).forEach((child) => walk(child, depth + 1));
    };
    walk(root);
    return lines.join("\n").slice(0, 6000);
  }

  function clearAttachedScreenshot() {
    if (attachedScreenshotUrl) {
      URL.revokeObjectURL(attachedScreenshotUrl);
    }
    attachedScreenshotBlob = null;
    attachedScreenshotUrl = "";
    attachedScreenshotSource = "";
    attachedScreenshotName = "feedback-screenshot.png";
    const preview = feedbackForm?.querySelector("[data-feedback-screenshot-preview]");
    const image = feedbackForm?.querySelector("[data-feedback-screenshot-image]");
    const meta = feedbackForm?.querySelector("[data-feedback-screenshot-meta]");
    const removeButton = feedbackForm?.querySelector("[data-feedback-remove-screenshot]");
    const screenshotStatus = feedbackForm?.querySelector("[data-feedback-screenshot-status]");
    if (preview) preview.hidden = true;
    if (image) image.removeAttribute("src");
    if (meta) meta.textContent = "";
    if (removeButton) removeButton.hidden = true;
    if (screenshotStatus) screenshotStatus.textContent = "";
  }

  async function pasteFeedbackScreenshot() {
    const screenshotStatus = feedbackForm?.querySelector("[data-feedback-screenshot-status]");
    if (screenshotStatus) {
      screenshotStatus.textContent = "Looking for an image in the clipboard...";
    }
    try {
      if (!navigator.clipboard?.read || !window.isSecureContext) {
        throw new Error("Clipboard image read is not available.");
      }
      const items = await navigator.clipboard.read();
      for (const item of items) {
        const type = item.types.find((entry) => entry.startsWith("image/"));
        if (type) {
          const blob = await item.getType(type);
          setAttachedScreenshot(blob, "paste", `feedback-screenshot${screenshotExtension(type)}`);
          return;
        }
      }
      throw new Error("No image was found in the clipboard.");
    } catch (error) {
      if (screenshotStatus) {
        screenshotStatus.textContent = `${error.message || "Clipboard image could not be read."} You can also copy a screenshot and press Ctrl+V while this dialog is open.`;
      }
    }
  }

  function imageFileFromClipboardData(data) {
    const files = Array.from(data?.files || []);
    const file = files.find((entry) => entry.type?.startsWith("image/"));
    if (file) return file;
    const items = Array.from(data?.items || []);
    const item = items.find((entry) => entry.type?.startsWith("image/"));
    return item?.getAsFile?.() || null;
  }

  function screenshotExtension(mime) {
    if (mime === "image/jpeg") return ".jpg";
    if (mime === "image/webp") return ".webp";
    return ".png";
  }

  function screenshotLabel(source) {
    return source === "paste" ? "Pasted screenshot" : "Uploaded screenshot";
  }

  function setAttachedScreenshot(blob, source, name = "feedback-screenshot.png") {
    const screenshotStatus = feedbackForm?.querySelector("[data-feedback-screenshot-status]");
    if (!["image/png", "image/jpeg", "image/webp"].includes(blob.type)) {
      if (screenshotStatus) screenshotStatus.textContent = "Only PNG, JPEG, or WebP screenshots can be attached.";
      return;
    }
    if (blob.size > 8 * 1024 * 1024) {
      if (screenshotStatus) screenshotStatus.textContent = "Screenshot must be 8 MB or smaller.";
      return;
    }
    clearAttachedScreenshot();
    attachedScreenshotBlob = blob;
    attachedScreenshotUrl = URL.createObjectURL(blob);
    attachedScreenshotSource = source;
    attachedScreenshotName = name || `feedback-screenshot${screenshotExtension(blob.type)}`;
    const preview = feedbackForm?.querySelector("[data-feedback-screenshot-preview]");
    const image = feedbackForm?.querySelector("[data-feedback-screenshot-image]");
    const meta = feedbackForm?.querySelector("[data-feedback-screenshot-meta]");
    const removeButton = feedbackForm?.querySelector("[data-feedback-remove-screenshot]");
    const status = feedbackForm?.querySelector("[data-feedback-screenshot-status]");
    if (image && attachedScreenshotUrl) {
      image.src = attachedScreenshotUrl;
    }
    if (meta) {
      const sizeKb = Math.max(1, Math.round(blob.size / 1024));
      meta.textContent = `${screenshotLabel(source)} · ${blob.type.replace("image/", "").toUpperCase()} · ${sizeKb} KB`;
    }
    if (preview) preview.hidden = !attachedScreenshotUrl;
    if (removeButton) removeButton.hidden = false;
    if (status) status.textContent = "Screenshot attached. Review the preview and remove it if it contains sensitive information.";
  }

  const editableElementForTarget = (target) => {
    const element = target?.closest?.("input, textarea, [contenteditable='true']");
    if (!element || element.matches("[readonly], [disabled]")) return null;
    const inputType = String(element.getAttribute("type") || "").toLowerCase();
    if (["button", "checkbox", "color", "file", "image", "radio", "range", "reset", "submit"].includes(inputType)) {
      return null;
    }
    return element;
  };

  const selectedTextForTarget = (target) => {
    const editable = editableElementForTarget(target);
    if (editable && typeof editable.selectionStart === "number" && typeof editable.selectionEnd === "number") {
      return editable.value.slice(editable.selectionStart, editable.selectionEnd);
    }
    return window.getSelection?.().toString() || "";
  };

  const hasInputSelection = (target) => {
    const editable = editableElementForTarget(target);
    if (!editable) return false;
    if (typeof editable.selectionStart === "number" && typeof editable.selectionEnd === "number") {
      return editable.selectionEnd > editable.selectionStart;
    }
    const selection = window.getSelection?.();
    return Boolean(selection && !selection.isCollapsed && editable.contains(selection.anchorNode));
  };

  const contextImageForTarget = (target) => target?.closest?.("img") || null;

  const readClipboardText = async () => {
    try {
      if (!navigator.clipboard?.readText || !window.isSecureContext) return "";
      return await navigator.clipboard.readText();
    } catch {
      return "";
    }
  };

  const setContextActionEnabled = (action, enabled) => {
    const button = contextMenu?.querySelector(`[data-context-action="${action}"]`);
    if (!button) return;
    button.setAttribute("aria-disabled", enabled ? "false" : "true");
    button.classList.toggle("is-disabled", !enabled);
    button.tabIndex = enabled ? 0 : -1;
  };

  const enabledContextButtons = () =>
    Array.from(contextMenu?.querySelectorAll("[data-context-action]:not(.is-disabled)") || []);

  const focusContextButton = (offset) => {
    const buttons = enabledContextButtons();
    if (!buttons.length) return;
    const current = buttons.indexOf(document.activeElement);
    const next = current === -1 ? 0 : (current + offset + buttons.length) % buttons.length;
    buttons[next].focus();
  };

  const updateContextMenuItems = async (target) => {
    if (!contextMenu) return;
    const active = document.activeElement;
    const pasteTarget = editableElementForTarget(active);
    const selectedText = selectedTextForTarget(target).trim();
    const image = contextImageForTarget(target);
    contextClipboardText = pasteTarget ? await readClipboardText() : "";
    const pasteButton = contextMenu.querySelector('[data-context-action="paste"]');
    if (pasteButton) {
      pasteButton.dataset.contextTooltip = navigator.clipboard?.readText && window.isSecureContext
        ? "Insert the current clipboard text into the active field."
        : "This browser blocks clipboard reading here. Hold Shift while right-clicking to use the browser menu, or focus the field and press Ctrl+V.";
    }
    setContextActionEnabled("back", window.history.length > 1);
    setContextActionEnabled("forward", Boolean(window.navigation?.canGoForward));
    setContextActionEnabled("copy", Boolean(selectedText || image));
    setContextActionEnabled("cut", hasInputSelection(target));
    setContextActionEnabled("paste", Boolean(pasteTarget && contextClipboardText.length > 0));
    setContextActionEnabled("link", true);
    setContextActionEnabled("reload", true);
    setContextActionEnabled("feedback", !contextMenu.querySelector('[data-context-action="feedback"][data-context-auth-required="true"]'));
  };

  const showContextMenu = async (event) => {
    if (!contextMenu || event.shiftKey) return;
    event.preventDefault();
    contextTarget = event.target;
    contextMenu.hidden = false;
    await updateContextMenuItems(contextTarget);
    const width = contextMenu.offsetWidth || 180;
    const height = contextMenu.offsetHeight || 260;
    contextMenu.style.left = `${Math.min(event.clientX, window.innerWidth - width - 8)}px`;
    contextMenu.style.top = `${Math.min(event.clientY, window.innerHeight - height - 8)}px`;
    contextMenu.querySelector("button:not(.is-disabled)")?.focus();
  };

  function hideContextMenu() {
    if (!contextMenu) return;
    contextMenu.hidden = true;
    hideContextTooltip();
  }

  const linkForTarget = (target) => {
    const element = target?.closest?.("[id]") || document.querySelector("h1[id]") || null;
    const url = new URL(window.location.href);
    if (element?.id) url.hash = element.id;
    return url.toString();
  };

  const copyImage = async (image) => {
    if (!image) return false;
    try {
      if (!navigator.clipboard?.write || !window.ClipboardItem || !window.isSecureContext) {
        return copyText(image.currentSrc || image.src);
      }
      const response = await fetch(image.currentSrc || image.src);
      const blob = await response.blob();
      await navigator.clipboard.write([new ClipboardItem({ [blob.type || "image/png"]: blob })]);
      return true;
    } catch {
      return false;
    }
  };

  const insertTextIntoEditable = (editable, text) => {
    if (!editable || !text) return;
    editable.focus();
    if (typeof editable.selectionStart === "number" && typeof editable.selectionEnd === "number") {
      const start = editable.selectionStart;
      const end = editable.selectionEnd;
      editable.setRangeText(text, start, end, "end");
      editable.dispatchEvent(new Event("input", { bubbles: true }));
      return;
    }
    document.execCommand("insertText", false, text);
  };

  const runContextAction = async (action, button) => {
    if (button?.classList.contains("is-disabled") || button?.getAttribute("aria-disabled") === "true") return;
    const editable = editableElementForTarget(contextTarget) || editableElementForTarget(document.activeElement);
    try {
      if (action === "back") window.history.back();
      if (action === "forward") {
        if (window.navigation?.canGoForward) window.history.forward();
      }
      if (action === "copy") {
        const selectedText = selectedTextForTarget(contextTarget);
        if (selectedText) await copyText(selectedText);
        else await copyImage(contextImageForTarget(contextTarget));
      }
      if (action === "cut" && editable) document.execCommand("cut");
      if (action === "paste" && editable) {
        const text = contextClipboardText || await readClipboardText();
        insertTextIntoEditable(editable, text);
      }
      if (action === "link") await copyText(linkForTarget(contextTarget));
      if (action === "reload") window.location.reload(true);
      if (action === "feedback") openFeedbackModal({ scope: "element", target: contextTarget });
    } catch {
      if (action === "paste" && editable) document.execCommand("paste");
    } finally {
      if (action !== "feedback") hideContextMenu();
    }
  };

  document.addEventListener("contextmenu", showContextMenu);
  document.addEventListener("click", (event) => {
    const button = event.target.closest("[data-context-action]");
    if (!button || !contextMenu?.contains(button)) {
      hideContextMenu();
      return;
    }
    event.preventDefault();
    runContextAction(button.dataset.contextAction, button);
  });
  contextMenu?.addEventListener("pointerover", (event) => {
    const button = event.target.closest("[data-context-action]");
    if (!button || !contextMenu.contains(button)) return;
    window.clearTimeout(contextTooltipTimer);
    contextTooltipTimer = window.setTimeout(() => showContextTooltip(button), 1000);
  });
  contextMenu?.addEventListener("pointerout", (event) => {
    const button = event.target.closest("[data-context-action]");
    if (!button) return;
    const next = event.relatedTarget;
    if (next && (button.contains(next) || contextTooltip?.contains(next))) return;
    window.clearTimeout(contextTooltipTimer);
    hideContextTooltip();
  });
  document.addEventListener("keydown", (event) => {
    if (!contextMenu?.hidden && contextMenu?.contains(document.activeElement)) {
      if (event.key === "ArrowDown") {
        event.preventDefault();
        focusContextButton(1);
        return;
      }
      if (event.key === "ArrowUp") {
        event.preventDefault();
        focusContextButton(-1);
        return;
      }
      if (event.key === "Home") {
        event.preventDefault();
        enabledContextButtons()[0]?.focus();
        return;
      }
      if (event.key === "End") {
        event.preventDefault();
        enabledContextButtons().at(-1)?.focus();
        return;
      }
      if (event.key === "Enter" || event.key === " ") {
        const button = document.activeElement?.closest?.("[data-context-action]");
        if (button) {
          event.preventDefault();
          runContextAction(button.dataset.contextAction, button);
          return;
        }
      }
      if (event.key === "Tab") {
        event.preventDefault();
        focusContextButton(event.shiftKey ? -1 : 1);
        return;
      }
    }
    if (event.key === "Escape") {
      hideContextMenu();
      closeFeedbackExportModal();
    }
  });
  window.addEventListener("blur", hideContextMenu);

  function showContextTooltip(button) {
    const text = button?.dataset.contextTooltip || "";
    if (!text) return;
    hideContextTooltip();
    contextTooltip = document.createElement("div");
    contextTooltip.className = "lumi-context-tooltip";
    contextTooltip.textContent = text;
    contextTooltip.setAttribute("role", "tooltip");
    document.body.append(contextTooltip);
    const buttonRect = button.getBoundingClientRect();
    const tooltipRect = contextTooltip.getBoundingClientRect();
    const padding = 8;
    let left = buttonRect.right + padding;
    let top = buttonRect.top + (buttonRect.height - tooltipRect.height) / 2;
    if (left + tooltipRect.width > window.innerWidth - padding) {
      left = buttonRect.left - tooltipRect.width - padding;
    }
    left = Math.max(padding, Math.min(left, window.innerWidth - tooltipRect.width - padding));
    top = Math.max(padding, Math.min(top, window.innerHeight - tooltipRect.height - padding));
    contextTooltip.style.left = `${left}px`;
    contextTooltip.style.top = `${top}px`;
  }

  function hideContextTooltip() {
    window.clearTimeout(contextTooltipTimer);
    contextTooltip?.remove();
    contextTooltip = null;
  }

  const feedbackExportModal = document.querySelector("[data-feedback-export-modal]");
  const feedbackExportOutput = feedbackExportModal?.querySelector("[data-feedback-export-output]");
  const feedbackExportStatus = feedbackExportModal?.querySelector("[data-feedback-export-status]");
  const feedbackExportAiInput = document.querySelector("[data-feedback-export-ai]");
  const feedbackExportAiOptions = document.querySelector("[data-feedback-export-ai-options]");
  const feedbackExportMode = feedbackExportModal?.querySelector("[data-feedback-export-mode]");
  const feedbackExportOutputLabel = feedbackExportModal?.querySelector("[data-feedback-export-output-label]");
  let lastFeedbackExportPayload = null;
  let lastFeedbackExportJson = "";

  function feedbackExportTokenLimit() {
    const value = Number.parseInt(document.querySelector("[data-feedback-export-token-limit]")?.value || "8000", 10);
    if (!Number.isFinite(value)) return 8000;
    return Math.max(1000, Math.min(24000, value));
  }

  function feedbackExportUseAi() {
    return Boolean(feedbackExportAiInput?.checked && !feedbackExportAiInput.hidden);
  }

  function feedbackExportModeValue() {
    return feedbackExportMode?.value === "debug" ? "debug" : "taskfile";
  }

  function selectedFeedbackExportIds() {
    return Array.from(document.querySelectorAll("[data-feedback-export-select]:checked"))
      .map((input) => input.value)
      .filter(Boolean);
  }

  function feedbackExportFilters() {
    const params = new URLSearchParams(window.location.search);
    const filters = {};
    ["status", "category", "severity", "scope", "area", "route", "plugin", "target", "submitter", "date_from", "date_to", "needs_action", "sort"].forEach((key) => {
      const value = params.get(key);
      if (value) filters[key] = value;
    });
    return filters;
  }

  function openFeedbackExportModal(json, message = "") {
    if (!feedbackExportModal || !feedbackExportOutput) {
      if (message) window.alert(message);
      return;
    }
    lastFeedbackExportJson = json;
    feedbackExportOutput.value = json;
    if (feedbackExportStatus) feedbackExportStatus.textContent = message;
    feedbackExportModal.hidden = false;
    feedbackExportModal.setAttribute("aria-hidden", "false");
    feedbackExportModal.classList.add("is-open");
    feedbackExportOutput.focus();
    feedbackExportOutput.select();
  }

  function activeFeedbackExportObject(payload = lastFeedbackExportPayload) {
    if (!payload) return null;
    return feedbackExportModeValue() === "debug"
      ? payload.debug_export || payload
      : payload.taskfile || payload;
  }

  function renderFeedbackExportPayload(payload, message = "Export ready.") {
    lastFeedbackExportPayload = payload;
    const output = activeFeedbackExportObject(payload);
    const label = feedbackExportModeValue() === "debug"
      ? "Full debug export JSON"
      : "Codex taskfile JSON";
    if (feedbackExportOutputLabel) feedbackExportOutputLabel.textContent = label;
    openFeedbackExportModal(JSON.stringify(output || {}, null, 2), message);
  }

  function closeFeedbackExportModal() {
    if (!feedbackExportModal) return;
    feedbackExportModal.classList.remove("is-open");
    feedbackExportModal.setAttribute("aria-hidden", "true");
    feedbackExportModal.hidden = true;
  }

  async function requestFeedbackExport(payload) {
    if (feedbackExportStatus) feedbackExportStatus.textContent = "Building export...";
    const useAi = feedbackExportUseAi();
    const response = await fetch("/admin/feedback/export", {
      method: "POST",
      headers: { "Content-Type": "application/json", Accept: "application/json" },
      body: JSON.stringify({
        ...payload,
        use_ai: useAi ? "1" : "0",
        ...(useAi ? { token_limit: feedbackExportTokenLimit() } : {})
      })
    });
    const result = await response.json().catch(() => ({
      ok: false,
      error: `Feedback export returned ${response.status || "an"} invalid response.`
    }));
    if (!response.ok || !result.ok) {
      throw new Error(result.error || "Feedback export failed.");
    }
    return result.export;
  }

  async function runFeedbackExport(payload) {
    try {
      if (feedbackExportMode) feedbackExportMode.value = "taskfile";
      openFeedbackExportModal("", "Building export...");
      const result = await requestFeedbackExport(payload);
      renderFeedbackExportPayload(result, "Export ready.");
    } catch (error) {
      lastFeedbackExportPayload = null;
      openFeedbackExportModal("", error.message || "Feedback export failed.");
    }
  }

  async function copyFeedbackExportJson() {
    if (!lastFeedbackExportJson) return;
    try {
      const copied = await copyText(lastFeedbackExportJson);
      if (!copied) throw new Error("Copy command was rejected.");
      if (feedbackExportStatus) feedbackExportStatus.textContent = "Copied JSON to clipboard.";
    } catch {
      feedbackExportOutput?.select();
      document.execCommand?.("copy");
      if (feedbackExportStatus) feedbackExportStatus.textContent = "Selected JSON for copying.";
    }
  }

  function syncFeedbackExportAiOptions() {
    if (feedbackExportAiOptions) {
      feedbackExportAiOptions.hidden = !feedbackExportUseAi();
    }
  }

  function downloadFeedbackExportJson() {
    if (!lastFeedbackExportJson) return;
    const blob = new Blob([lastFeedbackExportJson], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    const mode = feedbackExportModeValue() === "debug" ? "debug-export" : "codex-taskfile";
    link.href = url;
    link.download = `lumi-feedback-${mode}-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
    document.body.append(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);
  }

  feedbackExportAiInput?.addEventListener("change", syncFeedbackExportAiOptions);
  feedbackExportMode?.addEventListener("change", () => {
    if (lastFeedbackExportPayload) {
      renderFeedbackExportPayload(lastFeedbackExportPayload, feedbackExportModeValue() === "debug"
        ? "Showing full debug export."
        : "Showing compact Codex taskfile.");
    }
  });
  syncFeedbackExportAiOptions();

  document.addEventListener("click", (event) => {
    if (event.target.closest("[data-feedback-export-select-label]")) {
      event.stopPropagation();
    }
  }, true);

  document.addEventListener("click", (event) => {
    const single = event.target.closest("[data-feedback-export-one]");
    if (single) {
      event.preventDefault();
      runFeedbackExport({ ids: [single.dataset.feedbackExportOne] });
      return;
    }
    if (event.target.closest("[data-feedback-export-selected]")) {
      event.preventDefault();
      const ids = selectedFeedbackExportIds();
      if (!ids.length) {
        openFeedbackExportModal("", "Select at least one feedback item first.");
        return;
      }
      runFeedbackExport({ ids });
      return;
    }
    if (event.target.closest("[data-feedback-export-all]")) {
      event.preventDefault();
      runFeedbackExport({ mode: "all", ...feedbackExportFilters() });
      return;
    }
    if (event.target.closest("[data-feedback-export-copy]")) {
      event.preventDefault();
      copyFeedbackExportJson();
      return;
    }
    if (event.target.closest("[data-feedback-export-download]")) {
      event.preventDefault();
      downloadFeedbackExportJson();
      return;
    }
    if (event.target.closest("[data-feedback-export-close]") || event.target === feedbackExportModal) {
      event.preventDefault();
      closeFeedbackExportModal();
    }
  });
})();
