"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var gallery_viewer_exports = {};
__export(gallery_viewer_exports, {
  GalleryViewer: () => GalleryViewer
});
module.exports = __toCommonJS(gallery_viewer_exports);
var import_classnames = __toESM(require("classnames"));
var import_lodash = __toESM(require("lodash"));
var import_pro_gallery = require("pro-gallery");
var import_react = __toESM(require("react"));
var import_pro_gallery_layout_fixer = require("./../../bundled-dependencies/pro-gallery-layout-fixer.js");
var import_ricos_context = require("./../../ricos-context/index.js");
var import_resize_media_url = require("./../../_shared/media/resize-media-url.js");
var import_expand = require(".././icons/expand.js");
var import_types = require(".././types.js");
var import_data_hooks = require("../data-hooks.js");
var import_viewer_scss = __toESM(require("../statics/styles/viewer-scss.js"));
var import_is_valid_gallery_id = require("./is-valid-gallery-id.js");
var import_use_height = require("./use-height.js");
var import_use_items = require("./use-items.js");
var import_use_options = require("./use-options.js");
var import_utils = require("./utils.js");
const GALLERY_EVENTS = import_pro_gallery.GALLERY_CONSTS.events;
const createMediaUrl = ({ createMultiple, ...restArgs }) => createMultiple ? `${(0, import_resize_media_url.resizeMediaUrl)(restArgs)}, ${(0, import_resize_media_url.resizeMediaUrl)({
  ...restArgs,
  requiredHeight: restArgs.requiredHeight * 2,
  requiredWidth: restArgs.requiredWidth * 2
})} 2x` : (0, import_resize_media_url.resizeMediaUrl)(restArgs);
const GalleryViewer = import_react.default.memo(
  ({
    componentData,
    nodeId,
    settings,
    relValue,
    anchorTarget,
    seoMode,
    helpers,
    itemOverlayElement,
    baseUrl
  }) => {
    const { scrollingElement, lazyLoading = true, ...gallerySettings } = settings;
    const galleryRef = (0, import_react.useRef)(null);
    const {
      items: ricosItems,
      options: ricosOptions,
      disableExpand,
      disableDownload
    } = componentData || {};
    const { t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
    const items = (0, import_use_items.useItems)({ items: ricosItems || [], relValue, anchorTarget, baseUrl });
    const { options, calculatedOptions } = (0, import_use_options.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
    } = (0, import_use_height.useHeight)({
      options: galleryOptions,
      layout
    });
    const [scrollParent, setScrollParent] = import_react.default.useState(
      null
    );
    import_react.default.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 ? import_pro_gallery.GALLERY_CONSTS.viewMode.SEO : import_pro_gallery.GALLERY_CONSTS.viewMode.SITE;
    const hasExpand = !disableExpand && !settings.disableExpand && settings.onExpand && ricosItems.length > 0;
    const handleExpand = (itemId) => {
      helpers?.onViewerAction?.(import_types.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 (!(0, import_utils.isHorizontalLayout)(options)) {
              galleryRef.current.style.height = `${data.layoutHeight}px`;
            } else {
              galleryRef.current.style.height = "auto";
            }
          }
          break;
        default:
          break;
      }
    };
    const customHoverRenderer = (itemProps) => {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: import_viewer_scss.default.itemOverlay }, itemProps.title && /* @__PURE__ */ import_react.default.createElement("div", { className: import_viewer_scss.default.imageTitleContainer }, /* @__PURE__ */ import_react.default.createElement("div", { className: import_viewer_scss.default.imageTitle }, itemProps.title)), itemOverlayElement?.(itemProps));
    };
    const isPrerenderMode = !isMeasuredContainer;
    const uniqueNodeId = (0, import_react.useMemo)(() => {
      const id = `${nodeId}-${settings.scopingId ?? "not-scoped"}`;
      return (0, import_is_valid_gallery_id.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__ */ import_react.default.createElement("div", { className: import_viewer_scss.default.itemContainer }, /* @__PURE__ */ import_react.default.createElement(
        "img",
        {
          ...itemProps,
          alt,
          ...srcProps,
          ...isExpandable ? {
            onClick: () => {
              handleExpand(itemProps["data-idx"]);
            }
          } : {},
          tabIndex: isLink ? 0 : void 0
        }
      ), hasExpand && /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          className: import_viewer_scss.default.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__ */ import_react.default.createElement(import_expand.expand, { className: import_viewer_scss.default.expandIcon })
      ));
    };
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        ref: setContainerRef,
        className: (0, import_classnames.default)(import_viewer_scss.default.gallery_container, containerClassName, {
          [import_viewer_scss.default.clickableItem]: hasExpand
        }),
        style: containerStyle,
        "data-hook": import_data_hooks.ROOT,
        role: "none",
        onContextMenu: handleContextMenu
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_pro_gallery.ProGallery,
        {
          id: uniqueNodeId,
          items: items.length > 0 ? items : import_utils.sampleItems,
          options: galleryOptions,
          container,
          settings: gallerySettings,
          scrollingElement: scrollParent,
          eventsListener: handleGalleryEvents,
          createMediaUrl,
          viewMode,
          customComponents: { customHoverRenderer, customImageRenderer },
          totalItemsCount: items.length || import_utils.sampleItems.length,
          setLayoutHeightImp: setHeight,
          isPrerenderMode,
          activeIndex: lazyLoading ? void 0 : 0
        }
      ),
      uniqueNodeId ? /* @__PURE__ */ import_react.default.createElement(
        import_pro_gallery_layout_fixer.LayoutFixer,
        {
          id: uniqueNodeId,
          isPrerenderMode,
          items,
          options: calculatedOptions
        }
      ) : null
    );
  },
  (prevProps, nextProps) => {
    return import_lodash.default.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;
};
//# sourceMappingURL=gallery-viewer.js.map
