(() => {
  const focusableSelector = [
    "a[href]", "button:not([disabled])", "input:not([disabled]):not([type='hidden'])",
    "select:not([disabled])", "textarea:not([disabled])", "[tabindex]:not([tabindex='-1'])"
  ].join(",");
  const records = new WeakMap();
  let active = null;

  function focusables(dialog) {
    return Array.from(dialog.querySelectorAll(focusableSelector)).filter((item) => !item.hidden && item.getAttribute("aria-hidden") !== "true");
  }

  function isolate(backdrop) {
    const changed = [];
    let current = backdrop;
    while (current?.parentElement && current.parentElement !== document.documentElement) {
      for (const sibling of current.parentElement.children) {
        if (sibling === current || sibling.tagName === "SCRIPT") continue;
        changed.push({ node: sibling, inert: sibling.inert, ariaHidden: sibling.getAttribute("aria-hidden") });
        sibling.inert = true;
      }
      current = current.parentElement;
      if (current === document.body) break;
    }
    return changed;
  }

  function restoreIsolation(changed) {
    for (const item of changed || []) {
      item.node.inert = item.inert;
      if (item.ariaHidden === null) item.node.removeAttribute("aria-hidden");
      else item.node.setAttribute("aria-hidden", item.ariaHidden);
    }
  }

  function open(backdrop, options = {}) {
    if (!backdrop || records.has(backdrop)) return;
    if (active && active !== backdrop) close(active, { restoreFocus: false });
    const dialog = backdrop.matches("[role='dialog'], dialog") ? backdrop : backdrop.querySelector("[role='dialog'], dialog, .modal");
    if (!dialog) return;
    const opener = options.opener || document.activeElement;
    const record = {
      dialog,
      opener: opener instanceof HTMLElement ? opener : null,
      isolated: isolate(backdrop),
      previousOverflow: document.documentElement.style.overflow
    };
    records.set(backdrop, record);
    active = backdrop;
    backdrop.setAttribute("aria-hidden", "false");
    document.documentElement.classList.add("lumi-dialog-open");
    document.documentElement.style.overflow = "hidden";
    const initial = options.initialFocus || dialog.querySelector("[autofocus], [data-dialog-initial-focus]") || focusables(dialog)[0] || dialog;
    if (!dialog.hasAttribute("tabindex") && initial === dialog) dialog.setAttribute("tabindex", "-1");
    window.setTimeout(() => initial.focus?.({ preventScroll: true }), 0);
  }

  function close(backdrop, options = {}) {
    const record = records.get(backdrop);
    if (!record) return;
    records.delete(backdrop);
    if (active === backdrop) active = null;
    restoreIsolation(record.isolated);
    document.documentElement.classList.remove("lumi-dialog-open");
    document.documentElement.style.overflow = record.previousOverflow;
    backdrop.setAttribute("aria-hidden", "true");
    if (options.restoreFocus !== false && record.opener?.isConnected) {
      window.setTimeout(() => record.opener.focus({ preventScroll: true }), 0);
    }
  }

  function handleKeydown(event) {
    if (!active) return;
    const record = records.get(active);
    if (!record) return;
    if (event.key === "Escape" && active.dataset.dialogStatic !== "true") {
      event.preventDefault();
      active.dispatchEvent(new CustomEvent("lumi:dialog-cancel", { bubbles: true }));
      close(active);
      active.classList.remove("is-open");
      return;
    }
    if (event.key !== "Tab") return;
    const items = focusables(record.dialog);
    if (!items.length) {
      event.preventDefault();
      record.dialog.focus();
      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();
    }
  }

  function observe(root = document) {
    root.querySelectorAll?.(".modal-backdrop[aria-hidden='false']").forEach((item) => open(item));
    const observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        const item = mutation.target;
        if (!(item instanceof HTMLElement) || !item.matches(".modal-backdrop")) continue;
        if (item.getAttribute("aria-hidden") === "false") open(item);
        else close(item);
      }
    });
    observer.observe(root === document ? document.body : root, { subtree: true, attributes: true, attributeFilter: ["aria-hidden"] });
    return () => observer.disconnect();
  }

  document.addEventListener("keydown", handleKeydown);
  document.addEventListener("DOMContentLoaded", () => observe(document), { once: true });
  window.LumiDialog = Object.freeze({ open, close, observe });
})();
