import React__default, { useRef, useEffect } from 'react';
import { logger } from '@zenview/micro-utils';

const getMicroConfig = (appConfig = {}, appProps, container) => {
  const {
    name,
    script,
    entry
  } = appConfig;
  if (!name) {
    return;
  }
  const microAppEntry = entry ? entry : {
    scripts: [script],
    styles: undefined,
    html: `<div id="${name}" style="height:100%"></div>`
  };
  return {
    name,
    container,
    props: appProps,
    entry: microAppEntry
  };
};

const LOAD_STYLE = window.LOAD_STYLE = {};
const LOAD_SCRIPT = window.LOAD_SCRIPT = {};
function LoaderScript(src) {
  if (LOAD_SCRIPT[src]) {
    return Promise.resolve(LOAD_SCRIPT[src]);
  }
  return window.System.import(src).then(m => {
    LOAD_SCRIPT[src] = m;
    return m;
  });
}
function LoaderStyle(href) {
  if (LOAD_STYLE[href]) {
    return Promise.resolve();
  }
  return new Promise((resolve, reject) => {
    LOAD_STYLE[href] = true;
    let link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('type', 'text/css');
    link.setAttribute('href', href);
    link.addEventListener('load', () => {
      resolve();
    });
    link.addEventListener('error', e => {
      reject(e);
    });
    document.head.appendChild(link);
  });
}
async function LoaderModule({
  script,
  style
}) {
  await LoaderStyle(style);
  return await LoaderScript(script);
}

function LoaderApp({
  appConfig,
  appProps,
  style
}) {
  const domRef = useRef(null);
  const microAppRef = useRef(null);
  useEffect(() => {
    const config = getMicroConfig(appConfig, appProps, domRef.current);
    if (!config) {
      logger.debug('微应用不存在', 'config ->', appConfig, 'appProps ->', appProps);
      return;
    }
    // microAppRef.current = loadMicroApp(config, { singular: false, sandbox: { strictStyleIsolation: !excludeCssSandBox.includes(config.name), experimentalStyleIsolation: false } });
    const props = {
      ...appProps,
      container: domRef.current
    };
    LoaderModule({
      script: appConfig.script,
      style: appConfig.style
    }).then(async m => {
      microAppRef.current = m;
      await microAppRef.current.bootstrap(props);
      await microAppRef.current.mount(props);
    });
    return () => {
      try {
        microAppRef.current.unmount(props);
        microAppRef.current = null;
      } catch (error) {
        logger.debug(error);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return /*#__PURE__*/React__default.createElement("main", {
    ref: domRef,
    className: "loaded-app-layout",
    style: style
  }, /*#__PURE__*/React__default.createElement("div", {
    id: appConfig.name
  }));
}
var index = /*#__PURE__*/React__default.memo(LoaderApp);

export { index as default };
//# sourceMappingURL=index.js.map
