// src/hooks/useResizeObserver.tsx
import { pick } from "lodash-es";
import { useCallback, useEffect, useRef, useState } from "react";
function useResizeObserver(resizeProperties) {
  const resizeObserver = useRef(null);
  const [rect, setRect] = useState(null);
  const [selectedProperties, setSelectedProperties] = useState(null);
  const mounted = useRef(false);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
    };
  }, []);
  const onResize = useCallback(
    (entries) => {
      setTimeout(() => {
        if (mounted.current) {
          const changedRect = entries[0].contentRect;
          setRect(changedRect);
        } else if (resizeObserver.current) {
          resizeObserver.current.disconnect();
        }
      }, 0);
    },
    [setRect]
  );
  const ref = useCallback(
    (node) => {
      if (node && node instanceof Element && resizeProperties && resizeProperties.length > 0) {
        resizeObserver.current = new ResizeObserver(onResize);
        resizeObserver.current.observe(node);
      }
    },
    [onResize, resizeProperties]
  );
  useEffect(() => {
    if (resizeProperties) {
      const selectedProps = pick(rect, resizeProperties);
      if (JSON.stringify(selectedProperties) !== JSON.stringify(selectedProps)) {
        setSelectedProperties(selectedProps);
      }
    }
  }, [rect, resizeProperties, setSelectedProperties, selectedProperties]);
  return {
    ref,
    rect: selectedProperties
  };
}

export {
  useResizeObserver
};
