import { useRef, useState, useCallback, useEffect } from "react";
const DEFAULT_SIZE = {
  height: 0,
  width: 0,
  x: 0,
  y: 0
};
const useResize = () => {
  const elementRef = useRef(document.body);
  const isMeasured = useRef(false);
  const observer = useRef();
  const [resizeInfo, setResizeInfo] = useState({ ...DEFAULT_SIZE });
  const measureRef = useCallback((node) => {
    var _a, _b;
    isMeasured.current = true;
    (_a = observer.current) == null ? void 0 : _a.unobserve(elementRef.current);
    if (node)
      elementRef.current = node;
    const handleResize = (entries) => {
      const elements = entries.map((entry) => entry.target);
      if (!elementRef.current || elements.indexOf(elementRef.current) === -1)
        return;
      const rect2 = elementRef.current.getBoundingClientRect();
      setResizeInfo(rect2);
    };
    observer.current = new ResizeObserver(handleResize);
    (_b = observer.current) == null ? void 0 : _b.observe(elementRef.current);
    const rect = elementRef.current.getBoundingClientRect();
    setResizeInfo(rect);
  }, []);
  useEffect(() => {
    if (!isMeasured.current)
      measureRef(document.body);
  }, [measureRef]);
  useEffect(() => {
    return () => {
      var _a;
      (_a = observer.current) == null ? void 0 : _a.unobserve(elementRef.current);
      observer.current = void 0;
    };
  }, []);
  return { refCallback: measureRef, refObject: elementRef, size: resizeInfo };
};
export {
  useResize as default
};
