import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { memo, useLayoutEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { isSSR } from '../core-utils/is-ssr';
import { PortalBucket } from './PortalBucket';
export function createPortalRendererComponent(portalManager) {
  return function PortalRenderer() {
    var _useState = useState(portalManager.getBuckets()),
      _useState2 = _slicedToArray(_useState, 2),
      buckets = _useState2[0],
      setBuckets = _useState2[1];
    useLayoutEffect(function () {
      portalManager.registerPortalRenderer(setBuckets);
      return function () {
        portalManager.unregisterPortalRenderer();
      };
    }, []);
    var portalsElements = useMemo(
    // Ignored via go/ees005
    // eslint-disable-next-line react/no-array-index-key
    function () {
      return buckets.map(function (_, i) {
        return /*#__PURE__*/React.createElement(PortalBucket, {
          key: i,
          id: i,
          portalManager: portalManager
        });
      });
    }, [buckets]);
    return /*#__PURE__*/React.createElement(React.Fragment, null, portalsElements);
  };
}

/**
 * Wraps the children of a portal to allow for React rendering
 * lifecycle hook to be exposed, primarily for node virtualization.
 */
export var PortalRenderWrapperInner = function PortalRenderWrapperInner(_ref) {
  var getChildren = _ref.getChildren,
    onBeforeRender = _ref.onBeforeRender;
  useLayoutEffect(function () {
    if (onBeforeRender) {
      onBeforeRender();
    }
  }, [onBeforeRender]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, getChildren());
};
var PortalRenderWrapper = /*#__PURE__*/memo(PortalRenderWrapperInner);
PortalRenderWrapper.displayName = 'PortalRenderWrapper';

// Tree-shakable renderToStaticMarkup that should work only in SSR
function getRenderToStaticMarkup() {
  if (process.env.REACT_SSR) {
    return require('react-dom/server').renderToStaticMarkup;
  }
  return function () {
    return '';
  };
}

/**
 * Creates a portal provider for managing multiple React portals. The provider
 * facilitates rendering, removing, and destroying portals managed by a given
 * PortalManager.
 *
 * @param {PortalManager} portalManager - An instance of a PortalManager which
 * is responsible for registering, managing, and destroying portals.
 * @returns {PortalProviderAPI} An object containing methods to render, remove, and destroy
 * portals.
 *  - `render(children, container, key)` Renders a new React portal with the given
 *    children, mounts it into the specified DOM container, and registers it
 *    with the PortalManager using a unique key.
 *  - `remove(key)` Removes a previously rendered portal identified by its key
 *    and deregisters it from the PortalManager.
 *  - `destroy()` Clears all portals managed by this provider and invokes the
 *    destroy method on the PortalManager to clean up any resources.
 *
 */
export var getPortalProviderAPI = function getPortalProviderAPI(portalManager) {
  var portalsMap = new Map();
  return {
    render: function render(children, container, key, onBeforeReactDomRender) {
      var immediate = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
      if (isSSR() && expValEquals('platform_editor_editor_ssr_streaming', 'isEnabled', true)) {
        var html = '';
        try {
          var renderToStaticMarkup = getRenderToStaticMarkup();
          var Children = children;
          html = renderToStaticMarkup( /*#__PURE__*/React.createElement(Children, null));
        } catch (error) {
          if (process.env.NODE_ENV !== 'production') {
            var _Array$from$find$repl, _Array$from$find;
            // Extract the nodeView type name from container classes, e.g. "mediaSingleView-content-wrap" → "mediaSingle"
            var nodeTypeName = (_Array$from$find$repl = (_Array$from$find = Array.from(container.classList).find(function (c) {
              return c.endsWith('View-content-wrap');
            })) === null || _Array$from$find === void 0 ? void 0 : _Array$from$find.replace('View-content-wrap', '')) !== null && _Array$from$find$repl !== void 0 ? _Array$from$find$repl : 'unknown';
            // eslint-disable-next-line no-console
            console.warn("[EditorSSR] Failed to render \"".concat(nodeTypeName, "\" nodeView to static markup during SSR streaming. ") + 'The container will be empty. This is likely caused by a React hook ' + '(e.g. useSharedPluginStateWithSelector, useIntl) that requires a context ' + "not available during renderToStaticMarkup. Ensure the nodeView's render() " + 'is wrapped with Context Providers, or that the hook has an SSR-safe fallback.', error);
          }
        }
        container.innerHTML = html;
      } else {
        if (typeof onBeforeReactDomRender === 'function') {
          var portal = /*#__PURE__*/createPortal( /*#__PURE__*/React.createElement(PortalRenderWrapper, {
            getChildren: children,
            onBeforeRender: onBeforeReactDomRender
          }), container, key);
          portalsMap.set(key, portalManager.registerPortal(key, portal, immediate));
        } else {
          var _portal = /*#__PURE__*/createPortal(children(), container, key);
          portalsMap.set(key, portalManager.registerPortal(key, _portal, immediate));
        }
      }
    },
    remove: function remove(key) {
      var _portalsMap$get;
      if (isSSR() && expValEquals('platform_editor_editor_ssr_streaming', 'isEnabled', true)) {
        return;
      }
      (_portalsMap$get = portalsMap.get(key)) === null || _portalsMap$get === void 0 || _portalsMap$get();
      portalsMap.delete(key);
    },
    destroy: function destroy() {
      portalsMap.clear();
      portalManager.destroy();
    }
  };
};