import LoadingScreen from "@/components/LoadingScreen";
import { Modal } from "@/components/modal";
import { useDictionary, useModals } from "@/hooks/global";
import React from "react";

const GlobalContext = React.createContext<GlobalContextProps>(undefined);

export const Global = ({
  children,
}: GlobalContextProviderProps): React.JSX.Element => {
  const dict = useDictionary();
  const { list, ...modals } = useModals();

  return (
    <GlobalContext.Provider value={{ dict, ...modals }}>
      {!dict ? (
        <LoadingScreen />
      ) : (
        <>
          {children}
          {list.length > 0 && list.map((e, i) => <Modal key={i} {...e} />)}
        </>
      )}
    </GlobalContext.Provider>
  );
};

export const useGlobal = (): GlobalContextProps => {
  const context = React.useContext(GlobalContext);
  if (!context) {
    throw new Error("useGlobal must be used within a GlobalProvider");
  }
  return context;
};
