import React, { memo, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

export function createGlobalStyleOnce(GlobalStyle: () => React.ReactElement) {
  let isInjected = false;
  const InjectStyleOnce = memo(() => {
    const [isFirstInject] = useState(!isInjected);

    useEffect(() => {
      return () => {
        if (!isFirstInject) {
          return;
        }
        isInjected = false;
      };
    }, [isFirstInject]);

    if (!isFirstInject) {
      return null;
    } else {
      isInjected = true;
    }

    return <GlobalStyle />;
  });
  return InjectStyleOnce;
}

export function injectStyleToBody(globalStyle: React.ReactNode) {
  if (typeof document !== "undefined") {
    const container = document.createElement("div");
    const root = createRoot(container);
    root.render(globalStyle);
    document.body.appendChild(container);
  }
}
