import { _ as _slicedToArray } from '../slicedToArray-BB-AwwkK.js';
import { _ as _toConsumableArray } from '../toConsumableArray-dKQYsfpV.js';
import { useRef, useCallback, useState, useEffect } from 'react';

var BREAKPOINT_VALUES = {
  xs: 576,
  sm: 768,
  md: 992,
  lg: 1200
};
var DEFAULT_BREAKPOINTS = ["xs", "sm", "md", "lg"];
/**
 * Use mobile first breakpoints to determine values in a react component.
 *
 * ## Example
 * const columns = useBreakpoints([1, 2, 3])
 * // Here, if the screen is less than 576px, then `columns == 1`.
 * // If it's greater than 576px, but less than 758px, then `columns == 2`.
 * // Ifi it's greater than 768px, then `columns == 3`.
 *
 * @param {Array} values
 * @param {Object} options
 * @param {Array} options.breakpoints
 */

function useResponsiveValue(values) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref$breakpoints = _ref.breakpoints,
      breakpoints = _ref$breakpoints === void 0 ? DEFAULT_BREAKPOINTS : _ref$breakpoints;

  var breakpointValues = breakpoints.map(function (breakpointName) {
    return BREAKPOINT_VALUES[breakpointName];
  }); // if window.matchMedia is not defined (i.e in test environments), this value
  // will end up being empty, which will cause the value to be the default, or
  // the first in the array.

  var mediaQueryLists = useRef(window.matchMedia ? breakpointValues.map(function (breakpoint) {
    return window.matchMedia("(min-width: ".concat(breakpoint, "px)"));
  }) : []);
  var getValue = useCallback(function () {
    var queryList = _toConsumableArray(mediaQueryLists.current).reverse().find(function (query) {
      return query.matches;
    });

    var index = mediaQueryLists.current.indexOf(queryList);

    if (index < 0) {
      return values[0];
    } else {
      return typeof values[index + 1] !== "undefined" ? values[index + 1] : values[values.length - 1];
    }
  }, _toConsumableArray(values)); // anytime `values` changes, we need to update this function

  var _useState = useState(getValue),
      _useState2 = _slicedToArray(_useState, 2),
      value = _useState2[0],
      setValue = _useState2[1];

  useEffect(function () {
    var currentQueryLists = mediaQueryLists.current;

    var handleMediaQueryEvent = function handleMediaQueryEvent() {
      setValue(getValue());
    };

    currentQueryLists.forEach(function (queryList) {
      return queryList.addListener(handleMediaQueryEvent);
    });
    handleMediaQueryEvent();
    return function () {
      return currentQueryLists.forEach(function (queryList) {
        return queryList.removeListener(handleMediaQueryEvent);
      });
    };
  }, [getValue].concat(_toConsumableArray(breakpoints))); // anytime `breakpoints` or `getValue` change, we need to reset our listeners

  return value;
}

export { useResponsiveValue as default };
