import 'react';
import { jsx } from 'react/jsx-runtime';
import useTheme from '../useThemeWithoutDefault/useThemeWithoutDefault.mjs';
import useId from '../../../utils/esm/useId/useId.mjs';
import useEnhancedEffect from '../../../utils/esm/useEnhancedEffect/useEnhancedEffect.mjs';
import GlobalStyles from '../GlobalStyles/GlobalStyles.mjs';

function useLayerOrder(theme) {
  const upperTheme = useTheme();
  const id = useId() || '';
  const {
    modularCssLayers
  } = theme;
  let layerOrder = 'mui.global, mui.components, mui.theme, mui.custom, mui.sx';
  if (!modularCssLayers || upperTheme !== null) {
    // skip this hook if upper theme exists.
    layerOrder = '';
  } else if (typeof modularCssLayers === 'string') {
    layerOrder = modularCssLayers.replace(/mui(?!\.)/g, layerOrder);
  } else {
    layerOrder = `@layer ${layerOrder};`;
  }
  useEnhancedEffect(() => {
    const head = document.querySelector('head');
    if (!head) {
      return;
    }
    const firstChild = head.firstChild;
    if (layerOrder) {
      // Only insert if first child doesn't have data-mui-layer-order attribute
      if (firstChild && firstChild.hasAttribute?.('data-mui-layer-order') && firstChild.getAttribute('data-mui-layer-order') === id) {
        return;
      }
      const styleElement = document.createElement('style');
      styleElement.setAttribute('data-mui-layer-order', id);
      styleElement.textContent = layerOrder;
      head.prepend(styleElement);
    } else {
      head.querySelector(`style[data-mui-layer-order="${id}"]`)?.remove();
    }
  }, [layerOrder, id]);
  if (!layerOrder) {
    return null;
  }
  return /*#__PURE__*/jsx(GlobalStyles, {
    styles: layerOrder
  });
}

export { useLayerOrder as default };
//# sourceMappingURL=useLayerOrder.mjs.map
