/** @jsx jsx */
import React, { Fragment } from 'react';
import { css, jsx } from '@emotion/react';
import rafSchedule from 'raf-schd';
import { WidthObserver } from '@atlaskit/width-detector';
const SCROLLBAR_WIDTH = 30;
export function getBreakpoint(width = 0) {
  const MAX_S = 1266;
  const MAX_M = 2146;
  if (width >= MAX_S && width < MAX_M) {
    return 'M';
  } else if (width >= MAX_M) {
    return 'L';
  }
  return 'S';
}
export function createWidthContext(width = 0) {
  return {
    width,
    breakpoint: getBreakpoint(width)
  };
}
export const WidthContext = /*#__PURE__*/React.createContext(createWidthContext());
const {
  Provider,
  Consumer
} = WidthContext;
export const WidthProvider = ({
  className,
  shouldCheckExistingValue,
  children
}) => {
  const existingContextValue = React.useContext(WidthContext);
  const [width, setWidth] = React.useState(typeof document !== 'undefined' ? document.body.offsetWidth : 0);
  const providerValue = React.useMemo(() => createWidthContext(width), [width]);
  const updateWidth = rafSchedule(nextWidth => {
    // Ignore changes that are less than SCROLLBAR_WIDTH, otherwise it can cause infinite re-scaling
    if (Math.abs(width - nextWidth) < SCROLLBAR_WIDTH) {
      return;
    }
    setWidth(nextWidth);
  });
  const skipWidthDetection = shouldCheckExistingValue && existingContextValue.width > 0;
  return jsx("div", {
    css: css`
        position: relative;
        width: 100%;
      `,
    className: className
  }, !skipWidthDetection && jsx(Fragment, null, jsx(WidthObserver, {
    setWidth: updateWidth,
    offscreen: true
  }), jsx(Provider, {
    value: providerValue
  }, children)), skipWidthDetection && children);
};
export { Consumer as WidthConsumer };