"use strict";

exports.__esModule = true;
exports.default = useWaitForDOMRef;
exports.resolveContainerRef = void 0;
var _ownerDocument = _interopRequireDefault(require("dom-helpers/ownerDocument"));
var _canUseDOM = _interopRequireDefault(require("dom-helpers/canUseDOM"));
var _react = require("react");
var _useWindow = _interopRequireDefault(require("./useWindow"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const resolveContainerRef = (ref, document) => {
  if (!_canUseDOM.default) return null;
  if (ref == null) return (document || (0, _ownerDocument.default)()).body;
  if (typeof ref === 'function') ref = ref();
  if (ref && 'current' in ref) ref = ref.current;
  if (ref && ('nodeType' in ref || ref.getBoundingClientRect)) return ref;
  return null;
};
exports.resolveContainerRef = resolveContainerRef;
function useWaitForDOMRef(ref, onResolved) {
  const window = (0, _useWindow.default)();
  const [resolvedRef, setRef] = (0, _react.useState)(() => resolveContainerRef(ref, window == null ? void 0 : window.document));
  if (!resolvedRef) {
    const earlyRef = resolveContainerRef(ref);
    if (earlyRef) setRef(earlyRef);
  }
  (0, _react.useEffect)(() => {
    if (onResolved && resolvedRef) {
      onResolved(resolvedRef);
    }
  }, [onResolved, resolvedRef]);
  (0, _react.useEffect)(() => {
    const nextRef = resolveContainerRef(ref);
    if (nextRef !== resolvedRef) {
      setRef(nextRef);
    }
  }, [ref, resolvedRef]);
  return resolvedRef;
}