"use client";
import { $getRoot as O, $createLineBreakNode as D, $createTextNode as y, $isElementNode as I, $isDecoratorNode as B, $isParagraphNode as k, $isTextNode as N, $getSelection as J, $isLineBreakNode as V, $createParagraphNode as Y } from "../../lexical/Lexical.prod.js";
import { ListNode as w, ListItemNode as P, $isListNode as $, $createListItemNode as Z, $createListNode as tt, $isListItemNode as j } from "../list/LexicalList.prod.js";
import { HeadingNode as et, QuoteNode as nt, $isHeadingNode as ot, $isQuoteNode as L, $createQuoteNode as rt, $createHeadingNode as st } from "../rich-text/LexicalRichText.prod.js";
import { $findMatchingParent as it } from "../utils/LexicalUtils.prod.js";
import { CodeNode as at, $createCodeNode as R, $isCodeNode as lt } from "../code/LexicalCode.prod.js";
import { LinkNode as ct, $createLinkNode as ft, $isLinkNode as ut, $isAutoLinkNode as dt } from "../link/LexicalLink.prod.js";
function gt(t, e) {
  const r = {};
  for (const s of t) {
    const n = e(s);
    n && (r[n] ? r[n].push(s) : r[n] = [s]);
  }
  return r;
}
function H(t) {
  const e = gt(t, ((r) => r.type));
  return { element: e.element || [], multilineElement: e["multiline-element"] || [], textFormat: e["text-format"] || [], textMatch: e["text-match"] || [] };
}
const v = /[!-/:-@[-`{-~\s]/, pt = /^\s{0,3}$/;
function b(t) {
  if (!k(t)) return !1;
  const e = t.getFirstChild();
  return e == null || t.getChildrenSize() === 1 && N(e) && pt.test(e.getTextContent());
}
function mt(t, e, r, s) {
  for (const n of e) {
    if (!n.export) continue;
    const f = n.export(t, ((o) => C(o, r, s)));
    if (f != null) return f;
  }
  return I(t) ? C(t, r, s) : B(t) ? t.getTextContent() : null;
}
function C(t, e, r, s, n) {
  const f = [], o = t.getChildren();
  s || (s = []), n || (n = []);
  t: for (const a of o) {
    for (const u of r) {
      if (!u.export) continue;
      const c = u.export(a, ((i) => C(i, e, r, s, [...n, ...s])), ((i, g) => F(i, g, e, s, n)));
      if (c != null) {
        f.push(c);
        continue t;
      }
    }
    V(a) ? f.push(`
`) : N(a) ? f.push(F(a, a.getTextContent(), e, s, n)) : I(a) ? f.push(C(a, e, r, s, n)) : B(a) && f.push(a.getTextContent());
  }
  return f.join("");
}
function F(t, e, r, s, n) {
  let f = t.getFormat() === 0 ? e : (function(l) {
    return l.replace(/^\s+|\s+$/g, ((d) => [...d].map(((p) => "&#" + p.codePointAt(0) + ";")).join("")));
  })(e);
  t.hasFormat("code") || (f = f.replace(/([*_`~\\])/g, "\\$1"));
  let o = "", a = "", u = "";
  const c = M(t, !0), i = M(t, !1), g = /* @__PURE__ */ new Set();
  for (const l of r) {
    const d = l.format[0], p = l.tag;
    S(t, d) && !g.has(d) && (g.add(d), S(c, d) && s.find(((m) => m.tag === p)) || (s.push({ format: d, tag: p }), o += p));
  }
  for (let l = 0; l < s.length; l++) {
    const d = S(t, s[l].format), p = S(i, s[l].format);
    if (d && p) continue;
    const m = [...s];
    for (; m.length > l; ) {
      const h = m.pop();
      n && h && n.find(((T) => T.tag === h.tag)) || (h && typeof h.tag == "string" && (d ? p || (u += h.tag) : a += h.tag), s.pop());
    }
    break;
  }
  return f = o + f + u, a + f;
}
function M(t, e) {
  let r = e ? t.getPreviousSibling() : t.getNextSibling();
  if (!r) {
    const s = t.getParentOrThrow();
    s.isInline() && (r = e ? s.getPreviousSibling() : s.getNextSibling());
  }
  for (; r; ) {
    if (I(r)) {
      if (!r.isInline()) break;
      const s = e ? r.getLastDescendant() : r.getFirstDescendant();
      if (N(s)) return s;
      r = e ? r.getPreviousSibling() : r.getNextSibling();
    }
    if (N(r)) return r;
    if (!I(r)) return null;
  }
  return null;
}
function S(t, e) {
  return N(t) && t.hasFormat(e);
}
function ht(t, e) {
  const r = (function(n, f) {
    const o = n.match(f.openTagsRegExp);
    if (o == null) return null;
    for (const a of o) {
      const u = a.replace(/^\s/, ""), c = f.fullMatchRegExpByTag[u];
      if (c == null) continue;
      const i = n.match(c), g = f.transformersByTag[u];
      if (i != null && g != null) {
        if (g.intraword !== !1) return i;
        const { index: l = 0 } = i, d = n[l - 1], p = n[l + i[0].length];
        if ((!d || v.test(d)) && (!p || v.test(p))) return i;
      }
    }
    return null;
  })(t.getTextContent(), e);
  if (!r) return null;
  const s = r.index || 0;
  return { endIndex: s + r[0].length, match: r, startIndex: s, transformer: e.transformersByTag[r[1]] };
}
function E(t) {
  return N(t) && !t.hasFormat("code");
}
function x(t, e, r) {
  let s = ht(t, e), n = (function(o, a) {
    const u = o;
    let c, i, g, l;
    for (const d of a) {
      if (!d.replace || !d.importRegExp) continue;
      const p = u.getTextContent().match(d.importRegExp);
      if (!p) continue;
      const m = p.index || 0, h = d.getEndIndex ? d.getEndIndex(u, p) : m + p[0].length;
      h !== !1 && (c === void 0 || i === void 0 || m < c && h > i) && (c = m, i = h, g = d, l = p);
    }
    return c === void 0 || i === void 0 || g === void 0 || l === void 0 ? null : { endIndex: i, match: l, startIndex: c, transformer: g };
  })(t, r);
  if (s && n && (s.startIndex <= n.startIndex && s.endIndex >= n.endIndex ? n = null : s = null), s) {
    const o = (function(a, u, c, i, g) {
      const l = a.getTextContent();
      let d, p, m;
      if (g[0] === l ? d = a : u === 0 ? [d, p] = a.splitText(c) : [m, d, p] = a.splitText(u, c), d.setTextContent(g[2]), i) for (const h of i.format) d.hasFormat(h) || d.toggleFormat(h);
      return { nodeAfter: p, nodeBefore: m, transformedNode: d };
    })(t, s.startIndex, s.endIndex, s.transformer, s.match);
    E(o.nodeAfter) && x(o.nodeAfter, e, r), E(o.nodeBefore) && x(o.nodeBefore, e, r), E(o.transformedNode) && x(o.transformedNode, e, r);
  } else if (n) {
    const o = (function(a, u, c, i, g) {
      let l, d, p;
      return u === 0 ? [l, d] = a.splitText(c) : [p, l, d] = a.splitText(u, c), i.replace ? { nodeAfter: d, nodeBefore: p, transformedNode: i.replace(l, g) || void 0 } : null;
    })(t, n.startIndex, n.endIndex, n.transformer, n.match);
    if (!o) return;
    E(o.nodeAfter) && x(o.nodeAfter, e, r), E(o.nodeBefore) && x(o.nodeBefore, e, r), E(o.transformedNode) && x(o.transformedNode, e, r);
  }
  const f = t.getTextContent().replace(/\\([*_`~\\])/g, "$1").replace(/&#(\d+);/g, ((o, a) => String.fromCodePoint(a)));
  t.setTextContent(f);
}
function xt(t, e = !1) {
  const r = H(t), s = (function(n) {
    const f = {}, o = {}, a = [], u = "(?<![\\\\])";
    for (const c of n) {
      const { tag: i } = c;
      f[i] = c;
      const g = i.replace(/(\*|\^|\+)/g, "\\$1");
      a.push(g), i.length === 1 ? o[i] = new RegExp(`(?<![\\\\${g}])(${g})((\\\\${g})?.*?[^${g}\\s](\\\\${g})?)((?<!\\\\)|(?<=\\\\\\\\))(${g})(?![\\\\${g}])`) : o[i] = new RegExp(`(?<!\\\\)(${g})((\\\\${g})?.*?[^\\s](\\\\${g})?)((?<!\\\\)|(?<=\\\\\\\\))(${g})(?!\\\\)`);
    }
    return { fullMatchRegExpByTag: o, openTagsRegExp: new RegExp(`${u}(${a.join("|")})`, "g"), transformersByTag: f };
  })(r.textFormat);
  return (n, f) => {
    const o = n.split(`
`), a = o.length, u = f || O();
    u.clear();
    for (let i = 0; i < a; i++) {
      const g = o[i], [l, d] = $t(o, i, r.multilineElement, u);
      l ? i = d : Et(g, u, r.element, s, r.textMatch, e);
    }
    const c = u.getChildren();
    for (const i of c) !e && b(i) && u.getChildrenSize() > 1 && i.remove();
    J() !== null && u.selectStart();
  };
}
function $t(t, e, r, s) {
  for (const n of r) {
    const { handleImportAfterStartMatch: f, regExpEnd: o, regExpStart: a, replace: u } = n, c = t[e].match(a);
    if (!c) continue;
    if (f) {
      const p = f({ lines: t, rootNode: s, startLineIndex: e, startMatch: c, transformer: n });
      if (p === null) continue;
      if (p) return p;
    }
    const i = typeof o == "object" && "regExp" in o ? o.regExp : o, g = o && typeof o == "object" && "optional" in o ? o.optional : !o;
    let l = e;
    const d = t.length;
    for (; l < d; ) {
      const p = i ? t[l].match(i) : null;
      if (!p && (!g || g && l < d - 1)) {
        l++;
        continue;
      }
      if (p && e === l && p.index === c.index) {
        l++;
        continue;
      }
      const m = [];
      if (p && e === l) m.push(t[e].slice(c[0].length, -p[0].length));
      else for (let h = e; h <= l; h++) if (h === e) {
        const T = t[h].slice(c[0].length);
        m.push(T);
      } else if (h === l && p) {
        const T = t[h].slice(0, -p[0].length);
        m.push(T);
      } else m.push(t[h]);
      if (u(s, null, c, p, m, !0) !== !1) return [!0, l];
      break;
    }
  }
  return [!1, e];
}
function Et(t, e, r, s, n, f) {
  const o = y(t), a = Y();
  a.append(o), e.append(a);
  for (const { regExp: u, replace: c } of r) {
    const i = t.match(u);
    if (i && (o.setTextContent(t.slice(i[0].length)), c(a, [o], i, !0) !== !1)) break;
  }
  if (x(o, s, n), a.isAttached() && t.length > 0) {
    const u = a.getPreviousSibling();
    if (!f && (k(u) || L(u) || $(u))) {
      let c = u;
      if ($(u)) {
        const i = u.getLastDescendant();
        c = i == null ? null : it(i, j);
      }
      c != null && c.getTextContentSize() > 0 && (c.splice(c.getChildrenSize(), 0, [D(), ...a.getChildren()]), a.remove());
    }
  }
}
const U = /^(\s*)(\d{1,})\.\s/, z = /^(\s*)[-*+]\s/, Nt = /^(\s*)(?:-\s)?\s?(\[(\s|x)?\])\s/i, _ = /^(#{1,6})\s/, Q = /^>\s/, G = /^[ \t]*```(\w+)?/, K = /[ \t]*```$/, Tt = /^[ \t]*```[^`]+(?:(?:`{1,2}|`{4,})[^`]+)*```(?:[^`]|$)/, Rt = /^(?:\|)(.+)(?:\|)\s?$/, St = /^(\| ?:?-*:? ?)+\|\s?$/, X = (t) => (e, r, s, n) => {
  const f = t(s);
  f.append(...r), e.replace(f), n || f.select(0, 0);
}, W = (t) => (e, r, s, n) => {
  const f = e.getPreviousSibling(), o = e.getNextSibling(), a = Z(t === "check" ? s[3] === "x" : void 0);
  if ($(o) && o.getListType() === t) {
    const c = o.getFirstChild();
    c !== null ? c.insertBefore(a) : o.append(a), e.remove();
  } else if ($(f) && f.getListType() === t) f.append(a), e.remove();
  else {
    const c = tt(t, t === "number" ? Number(s[2]) : void 0);
    c.append(a), e.replace(c);
  }
  a.append(...r), n || a.select(0, 0);
  const u = (function(c) {
    const i = c.match(/\t/g), g = c.match(/ /g);
    let l = 0;
    return i && (l += i.length), g && (l += Math.floor(g.length / 4)), l;
  })(s[1]);
  u && a.setIndent(u);
}, A = (t, e, r) => {
  const s = [], n = t.getChildren();
  let f = 0;
  for (const o of n) if (j(o)) {
    if (o.getChildrenSize() === 1) {
      const i = o.getFirstChild();
      if ($(i)) {
        s.push(A(i, e, r + 1));
        continue;
      }
    }
    const a = " ".repeat(4 * r), u = t.getListType(), c = u === "number" ? `${t.getStart() + f}. ` : u === "check" ? `- [${o.getChecked() ? "x" : " "}] ` : "- ";
    s.push(a + c + e(o)), f++;
  }
  return s.join(`
`);
}, It = { dependencies: [et], export: (t, e) => {
  if (!ot(t)) return null;
  const r = Number(t.getTag().slice(1));
  return "#".repeat(r) + " " + e(t);
}, regExp: _, replace: X(((t) => {
  const e = "h" + t[1].length;
  return st(e);
})), type: "element" }, Ct = { dependencies: [nt], export: (t, e) => {
  if (!L(t)) return null;
  const r = e(t).split(`
`), s = [];
  for (const n of r) s.push("> " + n);
  return s.join(`
`);
}, regExp: Q, replace: (t, e, r, s) => {
  if (s) {
    const f = t.getPreviousSibling();
    if (L(f)) return f.splice(f.getChildrenSize(), 0, [D(), ...e]), void t.remove();
  }
  const n = rt();
  n.append(...e), t.replace(n), s || n.select(0, 0);
}, type: "element" }, Lt = { dependencies: [at], export: (t) => {
  if (!lt(t)) return null;
  const e = t.getTextContent();
  return "```" + (t.getLanguage() || "") + (e ? `
` + e : "") + "\n```";
}, regExpEnd: { optional: !0, regExp: K }, regExpStart: G, replace: (t, e, r, s, n, f) => {
  let o, a;
  if (!e && n) {
    if (n.length === 1) s ? (o = R(), a = r[1] + n[0]) : (o = R(r[1]), a = n[0].startsWith(" ") ? n[0].slice(1) : n[0]);
    else {
      if (o = R(r[1]), n[0].trim().length === 0) for (; n.length > 0 && !n[0].length; ) n.shift();
      else n[0] = n[0].startsWith(" ") ? n[0].slice(1) : n[0];
      for (; n.length > 0 && !n[n.length - 1].length; ) n.pop();
      a = n.join(`
`);
    }
    const u = y(a);
    o.append(u), t.append(o);
  } else e && X(((u) => R(u ? u[1] : void 0)))(t, e, r, f);
}, type: "multiline-element" }, bt = { dependencies: [w, P], export: (t, e) => $(t) ? A(t, e, 0) : null, regExp: z, replace: W("bullet"), type: "element" }, _t = { dependencies: [w, P], export: (t, e) => $(t) ? A(t, e, 0) : null, regExp: U, replace: W("number"), type: "element" }, yt = { format: ["code"], tag: "`", type: "text-format" }, At = { format: ["highlight"], tag: "==", type: "text-format" }, vt = { format: ["bold", "italic"], tag: "***", type: "text-format" }, Ft = { format: ["bold", "italic"], intraword: !1, tag: "___", type: "text-format" }, Mt = { format: ["bold"], tag: "**", type: "text-format" }, Ot = { format: ["bold"], intraword: !1, tag: "__", type: "text-format" }, Dt = { format: ["strikethrough"], tag: "~~", type: "text-format" }, Bt = { format: ["italic"], tag: "*", type: "text-format" }, kt = { format: ["italic"], intraword: !1, tag: "_", type: "text-format" }, wt = { dependencies: [ct], export: (t, e, r) => {
  if (!ut(t) || dt(t)) return null;
  const s = t.getTitle(), n = e(t);
  return s ? `[${n}](${t.getURL()} "${s}")` : `[${n}](${t.getURL()})`;
}, importRegExp: /(?:\[([^[]+)\])(?:\((?:([^()\s]+)(?:\s"((?:[^"]*\\")*[^"]*)"\s*)?)\))/, regExp: /(?:\[([^[]+)\])(?:\((?:([^()\s]+)(?:\s"((?:[^"]*\\")*[^"]*)"\s*)?)\))$/, replace: (t, e) => {
  const [, r, s, n] = e, f = ft(s, { title: n }), o = y(r);
  return o.setFormat(t.getFormat()), f.append(o), t.replace(f), o;
}, trigger: ")", type: "text-match" }, Pt = [It, Ct, bt, _t], jt = [Lt], Ht = [yt, vt, Ft, Mt, Ot, At, Bt, kt, Dt], Ut = [wt], q = [...Pt, ...jt, ...Ht, ...Ut];
function qt(t, e = q, r, s = !1, n = !1) {
  const f = s ? t : (function(o, a = !1) {
    const u = o.split(`
`);
    let c = !1;
    const i = [];
    for (let g = 0; g < u.length; g++) {
      const l = u[g], d = i[i.length - 1];
      Tt.test(l) ? i.push(l) : G.test(l) || K.test(l) ? (c = !c, i.push(l)) : c || l === "" || d === "" || !d || _.test(d) || _.test(l) || Q.test(l) || U.test(l) || z.test(l) || Nt.test(l) || Rt.test(l) || St.test(l) || !a ? i.push(l) : i[i.length - 1] = d + l;
    }
    return i.join(`
`);
  })(t, n);
  return xt(e, s)(f, r);
}
function Jt(t = q, e, r = !1) {
  return (function(n, f = !1) {
    const o = H(n), a = [...o.multilineElement, ...o.element], u = !f, c = o.textFormat.filter(((i) => i.format.length === 1)).sort(((i, g) => Number(i.format.includes("code")) - Number(g.format.includes("code"))));
    return (i) => {
      const g = [], l = (i || O()).getChildren();
      for (let d = 0; d < l.length; d++) {
        const p = l[d], m = mt(p, a, c, o.textMatch);
        m != null && g.push(u && d > 0 && !b(p) && !b(l[d - 1]) ? `
`.concat(m) : m);
      }
      return g.join(`
`);
    };
  })(t, r)(e);
}
export {
  qt as $convertFromMarkdownString,
  Jt as $convertToMarkdownString,
  vt as BOLD_ITALIC_STAR,
  Ft as BOLD_ITALIC_UNDERSCORE,
  Mt as BOLD_STAR,
  Ot as BOLD_UNDERSCORE,
  Lt as CODE,
  Pt as ELEMENT_TRANSFORMERS,
  It as HEADING,
  At as HIGHLIGHT,
  yt as INLINE_CODE,
  Bt as ITALIC_STAR,
  kt as ITALIC_UNDERSCORE,
  wt as LINK,
  jt as MULTILINE_ELEMENT_TRANSFORMERS,
  _t as ORDERED_LIST,
  Ct as QUOTE,
  Dt as STRIKETHROUGH,
  Ht as TEXT_FORMAT_TRANSFORMERS,
  Ut as TEXT_MATCH_TRANSFORMERS,
  q as TRANSFORMERS,
  bt as UNORDERED_LIST
};
