import _extends from "@babel/runtime/helpers/esm/extends";
import { createRef, useCallback, useContext, useEffect, useState } from 'react';
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { addResponsiveLayoutListener, checkMatches } from "../ResponsiveLayoutEvents";
export function useResponsiveLayout(_temp) {
  var _ref = _temp === void 0 ? {} : _temp,
    customMediaQueries = _ref.customMediaQueries;
  var theme = useContext(ThemeContext);
  var allMediaQueries = Object.entries(_extends({
    isMobile: theme.mobileMediaQuery
  }, customMediaQueries)).map(function (_ref2) {
    var key = _ref2[0],
      value = _ref2[1];
    return {
      flag: key,
      query: value,
      ref: /*#__PURE__*/createRef()
    };
  });
  var getLayoutFromGlobal = function getLayoutFromGlobal() {
    return allMediaQueries.reduce(function (result, mediaQuery) {
      var _Object$assign;
      return Object.assign(result, (_Object$assign = {}, _Object$assign[mediaQuery.flag] = checkMatches(mediaQuery.query), _Object$assign));
    }, {});
  };
  var _useState = useState(getLayoutFromGlobal()),
    state = _useState[0],
    setState = _useState[1];
  var prepareMediaQueries = useCallback(function () {
    if (!theme) {
      return;
    }
    allMediaQueries.forEach(function (mediaQuery) {
      return mediaQuery.ref.current = addResponsiveLayoutListener(mediaQuery.query, checkLayoutsMediaQueries);
    });

    // Checking for SSR use case
    var globalLayout = getLayoutFromGlobal();
    var hasChangedQuery = Object.entries(globalLayout).find(function (_ref3) {
      var key = _ref3[0],
        value = _ref3[1];
      return state[key] !== value;
    });
    if (hasChangedQuery) {
      setState(globalLayout);
    }
  }, [theme]);
  var checkLayoutsMediaQueries = useCallback(function (e) {
    if (!theme) {
      return;
    }
    allMediaQueries.forEach(function (mediaQuery) {
      if (e.media === mediaQuery.query) {
        setState(function (prevState) {
          var _extends2;
          return _extends({}, prevState, (_extends2 = {}, _extends2[mediaQuery.flag] = e.matches, _extends2));
        });
      }
    });
  }, [theme]);
  useEffect(function () {
    prepareMediaQueries();
    return function () {
      allMediaQueries.forEach(function (mediaQuery) {
        var _mediaQuery$ref$curre;
        return (_mediaQuery$ref$curre = mediaQuery.ref.current) == null ? void 0 : _mediaQuery$ref$curre.remove();
      });
    };
  }, []);
  return state;
}