import React, { useRef, useEffect } from 'react';
import { logger } from '@zenview/micro-utils';
import { getMicroConfig } from './utils';
import LoaderModule from './loader';
import './index.less';

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 (
    <main ref={domRef} className="loaded-app-layout" style={style}>
      <div id={appConfig.name}></div>
    </main>
  );
}

export default React.memo(LoaderApp);
