import imageClientAPI from "image-client-api/dist/imageClientSDK.js";
import lodash from "lodash";
import { useEffect, useMemo, useRef, useState } from "react";
import { getMediaId } from "./../../wix-rich-content-common/lib/image-utils.js";
const WIX_STATIC_MEDIA_PREFIX = "https://static.wixstatic.com/media";
const RESIZE_DEBOUNCE_MS = 300;
const SSR_FALLBACK_SIZE = 600;
const SSR_FALLBACK_QUALITY = 80;
const CLIENT_QUALITY = 100;
const useBackgroundImageUrl = (image) => {
  const [dimensions, setDimensions] = useState(null);
  const [loadedUrl, setLoadedUrl] = useState(() => getInitialUrl(image));
  const containerRef = useRef(null);
  useEffect(() => {
    const element = containerRef.current;
    if (!element || typeof window === "undefined" || !window.ResizeObserver) {
      return;
    }
    const handleResize = lodash.debounce((entries) => {
      const entry = entries[0];
      if (!entry) {
        return;
      }
      const { width, height } = entry.contentRect;
      setDimensions(
        (prev) => prev && prev.width === Math.ceil(width) && prev.height === Math.ceil(height) ? prev : { width: Math.ceil(width), height: Math.ceil(height) }
      );
    }, RESIZE_DEBOUNCE_MS);
    const observer = new ResizeObserver(handleResize);
    observer.observe(element);
    return () => {
      observer.disconnect();
      handleResize.cancel();
    };
  }, []);
  const mediaId = useMemo(() => resolveMediaId(image), [image?.src?.id, image?.src?.url]);
  useEffect(() => {
    if (!image?.src?.url && !mediaId) {
      setLoadedUrl(void 0);
      return;
    }
    if (!mediaId) {
      setLoadedUrl(image?.src?.url);
      return;
    }
    if (!dimensions || dimensions.width === 0 || dimensions.height === 0) {
      setLoadedUrl(getSsrFallbackUrl(mediaId, image));
      return;
    }
    const dpr = Math.min(typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1, 2);
    const targetUrl = getResizedUrl(
      mediaId,
      image,
      Math.ceil(dimensions.width * dpr),
      Math.ceil(dimensions.height * dpr),
      CLIENT_QUALITY
    );
    if (!targetUrl) {
      setLoadedUrl(image?.src?.url);
      return;
    }
    let cancelled = false;
    prefetchImage(targetUrl).then(
      (url) => {
        if (!cancelled) {
          setLoadedUrl(url);
        }
      },
      () => {
        if (!cancelled) {
          setLoadedUrl(image?.src?.url);
        }
      }
    );
    return () => {
      cancelled = true;
    };
  }, [mediaId, dimensions, image?.src?.url, image?.width, image?.height]);
  return { containerRef, backgroundImageUrl: loadedUrl };
};
const resolveMediaId = (image) => {
  if (!image) {
    return void 0;
  }
  if (image.src.id) {
    return image.src.id;
  }
  if (image.src.url?.startsWith(WIX_STATIC_MEDIA_PREFIX)) {
    return getMediaId(image.src.url);
  }
  return void 0;
};
const getResizedUrl = (mediaId, image, width, height, quality) => {
  try {
    return imageClientAPI.getScaleToFillImageURL(
      mediaId,
      image.width ?? width,
      image.height ?? height,
      width,
      height,
      { quality }
    );
  } catch {
    return image.src?.url;
  }
};
const getSsrFallbackUrl = (mediaId, image) => getResizedUrl(mediaId, image, SSR_FALLBACK_SIZE, SSR_FALLBACK_SIZE, SSR_FALLBACK_QUALITY);
const prefetchImage = (url) => new Promise((resolve, reject) => {
  const img = new Image();
  img.onload = () => resolve(url);
  img.onerror = reject;
  img.src = url;
});
const getInitialUrl = (image) => {
  if (!image) {
    return void 0;
  }
  const mediaId = resolveMediaId(image);
  if (mediaId) {
    return getSsrFallbackUrl(mediaId, image);
  }
  return image.src?.url;
};
export {
  resolveMediaId,
  useBackgroundImageUrl
};
//# sourceMappingURL=use-background-image-url.js.map
