"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ricos_viewer_next_exports = {};
__export(ricos_viewer_next_exports, {
  RicosViewerWithHelpers: () => RicosViewerWithHelpers
});
module.exports = __toCommonJS(ricos_viewer_next_exports);
var import_lodash = __toESM(require("lodash"));
var import_react = __toESM(require("react"));
var import_ricos_media = require("./../ricos-media/index.js");
var import_ricos_content = require("./../ricos-content/index.js");
var import_resolve_theme = require("./../ricos-styles/resolve-theme.js");
var import_theme_provider = require("./../ricos-styles/theme-provider.js");
var import_use_bi_helpers = require("./../_shared/bi-strategy/use-bi-helpers.js");
var import_extract_plugins_config = require("./../_shared/extract-plugins-config.js");
var import_has_plugin = require("./../_shared/has-plugin.js");
var import_parse_instance = require("./../_shared/request-service-provider/parse-instance.js");
var import_request_service_provider = require("./../_shared/request-service-provider/request-service-provider.js");
var import_wix_instance_context = require("./../_shared/request-service-provider/wix-instance-context.js");
var import_url_resolvers = require("./../_shared/url-resolvers.js");
var import_use_iframe_sandbox_domain = require("./../_shared/use-iframe-sandbox-domain.js");
var import_wix_rich_content_common = require("./../wix-rich-content-common/index.js");
var import_dev_tools = require("./../wix-rich-content-common/lib/dev-tools.js");
var import_ricos_content_analytics = require("./../wix-rich-content-common/lib/ricos-content-analytics.js");
var import_change_base_url = require("./change-base-url.js");
var import_ContentViewer = require("./ContentViewer/index.js");
var import_is_viewer_plugin = require("./is-viewer-plugin.js");
var import_utils = require("./utils.js");
class RicosViewerNext extends import_react.Component {
  constructor(props) {
    super(props);
    this.loadTextSelection = () => {
      const { textSelectionToolbar, isMobile } = this.props;
      const needTextSelectionToolbar = textSelectionToolbar && !isMobile;
      if (needTextSelectionToolbar && !this.state.TextSelectionToolbar) {
        const TextSelectionToolbar = import_react.default.lazy(() => Promise.resolve().then(() => __toESM(require("./text-selection-toolbar.js"))));
        this.setState({ TextSelectionToolbar });
      }
    };
    this.onMouseOver = () => {
      this.loadTextSelection();
    };
    this.getBiCallback = (key) => {
      const { children, helpers } = this.props;
      return children?.props.helpers?.[key] || helpers?.[key];
    };
    this.viewerRef = (0, import_react.createRef)();
    this.state = {};
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  componentDidCatch(error, errorInfo) {
    console.error({ error, errorInfo });
  }
  componentDidMount() {
    (0, import_wix_rich_content_common.addDevToolsClickListener)(
      this.viewerRef.current,
      () => this.setState({ debugInvokedWithMouse: true })
    );
  }
  render() {
    const { seoSettings, mediaSettings, content, debugMode, isPrint } = this.props;
    const { TextSelectionToolbar } = this.state;
    const mergedProps = (0, import_utils.mergeViewerProps)({
      ...this.props,
      viewerProps: {
        seoMode: seoSettings,
        onMouseOver: this.onMouseOver,
        locale: this.props.locale,
        isPrint
      }
    });
    try {
      if (this.state.error) {
        this.props.onError?.(this.state.error);
        return null;
      }
      return [
        /* @__PURE__ */ import_react.default.createElement(
          import_ContentViewer.ContentViewer,
          {
            ...mergedProps,
            content: this.state.content ?? mergedProps.content,
            config: mergedProps.config,
            onHover: () => {
            },
            key: "viewer",
            setRef: this.viewerRef,
            fullscreenProps: mediaSettings?.fullscreenProps,
            devTools: this.state.debugInvokedWithMouse || (0, import_dev_tools.shouldShowDebuggingInfo)(debugMode?.includes("all")) ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Suspense, null, /* @__PURE__ */ import_react.default.createElement(
              import_dev_tools.RicosDevToolsLazy,
              {
                schema: {
                  getContent: () => this.state.content ?? mergedProps.content,
                  setContent: (content2) => this.setState({ content: content2 })
                },
                version: import_ricos_content.Version.currentVersion,
                mode: "viewer",
                contentState: content,
                ricosProps: this.props,
                autoOpen: this.state.debugInvokedWithMouse ?? false
              }
            )) : null
          }
        ),
        TextSelectionToolbar ? /* @__PURE__ */ import_react.default.createElement(import_react.Suspense, { key: "TextSelectionToolbar", fallback: /* @__PURE__ */ import_react.default.createElement("div", null) }, /* @__PURE__ */ import_react.default.createElement(
          TextSelectionToolbar,
          {
            onButtonClick: this.getBiCallback("onViewerAction"),
            container: this.viewerRef.current
          }
        )) : null
      ];
    } catch (e) {
      this.props.onError?.(e);
      return null;
    }
  }
}
RicosViewerNext.displayName = "RicosViewerNext";
RicosViewerNext.defaultProps = {
  onError: (err) => {
    throw err;
  }
};
const RicosViewerWithHelpers = (props) => {
  const {
    biSettings,
    instance,
    wixClient,
    iframeSandboxDomain: explicitDomain,
    theme,
    baseUrl,
    ...restProps
  } = props;
  const { helpers: biHelpers, biLoadPromise } = (0, import_use_bi_helpers.useBiHelpers)({ instance, biSettings });
  const { metaSiteId } = (0, import_react.useMemo)(() => (0, import_parse_instance.parseInstance)(props.instance), [props.instance]);
  (0, import_react.useEffect)(() => {
    biLoadPromise.then((callbacks) => {
      const content = props.content;
      const { pluginsCount } = content && (0, import_ricos_content_analytics.getContentSummary)(content) || {};
      if (pluginsCount) {
        callbacks.onViewerLoaded?.({
          isPreview: false,
          version: import_ricos_content.Version.currentVersion,
          pluginsCount,
          url: document.URL,
          contentId: content?.metadata?.id
        });
      }
    });
  }, []);
  const iframeSandboxDomain = (0, import_use_iframe_sandbox_domain.useIframeSandboxDomain)(explicitDomain, instance);
  const resolvedTheme = (0, import_react.useMemo)(
    () => (0, import_resolve_theme.resolveTheme)({ theme, isMobile: restProps.isMobile }),
    [theme, restProps.isMobile]
  );
  const viewerPlugins = (0, import_react.useMemo)(() => props.plugins?.filter(import_is_viewer_plugin.isViewerPlugin), [props.plugins]);
  const extractedPluginConfig = (0, import_react.useMemo)(() => (0, import_extract_plugins_config.extractPluginsConfig)(viewerPlugins), [viewerPlugins]);
  const verticalEmbedConfig = (0, import_react.useMemo)(() => {
    if (baseUrl && (0, import_has_plugin.hasPlugin)(import_ricos_content.VERTICAL_EMBED_TYPE, viewerPlugins)) {
      return {
        [import_ricos_content.VERTICAL_EMBED_TYPE]: {
          changeBaseUrl: (url) => (0, import_change_base_url.changeBaseUrl)(url, baseUrl)
        }
      };
    }
    return {};
  }, [baseUrl, viewerPlugins]);
  const pluginConfig = (0, import_react.useMemo)(
    () => import_lodash.default.merge({}, extractedPluginConfig.config, verticalEmbedConfig),
    [extractedPluginConfig, verticalEmbedConfig]
  );
  const helpers = (0, import_react.useMemo)(
    () => ({
      ...biHelpers,
      getImageUrl: import_url_resolvers.getImageUrl,
      resolveFileUrl: (
        // Some urls might be resolved even without msid or instance, so we call it regardless
        (0, import_ricos_media.resolveFileUrl)(props.msid ?? metaSiteId ?? "", props.instance ?? "")
      )
    }),
    [biHelpers, props.msid, props.instance, metaSiteId]
  );
  return /* @__PURE__ */ import_react.default.createElement(import_request_service_provider.RequestServiceProvider, { wixClient, instance }, /* @__PURE__ */ import_react.default.createElement(import_wix_instance_context.WixInstanceContextProvider, { instance }, /* @__PURE__ */ import_react.default.createElement(import_theme_provider.ThemeProvider, { theme: resolvedTheme }, /* @__PURE__ */ import_react.default.createElement(
    RicosViewerNext,
    {
      ...restProps,
      msid: props.msid ?? metaSiteId,
      pluginConfig,
      helpers,
      iframeSandboxDomain,
      theme: resolvedTheme,
      baseUrl
    }
  ))));
};
RicosViewerWithHelpers.displayName = "RicosViewer";
//# sourceMappingURL=ricos-viewer-next.js.map
