'use client';
import * as React from 'react';
import RtlProvider from '../RtlProvider/index.mjs';
import useLayerOrder from './useLayerOrder.mjs';
import { jsx, jsxs } from 'react/jsx-runtime';
import useTheme from '../useThemeWithoutDefault/useThemeWithoutDefault.mjs';
import useTheme$1 from '../../../private-theming/useTheme/useTheme.mjs';
import ThemeProvider from '../../../private-theming/ThemeProvider/ThemeProvider.mjs';
import { T as ThemeContext } from '../../../../@emotion/react/dist/emotion-element-f0de968e.browser.esm.mjs';
import DefaultPropsProvider from '../DefaultPropsProvider/DefaultPropsProvider.mjs';

const EMPTY_THEME = {};
function useThemeScoping(themeId, upperTheme, localTheme, isPrivate = false) {
  return React.useMemo(() => {
    const resolvedTheme = themeId ? upperTheme[themeId] || upperTheme : upperTheme;
    if (typeof localTheme === 'function') {
      const mergedTheme = localTheme(resolvedTheme);
      const result = themeId ? {
        ...upperTheme,
        [themeId]: mergedTheme
      } : mergedTheme;
      // must return a function for the private theme to NOT merge with the upper theme.
      // see the test case "use provided theme from a callback" in ThemeProvider.test.js
      if (isPrivate) {
        return () => result;
      }
      return result;
    }
    return themeId ? {
      ...upperTheme,
      [themeId]: localTheme
    } : {
      ...upperTheme,
      ...localTheme
    };
  }, [themeId, upperTheme, localTheme, isPrivate]);
}

/**
 * This component makes the `theme` available down the React tree.
 * It should preferably be used at **the root of your component tree**.
 *
 * <ThemeProvider theme={theme}> // existing use case
 * <ThemeProvider theme={{ id: theme }}> // theme scoping
 */
function ThemeProvider$1(props) {
  const {
    children,
    theme: localTheme,
    themeId
  } = props;
  const upperTheme = useTheme(EMPTY_THEME);
  const upperPrivateTheme = useTheme$1() || EMPTY_THEME;
  const engineTheme = useThemeScoping(themeId, upperTheme, localTheme);
  const privateTheme = useThemeScoping(themeId, upperPrivateTheme, localTheme, true);
  const rtlValue = (themeId ? engineTheme[themeId] : engineTheme).direction === 'rtl';
  const layerOrder = useLayerOrder(engineTheme);
  return /*#__PURE__*/jsx(ThemeProvider, {
    theme: privateTheme,
    children: /*#__PURE__*/jsx(ThemeContext.Provider, {
      value: engineTheme,
      children: /*#__PURE__*/jsx(RtlProvider, {
        value: rtlValue,
        children: /*#__PURE__*/jsxs(DefaultPropsProvider, {
          value: themeId ? engineTheme[themeId].components : engineTheme.components,
          children: [layerOrder, children]
        })
      })
    })
  });
}

export { ThemeProvider$1 as default };
//# sourceMappingURL=ThemeProvider.mjs.map
