import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
/** @jsx jsx */
import React, { Fragment } from 'react';
import { css, jsx } from '@emotion/react';
import rafSchedule from 'raf-schd';
import { WidthObserver } from '@atlaskit/width-detector';
var styles = css({
  position: 'relative',
  width: '100%'
});
var SCROLLBAR_WIDTH = 30;
export function getBreakpoint() {
  var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  var MAX_S = 1266;
  var MAX_M = 2146;
  if (width >= MAX_S && width < MAX_M) {
    return 'M';
  } else if (width >= MAX_M) {
    return 'L';
  }
  return 'S';
}
export function createWidthContext() {
  var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  return {
    width: width,
    breakpoint: getBreakpoint(width)
  };
}
export var WidthContext = /*#__PURE__*/React.createContext(createWidthContext());
var Provider = WidthContext.Provider,
  Consumer = WidthContext.Consumer;
export var WidthProvider = function WidthProvider(_ref) {
  var _document$body$offset, _document$body;
  var className = _ref.className,
    shouldCheckExistingValue = _ref.shouldCheckExistingValue,
    children = _ref.children;
  var existingContextValue = React.useContext(WidthContext);
  var _React$useState = React.useState(typeof document !== 'undefined' ? (_document$body$offset = (_document$body = document.body) === null || _document$body === void 0 ? void 0 : _document$body.offsetWidth) !== null && _document$body$offset !== void 0 ? _document$body$offset : 0 : 0),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    width = _React$useState2[0],
    setWidth = _React$useState2[1];
  var providerValue = React.useMemo(function () {
    return createWidthContext(width);
  }, [width]);
  var updateWidth = rafSchedule(function (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);
  });
  var skipWidthDetection = shouldCheckExistingValue && existingContextValue.width > 0;
  return jsx("div", {
    css: styles,
    className: className
  }, !skipWidthDetection && jsx(Fragment, null, jsx(WidthObserver, {
    setWidth: updateWidth,
    offscreen: true
  }), jsx(Provider, {
    value: providerValue
  }, children)), skipWidthDetection && children);
};
export { Consumer as WidthConsumer };