import { jsxs as I, jsx as o, Fragment as V } from "react/jsx-runtime";
import { useMemo as re, useState as b, useCallback as v, useContext as le, useRef as ye, useEffect as x } from "react";
import { useTranslation as U } from "react-i18next";
import { useLexicalComposerContext as z } from "@lexical/react/LexicalComposerContext";
import { Menu as S, Flex as te, Stack as De, Button as H, Box as Oe, LoadingOverlay as Ae } from "@mantine/core";
import { $getNodeByKey as O, COMMAND_PRIORITY_LOW as Ne, $setSelection as xe } from "lexical";
import { x as Se, A as G, K as Te, H as T, y as se, m as de, z as ce, B as A, N as me, D as Ee, F as Pe, o as Me, C as ue, G as ke, J as Le, L as $, P as Ue, Q as ze, S as _e, U as Re, V as We, W as Fe, R as je, k as oe, O as He, j as ne, X as ie, n as $e } from "./layers.0_o7xyFB.js";
import { AttachmentsGalleryModal as ge, showErrorNotification as Be } from "@layers-app/shared";
import { useLexicalEditable as Ve } from "@lexical/react/useLexicalEditable";
import { useDisclosure as B } from "@mantine/hooks";
import "@lexical/react/LexicalDecoratorBlockNode";
import "@lexical/utils";
import "@lexical/mark";
import "@lexical/code";
import "@lexical/selection";
import "react-dom";
import "@lexical/react/LexicalErrorBoundary";
import "@lexical/react/LexicalBlockWithAlignableContents";
import "@mantine/notifications";
function Ge(e, n) {
  const t = document.createElement("a");
  t.href = e, t.download = n, t.rel = "noopener", document.body.appendChild(t), t.click(), t.remove();
}
function X(e) {
  try {
    const t = new URL(e, window.location.origin).pathname.split("/").pop() || "image";
    return t.includes(".") ? t : `${t}.png`;
  } catch {
    return "image";
  }
}
async function J(e, n) {
  const t = await fetch(e);
  if (!t.ok)
    throw new Error("fetch failed");
  const a = await t.blob(), l = URL.createObjectURL(a);
  try {
    Ge(l, n);
  } finally {
    setTimeout(() => URL.revokeObjectURL(l), 0);
  }
}
function pe({
  opened: e,
  onOpenChange: n,
  t,
  onDownload: a,
  onDelete: l
}) {
  return /* @__PURE__ */ I(
    S,
    {
      opened: e,
      onChange: n,
      transitionProps: Se,
      shadow: "md",
      position: "bottom-start",
      offset: 4,
      withinPortal: !0,
      closeOnItemClick: !0,
      children: [
        /* @__PURE__ */ o(S.Target, { children: /* @__PURE__ */ o(
          G,
          {
            label: t("editor.toolbar.more"),
            icon: Te,
            iconColor: "var(--mantine-color-gray-text)",
            "aria-label": t("editor.toolbar.more")
          }
        ) }),
        /* @__PURE__ */ I(S.Dropdown, { p: 4, w: 164, onMouseDown: (r) => r.preventDefault(), children: [
          /* @__PURE__ */ o(
            S.Item,
            {
              leftSection: /* @__PURE__ */ o(te, { align: "center", justify: "center", c: "gray.6", children: /* @__PURE__ */ o(T, { icon: se, size: 16 }) }),
              onClick: (r) => {
                r.stopPropagation(), a();
              },
              children: t("editor.gallery.download")
            }
          ),
          /* @__PURE__ */ o(
            S.Item,
            {
              color: "red",
              leftSection: /* @__PURE__ */ o(te, { align: "center", justify: "center", c: "red.6", children: /* @__PURE__ */ o(T, { icon: de, size: 16 }) }),
              onClick: (r) => {
                r.stopPropagation(), l();
              },
              children: t("editor.contextMenu.delete")
            }
          )
        ] })
      ]
    }
  );
}
const he = ({
  t: e,
  src: n,
  setShown: t,
  id: a
}) => {
  const [l, { open: r, close: m }] = B(!1), d = re(() => [
    {
      id: !a || a === "0" ? "" : a,
      Url: n ?? "",
      contentType: "image/*",
      originalFileName: "",
      fileSize: 0,
      storageType: "",
      storagePath: "",
      fileName: "",
      parentType: "",
      parentId: "",
      ownerId: "",
      createdAt: /* @__PURE__ */ new Date(),
      updatedAt: /* @__PURE__ */ new Date(),
      version: 0,
      deleted: !1,
      deletedAt: /* @__PURE__ */ new Date()
    }
  ], [n, a]);
  return /* @__PURE__ */ I(V, { children: [
    /* @__PURE__ */ o(
      ge,
      {
        opened: l,
        onOpenChange: (g) => {
          g ? r() : m();
        },
        attachments: d
      }
    ),
    /* @__PURE__ */ o(
      G,
      {
        label: e("editor.image.preview"),
        icon: ce,
        iconColor: "var(--mantine-color-gray-text)",
        "aria-label": e("editor.image.preview"),
        onClick: () => {
          t(!1), r();
        }
      }
    )
  ] });
}, Xe = ({
  nodeKey: e,
  src: n
}) => {
  const [t] = z(), a = Ve(), [l, r] = b(!1), [m, d] = b(!1), { t: u } = U(), g = v(() => {
    t.update(() => {
      const f = O(e);
      A(f) && f.remove();
    });
  }, [t, e]), C = v(async () => {
    if (n)
      try {
        await J(n, X(n));
      } catch {
      }
  }, [n]);
  return /* @__PURE__ */ I(
    "div",
    {
      className: `media-actions ${a ? "" : "media-actions--readonly"}`,
      children: [
        /* @__PURE__ */ o(he, { t: u, src: n, setShown: () => {
        } }),
        a && /* @__PURE__ */ I(V, { children: [
          /* @__PURE__ */ o(
            me,
            {
              opened: l,
              setOpened: r,
              t: u,
              editor: t,
              nodeKey: e,
              setShown: () => {
              }
            }
          ),
          /* @__PURE__ */ o(
            pe,
            {
              opened: m,
              onOpenChange: d,
              t: u,
              onDownload: () => void C(),
              onDelete: g
            }
          )
        ] })
      ]
    }
  );
}, Je = () => {
};
function Qe({ nodeKey: e, src: n, id: t }) {
  const { t: a } = U(), [l] = z(), [r, m] = b(!1), [d, u] = b(!1), g = v(() => {
    u(!1), l.update(() => {
      const f = O(e);
      if (!A(f)) return;
      const y = f.getParent();
      Ee(y) ? y.remove() : f.remove();
    });
  }, [l, e]), C = v(async () => {
    if (n)
      try {
        await J(n, X(n));
      } catch {
      }
  }, [n]);
  return /* @__PURE__ */ I(
    "div",
    {
      className: "media-actions visible",
      style: {
        position: "absolute",
        top: 10,
        right: 10,
        zIndex: 10,
        pointerEvents: "auto",
        display: "flex",
        gap: 4
      },
      onClick: (f) => f.stopPropagation(),
      children: [
        /* @__PURE__ */ o(he, { t: a, src: n, setShown: Je, id: t }),
        /* @__PURE__ */ o(
          me,
          {
            opened: r,
            setOpened: m,
            t: a,
            editor: l,
            nodeKey: e
          }
        ),
        /* @__PURE__ */ o(
          pe,
          {
            opened: d,
            onOpenChange: u,
            t: a,
            onDownload: () => void C(),
            onDelete: g
          }
        )
      ]
    }
  );
}
function Ye({ nodeKey: e, src: n, id: t }) {
  const { t: a } = U(), [l] = z(), [r, { open: m, close: d }] = B(!1), [u, { open: g, close: C }] = B(!1), f = re(
    () => [
      {
        id: !t || t === "0" ? "" : t,
        Url: n ?? "",
        contentType: "",
        originalFileName: "",
        fileSize: 0,
        storageType: "",
        storagePath: "",
        fileName: "",
        parentType: "",
        parentId: "",
        ownerId: "",
        createdAt: /* @__PURE__ */ new Date(),
        updatedAt: /* @__PURE__ */ new Date(),
        version: 0,
        deleted: !1,
        deletedAt: /* @__PURE__ */ new Date()
      }
    ],
    [n, t]
  ), y = () => {
    d(), g();
  }, E = v(async () => {
    if (d(), !!n)
      try {
        await J(n, X(n));
      } catch {
      }
  }, [n, d]), D = v(() => {
    d(), l.update(() => {
      const s = O(e);
      A(s) && s.remove();
    });
  }, [l, e, d]);
  return /* @__PURE__ */ I(V, { children: [
    /* @__PURE__ */ o(
      "div",
      {
        className: "image-touch-actions",
        style: {
          position: "absolute",
          top: 8,
          right: 8,
          zIndex: 10,
          pointerEvents: "auto"
        },
        onClick: (s) => s.stopPropagation(),
        children: /* @__PURE__ */ o(
          G,
          {
            label: a("editor.toolbar.more"),
            icon: Pe,
            iconColor: "var(--mantine-color-gray-text)",
            "aria-label": a("editor.toolbar.more"),
            onClick: m
          }
        )
      }
    ),
    /* @__PURE__ */ o(
      ge,
      {
        opened: u,
        onOpenChange: (s) => s ? g() : C(),
        attachments: f
      }
    ),
    /* @__PURE__ */ o(
      Me,
      {
        opened: r,
        onClose: d,
        title: a("editor.image.mobileActions"),
        children: /* @__PURE__ */ I(De, { gap: 4, p: 0, children: [
          /* @__PURE__ */ o(
            H,
            {
              type: "button",
              variant: "subtle",
              color: "gray",
              fullWidth: !0,
              justify: "flex-start",
              bg: "var(--editor-action-bg)",
              onClick: y,
              leftSection: /* @__PURE__ */ o(
                T,
                {
                  icon: ce,
                  size: 16,
                  color: "var(--mantine-color-dimmed)"
                }
              ),
              children: a("editor.image.previewFullScreen")
            }
          ),
          /* @__PURE__ */ o(
            H,
            {
              type: "button",
              variant: "subtle",
              color: "gray",
              fullWidth: !0,
              justify: "flex-start",
              bg: "var(--editor-action-bg)",
              onClick: () => void E(),
              leftSection: /* @__PURE__ */ o(
                T,
                {
                  icon: se,
                  size: 16,
                  color: "var(--mantine-color-dimmed)"
                }
              ),
              children: a("editor.gallery.download")
            }
          ),
          /* @__PURE__ */ o(
            H,
            {
              type: "button",
              variant: "subtle",
              color: "red",
              fullWidth: !0,
              justify: "flex-start",
              bg: "var(--editor-action-bg)",
              onClick: D,
              leftSection: /* @__PURE__ */ o(
                T,
                {
                  icon: de,
                  size: 16,
                  color: "var(--mantine-color-red-6)"
                }
              ),
              children: a("editor.actions.delete")
            }
          )
        ] })
      }
    )
  ] });
}
const ae = (e) => {
  const {
    width: n,
    height: t,
    isLoading: a,
    isError: l,
    src: r,
    id: m,
    altText: d,
    imageRef: u,
    maxWidth: g
  } = e;
  return /* @__PURE__ */ I(
    "div",
    {
      className: "media-wrapper",
      style: {
        width: n,
        height: t,
        display: "inline-flex",
        position: "relative"
      },
      children: [
        /* @__PURE__ */ o(
          Ae,
          {
            visible: a,
            zIndex: 1e3,
            overlayProps: { backgroundOpacity: 0.5 },
            loaderProps: { size: 24, color: "black" }
          }
        ),
        /* @__PURE__ */ o(
          Ze,
          {
            className: null,
            src: r,
            altText: d,
            imageRef: u,
            width: "inherit",
            height: "inherit",
            maxWidth: g || "auto",
            id: m
          }
        ),
        ne && /* @__PURE__ */ o(Ye, { nodeKey: e.nodeKey, src: r, id: m }),
        ie && /* @__PURE__ */ o(Qe, { nodeKey: e.nodeKey, src: r, id: m }),
        $e && !ne && !ie && /* @__PURE__ */ o(Xe, { nodeKey: e.nodeKey, src: r })
      ]
    }
  );
};
function Ze({
  altText: e,
  className: n,
  imageRef: t,
  src: a,
  width: l,
  height: r,
  maxWidth: m,
  id: d
}) {
  const [u, g] = b(!1);
  return /* @__PURE__ */ o(
    "img",
    {
      className: `${n || void 0} ${u ? "" : "loading"}`,
      src: a,
      alt: e,
      ref: t,
      style: {
        height: r,
        maxWidth: m,
        width: l
      },
      onLoad: () => {
        a.includes("splash") ? setTimeout(() => {
          g(!0);
        }, 100) : g(!0);
      },
      draggable: "false",
      "data-id": d
    }
  );
}
function Ct(e) {
  const { disable: n } = le(ue);
  return n && ke.isPlaceholderSrc(e.src) ? null : /* @__PURE__ */ o(qe, { ...e });
}
function qe({
  src: e,
  altText: n,
  nodeKey: t,
  width: a,
  height: l,
  maxWidth: r,
  showCaption: m,
  caption: d,
  id: u,
  create: g,
  alignment: C,
  imagePickerTab: f
}) {
  var K, ee;
  const y = ye(null), [E, D] = b(!0), [s] = z(), [N, _] = b(!0), [w, R] = b({
    width: 0,
    height: 0
  }), { start: Q } = Le(), [Ke, W] = b(0), {
    fetchUploadMedia: P,
    fetchDeleteMedia: Y,
    maxFileSize: et,
    imperativeHandleRef: M,
    disable: fe
  } = le(ue), k = $.has(e) && (((K = $.get(e)) == null ? void 0 : K.mediaNodeKeys.length) === 0 || ((ee = $.get(e)) == null ? void 0 : ee.mediaNodeKeys.length) === void 0 || e.trim() === ""), { t: L } = U(), [tt, we] = b(0);
  x(() => s.registerDecoratorListener(() => {
    we((i) => i + 1);
  }), [k]), x(() => {
    if (!e || e.startsWith("data:image/") || !e.trim()) {
      D(!1);
      return;
    }
    const i = new Image();
    i.src = e, i.onload = () => D(!1), i.onerror = () => {
      D(!1);
    };
  }, [e, k]);
  const be = (i, p) => {
    s.update(() => {
      xe(null);
      const c = O(t);
      A(c) && c.setWidthAndHeight(i, p);
    });
  }, { historyState: Z } = Ue(), {
    settings: { showNestedEditorTreeView: q }
  } = ze();
  function ve(i) {
    return i.endsWith(".svg") || i.includes("image/svg+xml");
  }
  function Ie(i) {
    return new Promise((p, c) => {
      if (ve(i)) {
        p(0);
        return;
      }
      const h = new Image();
      h.src = i, h.onload = () => {
        p(h.width);
      }, h.onerror = () => {
        c(new Error("Failed to load image"));
      };
    });
  }
  x(() => {
    let i = a, p = l, c = 100;
    (e.includes("unsplash") ? e.trim() : !k && e.trim() || e.includes("upload-src-editor")) && e !== "upload" && Ie(e).then((h) => {
      typeof i == "number" && i < c && h < c ? (_(!0), R({
        width: i,
        height: p
      })) : h < c ? (_(!0), R({
        width: "auto",
        height: "auto"
      })) : (R({
        width: h,
        height: h
      }), _(!1));
    }).catch((h) => {
      console.warn("Ошибка при загрузке изображения:", h.message);
    });
  }, [e, k]), x(() => {
    w.width && w.height && N && s.update(() => {
      const i = O(t);
      A(i) && i.setWidthAndHeight(w.width, w.height);
    });
  }, [w.width, w.height, N]);
  const Ce = v(
    (i) => _e(s, t, i),
    [s, t]
  ), F = v(
    (i, p) => {
      D(!1), s.update(() => {
        const c = O(t);
        A(c) && (c.setSrc(i), c.setId(p));
      });
    },
    [s, t]
  ), j = v(
    (i) => {
      D(!0);
      const p = Q();
      P && P(
        i[0],
        (c, h) => {
          F(c, h), W(0);
        },
        (c) => {
          c && Be({
            message: L("editor.gallery.errorFile")
          }), W(0), F("", "");
        },
        p,
        (c) => {
          W(c);
        }
      );
    },
    [P, Q, L, F]
  );
  return x(() => s.registerCommand(
    Re,
    (i) => e !== "upload" || i.targetNodeKey !== t ? !1 : (j(i.files), !0),
    Ne
  ), [s, j, t, e]), !e || e === "upload" ? /* @__PURE__ */ o(Oe, { "data-editor-image-picker-drop-root": !0, w: "100%", children: /* @__PURE__ */ o(
    We,
    {
      inline: !0,
      nodeKey: t,
      defaultTabValue: f,
      onWriteTabToNode: Ce,
      uploading: !1,
      onUpload: (i) => {
        !P || !i.length || j(i);
      },
      popoverProps: {
        opened: !0,
        position: "bottom",
        zIndex: Fe
      },
      onChange: (i) => {
        s.update(() => {
          const p = O(t);
          A(p) && p.setSrc(i);
        });
      }
    }
  ) }) : N ? /* @__PURE__ */ o(
    ae,
    {
      width: w.width,
      height: w.height,
      isLoading: E,
      isError: !1,
      isIcon: N,
      src: e,
      id: u,
      editor: s,
      nodeKey: t,
      fetchDeleteMedia: Y,
      altText: n,
      imageRef: y,
      maxWidth: r,
      showCaption: m,
      caption: d,
      isCollabActive: !1,
      historyState: Z,
      showNestedEditorTreeView: q,
      t: L
    }
  ) : /* @__PURE__ */ o(
    je,
    {
      editor: s,
      isIcon: N,
      width: oe(a),
      height: oe(l),
      initialWidth: w.width || "",
      initialHeight: w.height || "",
      onResizeEnd: be,
      alignment: C,
      disable: fe,
      onRegisterDecoratorEnter: (i) => {
        M != null && M.current && (M.current.decoratorEnterAction = i);
      },
      onActivate: () => s.dispatchCommand(He, "show_menu"),
      children: /* @__PURE__ */ o(
        ae,
        {
          width: "inherit",
          height: "inherit",
          isLoading: E,
          isError: !1,
          isIcon: N,
          src: e,
          id: u,
          editor: s,
          nodeKey: t,
          fetchDeleteMedia: Y,
          altText: n,
          imageRef: y,
          maxWidth: r,
          showCaption: m,
          caption: d,
          isCollabActive: !1,
          historyState: Z,
          showNestedEditorTreeView: q,
          t: L
        }
      )
    }
  );
}
export {
  Ct as default
};
