import { useEffect, useRef } from "react";
import PropTypes from "prop-types";

const SizeMemoryWrapper = ({ children, maxHeight, setMaxHeight, maxWidth, setMaxWidth }) => {
  const ref = useRef(null);

  useEffect(() => {
    const currentRef = ref.current;

    const updateSize = () => {
      const currentHeight = currentRef?.firstChild?.clientHeight || 0;
      const currentWidth = currentRef?.firstChild?.clientWidth || 0;
      setMaxHeight((prevHeight) => Math.max(prevHeight, currentHeight));
      setMaxWidth((prevWidth) => Math.max(prevWidth, currentWidth));
    };

    const resizeObserver = new ResizeObserver(updateSize);

    if (currentRef?.firstChild) {
      resizeObserver.observe(currentRef.firstChild);
    }

    const handleLoad = () => {
      if (window.devicePixelRatio < 1) {
        return; // Do not update width and height
      }
      updateSize();
    };

    window.addEventListener("load", handleLoad);

    return () => {
      if (currentRef?.firstChild) {
        resizeObserver.unobserve(currentRef.firstChild);
      }
      window.removeEventListener("load", handleLoad);
    };
  }, [setMaxHeight, setMaxWidth]);

  return (
    <div ref={ref} className="size-memory-wrapper" style={{ minHeight: maxHeight, minWidth: maxWidth }}>
      {children}
    </div>
  );
};

SizeMemoryWrapper.propTypes = {
  children: PropTypes.node.isRequired,
  maxHeight: PropTypes.number.isRequired,
  setMaxHeight: PropTypes.func.isRequired,
  maxWidth: PropTypes.number.isRequired,
  setMaxWidth: PropTypes.func.isRequired
};

export default SizeMemoryWrapper;
