const M = "__editoraCommandEditorRoot", H = (e) => {
  if (!e) return null;
  const t = e.querySelector('[contenteditable="true"]');
  return t instanceof HTMLElement ? t : null;
}, R = () => {
  if (typeof window > "u") return null;
  const e = window[M];
  if (!(e instanceof HTMLElement)) return null;
  window[M] = null;
  const t = e.closest("[data-editora-editor], .rte-editor, .editora-editor, editora-editor") || (e.matches("[data-editora-editor], .rte-editor, .editora-editor, editora-editor") ? e : null);
  if (t) {
    const n = H(t);
    if (n) return n;
    if (t.getAttribute("contenteditable") === "true") return t;
  }
  if (e.getAttribute("contenteditable") === "true")
    return e;
  const r = e.closest('[contenteditable="true"]');
  return r instanceof HTMLElement ? r : null;
}, _ = () => {
  const e = R();
  if (e && document.contains(e))
    return e;
  const t = window.getSelection();
  if (t && t.rangeCount > 0) {
    let n = t.getRangeAt(0).startContainer;
    for (; n && n !== document.body; ) {
      if (n.nodeType === Node.ELEMENT_NODE) {
        const o = n;
        if (o.getAttribute("contenteditable") === "true")
          return o;
      }
      n = n.parentNode;
    }
  }
  const r = document.activeElement;
  if (r) {
    if (r.getAttribute("contenteditable") === "true")
      return r;
    const n = r.closest('[contenteditable="true"]');
    if (n) return n;
  }
  return document.querySelector('[contenteditable="true"]');
}, A = (e) => e ? e.nodeType === Node.ELEMENT_NODE ? e : e.parentElement : null, I = (e) => {
  const t = window.getSelection();
  if (!t || t.rangeCount === 0) return null;
  const r = t.getRangeAt(0);
  return e.contains(r.commonAncestorContainer) ? r : null;
}, T = (e) => {
  e.dispatchEvent(new Event("input", { bubbles: !0 }));
}, b = (e, t) => {
  if (t === e.innerHTML) return;
  const r = window.execEditorCommand || window.executeEditorCommand;
  if (typeof r == "function")
    try {
      r("recordDomTransaction", e, t, e.innerHTML);
    } catch {
    }
}, C = (e, t) => {
  if (!e.isConnected) {
    t.focus({ preventScroll: !0 });
    return;
  }
  const r = window.getSelection();
  if (!r) return;
  const n = document.createRange();
  n.selectNodeContents(e), n.collapse(!1), r.removeAllRanges();
  try {
    r.addRange(n);
  } catch {
    t.focus({ preventScroll: !0 });
    return;
  }
  t.focus({ preventScroll: !0 });
}, N = (e) => {
  let t = e.querySelector(":scope > p");
  if (!t) {
    t = document.createElement("p");
    const r = [];
    e.childNodes.forEach((n) => {
      n.nodeType === Node.ELEMENT_NODE && ["UL", "OL"].includes(n.tagName) || r.push(n);
    }), r.forEach((n) => t.appendChild(n)), e.insertBefore(t, e.firstChild);
  }
  return t.innerHTML.trim() || (t.innerHTML = "<br>"), t;
}, v = (e) => (e.textContent || "").replace(/\u200B/g, "").trim() ? !1 : !e.querySelector("img, video, table, iframe, hr, pre, ul, ol"), x = () => {
  const e = document.createElement("p");
  return e.innerHTML = "<br>", e;
}, S = (e, t) => {
  if (!e.isConnected) {
    t.focus({ preventScroll: !0 });
    return;
  }
  const r = window.getSelection();
  if (!r) return;
  const n = document.createRange();
  n.selectNodeContents(e), n.collapse(!0), r.removeAllRanges();
  try {
    r.addRange(n);
  } catch {
    t.focus({ preventScroll: !0 });
    return;
  }
  t.focus({ preventScroll: !0 });
}, P = (e, t) => {
  e.appendChild(t), e.innerHTML.trim() || (e.innerHTML = "<br>");
}, D = (e, t, r) => {
  const n = x();
  t.parentNode?.insertBefore(n, t.nextSibling), r.remove(), y(t).length === 0 && t.remove(), S(n, e);
}, O = (e, t, r) => {
  const n = N(t), o = r.cloneRange();
  o.deleteContents();
  const i = document.createRange();
  i.setStart(o.startContainer, o.startOffset), i.setEndAfter(n.lastChild || n);
  const d = document.createDocumentFragment();
  try {
    d.appendChild(i.extractContents());
  } catch {
  }
  n.innerHTML.trim() || (n.innerHTML = "<br>");
  const c = document.createElement("li");
  c.setAttribute("data-type", "checklist-item"), c.setAttribute("data-checked", "false");
  const h = document.createElement("p");
  P(h, d), c.appendChild(h), t.parentNode?.insertBefore(c, t.nextSibling), S(h, e);
}, k = (e) => {
  const t = document.createElement("li");
  t.setAttribute("data-type", "checklist-item"), t.setAttribute("data-checked", "false");
  const r = document.createElement("p");
  return r.innerHTML = e.trim() || "<br>", t.appendChild(r), t;
}, y = (e) => Array.from(e.children).filter(
  (t) => t instanceof HTMLLIElement
), F = /* @__PURE__ */ new Set([
  "P",
  "DIV",
  "H1",
  "H2",
  "H3",
  "H4",
  "H5",
  "H6",
  "BLOCKQUOTE",
  "PRE",
  "LI"
]), L = (e) => F.has(e.tagName) && e.getAttribute("contenteditable") !== "true", B = (e, t) => {
  const r = [], n = /* @__PURE__ */ new Set(), o = (s) => {
    !s || n.has(s) || t.contains(s) && L(s) && (s.closest("ul, ol") || (n.add(s), r.push(s)));
  }, i = (s) => {
    let l = s;
    for (; l && l !== document.body; ) {
      if (l.nodeType === Node.ELEMENT_NODE) {
        const p = l;
        if (L(p)) return p;
        if (p.getAttribute("contenteditable") === "true") break;
      }
      l = l.parentNode;
    }
    return null;
  };
  if (e.collapsed)
    return o(i(e.startContainer)), r;
  const d = document.createTreeWalker(
    t,
    NodeFilter.SHOW_ELEMENT,
    {
      acceptNode: (s) => {
        const l = s;
        if (!L(l) || l.closest("ul, ol")) return NodeFilter.FILTER_SKIP;
        if (typeof e.intersectsNode == "function")
          return e.intersectsNode(l) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
        const p = document.createRange();
        return p.selectNodeContents(l), e.compareBoundaryPoints(Range.END_TO_START, p) > 0 && e.compareBoundaryPoints(Range.START_TO_END, p) < 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
      }
    }
  );
  let c = d.nextNode();
  for (; c; )
    o(c), c = d.nextNode();
  if (r.length === 0 && o(i(e.commonAncestorContainer)), r.length <= 1)
    return r;
  const h = r.filter((s) => !r.some((l) => l !== s && s.contains(l)));
  return h.length > 0 ? h : r;
}, K = (e) => {
  const t = [], r = document.createElement("div"), n = () => {
    const o = r.innerHTML.trim();
    if (!o) return;
    const i = document.createElement("p");
    i.innerHTML = o, t.push(i), r.innerHTML = "";
  };
  if (e.childNodes.forEach((o) => {
    if (o.nodeType === Node.ELEMENT_NODE && ["UL", "OL"].includes(o.tagName)) {
      n();
      return;
    }
    if (o.nodeType === Node.ELEMENT_NODE && o.tagName === "P") {
      n();
      const i = o.innerHTML.trim(), d = document.createElement("p");
      d.innerHTML = i || "<br>", t.push(d);
      return;
    }
    o.nodeType === Node.TEXT_NODE && !(o.textContent || "").trim() || r.appendChild(o.cloneNode(!0));
  }), n(), t.length === 0) {
    const o = document.createElement("p");
    o.innerHTML = "<br>", t.push(o);
  }
  return t;
}, z = () => ({
  name: "checklist",
  // Initialize click handler when plugin is loaded
  init: () => {
    if (!(typeof document > "u" || typeof window > "u")) {
      if (!window.__checklistPluginClickInitialized) {
        window.__checklistPluginClickInitialized = !0;
        const e = (t) => {
          const n = t.target.closest('li[data-type="checklist-item"]');
          if (!n) return;
          const o = n.getBoundingClientRect();
          if (!(t.clientX - o.left < 32)) return;
          t.preventDefault(), t.stopPropagation();
          const c = n.closest("[contenteditable], .rte-content, .editora-content");
          if (c?.getAttribute("contenteditable") === "false" || !!c?.closest('[data-readonly="true"], .editora-editor[readonly], editora-editor[readonly]')) return;
          const s = c?.innerHTML || "", l = n.getAttribute("data-checked") === "true";
          n.setAttribute("data-checked", (!l).toString()), c && (b(c, s), T(c));
        };
        document.addEventListener("click", e);
      }
      if (!window.__checklistPluginKeydownInitialized) {
        window.__checklistPluginKeydownInitialized = !0;
        const e = (t) => {
          if (t.key !== "Enter" || t.shiftKey || t.altKey || t.ctrlKey || t.metaKey || t.defaultPrevented) return;
          const r = window.getSelection();
          if (!r || r.rangeCount === 0) return;
          const n = r.getRangeAt(0), i = A(n.startContainer)?.closest('li[data-type="checklist-item"]');
          if (!i) return;
          const d = i.closest('ul[data-type="checklist"]');
          if (!d) return;
          const c = i.closest("[contenteditable], .rte-content, .editora-content");
          if (!c || c.getAttribute("contenteditable") === "false" || !!c.closest('[data-readonly="true"], .editora-editor[readonly], editora-editor[readonly]')) return;
          t.preventDefault();
          const s = c.innerHTML, l = N(i);
          v(l) ? D(c, d, i) : O(c, i, n), b(c, s), T(c);
        };
        document.addEventListener("keydown", e);
      }
    }
  },
  // Schema definition for checklist nodes
  nodes: {
    checklist: {
      content: "checklistItem+",
      group: "block",
      parseDOM: [{ tag: 'ul[data-type="checklist"]' }],
      toDOM: () => ["ul", { "data-type": "checklist" }, 0]
    },
    checklistItem: {
      content: "paragraph",
      attrs: {
        checked: { default: !1 }
      },
      parseDOM: [
        {
          tag: 'li[data-type="checklist-item"]',
          getAttrs: (e) => ({
            checked: e.getAttribute("data-checked") === "true"
          })
        }
      ],
      toDOM: (e) => [
        "li",
        {
          "data-type": "checklist-item",
          "data-checked": e?.attrs?.checked ? "true" : "false"
        },
        0
      ]
    }
  },
  toolbar: [
    {
      label: "Checklist",
      command: "toggleChecklist",
      icon: '<svg width="24px" height="24px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="#000000"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path fill-rule="evenodd" clip-rule="evenodd" d="M3.75 4.48h-.71L2 3.43l.71-.7.69.68L4.81 2l.71.71-1.77 1.77zM6.99 3h8v1h-8V3zm0 3h8v1h-8V6zm8 3h-8v1h8V9zm-8 3h8v1h-8v-1zM3.04 7.48h.71l1.77-1.77-.71-.7L3.4 6.42l-.69-.69-.71.71 1.04 1.04zm.71 3.01h-.71L2 9.45l.71-.71.69.69 1.41-1.42.71.71-1.77 1.77zm-.71 3.01h.71l1.77-1.77-.71-.71-1.41 1.42-.69-.69-.71.7 1.04 1.05z"></path></g></svg>',
      shortcut: "Mod-Shift-9"
    }
  ],
  commands: {
    toggleChecklist: () => {
      try {
        const e = _();
        if (!e) return !1;
        const t = e.innerHTML, r = () => (b(e, t), T(e), !0), n = I(e);
        if (!n) return !1;
        const o = A(n.startContainer);
        if (!o) return !1;
        const i = o.closest('ul[data-type="checklist"]');
        if (i && e.contains(i)) {
          const a = y(i);
          if (a.length === 0) return !1;
          const f = document.createDocumentFragment();
          let u = null;
          return a.forEach((m, g) => {
            const E = K(m);
            E.forEach((w) => {
              f.appendChild(w), !u && (m.contains(n.startContainer) || g === 0) && (u = w);
            }), !u && g === 0 && E[0] && (u = E[0]);
          }), i.replaceWith(f), u && C(u, e), r();
        }
        const d = o.closest("ul, ol");
        if (d && e.contains(d)) {
          let a;
          if (d.tagName.toLowerCase() === "ul")
            a = d;
          else {
            for (a = document.createElement("ul"); d.firstChild; )
              a.appendChild(d.firstChild);
            d.replaceWith(a);
          }
          a.setAttribute("data-type", "checklist");
          let f = y(a);
          f.length === 0 && (a.appendChild(k("")), f = y(a));
          let u = null;
          f.forEach((g) => {
            g.setAttribute("data-type", "checklist-item"), g.hasAttribute("data-checked") || g.setAttribute("data-checked", "false");
            const E = N(g);
            g.contains(n.startContainer) && (u = E);
          });
          const m = a.querySelector(':scope > li[data-type="checklist-item"] > p');
          return C(u || m || a, e), r();
        }
        const c = B(n, e);
        if (c.length > 1) {
          const a = document.createElement("ul");
          a.setAttribute("data-type", "checklist"), c.forEach((m) => {
            a.appendChild(k(m.innerHTML));
          }), c[0].replaceWith(a), c.slice(1).forEach((m) => {
            m.isConnected && m.remove();
          });
          const u = a.querySelector(':scope > li[data-type="checklist-item"] > p');
          return u && C(u, e), r();
        }
        const h = c[0] || o.closest("p, h1, h2, h3, h4, h5, h6, blockquote, pre");
        if (h && h !== e) {
          const a = document.createElement("ul");
          a.setAttribute("data-type", "checklist");
          const f = k(h.innerHTML);
          a.appendChild(f), h.replaceWith(a);
          const u = f.querySelector(":scope > p");
          return u && C(u, e), r();
        }
        const s = document.createElement("ul");
        s.setAttribute("data-type", "checklist");
        const l = k("");
        s.appendChild(l), n.deleteContents(), n.insertNode(s);
        const p = l.querySelector(":scope > p");
        return p && C(p, e), r();
      } catch (e) {
        return console.error("Failed to toggle checklist:", e), !1;
      }
    }
  },
  keymap: {
    "Mod-Shift-9": "toggleChecklist"
  }
});
export {
  z as ChecklistPlugin
};
