import lodash from "lodash";
import React, { Suspense, forwardRef, useCallback, useEffect, useMemo, useState } from "react";
import { LINK_PREVIEW_TYPE } from "./../ricos-content/index.js";
import { isCommonPluginOptions } from ".//utils/is-editor-plugin.js";
import { RICOS_VERSION } from "./../ricos-schema/next-schema/index.js";
import { resolveTheme } from "./../ricos-styles/resolve-theme.js";
import { useBiHelpers } from "./../_shared/bi-strategy/use-bi-helpers.js";
import { extractPluginsConfig } from "./../_shared/extract-plugins-config.js";
import { fetchEmbedData } from "./../_shared/fetch-embed-data.js";
import { hasPlugin } from "./../_shared/has-plugin.js";
import { useSetRicosEditorApi } from "./../_shared/ricos-editor-api-context/ricos-editor-api-context.js";
import { getImageUrl } from "./../_shared/url-resolvers.js";
import { useIframeSandboxDomain } from "./../_shared/use-iframe-sandbox-domain.js";
import { isSSR } from "./../wix-rich-content-common/index.js";
import {
  DevContextProvider,
  shouldShowDebuggingInfo
} from "./../wix-rich-content-common/lib/dev-tools.js";
import {
  OverrideFullRicosEditorLazy,
  hasWixInsiderOverride,
  useOverridePluginsMap
} from "./../wix-rich-content-common/lib/overrides.js";
import { isiOS } from "./../editor-common/index.js";
import { loadCSS } from "./load-css.js";
import { RicosErrorBoundary } from "./tiptap/ricos-error-boundary.js";
const FullRicosEditorLazy = React.lazy(() => {
  loadCSS();
  return import(
    /* webpackChunkName: "ricos_FullRicosEditor" */
    "./tiptap/full-ricos-editor.js"
  );
});
const LocaleResourceProviderLazy = React.lazy(
  () => import(
    /* webpackChunkName: "ricos_LocaleResourceProvider" */
    "./RicosContext/locale-resource-provider.js"
  )
);
const renderMobileDevTools = () => {
  if (typeof window !== "undefined" && !window.__RICOS_DEVTOOLS_MOBILE_HOOK__) {
    window.__RICOS_DEVTOOLS_MOBILE_HOOK__ = true;
    const cdnTag = document.createElement("script");
    cdnTag.src = "//cdn.jsdelivr.net/npm/eruda";
    cdnTag.onload = () => {
      eruda.init();
    };
    window.document.head.appendChild(cdnTag);
  }
};
const RicosEditor = forwardRef(
  (props, ref) => {
    const {
      biSettings,
      instance,
      wixClient,
      iframeSandboxDomain: explicitDomain,
      msid,
      theme,
      environment: explicitEnvironment,
      ...restProps
    } = props;
    const {
      helpers: biHelpers,
      biLogger,
      biLoadPromise
    } = useBiHelpers({ instance, biSettings, msid });
    useEffect(() => {
      biLoadPromise.then((callbacks) => {
        callbacks.onOpenEditorSuccess?.(
          RICOS_VERSION,
          "INLINE",
          restProps.content?.metadata?.id
        );
      });
    }, [biLoadPromise]);
    const iframeSandboxDomain = useIframeSandboxDomain(explicitDomain, instance);
    const isBmPlatform = typeof window !== "undefined" && !!window?.ModuleRegistry;
    const environment = explicitEnvironment ?? (isBmPlatform ? "businessManager" : "liveSite");
    const resolvedTheme = useMemo(
      () => resolveTheme({ theme, environment, isMobile: restProps.isMobile }),
      [theme, environment, restProps.isMobile]
    );
    const editorPlugins = props.plugins;
    const pluginTypes = useMemo(
      () => (editorPlugins || []).filter((opt) => !isCommonPluginOptions(opt) && !("tiptapExtensions" in opt)).map((opt) => opt.type),
      [editorPlugins]
    );
    const overridePluginsMap = useOverridePluginsMap();
    const extractedPluginConfig = useMemo(
      () => extractPluginsConfig(editorPlugins),
      [editorPlugins]
    );
    const linkPreviewConfig = useMemo(() => {
      if (instance && hasPlugin(LINK_PREVIEW_TYPE, editorPlugins)) {
        return { [LINK_PREVIEW_TYPE]: { fetchData: fetchEmbedData(instance) } };
      }
      return {};
    }, [instance, editorPlugins]);
    const pluginConfig = useMemo(
      () => lodash.merge({}, extractedPluginConfig.config, linkPreviewConfig),
      [extractedPluginConfig, linkPreviewConfig]
    );
    const helpers = useMemo(() => ({ ...biHelpers, getImageUrl }), [biHelpers]);
    const setRicosEditorApi = useSetRicosEditorApi();
    const [registeredApi, setRegisteredApi] = useState(null);
    const mergedRef = useCallback(
      (node) => {
        setRegisteredApi(node);
        if (typeof ref === "function") {
          ref(node);
        } else if (ref) {
          ref.current = node;
        }
      },
      [ref]
    );
    useEffect(() => {
      setRicosEditorApi(registeredApi);
      return () => setRicosEditorApi(null);
    }, [registeredApi, setRicosEditorApi]);
    if ((restProps.debugMode?.includes("mobile") || restProps.debugMode?.includes("all")) && restProps.isMobile) {
      renderMobileDevTools();
    }
    const loadingPlaceholder = restProps.loadingPlaceholder || /* @__PURE__ */ React.createElement("div", null);
    const Wrapper = shouldShowDebuggingInfo(restProps.debugMode?.includes("all")) ? DevContextProvider : React.Fragment;
    const editorProps = {
      ...restProps,
      pluginConfig,
      helpers,
      biLogger,
      wixClient,
      instance,
      plugins: restProps.plugins,
      iframeSandboxDomain,
      theme: resolvedTheme,
      environment
    };
    return isSSR() ? /* @__PURE__ */ React.createElement("div", null) : /* @__PURE__ */ React.createElement(Wrapper, null, /* @__PURE__ */ React.createElement(RicosErrorBoundary, { onError: restProps.onError }, /* @__PURE__ */ React.createElement(Suspense, { fallback: loadingPlaceholder }, /* @__PURE__ */ React.createElement(LocaleResourceProviderLazy, { fallback: loadingPlaceholder, locale: restProps.locale }, (locale) => (t) => hasWixInsiderOverride ? overridePluginsMap ? /* @__PURE__ */ React.createElement(
      OverrideFullRicosEditorLazy,
      {
        ...editorProps,
        pluginsMap: overridePluginsMap,
        locale,
        t,
        ref: mergedRef,
        platform: isiOS() ? "macOs" : "windows"
      }
    ) : loadingPlaceholder : /* @__PURE__ */ React.createElement(
      FullRicosEditorLazy,
      {
        ...editorProps,
        pluginTypes,
        locale,
        t,
        ref: mergedRef,
        platform: isiOS() ? "macOs" : "windows"
      }
    )))));
  }
);
RicosEditor.displayName = "RicosEditor";
export {
  RicosEditor
};
//# sourceMappingURL=ricos-editor.js.map
