import { CacheProvider, ThemeProvider } from '@emotion/react';
import { useContext, useRef } from 'react';
import * as React from 'react';
import { createEmotionCache } from './cache';
import { Reboot, Typography } from './globals';
import { Variables } from './globals/Variables';
import { coreTheme } from './themes/core';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
export const GamutContext = /*#__PURE__*/React.createContext({
  hasGlobals: false,
  hasCache: false
});
GamutContext.displayName = 'GamutContext';
export const GamutProvider = ({
  children,
  cache,
  theme = coreTheme,
  variables,
  useGlobals = true,
  useCache = true,
  nonce,
  useLogicalProperties = true
}) => {
  const {
    hasGlobals,
    hasCache
  } = useContext(GamutContext);
  const shouldCreateCache = useCache && !hasCache;
  const shouldInsertGlobals = useGlobals && !hasGlobals;

  // Do not initialize a new cache if one has been provided as props
  const activeCache = useRef(shouldCreateCache && (cache ?? createEmotionCache(nonce ? {
    nonce
  } : {})));
  const contextValue = {
    hasGlobals: shouldInsertGlobals,
    hasCache: shouldCreateCache
  };
  const globals = shouldInsertGlobals && /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsx(Typography, {
      theme: theme
    }), /*#__PURE__*/_jsx(Reboot, {
      theme: theme
    }), /*#__PURE__*/_jsx(Variables, {
      variables: theme._variables
    }), variables && /*#__PURE__*/_jsx(Variables, {
      variables: variables
    })]
  });

  // Merge useLogicalProperties into theme so variance can access it via props.theme
  const themeWithLogicalProperties = {
    ...theme,
    useLogicalProperties
  };
  if (activeCache.current) {
    return /*#__PURE__*/_jsx(GamutContext.Provider, {
      value: contextValue,
      children: /*#__PURE__*/_jsxs(CacheProvider, {
        value: activeCache.current,
        children: [globals, /*#__PURE__*/_jsx(ThemeProvider, {
          theme: themeWithLogicalProperties,
          children: children
        })]
      })
    });
  }
  return /*#__PURE__*/_jsxs(GamutContext.Provider, {
    value: contextValue,
    children: [globals, /*#__PURE__*/_jsx(ThemeProvider, {
      theme: themeWithLogicalProperties,
      children: children
    })]
  });
};