import lodash from "lodash";
import React, { useCallback, useContext, useMemo, useState } from "react";
import { RicosContext } from "./../../ricos-context/index.js";
import { GalleryOptions_Layout_Type } from "./../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import styles from "../statics/styles/viewer-scss.js";
import { useIsPrerender } from "./use-prerender.js";
import { useResizeObserver } from "./use-resize-observer.js";
const THUMBNAIL_GALLERY_HEIGHT = 620;
const RESIZE_OBSERVER_DELAY = 100;
const defaultContainers = {
  desktop: {
    width: 980,
    height: 500
  },
  mobile: {
    width: 320,
    height: 500
  }
};
const useHeight = (props) => {
  const [isMeasuredContainer, setIsMeasuredContainer] = React.useState(false);
  const isPrerender = useIsPrerender();
  const { options, layout } = props;
  const { responsive } = options;
  const { mobile, desktop } = defaultContainers;
  const { isMobile, jsdomMode } = useContext(RicosContext);
  const containerWidthResponsive = isMobile ? mobile.width : desktop.width;
  const containerHeightResponsive = isMobile ? mobile.height : desktop.height;
  const defaultContainer = {
    isDefaultContainer: true,
    width: containerWidthResponsive,
    height: containerHeightResponsive
  };
  const [container, setContainer] = useState(defaultContainer);
  const [height, setHeight] = useState(container.height);
  const [containerRef, setContainerRef] = useState(null);
  React.useEffect(() => {
    if (isMeasuredContainer) {
      setIsMeasuredContainer(false);
      setContainer(defaultContainer);
    }
  }, [layout]);
  const resizeGallery = useCallback(() => {
    setContainer((prevState) => {
      if (containerRef?.clientHeight && prevState.height && Math.abs(prevState.height - containerRef?.clientHeight) <= 1 && Math.abs(prevState.width - containerRef?.clientWidth) <= 1) {
        return prevState;
      }
      return {
        width: containerRef?.clientWidth,
        height: containerRef?.clientHeight
      };
    });
    setIsMeasuredContainer(true);
  }, [containerRef, setIsMeasuredContainer]);
  const resizeObserverCallback = useMemo(
    () => lodash.debounce(resizeGallery, RESIZE_OBSERVER_DELAY),
    [resizeGallery]
  );
  useResizeObserver({
    element: containerRef,
    callback: resizeObserverCallback
  });
  const heightStyle = layout === GalleryOptions_Layout_Type.THUMBNAIL && !isMobile ? { height: THUMBNAIL_GALLERY_HEIGHT } : responsive ? {} : { height };
  const setHeightImp = (newHeight) => {
    setHeight(newHeight);
  };
  const containerClassName = isPrerender ? styles.prerender : "";
  return {
    isMeasuredContainer: jsdomMode ? !isPrerender : isMeasuredContainer,
    setHeight: setHeightImp,
    container,
    setContainerRef,
    containerRef,
    containerStyle: heightStyle,
    containerClassName
  };
};
export {
  useHeight
};
//# sourceMappingURL=use-height.js.map
