import { jsx as l, jsxs as S, Fragment as le } from "react/jsx-runtime";
import { useContext as ie, useMemo as ae, useState as B, useEffect as A, useRef as z, useCallback as F, Suspense as me, lazy as ge } from "react";
import { useLexicalComposerContext as he } from "@lexical/react/LexicalComposerContext";
import { useLexicalEditable as Ce } from "@lexical/react/useLexicalEditable";
import { useLexicalNodeSelection as be } from "@lexical/react/useLexicalNodeSelection";
import { mergeRegister as pe } from "@lexical/utils";
import { $setSelection as xe, $getNodeByKey as V, CLICK_COMMAND as ve, COMMAND_PRIORITY_LOW as X, KEY_DELETE_COMMAND as we, KEY_BACKSPACE_COMMAND as Ee } from "lexical";
import { C as se, R as ye, j as J, k as Z, A as K, K as ke, t as P, N as Te, m as ee, n as Me, o as De, H as te, O as Oe, a as ce, q as oe, l as Ne, p as _e, r as ne, s as Se, v as Ae, w as Be } from "./layers.0_o7xyFB.js";
import { useTranslation as Q } from "react-i18next";
import { Modal as Le, Text as Re, Flex as je, Button as $, Box as re, Stack as We, useMantineColorScheme as ze, Loader as Fe } from "@mantine/core";
import { useDisclosure as Ie } from "@mantine/hooks";
import "@lexical/mark";
import "@lexical/code";
import { BottomDrawerWithoutHeader as He } from "@layers-app/shared";
const Ge = ({
  isCloseModal: r,
  setCloseModalOpen: i,
  confirmClose: C
}) => {
  const { t: b } = Q();
  return /* @__PURE__ */ l(
    Le,
    {
      opened: r,
      onClose: () => {
        i(!1);
      },
      centered: !0,
      title: b("editor.unsavedChanges.title"),
      closeOnClickOutside: !0,
      closeOnEscape: !0,
      size: "500",
      zIndex: 999,
      children: /* @__PURE__ */ S("div", { children: [
        /* @__PURE__ */ l(Re, { mb: "md", children: b("editor.unsavedChanges.message") }),
        /* @__PURE__ */ S(je, { justify: "flex-end", gap: "sm", children: [
          /* @__PURE__ */ l(
            $,
            {
              variant: "default",
              onClick: () => {
                i(!1);
              },
              fullWidth: !0,
              children: b("editor.unsavedChanges.cancel")
            }
          ),
          /* @__PURE__ */ l($, { color: "red", onClick: C, fullWidth: !0, children: b("editor.unsavedChanges.closeWithoutSaving") })
        ] })
      ] })
    }
  );
};
function Ve({
  imageContainerRef: r,
  editor: i,
  rootClassName: C = null,
  width: b = "inherit",
  height: u = "inherit",
  nodeKey: s,
  alignment: I,
  setModalOpen: L,
  previewSVG: n,
  isModalOpen: m
}) {
  const { disable: g, imperativeHandleRef: v } = ie(se), H = ae(() => n ?? "", [n]), [T, h] = B(!1), [
    G,
    { open: w, close: M }
  ] = Ie(!1), { t: x } = Q();
  A(() => {
    m && h(!1);
  }, [m]);
  const D = (e, p) => {
    i.update(() => {
      xe(null);
      const a = V(s);
      return ce(a) && a.setWidthAndHeight(e, p), !0;
    });
  }, E = () => {
    oe(i, s);
  }, R = () => {
    M(), L(!0);
  }, O = () => {
    M(), oe(i, s);
  };
  return /* @__PURE__ */ S(
    ye,
    {
      editor: i,
      isIcon: !1,
      isEmbed: !0,
      width: Z(b),
      height: Z(u),
      onResizeEnd: D,
      alignment: I,
      disable: g,
      onRegisterDecoratorEnter: (e) => {
        v != null && v.current && (v.current.decoratorEnterAction = e);
      },
      onActivate: () => i.dispatchCommand(Oe, "show_menu"),
      children: [
        /* @__PURE__ */ S(re, { className: "media-wrapper excaildraw", children: [
          /* @__PURE__ */ l(
            "div",
            {
              className: `media-actions${J || !Me ? " visible" : ""}`,
              children: J ? /* @__PURE__ */ l(
                K,
                {
                  "aria-label": x("editor.toolbar.more"),
                  label: x("editor.toolbar.more"),
                  flexBorder: !0,
                  onClick: w,
                  icon: ke,
                  iconColor: "var(--mantine-color-gray-text)"
                }
              ) : /* @__PURE__ */ S(le, { children: [
                /* @__PURE__ */ l(
                  K,
                  {
                    "aria-label": "Settings",
                    label: x("editor.link.edit"),
                    flexBorder: !0,
                    onClick: () => {
                      L(!0);
                    },
                    icon: P,
                    iconColor: "var(--mantine-color-gray-text)"
                  }
                ),
                /* @__PURE__ */ l(
                  Te,
                  {
                    opened: T,
                    setOpened: h,
                    t: x,
                    editor: i,
                    nodeKey: s,
                    flexBorder: !0
                  }
                ),
                /* @__PURE__ */ l(
                  K,
                  {
                    "aria-label": "Delete",
                    label: x("editor.actions.delete"),
                    flexBorder: !0,
                    onClick: E,
                    icon: ee,
                    iconColor: "var(--mantine-color-red-outline)"
                  }
                )
              ] })
            }
          ),
          /* @__PURE__ */ l(
            re,
            {
              w: "100%",
              ref: (e) => {
                e && r && (r.current = e);
              },
              className: C ?? "",
              dangerouslySetInnerHTML: { __html: H }
            }
          )
        ] }),
        J && /* @__PURE__ */ l(
          De,
          {
            opened: G,
            onClose: M,
            title: x("editor.image.mobileActions"),
            children: /* @__PURE__ */ S(We, { gap: 4, p: 0, children: [
              /* @__PURE__ */ l(
                $,
                {
                  type: "button",
                  variant: "subtle",
                  color: "gray",
                  fullWidth: !0,
                  justify: "flex-start",
                  bg: "var(--editor-action-bg)",
                  onClick: R,
                  leftSection: /* @__PURE__ */ l(
                    te,
                    {
                      icon: P,
                      size: 16,
                      color: "var(--mantine-color-dimmed)"
                    }
                  ),
                  children: x("editor.link.edit")
                }
              ),
              /* @__PURE__ */ l(
                $,
                {
                  type: "button",
                  variant: "subtle",
                  color: "red",
                  fullWidth: !0,
                  justify: "flex-start",
                  bg: "var(--editor-action-bg)",
                  onClick: O,
                  leftSection: /* @__PURE__ */ l(
                    te,
                    {
                      icon: ee,
                      size: 16,
                      color: "var(--mantine-color-red-6)"
                    }
                  ),
                  children: x("editor.actions.delete")
                }
              )
            ] })
          }
        )
      ]
    }
  );
}
let U = null;
const qe = /* @__PURE__ */ ge(async () => {
  var i;
  const r = await import("./layers.D-vM7CY8.js").then((C) => C.K);
  return !U && r && (U = r.exportToSvg || ((i = r.default) == null ? void 0 : i.exportToSvg) || r.default), { default: r.Excalidraw };
}), $e = () => {
  const [r, i] = B(
    null
  ), C = F(
    (b) => i(b),
    []
  );
  return [r, C];
};
function Ue({
  onSave: r,
  initialElements: i,
  initialAppState: C,
  initialFiles: b,
  isShown: u = !1,
  onDelete: s,
  onClose: I,
  isEdited: L
}) {
  const [n, m] = $e(), { i18n: g, t: v } = Q(), { colorScheme: H } = ze(), T = z(!1), [h, G] = B(i), [w, M] = B(b), [x, D] = B(u);
  A(() => {
    u && D(!0);
  }, [u]), A(() => {
    !u || T.current || (T.current = !0, Promise.resolve({           }));
  }, [u]), A(() => {
    u && setTimeout(() => {
      var e, p;
      (e = n == null ? void 0 : n.refresh) == null || e.call(n), (p = n == null ? void 0 : n.scrollToContent) == null || p.call(n);
    }, 500);
  }, [u, n]), A(() => {
    if (!u)
      return;
    const e = (o, c) => {
      const t = v(o);
      return t.startsWith("editor.menu") ? c : t;
    }, p = e(
      "editor.menu.excalidraw.tools.frameTool",
      g.language === "ru" ? "Инструмент рамки" : g.language === "es" ? "Herramienta de marco" : "Frame tool"
    ), a = e(
      "editor.menu.excalidraw.tools.webEmbed",
      g.language === "ru" ? "Веб-встраивание" : g.language === "es" ? "Incrustación web" : "Web Embed"
    ), d = e(
      "editor.menu.excalidraw.tools.generate",
      g.language === "ru" ? "Генерировать" : g.language === "es" ? "Generar" : "Generate"
    ), j = {
      "Frame tool": p,
      "Web Embed": a,
      "Web embeded": a,
      Generate: d
    }, W = () => {
      const o = document.querySelector(".App-toolbar__extra-tools-dropdown");
      if (!o)
        return;
      const c = document.createTreeWalker(
        o,
        NodeFilter.SHOW_TEXT,
        null
      );
      let t;
      for (; t = c.nextNode(); )
        if (t.nodeType === Node.TEXT_NODE && t.textContent) {
          const f = t.textContent.trim();
          for (const [k, _] of Object.entries(j))
            if (f === k && _ && !f.includes(_)) {
              t.textContent = t.textContent.replace(k, _);
              break;
            }
        }
    }, N = () => {
      setTimeout(() => {
        W();
      }, 0);
    }, y = setTimeout(() => {
      const o = document.querySelector(
        ".excalidraw-container"
      );
      if (o) {
        const c = o.querySelector(
          ".App-toolbar__extra-tools-trigger"
        );
        c && c.addEventListener("click", N);
      }
    }, 300);
    return () => {
      clearTimeout(y);
      const o = document.querySelector(
        ".excalidraw-container"
      );
      if (o) {
        const c = o.querySelector(
          ".App-toolbar__extra-tools-trigger"
        );
        c && c.removeEventListener("click", N);
      }
    };
  }, [u, g.language, v]);
  const E = F(async () => {
    var W, N, y;
    let e = U;
    if (!e || typeof e != "function") {
      const o = await import("./layers.D-vM7CY8.js").then((c) => c.K);
      e = o.exportToSvg || ((W = o.default) == null ? void 0 : W.exportToSvg) || o.default, e && typeof e == "function" && (U = e);
    }
    if (!e || typeof e != "function") {
      const o = await import("./layers.D-vM7CY8.js").then((t) => t.K), c = o ? Object.keys(o) : [];
      throw console.error("Excalidraw module structure:", {
        keys: c,
        hasExportToSvg: o && "exportToSvg" in o,
        hasDefault: o && "default" in o,
        moduleType: typeof o,
        module: o
      }), new Error(
        `exportToSvg is not available from @excalidraw/excalidraw. Module keys: ${c.join(", ")}. Please ensure @excalidraw/excalidraw is properly installed.`
      );
    }
    const p = ((N = n == null ? void 0 : n.getAppState) == null ? void 0 : N.call(n)) ?? C, a = await e({
      appState: p,
      elements: h,
      files: w
    }), d = (y = a == null ? void 0 : a.firstElementChild) == null ? void 0 : y.firstElementChild, j = a.getAttribute("viewBox");
    if (j != null) {
      const o = j.split(" ");
      a.setAttribute("width", o[2]), a.setAttribute("height", o[3]);
    }
    return d && d.tagName === "style" && d.remove(), a.setAttribute("width", "100%"), a.setAttribute("height", "100%"), a.setAttribute("display", "block"), a.classList.add("excalidraw-svg"), a.outerHTML;
  }, [h, w, n, C]), R = () => {
    if (h && h.filter((e) => !e.isDeleted).length > 0) {
      const e = n == null ? void 0 : n.getAppState(), p = {
        exportBackground: e == null ? void 0 : e.exportBackground,
        exportScale: e == null ? void 0 : e.exportScale,
        exportWithDarkMode: (e == null ? void 0 : e.theme) === "dark",
        isBindingEnabled: e == null ? void 0 : e.isBindingEnabled,
        isLoading: e == null ? void 0 : e.isLoading,
        name: e == null ? void 0 : e.name,
        theme: e == null ? void 0 : e.theme,
        viewBackgroundColor: e == null ? void 0 : e.viewBackgroundColor,
        viewModeEnabled: e == null ? void 0 : e.viewModeEnabled,
        zenModeEnabled: e == null ? void 0 : e.zenModeEnabled,
        zoom: e == null ? void 0 : e.zoom
      };
      (async () => {
        const a = await E();
        r(h, p, w, a);
      })();
    } else
      s();
  }, O = (e, p, a) => {
    (e == null ? void 0 : e.length) !== (i == null ? void 0 : i.length) && (L.current = !0), G(e), M(a);
  };
  return /* @__PURE__ */ l(
    He,
    {
      opened: u,
      onClose: I,
      onSave: R,
      className: "excaildraw-modal",
      closeOnEscape: !1,
      children: x && /* @__PURE__ */ l(
        me,
        {
          fallback: /* @__PURE__ */ l(
            "div",
            {
              style: {
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                height: "100%",
                minHeight: "400px"
              },
              children: /* @__PURE__ */ l(Fe, { size: "sm" })
            }
          ),
          children: /* @__PURE__ */ l(
            qe,
            {
              langCode: Ne[g.language],
              theme: H,
              onChange: O,
              excalidrawAPI: m,
              initialData: {
                appState: { ...C || { isLoading: !1 } },
                elements: i,
                files: b,
                scrollToContent: !0
              }
            }
          )
        }
      )
    }
  );
}
function at({
  nodeKey: r,
  data: i,
  width: C,
  height: b,
  alignment: u
}) {
  var c;
  const [s] = he(), { fetchUploadMedia: I, fetchDeleteMedia: L } = ie(se), n = Ce(), m = ae(() => _e(i), [i]), g = z(
    ne(m.files ?? {})
  ), v = z(
    Object.keys(m.files ?? {})
  );
  A(() => {
    const t = ne(m.files ?? {});
    for (const f of Object.keys(t))
      g.current[f] = t[f];
  }, [m.files]);
  const H = ((c = m == null ? void 0 : m.elements) == null ? void 0 : c.length) === 0 && !m.previewSVG, [T, h] = B(
    H && s.isEditable()
  ), [G, w] = B(!1), M = z(null), x = z(null), D = z(null), [E, R, O] = be(r), e = F(
    (t) => (E && (t.preventDefault(), s.update(() => {
      const f = V(r);
      f && f.remove();
    })), !1),
    [s, E, r]
  );
  A(() => {
    if (!n) {
      E && O();
      return;
    }
    return pe(
      s.registerCommand(
        ve,
        (t) => {
          const f = x.current, k = t.target;
          return f !== null && f.contains(k) ? (t.shiftKey || O(), R(!E), t.detail > 1 && h(!0), !0) : !1;
        },
        X
      ),
      s.registerCommand(
        we,
        e,
        X
      ),
      s.registerCommand(
        Ee,
        e,
        X
      )
    );
  }, [O, s, E, e, R, n]);
  const p = F(() => (h(!1), s.update(() => {
    const t = V(r);
    t && t.remove();
  })), [s, r]), a = async (t, f, k, _) => {
    const {
      files: q,
      urlByDataUrl: de,
      attachmentIdByFileId: ue
    } = await Se(
      k,
      I,
      g.current
    );
    g.current = Ae(
      v.current,
      q,
      ue,
      L
    ), v.current = Object.keys(q);
    const fe = Be(_, de);
    s.update(() => {
      const Y = V(r);
      ce(Y) && (t && t.length > 0 || Object.keys(q).length > 0 ? Y.setData(
        JSON.stringify({
          appState: f,
          elements: t,
          files: q,
          previewSVG: fe
        })
      ) : Y.remove());
    });
  }, { elements: d = [], files: j = {}, appState: W = {}, previewSVG: N } = m, y = F(() => {
    h(!1), w(!1), D.current = !1, (d == null ? void 0 : d.length) === 0 && s.update(() => {
      const t = V(r);
      t && t.remove();
    });
  }, [s, r, d == null ? void 0 : d.length]), o = F(() => {
    D.current ? w(!0) : y();
  }, [y]);
  return /* @__PURE__ */ S(le, { children: [
    /* @__PURE__ */ l(
      Ge,
      {
        isCloseModal: G,
        confirmClose: y,
        setCloseModalOpen: w
      }
    ),
    /* @__PURE__ */ l(
      Ue,
      {
        initialElements: d,
        isEdited: D,
        initialFiles: j,
        initialAppState: W,
        isShown: T,
        onDelete: p,
        onClose: o,
        onSave: async (t, f, k, _) => {
          await a(t, f, k, _), h(!1);
        },
        closeOnClickOutside: !1
      }
    ),
    (d == null ? void 0 : d.length) && /* @__PURE__ */ l(
      "div",
      {
        style: {
          display: "flex",
          justifyContent: u
        },
        children: /* @__PURE__ */ l(
          Ve,
          {
            imageContainerRef: M,
            className: "image",
            width: C,
            height: b,
            editor: s,
            nodeKey: r,
            alignment: u,
            setModalOpen: h,
            previewSVG: N,
            isModalOpen: T
          }
        )
      }
    )
  ] });
}
export {
  at as default
};
