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 } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
export var GamutContext = /*#__PURE__*/React.createContext({
  hasGlobals: false,
  hasCache: false
});
GamutContext.displayName = 'GamutContext';
export var GamutProvider = function GamutProvider(_ref) {
  var children = _ref.children,
    cache = _ref.cache,
    _ref$theme = _ref.theme,
    theme = _ref$theme === void 0 ? coreTheme : _ref$theme,
    variables = _ref.variables,
    _ref$useGlobals = _ref.useGlobals,
    useGlobals = _ref$useGlobals === void 0 ? true : _ref$useGlobals,
    _ref$useCache = _ref.useCache,
    useCache = _ref$useCache === void 0 ? true : _ref$useCache;
  var _useContext = useContext(GamutContext),
    hasGlobals = _useContext.hasGlobals,
    hasCache = _useContext.hasCache;
  var shouldCreateCache = useCache && !hasCache;
  var shouldInsertGlobals = useGlobals && !hasGlobals;

  // Do not initialize a new cache if one has been provided as props
  var activeCache = useRef(shouldCreateCache && (cache !== null && cache !== void 0 ? cache : createEmotionCache()));
  var contextValue = {
    hasGlobals: shouldInsertGlobals,
    hasCache: shouldCreateCache
  };
  var globals = shouldInsertGlobals && /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsx(Typography, {}), /*#__PURE__*/_jsx(Reboot, {}), /*#__PURE__*/_jsx(Variables, {
      variables: theme._variables
    }), variables && /*#__PURE__*/_jsx(Variables, {
      variables: variables
    })]
  });
  if (activeCache.current) {
    return /*#__PURE__*/_jsx(GamutContext.Provider, {
      value: contextValue,
      children: /*#__PURE__*/_jsxs(CacheProvider, {
        value: activeCache.current,
        children: [globals, /*#__PURE__*/_jsx(ThemeProvider, {
          theme: theme,
          children: children
        })]
      })
    });
  }
  return /*#__PURE__*/_jsxs(GamutContext.Provider, {
    value: contextValue,
    children: [globals, /*#__PURE__*/_jsx(ThemeProvider, {
      theme: theme,
      children: children
    })]
  });
};