"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 guest_microapp_exports = {};
__export(guest_microapp_exports, {
  GuestMicroApp: () => GuestMicroApp
});
module.exports = __toCommonJS(guest_microapp_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_styled_components = __toESM(require("styled-components"));
var import_react_redux = require("react-redux");
var import_pui_logrocket = require("@elliemae/pui-logrocket");
var import_types = require("../utils/micro-frontend/types.js");
var import_app_bridge = require("../utils/micro-frontend/app-bridge.js");
var import_ssf_host2 = require("../utils/micro-frontend/ssf-host.js");
var import_actions = require("../data/wait-message/actions.js");
var import_micro_frontend = require("../utils/micro-frontend/index.js");
const Div = import_styled_components.default.div`
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: column;
  overflow: hidden;
`;
const useAppRenderer = (props) => {
  const {
    id,
    history,
    homeRoute,
    initialRoute,
    onLoadComplete,
    onUnloadComplete,
    containerId,
    ssfAppOptions = {},
    disableWaitMessage = false
  } = props;
  const dispatch = (0, import_react_redux.useDispatch)();
  const getConfig = (0, import_react.useCallback)(
    () => (0, import_micro_frontend.getMicroFrontEndAppConfig)({
      id
    }),
    [id]
  );
  (0, import_react.useLayoutEffect)(() => {
    let isMounted = true;
    let appBridge = null;
    let ssfHost = null;
    let unloadInProgress = Promise.resolve();
    let instanceId = null;
    (async () => {
      await unloadInProgress;
      if (!disableWaitMessage) {
        dispatch(import_actions.waitMessage.open());
      }
      try {
        const {
          microappManager = import_types.MicroAppManager.APPSDK,
          hostUrl,
          title,
          name,
          ssfAppOptions: configSsfAppOptions = {}
        } = getConfig();
        const mergedSsfAppOptions = {
          ...configSsfAppOptions,
          ...ssfAppOptions
        };
        if (microappManager === import_types.MicroAppManager.SSF) {
          ssfHost = (0, import_ssf_host2.getSSFHost)();
          if (!ssfHost)
            throw new Error(`Failed to load ${id}, SSFHost not initialized`);
          if (isMounted) {
            const { searchParams, ...guestOptions } = mergedSsfAppOptions;
            const guest = ssfHost.loadGuest({
              id,
              url: hostUrl,
              title: title ?? name,
              targetElement: document.getElementById(containerId),
              searchParams,
              onLoad: onLoadComplete,
              options: guestOptions
            });
            instanceId = guest.id;
          }
        } else {
          appBridge = await (0, import_app_bridge.getAppBridge)();
          if (!appBridge)
            throw new Error(`Failed to load ${id}, AppBridge not initialized`);
          if (isMounted) {
            instanceId = await appBridge.openApp({
              id,
              frameOptions: {
                containerId,
                queryParams: (0, import_pui_logrocket.buildLogRocketQueryParams)()
              },
              history,
              homeRoute,
              initialRoute
            });
            setTimeout(() => {
              try {
                onLoadComplete?.(instanceId);
              } catch (ex) {
              }
            }, 0);
          }
        }
      } catch (ex) {
        (0, import_micro_frontend.getLogger)().error({
          message: `Failed to load ${id}`,
          exception: ex
        });
        isMounted = false;
        if (appBridge && instanceId)
          unloadInProgress = appBridge.closeApp(instanceId);
        if (ssfHost && instanceId)
          unloadInProgress = Promise.resolve(ssfHost.unloadGuest(instanceId));
        throw ex;
      } finally {
        if (!disableWaitMessage) {
          dispatch(import_actions.waitMessage.close());
        }
      }
    })();
    return () => {
      isMounted = false;
      if (ssfHost) {
        unloadInProgress = Promise.resolve(ssfHost.unloadGuest(instanceId));
      } else if (appBridge) {
        unloadInProgress = appBridge.closeApp(instanceId);
      }
      unloadInProgress.then(() => {
        instanceId = null;
        setTimeout(() => {
          try {
            onUnloadComplete?.();
          } catch (ex) {
          }
        }, 0);
      }).catch(() => {
      });
    };
  }, [
    containerId,
    dispatch,
    history,
    homeRoute,
    initialRoute,
    id,
    onLoadComplete,
    onUnloadComplete,
    getConfig,
    ssfAppOptions,
    disableWaitMessage
  ]);
};
const GuestMicroApp = (0, import_react.memo)(
  (props) => {
    const containerId = (0, import_react.useRef)(crypto.randomUUID());
    useAppRenderer({ ...props, containerId: containerId.current });
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Div, { id: containerId.current });
  }
);
