import { jsx as t, jsxs as R, Fragment as H } from "react/jsx-runtime";
import { AutoFocusPlugin as Q } from "@lexical/react/LexicalAutoFocusPlugin";
import { useLexicalComposerContext as G } from "@lexical/react/LexicalComposerContext";
import { LexicalErrorBoundary as ee } from "@lexical/react/LexicalErrorBoundary";
import { LexicalNestedComposer as te } from "@lexical/react/LexicalNestedComposer";
import { RichTextPlugin as ne } from "@lexical/react/LexicalRichTextPlugin";
import { useLexicalNodeSelection as oe } from "@lexical/react/useLexicalNodeSelection";
import { $findMatchingParent as X, mergeRegister as O } from "@lexical/utils";
import { $getSelection as y, $isRangeSelection as U, SELECTION_CHANGE_COMMAND as K, COMMAND_PRIORITY_CRITICAL as ie, COMMAND_PRIORITY_LOW as M, KEY_ESCAPE_COMMAND as Z, COMMAND_PRIORITY_HIGH as se, $isTextNode as le, FORMAT_TEXT_COMMAND as _, $isNodeSelection as $, $getNodeByKey as q, $setSelection as j, CLICK_COMMAND as re, DRAGSTART_COMMAND as ae, KEY_DELETE_COMMAND as ce, KEY_BACKSPACE_COMMAND as ue, KEY_ENTER_COMMAND as de } from "lexical";
import { useState as C, useCallback as D, useEffect as x, useRef as A, Suspense as me } from "react";
import { g as z, s as pe, u as fe, $ as ge, L as he, P as Ce, a as Ee, T as ve, S as Ne, D as be, B as Le } from "./main-B6U4rLPa.js";
import { $isLinkNode as P, $isAutoLinkNode as Se, TOGGLE_LINK_COMMAND as Y } from "@lexical/link";
import { createPortal as J } from "react-dom";
import { $isCodeHighlightNode as ke } from "@lexical/code";
const Ie = 10, Re = 5;
function V(e, n, s, l = Ie, c = Re) {
  const u = s.parentElement;
  if (e === null || !u) {
    n.style.opacity = "0", n.style.transform = "translate(-10000px, -10000px)";
    return;
  }
  const r = n.getBoundingClientRect(), d = s.getBoundingClientRect(), p = u.getBoundingClientRect();
  let f = e.top - l, i = e.left - c;
  f < p.top && (f += r.height + e.height + l * 2), i + r.width > p.right && (i = p.right - r.width - c), f -= d.top, i -= d.left, n.style.opacity = "1", n.style.transform = `translate(${i}px, ${f}px)`;
}
function xe({
  editor: e,
  isLink: n,
  setIsLink: s,
  anchorElem: l
}) {
  const c = A(null), u = A(null), [r, d] = C(""), [p, f] = C(""), [i, S] = C(!1), [N, E] = C(null), g = D(() => {
    const o = y();
    if (U(o)) {
      const I = z(o), F = I.getParent();
      P(F) ? d(F.getURL()) : P(I) ? d(I.getURL()) : d("");
    }
    const a = c.current, v = window.getSelection(), b = document.activeElement;
    if (a === null)
      return;
    const m = e.getRootElement();
    if (o !== null && v !== null && m !== null && m.contains(v.anchorNode) && e.isEditable()) {
      const I = v.focusNode?.parentElement?.getBoundingClientRect();
      I && (I.y += 40, V(I, a, l)), E(o);
    } else (!b || b.className !== "link-input") && (m !== null && V(null, a, l), E(null), S(!1), d(""));
    return !0;
  }, [l, e]);
  x(() => {
    const o = l.parentElement, a = () => {
      e.getEditorState().read(() => {
        g();
      });
    };
    return window.addEventListener("resize", a), o && o.addEventListener("scroll", a), () => {
      window.removeEventListener("resize", a), o && o.removeEventListener("scroll", a);
    };
  }, [l.parentElement, e, g]), x(() => O(
    e.registerUpdateListener(({ editorState: o }) => {
      o.read(() => {
        g();
      });
    }),
    e.registerCommand(
      K,
      () => (g(), !0),
      M
    ),
    e.registerCommand(
      Z,
      () => n ? (s(!1), !0) : !1,
      se
    )
  ), [e, g, s, n]), x(() => {
    e.getEditorState().read(() => {
      g();
    });
  }, [e, g]), x(() => {
    i && u.current && u.current.focus();
  }, [i]);
  const h = (o) => {
    o.key === "Enter" ? (o.preventDefault(), T()) : o.key === "Escape" && (o.preventDefault(), S(!1));
  }, T = () => {
    N !== null && (r !== "" && e.dispatchCommand(Y, pe(p)), S(!1));
  };
  return /* @__PURE__ */ t("div", { ref: c, className: "link-editor", children: n ? i ? /* @__PURE__ */ R(H, { children: [
    /* @__PURE__ */ t(
      "input",
      {
        ref: u,
        className: "link-input",
        value: p,
        onChange: (o) => {
          f(o.target.value);
        },
        onKeyDown: (o) => {
          h(o);
        }
      }
    ),
    /* @__PURE__ */ R("div", { children: [
      /* @__PURE__ */ t(
        "div",
        {
          className: "link-cancel",
          role: "button",
          tabIndex: 0,
          onMouseDown: (o) => o.preventDefault(),
          onClick: () => {
            S(!1);
          }
        }
      ),
      /* @__PURE__ */ t(
        "div",
        {
          className: "link-confirm",
          role: "button",
          tabIndex: 0,
          onMouseDown: (o) => o.preventDefault(),
          onClick: T
        }
      )
    ] })
  ] }) : /* @__PURE__ */ R("div", { className: "link-view", children: [
    /* @__PURE__ */ t("a", { href: r, target: "_blank", rel: "noopener noreferrer", children: r }),
    /* @__PURE__ */ t(
      "div",
      {
        className: "link-edit",
        role: "button",
        tabIndex: 0,
        onMouseDown: (o) => o.preventDefault(),
        onClick: () => {
          f(r), S(!0);
        }
      }
    ),
    /* @__PURE__ */ t(
      "div",
      {
        className: "link-trash",
        role: "button",
        tabIndex: 0,
        onMouseDown: (o) => o.preventDefault(),
        onClick: () => {
          e.dispatchCommand(Y, null);
        }
      }
    )
  ] }) : null });
}
function Te(e, n) {
  const [s, l] = C(e), [c, u] = C(!1), r = D(() => {
    const d = y();
    if (U(d)) {
      const p = z(d), f = X(p, P), i = X(p, Se);
      f != null && i == null ? u(!0) : u(!1);
    }
  }, []);
  return x(() => O(
    e.registerUpdateListener(({ editorState: d }) => {
      d.read(() => {
        r();
      });
    }),
    e.registerCommand(
      K,
      (d, p) => (r(), l(p), !1),
      ie
    )
  ), [e, r]), J(
    /* @__PURE__ */ t(
      xe,
      {
        editor: s,
        isLink: c,
        anchorElem: n,
        setIsLink: u
      }
    ),
    n
  );
}
function we({
  anchorElem: e = document.body
}) {
  const [n] = G();
  return Te(n, e);
}
function Me(e, n) {
  const s = e.getRangeAt(0);
  let l;
  if (e.anchorNode === n) {
    let c = n;
    for (; c.firstElementChild != null; )
      c = c.firstElementChild;
    l = c.getBoundingClientRect();
  } else
    l = s.getBoundingClientRect();
  return l;
}
const Fe = 10, De = 5;
function _e(e, n, s, l = Fe, c = De) {
  const u = s.parentElement;
  if (e === null || !u) {
    n.style.opacity = "0", n.style.transform = "translate(-10000px, -10000px)";
    return;
  }
  const r = n.getBoundingClientRect(), d = s.getBoundingClientRect(), p = u.getBoundingClientRect();
  let f = e.top - r.height - l, i = e.left - c;
  f < p.top && (f += r.height + e.height + l * 2), i + r.width > p.right && (i = p.right - r.width - c), f -= d.top, i -= d.left, n.style.opacity = "1", n.style.transform = `translate(${i}px, ${f}px)`;
}
function ye({
  editor: e,
  anchorElem: n,
  isLink: s,
  isBold: l,
  isItalic: c,
  isUnderline: u,
  isCode: r,
  isStrikethrough: d,
  isSubscript: p,
  isSuperscript: f
}) {
  const i = A(null), S = D(() => {
    s ? e.dispatchCommand(Y, null) : e.dispatchCommand(Y, "https://");
  }, [e, s]), N = 5;
  let E = { x: 0, y: 0 };
  function g(a) {
    E = { x: a.clientX, y: a.clientY };
  }
  function h(a) {
    i?.current && (a.buttons === 1 || a.buttons === 3) && Math.sqrt(
      Math.pow(a.clientX - E.x, 2) + Math.pow(a.clientY - E.y, 2)
    ) > N && (i.current.style.pointerEvents = "none");
  }
  function T(a) {
    i?.current && (i.current.style.pointerEvents = "auto");
  }
  x(() => {
    if (i?.current)
      return document.addEventListener("mousedown", g), document.addEventListener("mousemove", h), document.addEventListener("mouseup", T), () => {
        document.removeEventListener("mousedown", g), document.removeEventListener("mousemove", h), document.removeEventListener("mouseup", T);
      };
  }, [i]);
  const o = D(() => {
    const a = y(), v = i.current, b = window.getSelection();
    if (v === null)
      return;
    const m = e.getRootElement();
    if (a !== null && b !== null && !b.isCollapsed && m !== null && m.contains(b.anchorNode)) {
      const I = Me(b, m);
      _e(I, v, n);
    }
  }, [e, n]);
  return x(() => {
    const a = n.parentElement, v = () => {
      e.getEditorState().read(() => {
        o();
      });
    };
    return window.addEventListener("resize", v), a && a.addEventListener("scroll", v), () => {
      window.removeEventListener("resize", v), a && a.removeEventListener("scroll", v);
    };
  }, [e, o, n]), x(() => (e.getEditorState().read(() => {
    o();
  }), O(
    e.registerUpdateListener(({ editorState: a }) => {
      a.read(() => {
        o();
      });
    }),
    e.registerCommand(
      K,
      () => (o(), !1),
      M
    )
  )), [e, o]), /* @__PURE__ */ t("div", { ref: i, className: "floating-text-format-popup", children: e.isEditable() && /* @__PURE__ */ R(H, { children: [
    /* @__PURE__ */ t(
      "button",
      {
        onClick: () => {
          e.dispatchCommand(_, "bold");
        },
        className: "popup-item spaced " + (l ? "active" : ""),
        "aria-label": "Format text as bold",
        children: /* @__PURE__ */ t("i", { className: "format bold" })
      }
    ),
    /* @__PURE__ */ t(
      "button",
      {
        onClick: () => {
          e.dispatchCommand(_, "italic");
        },
        className: "popup-item spaced " + (c ? "active" : ""),
        "aria-label": "Format text as italics",
        children: /* @__PURE__ */ t("i", { className: "format italic" })
      }
    ),
    /* @__PURE__ */ t(
      "button",
      {
        onClick: () => {
          e.dispatchCommand(_, "underline");
        },
        className: "popup-item spaced " + (u ? "active" : ""),
        "aria-label": "Format text to underlined",
        children: /* @__PURE__ */ t("i", { className: "format underline" })
      }
    ),
    /* @__PURE__ */ t(
      "button",
      {
        onClick: () => {
          e.dispatchCommand(_, "strikethrough");
        },
        className: "popup-item spaced " + (d ? "active" : ""),
        "aria-label": "Format text with a strikethrough",
        children: /* @__PURE__ */ t("i", { className: "format strikethrough" })
      }
    ),
    /* @__PURE__ */ t(
      "button",
      {
        onClick: () => {
          e.dispatchCommand(_, "subscript");
        },
        className: "popup-item spaced " + (p ? "active" : ""),
        title: "Subscript",
        "aria-label": "Format Subscript",
        children: /* @__PURE__ */ t("i", { className: "format subscript" })
      }
    ),
    /* @__PURE__ */ t(
      "button",
      {
        onClick: () => {
          e.dispatchCommand(_, "superscript");
        },
        className: "popup-item spaced " + (f ? "active" : ""),
        title: "Superscript",
        "aria-label": "Format Superscript",
        children: /* @__PURE__ */ t("i", { className: "format superscript" })
      }
    ),
    /* @__PURE__ */ t(
      "button",
      {
        onClick: () => {
          e.dispatchCommand(_, "code");
        },
        className: "popup-item spaced " + (r ? "active" : ""),
        "aria-label": "Insert code block",
        children: /* @__PURE__ */ t("i", { className: "format code" })
      }
    ),
    /* @__PURE__ */ t(
      "button",
      {
        onClick: S,
        className: "popup-item spaced " + (s ? "active" : ""),
        "aria-label": "Insert link",
        children: /* @__PURE__ */ t("i", { className: "format link" })
      }
    )
  ] }) });
}
function Ae(e, n) {
  const [s, l] = C(!1), [c, u] = C(!1), [r, d] = C(!1), [p, f] = C(!1), [i, S] = C(!1), [N, E] = C(!1), [g, h] = C(!1), [T, o] = C(!1), [a, v] = C(!1), b = D(() => {
    e.getEditorState().read(() => {
      if (e.isComposing())
        return;
      const m = y(), I = window.getSelection(), F = e.getRootElement();
      if (I !== null && (!U(m) || F === null || !F.contains(I.anchorNode))) {
        l(!1);
        return;
      }
      if (!U(m))
        return;
      const k = z(m);
      d(m.hasFormat("bold")), f(m.hasFormat("italic")), S(m.hasFormat("underline")), E(m.hasFormat("strikethrough")), h(m.hasFormat("subscript")), o(m.hasFormat("superscript")), v(m.hasFormat("code"));
      const w = k.getParent();
      P(w) || P(k) ? u(!0) : u(!1), !ke(m.anchor.getNode()) && m.getTextContent() !== "" ? l(le(k)) : l(!1);
      const L = m.getTextContent().replace(/\n/g, "");
      if (!m.isCollapsed() && L === "") {
        l(!1);
        return;
      }
    });
  }, [e]);
  return x(() => (document.addEventListener("selectionchange", b), () => {
    document.removeEventListener("selectionchange", b);
  }), [b]), x(() => O(
    e.registerUpdateListener(() => {
      b();
    }),
    e.registerRootListener(() => {
      e.getRootElement() === null && l(!1);
    })
  ), [e, b]), !s || c ? null : J(
    /* @__PURE__ */ t(
      ye,
      {
        editor: e,
        anchorElem: n,
        isLink: c,
        isBold: r,
        isItalic: p,
        isStrikethrough: N,
        isSubscript: g,
        isSuperscript: T,
        isUnderline: i,
        isCode: a
      }
    ),
    n
  );
}
function Pe({
  anchorElem: e = document.body
}) {
  const [n] = G();
  return Ae(n, e);
}
const W = /* @__PURE__ */ new Set();
function Oe(e) {
  if (!W.has(e))
    throw new Promise((n) => {
      const s = new Image();
      s.src = e, s.onload = () => {
        W.add(e), n(null);
      };
    });
}
function Be({
  altText: e,
  className: n,
  imageRef: s,
  src: l,
  width: c,
  height: u,
  position: r
}) {
  return Oe(l), /* @__PURE__ */ t(
    "img",
    {
      className: n || void 0,
      src: l,
      alt: e,
      ref: s,
      "data-position": r,
      style: {
        height: u,
        width: c,
        display: "block"
      },
      draggable: "false"
    }
  );
}
function $e({ activeEditor: e, nodeKey: n, onClose: s }) {
  const c = e.getEditorState().read(() => q(n)), [u, r] = C(c.getAltText()), [d, p] = C(c.getShowCaption()), [f, i] = C(c.getPosition()), S = (g) => {
    p(g.target.checked);
  }, N = (g) => {
    i(g.target.value);
  }, E = () => {
    const g = { altText: u, showCaption: d, position: f };
    c && e.update(() => {
      c.update(g);
    }), s();
  };
  return /* @__PURE__ */ R(H, { children: [
    /* @__PURE__ */ t("div", { style: { marginBottom: "1em" }, children: /* @__PURE__ */ t(
      ve,
      {
        label: "Alt Text",
        placeholder: "Descriptive alternative text",
        onChange: r,
        value: u,
        "data-test-id": "image-modal-alt-text-input"
      }
    ) }),
    /* @__PURE__ */ R(
      Ne,
      {
        style: { marginBottom: "1em", width: "208px" },
        value: f,
        label: "Position",
        name: "position",
        id: "position-select",
        onChange: N,
        children: [
          /* @__PURE__ */ t("option", { value: "left", children: "Left" }),
          /* @__PURE__ */ t("option", { value: "right", children: "Right" }),
          /* @__PURE__ */ t("option", { value: "full", children: "Full Width" })
        ]
      }
    ),
    /* @__PURE__ */ R("div", { className: "Input__wrapper", children: [
      /* @__PURE__ */ t(
        "input",
        {
          id: "caption",
          type: "checkbox",
          checked: d,
          onChange: S
        }
      ),
      /* @__PURE__ */ t("label", { htmlFor: "caption", children: "Show Caption" })
    ] }),
    /* @__PURE__ */ t(be, { children: /* @__PURE__ */ t(
      Le,
      {
        "data-test-id": "image-modal-file-upload-btn",
        onClick: () => E(),
        children: "Confirm"
      }
    ) })
  ] });
}
function et({
  src: e,
  altText: n,
  nodeKey: s,
  width: l,
  height: c,
  showCaption: u,
  caption: r,
  position: d
}) {
  const [p, f] = fe(), i = A(null), S = A(null), [N, E, g] = oe(s), [h] = G(), [T, o] = C(null), a = A(null), v = D(
    (k) => {
      if (N && $(y())) {
        k.preventDefault();
        const L = q(s);
        ge(L) && L?.remove(), E(!1);
      }
      return !1;
    },
    [N, s, E]
  ), b = D(
    (k) => {
      const w = y(), L = S.current;
      if (N && $(w) && w.getNodes().length === 1) {
        if (u)
          return j(null), k.preventDefault(), r.focus(), !0;
        if (L !== null && L !== document.activeElement)
          return k.preventDefault(), L.focus(), !0;
      }
      return !1;
    },
    [r, N, u]
  ), m = D(
    (k) => a.current === r || S.current === k.target ? (j(null), h.update(() => {
      E(!0);
      const w = h.getRootElement();
      w !== null && w.focus();
    }), !0) : !1,
    [r, h, E]
  );
  x(() => {
    let k = !0;
    const w = O(
      h.registerUpdateListener(({ editorState: L }) => {
        k && o(L.read(() => y()));
      }),
      h.registerCommand(
        K,
        (L, B) => (a.current = B, !1),
        M
      ),
      h.registerCommand(
        re,
        (L) => {
          const B = L;
          return B.target === i.current ? (B.shiftKey ? E(!N) : (g(), E(!0)), !0) : !1;
        },
        M
      ),
      h.registerCommand(
        ae,
        (L) => L.target === i.current ? (L.preventDefault(), !0) : !1,
        M
      ),
      h.registerCommand(
        ce,
        v,
        M
      ),
      h.registerCommand(
        ue,
        v,
        M
      ),
      h.registerCommand(de, b, M),
      h.registerCommand(Z, m, M)
    );
    return () => {
      k = !1, w();
    };
  }, [
    g,
    h,
    N,
    s,
    v,
    b,
    m,
    E
  ]);
  const I = N && $(T), F = N;
  return /* @__PURE__ */ R(me, { fallback: null, children: [
    /* @__PURE__ */ R(H, { children: [
      /* @__PURE__ */ R("div", { draggable: I, children: [
        F && /* @__PURE__ */ t(
          "button",
          {
            className: "image-edit-button",
            ref: S,
            onClick: () => {
              f("Update Inline Image", (k) => /* @__PURE__ */ t(
                $e,
                {
                  activeEditor: h,
                  nodeKey: s,
                  onClose: k
                }
              ));
            },
            children: "Edit"
          }
        ),
        /* @__PURE__ */ t(
          Be,
          {
            className: F ? `focused ${$(T) ? "draggable" : ""}` : null,
            src: e,
            altText: n,
            imageRef: i,
            width: l,
            height: c,
            position: d
          }
        )
      ] }),
      u && /* @__PURE__ */ t("div", { className: "image-caption-container", children: /* @__PURE__ */ R(te, { initialEditor: r, children: [
        /* @__PURE__ */ t(Q, {}),
        /* @__PURE__ */ t(he, {}),
        /* @__PURE__ */ t(we, {}),
        /* @__PURE__ */ t(Pe, {}),
        /* @__PURE__ */ t(
          ne,
          {
            contentEditable: /* @__PURE__ */ t(Ee, { className: "InlineImageNode__contentEditable" }),
            placeholder: /* @__PURE__ */ t(Ce, { className: "InlineImageNode__placeholder", children: "Enter a caption..." }),
            ErrorBoundary: ee
          }
        )
      ] }) })
    ] }),
    p
  ] });
}
export {
  $e as UpdateInlineImageDialog,
  et as default
};
