import { useEffect } from "react";
import { render, unmountComponentAtNode } from "react-dom";

import styles from "./index.module.scss";

const _Background: React.FC<{
  style?: React.CSSProperties;
  innerStyle?: React.CSSProperties;
}> = ({ style, innerStyle }) => {
  return (
    <div className={styles.background} style={style}>
      <div className={styles.inner} style={innerStyle}></div>
    </div>
  );
};

/** HOC: 将组件发射到body下 */
const withPortalToBody = <P extends object>(
  WrappedComponent: React.ComponentType<P>
) => {
  return (props: P) => {
    useEffect(() => {
      // 创建一个新的容器元素
      const portalRoot = document.body;
      const firstChild = portalRoot.firstChild;
      const newNode = document.createElement("div");
      portalRoot.insertBefore(newNode, firstChild);

      // 渲染组件到新的容器中
      render(<WrappedComponent {...props} />, newNode);

      return () => {
        // 卸载组件并且移除容器
        unmountComponentAtNode(newNode);
        portalRoot.removeChild(newNode);
      };
    }, []);

    return null; // 返回null，避免在原来的位置渲染任何东西
  };
};

export const Background = withPortalToBody(_Background);
