import classNames from "classnames";
import lodash from "lodash";
import { GALLERY_CONSTS, ProGallery } from "pro-gallery";
import React, { useContext, useMemo, useRef } from "react";
import { LayoutFixer } from "./../../bundled-dependencies/pro-gallery-layout-fixer.js";
import { RicosContext } from "./../../ricos-context/index.js";
import { resizeMediaUrl } from "./../../_shared/media/resize-media-url.js";
import { expand as ExpandIcon } from ".././icons/expand.js";
import { GALLERY_TYPE } from ".././types.js";
import { ROOT } from "../data-hooks.js";
import classes from "../statics/styles/viewer-scss.js";
import { isValidGalleryId } from "./is-valid-gallery-id.js";
import { useHeight } from "./use-height.js";
import { useItems } from "./use-items.js";
import { useOptions } from "./use-options.js";
import { isHorizontalLayout, sampleItems } from "./utils.js";
const GALLERY_EVENTS = GALLERY_CONSTS.events;
const createMediaUrl = ({ createMultiple, ...restArgs }) => createMultiple ? `${resizeMediaUrl(restArgs)}, ${resizeMediaUrl({
  ...restArgs,
  requiredHeight: restArgs.requiredHeight * 2,
  requiredWidth: restArgs.requiredWidth * 2
})} 2x` : resizeMediaUrl(restArgs);
const GalleryViewer = React.memo(
  ({
    componentData,
    nodeId,
    settings,
    relValue,
    anchorTarget,
    seoMode,
    helpers,
    itemOverlayElement,
    baseUrl
  }) => {
    const { scrollingElement, lazyLoading = true, ...gallerySettings } = settings;
    const galleryRef = useRef(null);
    const {
      items: ricosItems,
      options: ricosOptions,
      disableExpand,
      disableDownload
    } = componentData || {};
    const { t } = useContext(RicosContext);
    const items = useItems({ items: ricosItems || [], relValue, anchorTarget, baseUrl });
    const { options, calculatedOptions } = useOptions(ricosOptions || {}, disableDownload, items);
    const galleryOptions = {
      ...options,
      behaviourParams_item_overlay_backgroundColor: "transparent"
    };
    const layout = ricosOptions?.layout?.type || "";
    const {
      setHeight,
      container,
      containerRef,
      setContainerRef,
      containerStyle,
      containerClassName,
      isMeasuredContainer
    } = useHeight({
      options: galleryOptions,
      layout
    });
    const [scrollParent, setScrollParent] = React.useState(
      null
    );
    React.useEffect(() => {
      if (typeof scrollingElement !== "undefined") {
        setScrollParent(
          typeof scrollingElement === "function" ? scrollingElement() : scrollingElement
        );
        return;
      }
      if (typeof window !== "undefined" && containerRef) {
        setScrollParent(getScrollParent(containerRef));
        return;
      }
    }, [containerRef]);
    const handleContextMenu = (e) => {
      return disableDownload && e.preventDefault();
    };
    const viewMode = seoMode ? GALLERY_CONSTS.viewMode.SEO : GALLERY_CONSTS.viewMode.SITE;
    const hasExpand = !disableExpand && !settings.disableExpand && settings.onExpand && ricosItems.length > 0;
    const handleExpand = (itemId) => {
      helpers?.onViewerAction?.(GALLERY_TYPE, "Click", "expand_gallery");
      hasExpand && settings.onExpand(nodeId, itemId);
    };
    const handleGalleryEvents = (name, data) => {
      switch (name) {
        case GALLERY_EVENTS.GALLERY_CHANGE:
          if (galleryRef.current) {
            if (!isHorizontalLayout(options)) {
              galleryRef.current.style.height = `${data.layoutHeight}px`;
            } else {
              galleryRef.current.style.height = "auto";
            }
          }
          break;
        default:
          break;
      }
    };
    const customHoverRenderer = (itemProps) => {
      return /* @__PURE__ */ React.createElement("div", { className: classes.itemOverlay }, itemProps.title && /* @__PURE__ */ React.createElement("div", { className: classes.imageTitleContainer }, /* @__PURE__ */ React.createElement("div", { className: classes.imageTitle }, itemProps.title)), itemOverlayElement?.(itemProps));
    };
    const isPrerenderMode = !isMeasuredContainer;
    const uniqueNodeId = useMemo(() => {
      const id = `${nodeId}-${settings.scopingId ?? "not-scoped"}`;
      return isValidGalleryId(id) ? id : "";
    }, [nodeId]);
    const customImageRenderer = ({ alt, src, ...itemProps }) => {
      const srcProps = src.includes(", ") ? { src: src.split(", ")[0], srcSet: src } : { src };
      const item = items[itemProps?.["data-idx"]];
      const isLink = item?.metaData.link;
      const isExpandable = item?.metaData.type === "image" && !isLink && !disableExpand;
      return /* @__PURE__ */ React.createElement("div", { className: classes.itemContainer }, /* @__PURE__ */ React.createElement(
        "img",
        {
          ...itemProps,
          alt,
          ...srcProps,
          ...isExpandable ? {
            onClick: () => {
              handleExpand(itemProps["data-idx"]);
            }
          } : {},
          tabIndex: isLink ? 0 : void 0
        }
      ), hasExpand && /* @__PURE__ */ React.createElement(
        "button",
        {
          className: classes.expandButton,
          onClick: (e) => {
            e.preventDefault();
            e.stopPropagation();
            handleExpand(itemProps["data-idx"]);
          },
          onKeyDown: (e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              e.stopPropagation();
              handleExpand(itemProps["data-idx"]);
            }
          },
          onKeyUp: (e) => {
            if (e.key === "Enter") {
              e.stopPropagation();
            }
          },
          type: "button",
          "aria-label": t("Image_Expand_Button_AriaLabel")
        },
        /* @__PURE__ */ React.createElement(ExpandIcon, { className: classes.expandIcon })
      ));
    };
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: setContainerRef,
        className: classNames(classes.gallery_container, containerClassName, {
          [classes.clickableItem]: hasExpand
        }),
        style: containerStyle,
        "data-hook": ROOT,
        role: "none",
        onContextMenu: handleContextMenu
      },
      /* @__PURE__ */ React.createElement(
        ProGallery,
        {
          id: uniqueNodeId,
          items: items.length > 0 ? items : sampleItems,
          options: galleryOptions,
          container,
          settings: gallerySettings,
          scrollingElement: scrollParent,
          eventsListener: handleGalleryEvents,
          createMediaUrl,
          viewMode,
          customComponents: { customHoverRenderer, customImageRenderer },
          totalItemsCount: items.length || sampleItems.length,
          setLayoutHeightImp: setHeight,
          isPrerenderMode,
          activeIndex: lazyLoading ? void 0 : 0
        }
      ),
      uniqueNodeId ? /* @__PURE__ */ React.createElement(
        LayoutFixer,
        {
          id: uniqueNodeId,
          isPrerenderMode,
          items,
          options: calculatedOptions
        }
      ) : null
    );
  },
  (prevProps, nextProps) => {
    return lodash.isEqual(
      filterOutNonDisplayedProps(prevProps),
      filterOutNonDisplayedProps(nextProps)
    );
  }
);
function filterOutNonDisplayedProps(props) {
  return {
    ...props,
    componentData: {
      ...props.componentData,
      items: props.componentData.items.map(
        ({ altText: _altText, title: _title, image, ...rest }) => {
          if (!image) {
            return rest;
          }
          const { link: _link, ...imageRest } = image;
          return { ...rest, image: imageRest };
        }
      )
    }
  };
}
const getScrollParent = (node) => {
  let currentElement = node;
  while (currentElement) {
    if (currentElement === document.body || currentElement === document.documentElement) {
      return window;
    }
    const computedStyle = window.getComputedStyle(currentElement);
    const overflowY = computedStyle.overflowY;
    const overflowX = computedStyle.overflowX;
    const isScrollable = (overflowY === "scroll" || overflowY === "auto" || overflowX === "scroll" || overflowX === "auto") && (currentElement.scrollHeight > currentElement.clientHeight || currentElement.scrollWidth > currentElement.clientWidth);
    if (isScrollable) {
      return currentElement;
    }
    currentElement = currentElement.parentElement;
  }
  return null;
};
export {
  GalleryViewer
};
//# sourceMappingURL=gallery-viewer.js.map
