import lodash from "lodash";
import React, { useEffect } from "react";
import { ConvertersContext } from "./../../pm-converters/context.js";
import { ContentQueryProvider } from "./../../ricos-content-query/index.js";
import {
  EditorContextProvider,
  EditorQueryContextProvider,
  PluginExportsContextProvider,
  PluginsContextProvider,
  PluginsEventsContextProvider,
  RicosContextProvider,
  SchemaContextProvider,
  ShortcutsContextProvider,
  ToolbarContextProvider,
  UploadContextProvider,
  ZIndexContextProvider,
  useDevService,
  useTrackRender
} from "./../../ricos-context/index.js";
import { OrchestratorContext } from "./../../ricos-context/orchestrator-context.js";
import { PmContentContextProvider } from "./../../ricos-context/pm-content-context.js";
import { SelectionContextProvider } from "./../../ricos-context/selection-context.js";
import { useShortcuts } from "./../shortcuts/use-shortcuts.js";
import { ModalRenderer } from "./../../ricos-modals/index.js";
import {
  ModalProvider,
  useModalService,
  useModalStateContext
} from "./../../ricos-modals/modal-service-provider.js";
import { RicosOrchestrator } from "./../../ricos-orchestrator/index.js";
import { PluginGlobalComponents } from "./../../ricos-plugins/plugin-global-components.js";
import { PluginProviders } from "./../../ricos-plugins/plugin-providers.js";
import { StylesContextProvider } from "./../../ricos-styles/index.js";
import { ThemeProvider, useTheme } from "./../../ricos-styles/theme-provider.js";
import { BiContextProvider } from "./../../_shared/bi-context-provider/bi-context-provider.js";
import { BiHelpersProvider } from "./../../_shared/bi-helpers-context/bi-helpers-context.js";
import { EditorBaseUrlContextProvider } from "./../../_shared/editor-base-url/editor-base-url-context.js";
import {
  RequestServiceProvider,
  useRequestService
} from "./../../_shared/request-service-provider/request-service-provider.js";
import {
  WixInstanceContextProvider,
  useWixInstanceService
} from "./../../_shared/request-service-provider/wix-instance-context.js";
import { SitePagesFetchContextProvider } from "./../../_shared/site-pages/site-pages-fetch-context.js";
import { SomeEditorPropsContextProvider } from "./../../_shared/some-editor-props-context.js";
import { useUserInteraction } from "./../../_shared/use-user-interaction.js";
import { getLangDir } from "./../../wix-rich-content-common/index.js";
import { RicosPortal } from "./../../editor-common/index.js";
import { MobileToolbar } from "./../../toolbars-v3/index.js";
import { ToolbarBoundaryProvider } from "./../../toolbars-v3/toolbar-boundary.js";
import { resolvePlugins } from "../../_shared/dynamic-plugins-map.js";
import { normalizeContent } from "../normalize-content.js";
import { hasActiveUploads } from "./active-uploads.js";
import { ErrorNotifier } from "./error-notifier.js";
import { RicosEditorWithForwardRef as RicosEditor } from "./ricos-editor.js";
import { RicosErrorBoundary } from "./ricos-error-boundary.js";
import { RicosToolbars } from "./ricos-toolbars.js";
import { StyledEditorContainer } from "./styled-editor-container.js";
const InjectedContentContext = React.createContext(void 0);
const PlaceholderContext = React.createContext(void 0);
const RicosEditorFallback = ({ Editor }) => /* @__PURE__ */ React.createElement(Editor, null);
const ShortcutsSetup = () => {
  useShortcuts();
  return null;
};
const InnerFullRicosEditor = React.forwardRef((props, ref) => {
  const modalService = useModalService();
  const theme = useTheme();
  const devService = useDevService();
  const wixInstance = useWixInstanceService();
  const makeRequestService = useRequestService();
  const [orchestrator] = React.useState(
    () => new RicosOrchestrator({
      editorProps: props,
      t: props.t,
      platform: props.platform,
      modalService,
      devService,
      wixInstance,
      makeRequestService,
      pluginsMap: props.pluginsMap
    })
  );
  useModalStateContext({
    onSelectorContextValue: (selectorContextValue) => {
      return orchestrator.modalStateSelectorContextValue = selectorContextValue;
    }
  });
  const [portalRef, setPortalRef] = React.useState(null);
  const editorRef = React.useRef(null);
  const [errorNotifierRef, setErrorNotifierRef] = React.useState(null);
  const [inputRef, setInputRef] = React.useState(null);
  useTrackRender("FullRicosEditor");
  const { lastInteraction } = useUserInteraction();
  React.useEffect(() => {
    window.ricosEditor = orchestrator.getServices().editor;
    return () => {
      delete window.ricosEditor;
    };
  }, []);
  React.useEffect(() => {
    if (errorNotifierRef && inputRef) {
      orchestrator.setUpdateServiceDom(
        () => errorNotifierRef,
        () => inputRef
      );
    }
  }, [orchestrator, errorNotifierRef, inputRef]);
  const Editor = React.useMemo(
    () => React.memo(() => {
      const injectedContent = React.useContext(InjectedContentContext);
      const placeholder = React.useContext(PlaceholderContext);
      const [isBusy, setIsBusy] = React.useState(false);
      const onBusyChange = React.useCallback(
        (pmContent) => {
          const { onBusyChange: onBusyChange2 } = props;
          const isCurrentlyBusy = hasActiveUploads(pmContent);
          if (isBusy !== isCurrentlyBusy) {
            setIsBusy(isCurrentlyBusy);
            onBusyChange2?.(isCurrentlyBusy);
          }
        },
        [props.onBusyChange, isBusy]
      );
      const onChange = React.useCallback(
        (content2, meta) => {
          props.onChange?.(content2, meta);
        },
        [props.onChange]
      );
      return /* @__PURE__ */ React.createElement(
        RicosEditor,
        {
          ...props,
          injectedContent,
          placeholder,
          onChange,
          onInternalBusyChange: onBusyChange,
          ref
        }
      );
    }),
    []
  );
  const Children = props.children || RicosEditorFallback;
  const {
    plugins,
    shortcuts,
    content,
    uploadService,
    updateService,
    editor,
    styles,
    pluginsEvents,
    schema,
    zIndexService,
    getEditorQuery,
    context,
    converters
  } = orchestrator.getServices();
  const pluginExports = orchestrator.getPluginExports();
  const documentStyle = schema.getContent().documentStyle || {};
  const languageDir = getLangDir(context.locale);
  useEffect(() => {
    if (portalRef) {
      orchestrator.setPortalRef(portalRef);
    }
  }, [portalRef]);
  orchestrator.biHelpersRef.current = props.helpers || {};
  return /* @__PURE__ */ React.createElement(OrchestratorContext.Provider, { value: orchestrator }, /* @__PURE__ */ React.createElement(RicosErrorBoundary, { onError: props.onError, editor }, /* @__PURE__ */ React.createElement(BiContextProvider, { biLogger: props.biLogger }, /* @__PURE__ */ React.createElement(BiHelpersProvider, { helpers: props.helpers || {} }, /* @__PURE__ */ React.createElement(EditorBaseUrlContextProvider, { baseUrl: props.baseUrl }, /* @__PURE__ */ React.createElement(SitePagesFetchContextProvider, null, /* @__PURE__ */ React.createElement(ConvertersContext.Provider, { value: converters }, /* @__PURE__ */ React.createElement(
    ToolbarBoundaryProvider,
    {
      editorContainer: editorRef.current,
      externalContainer: props.container
    },
    /* @__PURE__ */ React.createElement(
      StylesContextProvider,
      {
        styles,
        documentStyle,
        theme,
        environment: props.environment ?? "liveSite",
        isMobile: context.isMobile
      },
      /* @__PURE__ */ React.createElement(StyledEditorContainer, { ref: editorRef }, /* @__PURE__ */ React.createElement(ZIndexContextProvider, { zIndexService }, /* @__PURE__ */ React.createElement(PluginsContextProvider, { plugins }, /* @__PURE__ */ React.createElement(PluginProviders, { plugins }, /* @__PURE__ */ React.createElement(
        RicosPortal,
        {
          languageDir,
          ref: setPortalRef,
          environment: props.environment
        }
      ), portalRef && /* @__PURE__ */ React.createElement(
        RicosContextProvider,
        {
          t: context.t,
          isMobile: context.isMobile,
          experiments: context.experiments,
          locale: context.locale,
          localeContent: context.localeContent,
          languageDir: context.languageDir,
          theme,
          portal: portalRef,
          debugMode: context.debugMode,
          jsdomMode: context.jsdomMode,
          platform: context.platform,
          content,
          environment: context.environment,
          tabIndex: context.tabIndex,
          lastInteraction,
          tabFocusBehavior: context.tabFocusBehavior,
          colorManager: props.colorManager
        },
        /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(EditorContextProvider, { editor }, /* @__PURE__ */ React.createElement(EditorQueryContextProvider, { editorQuery: getEditorQuery() }, /* @__PURE__ */ React.createElement(ShortcutsContextProvider, { shortcuts }, /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
          PluginsEventsContextProvider,
          {
            pluginsEvents
          },
          /* @__PURE__ */ React.createElement(PluginExportsContextProvider, { value: pluginExports }, /* @__PURE__ */ React.createElement(SchemaContextProvider, { schema }, /* @__PURE__ */ React.createElement(
            UploadContextProvider,
            {
              uploadService,
              updateService
            },
            /* @__PURE__ */ React.createElement(
              ToolbarContextProvider,
              {
                toolbarSettings: props.toolbarSettings,
                onSelectorContextValue: (selectorContextValue) => orchestrator.toolbarStateSelectorContextValue = selectorContextValue
              },
              /* @__PURE__ */ React.createElement(
                ContentQueryProvider,
                {
                  editor: editor.adapter.tiptapEditor
                },
                /* @__PURE__ */ React.createElement(
                  SelectionContextProvider,
                  {
                    onSelectorContextValue: (selectorContextValue) => orchestrator.selectionSelectorContextValue = selectorContextValue
                  },
                  /* @__PURE__ */ React.createElement(
                    PmContentContextProvider,
                    {
                      onSelectorContextValue: (selectorContextValue) => orchestrator.pmContentSelectorContextValue = selectorContextValue
                    },
                    /* @__PURE__ */ React.createElement(MobileToolbar, null),
                    /* @__PURE__ */ React.createElement(
                      InjectedContentContext.Provider,
                      {
                        value: props.injectedContent
                      },
                      /* @__PURE__ */ React.createElement(
                        PlaceholderContext.Provider,
                        {
                          value: props.placeholder
                        },
                        /* @__PURE__ */ React.createElement(Children, { Editor }),
                        /* @__PURE__ */ React.createElement(
                          PluginGlobalComponents,
                          {
                            plugins
                          }
                        )
                      )
                    ),
                    /* @__PURE__ */ React.createElement(RicosToolbars, null)
                  )
                ),
                /* @__PURE__ */ React.createElement(ModalRenderer, null)
              )
            )
          )))
        ), /* @__PURE__ */ React.createElement(ShortcutsSetup, null))))), /* @__PURE__ */ React.createElement(
          ErrorNotifier,
          {
            ref: setErrorNotifierRef,
            isMobile: props.isMobile,
            languageDir
          }
        ), /* @__PURE__ */ React.createElement(
          "input",
          {
            ref: setInputRef,
            id: "ricos-file-upload-input",
            key: "ricosUploadInput",
            type: "file",
            style: { display: "none" },
            tabIndex: -1,
            multiple: true
          }
        ))
      )))))
    )
  ))))))));
});
const FullRicosEditor = React.forwardRef(
  ({ content, injectedContent, pluginTypes, pluginsMap: pluginsMapProp, ...restProps }, ref) => {
    if (!(lodash.isPlainObject(content) || content === null || content === void 0)) {
      console.error("Invalid content prop provided to RicosEditor:", content);
      restProps.onError?.("Invalid content prop provided to RicosEditor");
      throw Error("Invalid content prop provided to RicosEdidtor");
    }
    if (!(lodash.isPlainObject(injectedContent) || injectedContent === null || injectedContent === void 0)) {
      console.error("Invalid injectedContent prop provided to RicosEditor:", injectedContent);
      restProps.onError?.("Invalid injectedContent prop provided to RicosEditor");
      throw Error("Invalid injectedContent prop provided to RicosEditor");
    }
    const normalizedContent = React.useMemo(
      () => content ? normalizeContent(content) : content,
      [content]
    );
    const normalizedInjectedContent = React.useMemo(
      () => injectedContent ? normalizeContent(injectedContent) : injectedContent,
      [injectedContent]
    );
    const [resolvedPluginsMap, setResolvedPluginsMap] = React.useState(pluginsMapProp ?? null);
    React.useEffect(() => {
      if (pluginsMapProp) {
        return;
      }
      let cancelled = false;
      resolvePlugins(pluginTypes ?? []).then((map) => {
        if (!cancelled) {
          setResolvedPluginsMap(map);
        }
      });
      return () => {
        cancelled = true;
      };
    }, [pluginTypes, pluginsMapProp]);
    if (!resolvedPluginsMap) {
      return /* @__PURE__ */ React.createElement(React.Fragment, null, restProps.loadingPlaceholder || /* @__PURE__ */ React.createElement("div", null));
    }
    return /* @__PURE__ */ React.createElement(ModalProvider, { modalSettings: restProps.modalSettings }, /* @__PURE__ */ React.createElement(ThemeProvider, { theme: restProps.theme }, /* @__PURE__ */ React.createElement(
      SomeEditorPropsContextProvider,
      {
        visitorUploads: restProps.visitorUploads,
        fileUploadSizeLimit: restProps.fileUploadSizeLimit,
        biSettings: restProps.biSettings,
        pickMedia: restProps.pickMedia,
        generalLinkSettings: restProps.generalLinkSettings,
        historySettings: restProps.historySettings,
        helpers: restProps.helpers,
        iframeSandboxDomain: restProps.iframeSandboxDomain,
        instance: restProps.instance
      },
      /* @__PURE__ */ React.createElement(RequestServiceProvider, { wixClient: restProps.wixClient, instance: restProps.instance }, /* @__PURE__ */ React.createElement(WixInstanceContextProvider, { instance: restProps.instance }, /* @__PURE__ */ React.createElement(
        InnerFullRicosEditor,
        {
          ...restProps,
          pluginsMap: resolvedPluginsMap,
          content: normalizedContent,
          injectedContent: normalizedInjectedContent,
          ref
        }
      )))
    )));
  }
);
var full_ricos_editor_default = FullRicosEditor;
export {
  FullRicosEditor,
  full_ricos_editor_default as default
};
//# sourceMappingURL=full-ricos-editor.js.map
