import { a as f, J as z, j as t, I as H, n as M, f as h, t as X, b as C } from "./chunk-BKyTJ1V5.js";
function B(n, d, c, p = void 0) {
  const i = window.localStorage, g = (s) => {
    const u = i.getItem(s);
    return u ? JSON.parse(u) : null;
  }, [m, x] = f.useState(() => {
    const s = g(d);
    return s ? Array.isArray(s) && Array.isArray(n) && n.length > 0 ? s.length === n.length ? s : n : s : n;
  }), j = (s, u) => {
    p ? i.setItem(s, p(u)) : i.setItem(s, JSON.stringify(u));
  };
  return [m, (s) => {
    s instanceof Function ? x((u) => {
      const v = s(u);
      return j(d, v), v;
    }) : (j(d, s), x(s));
  }, () => {
    i.removeItem(d);
  }, () => {
    const s = g(d);
    x(s);
  }];
}
const K = () => {
  const [n, d] = f.useState(null), c = f.useCallback((p) => d(p), []);
  return [n, c];
}, e = ninjadraw_globals, w = new window.Yalogica.NinjaDraw.Plugins.Notify(), W = (n, d) => fetch(n, {
  method: "GET",
  headers: {
    "X-WP-Nonce": d,
    "X-HTTP-Method-Override": "GET"
  },
  cache: "no-store"
}).then((c) => {
  if (!c.ok)
    throw new Error(e.i18n.error_network_response);
  return c.json();
}).then((c) => {
  if (!c.success)
    throw new Error(c.msg ? c.msg : e.i18n.operation_failed);
  return c;
}).catch((c) => {
  throw console.error("There was a problem with the fetch operation:", c), c;
}), T = (n, d, c, p) => fetch(n, {
  method: c,
  headers: {
    "Content-Type": "application/json",
    "X-WP-Nonce": d,
    "X-HTTP-Method-Override": c
  },
  cache: "no-store",
  body: JSON.stringify(p)
}).then((i) => {
  if (!i.ok)
    throw new Error(e.i18n.error_network_response);
  return i.json();
}).then((i) => {
  if (!i.success)
    throw new Error(i.msg ? i.msg : e.i18n.operation_failed);
  return i.data;
}).catch((i) => {
  throw console.error("There was a problem with the fetch operation:", i), i;
});
function Z() {
  const [n, d] = K(), [c, p] = B(null, "currentLibrary"), i = f.useRef(0), [g, m] = f.useState(!1), [x, j] = f.useState(!1), [y, _] = f.useState(e.data.item.title ?? ""), N = {
    canvasActions: { saveToActiveFile: !1 }
  }, s = () => {
    if (!n)
      return 0;
    const o = n.getSceneElements();
    return o.length < 1 ? 0 : M(o);
  }, u = () => {
    if (!n)
      return;
    const o = async () => {
      try {
        const a = n.getSceneElements(), r = n.getAppState(), l = n.getFiles(), S = X(a, r, l, "database"), k = {
          elements: a,
          appState: { ...r, exportBackground: !1 },
          files: l
        }, R = await C(k);
        k.appState.exportWithDarkMode = !0;
        const G = await C(k), U = decodeURIComponent(e.api.url + "/items" + (e.data.item.id ? "/" + e.data.item.id : "")), J = new XMLSerializer(), F = {
          id: e.data.item.id,
          title: y,
          source: S,
          files: JSON.stringify(l),
          svg: J.serializeToString(R)
        };
        T(U, e.api.nonce, e.data.item.id ? "PUT" : "POST", F).then((b) => {
          if (!e.data.item.id && b.id) {
            e.data.item.id = b.id, e.data.item.status = "draft";
            const I = new URL(window.location.href);
            I.searchParams.set("id", e.data.item.id), I.searchParams.set("action", "edit"), window.history.replaceState(null, "", I);
          }
          w.show(e.i18n.operation_success, "ninjadraw-success");
        }).catch((b) => {
          w.show(b instanceof Error ? b.message : e.i18n.error_unknown, "ninjadraw-error");
        }).finally(() => {
          i.current = s(), j(!1), m(!1);
        });
      } catch (a) {
        console.error(a), w.show("Error occured during saving :" + a, "ninjadraw-error");
      }
    };
    e.data.is_licensed || e.data.item.id ? (m(!0), o()) : (m(!0), W(`${e.api.url}/items/count`, e.api.nonce).then((a) => {
      a.data.count >= 5 ? w.show(e.i18n.limits_diagrams, "ninjadraw-warning") : (m(!0), o());
    }).catch((a) => {
      w.show(a instanceof Error ? a.message : e.i18n.error_unknown, "ninjadraw-error");
    }).finally(() => {
      m(!1);
    }));
  }, v = (o) => {
    if (!n)
      return;
    const a = async () => {
      try {
        const r = decodeURIComponent(e.api.url + "/items/" + e.data.item.id + "/status/" + o);
        T(r, e.api.nonce, "PUT", null).then(() => {
          e.data.item.status = o, w.show(e.i18n.operation_success, "ninjadraw-success");
        }).catch((l) => {
          w.show(l instanceof Error ? l.message : e.i18n.unknown_error, "ninjadraw-error");
        }).finally(() => {
          m(!1);
        });
      } catch (r) {
        console.error(r), w.show("Error occured during saving :" + r, "ninjadraw-error");
      }
    };
    m(!0), a();
  };
  f.useEffect(() => {
    if (!n)
      return;
    if (e.data.item.source)
      try {
        const r = JSON.parse(e.data.item.source), l = JSON.parse(e.data.item.files);
        n.updateScene(r), n.addFiles(Object.keys(l).map((S) => l[S])), n.scrollToContent(), i.current = s(), j(!1);
      } catch (r) {
        console.error(r), w.show("Error occured during loading :" + r, "ninjadraw-error");
      }
    const a = setInterval(() => {
      s() != i.current ? j(!0) : j(!1);
    }, 1e3);
    return () => {
      clearInterval(a);
    };
  }, [n]), f.useEffect(() => {
    const o = (a) => {
      (a.ctrlKey || a.metaKey) && a.key === "s" && (a.preventDefault(), u());
    };
    return window.addEventListener("keydown", o), () => {
      window.removeEventListener("keydown", o);
    };
  }, [y, n]), z({ excalidrawAPI: n });
  const E = (o) => {
    p(o);
  }, D = (o) => {
    _(o.target.value), i.current++;
  }, O = () => {
    u();
  }, P = () => {
    v("publish");
  }, A = () => {
    v("draft");
  }, L = async () => new Promise((o) => {
    if (typeof wp > "u" || !wp.media) {
      o(null);
      return;
    }
    let a = !1;
    const r = wp.media({
      library: { type: ["image"] },
      multiple: !1
    });
    r.on("open", () => {
      const l = r.state("library");
      l && l.set("contentUserSetting", !1), r.content.mode("browse");
    }), r.on("select", () => {
      a = !0;
      const l = r.state().get("selection").first().toJSON();
      o({
        dataURL: l.url,
        mimeType: l.mime,
        width: l.width,
        height: l.height
      });
    }), r.on("close", () => {
      setTimeout(() => {
        a || o(null);
      }, 0);
    }), r.open();
  }), V = () => /* @__PURE__ */ t.jsxs(h, { children: [
    e.data.is_licensed ? /* @__PURE__ */ t.jsx(t.Fragment, { children: /* @__PURE__ */ t.jsx(h.DefaultItems.LoadScene, {}) }) : /* @__PURE__ */ t.jsx(t.Fragment, { children: /* @__PURE__ */ t.jsx(h.ItemCustom, { children: /* @__PURE__ */ t.jsxs("button", { className: "dropdown-menu-item dropdown-menu-item-base", title: "Open", children: [
      /* @__PURE__ */ t.jsx("div", { className: "dropdown-menu-item__icon", children: /* @__PURE__ */ t.jsx("svg", { "aria-hidden": "true", focusable: "false", role: "img", viewBox: "0 0 20 20", className: "", fill: "none", stroke: "currentColor", "stroke-linecap": "round", "stroke-linejoin": "round", children: /* @__PURE__ */ t.jsx("path", { d: "m9.257 6.351.183.183H15.819c.34 0 .727.182 1.051.506.323.323.505.708.505 1.05v5.819c0 .316-.183.7-.52 1.035-.337.338-.723.522-1.037.522H4.182c-.352 0-.74-.181-1.058-.5-.318-.318-.499-.705-.499-1.057V5.182c0-.351.181-.736.5-1.054.32-.321.71-.503 1.057-.503H6.53l2.726 2.726Z", "stroke-width": "1.25" }) }) }),
      /* @__PURE__ */ t.jsx("div", { className: "dropdown-menu-item__text", children: "Open" }),
      /* @__PURE__ */ t.jsx("div", { className: "dropdown-menu-item__pro", children: "pro" })
    ] }) }) }),
    /* @__PURE__ */ t.jsx(h.DefaultItems.Export, {}),
    /* @__PURE__ */ t.jsx(h.DefaultItems.SaveAsImage, {}),
    /* @__PURE__ */ t.jsx(h.DefaultItems.Help, {}),
    /* @__PURE__ */ t.jsx(h.DefaultItems.ClearCanvas, {}),
    /* @__PURE__ */ t.jsx(h.Separator, {}),
    /* @__PURE__ */ t.jsx(h.DefaultItems.ToggleTheme, {}),
    /* @__PURE__ */ t.jsx(h.DefaultItems.ChangeCanvasBackground, {})
  ] });
  return /* @__PURE__ */ t.jsxs(t.Fragment, { children: [
    /* @__PURE__ */ t.jsxs("div", { className: "ninjadraw-header", children: [
      /* @__PURE__ */ t.jsxs("div", { className: "ninjadraw-title", children: [
        /* @__PURE__ */ t.jsx("span", { children: /* @__PURE__ */ t.jsx("svg", { width: "24", height: "24", viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ t.jsx("path", { style: { fill: "rgba(255,255,255,.5)", strokeWidth: "0" }, d: "m18.447 1.1565c-0.44023-0.43911-1.0117-0.45733-1.4701-2e-7l-16.171 16.15v5.8728h5.8803l16.171-16.15c0.45849-0.45839 0.44106-1.0288 1e-6 -1.4682zm-0.73504 2.2023 2.9401 2.9364-1.4701 1.4682-2.9401-2.9364zm-2.9401 2.9364 2.9401 2.9364-10.29 10.277-2.9401-2.9364zm-11.761 11.746 2.9401 2.9364h-2.9401zm3.3697-17.22c-0.25977 0.0022195-0.51626 0.11922-0.74023 0.34375l-4.4922 4.4902c-0.44764 0.44821-0.46622 1.0294 0 1.4961l4.1621 4.1641 1.5-1.498c-0.2994-0.30021-0.60002-0.59919-0.90039-0.89844l1.5039-1.5039-1.4141-1.4141-1.5039 1.5039c-0.36896-0.36607-0.736-0.73405-1.1035-1.1016l2.9961-2.9941 3.4141 3.416 1.4941-1.4961-4.1602-4.1641c-0.23364-0.23341-0.49609-0.34597-0.75586-0.34375zm12.291 11.881-1.4961 1.4961 3.4297 3.4316-2.9922 2.9922c-0.37391-0.37088-0.74533-0.74425-1.1172-1.1172l1.5039-1.5039-1.4141-1.4141-1.5039 1.5039c-0.30109-0.29787-0.59938-0.59853-0.89844-0.89844l-1.4961 1.498 4.1758 4.1777c0.47328 0.473 1.118 0.37827 1.5723-0.07617l4.4141-4.4141c0.44853-0.44783 0.46709-1.0298 0-1.4961z" }) }) }),
        /* @__PURE__ */ t.jsxs("span", { children: [
          "NinjaDraw",
          /* @__PURE__ */ t.jsx("sup", { children: e.i18n.sup })
        ] })
      ] }),
      /* @__PURE__ */ t.jsxs("div", { className: "ninjadraw-toolbar" + (x ? " ninjadraw-dirty" : ""), children: [
        g && /* @__PURE__ */ t.jsx("div", { className: "ninjadraw-spinner" }),
        e.data.rights.publish && e.data.item.status === "publish" && /* @__PURE__ */ t.jsx("button", { className: "ninjadraw-button ninjadraw-button-draft", onClick: A, disabled: g, children: e.i18n.switch_to_draft }),
        /* @__PURE__ */ t.jsx("button", { className: "ninjadraw-button ninjadraw-button-save", onClick: O, disabled: g, children: e.i18n.save }),
        e.data.rights.publish && e.data.item.status === "draft" && /* @__PURE__ */ t.jsx("button", { className: "ninjadraw-button ninjadraw-button-publish", onClick: P, disabled: g, children: e.i18n.publish })
      ] })
    ] }),
    /* @__PURE__ */ t.jsxs("div", { className: "ninjadraw-data", children: [
      /* @__PURE__ */ t.jsx("div", { className: "ninjadraw-title", children: /* @__PURE__ */ t.jsx("input", { type: "text", value: y, onChange: D, placeholder: e.i18n.editor_placeholder_title }) }),
      /* @__PURE__ */ t.jsx("div", { className: "ninjadraw-excalidraw" + (e.data.is_licensed ? "" : " ninjadraw-lock-in-lite"), children: /* @__PURE__ */ t.jsx(
        H,
        {
          excalidrawAPI: d,
          initialData: { libraryItems: c },
          onLibraryChange: E,
          libraryReturnUrl: e.data.url.libraryreturn,
          autoFocus: !0,
          handleKeyboardGlobally: !0,
          UIOptions: N,
          onImageInsert: L,
          children: V()
        }
      ) })
    ] })
  ] });
}
export {
  Z as default
};
