import lodash from "lodash";
import { ProGallery } from "pro-gallery";
import { migrateOptions } from "pro-gallery-lib";
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { FocusManager } from "./../../../_shared/focus-manager/focus-manager.js";
import { convertToGalleryItem } from "./../../../_shared/media/convert-to-gallery-item.js";
import { fullscreenResizeMediaUrl } from "./../../../_shared/media/fullscreen-resize-media-url.js";
import {
  FULLSCREEN_CLOSE_BUTTON,
  FULLSCREEN_IMAGE_ITEM,
  FULLSCREEN_ROOT,
  FULLSCREEN_TOGGLE_BUTTON
} from "./data-hooks.js";
import styles from "./fullscreen-scss.js";
const FullscreenModal = ({
  container = document.body,
  ...props
}) => {
  const target = lodash.isFunction(container) ? container() : container;
  const fullscreen = /* @__PURE__ */ React.createElement(InnerFullscreen, { ...props });
  return target ? ReactDOM.createPortal(fullscreen, target) : fullscreen;
};
const InnerFullscreen = (props) => {
  const { backgroundColor = "white", foregroundColor = "#2F2E2E", isMobile, t } = props;
  const [isInFullscreen, setIsInFullscreen] = React.useState(false);
  const [closeButtonRef, setCloseButtonRef] = React.useState(null);
  const [size, setSize] = React.useState({ width: window.innerWidth, height: window.innerHeight });
  const items = props.images.map((item, index) => ({
    ...convertToGalleryItem({ item, index }),
    disableDownload: item.disableDownload
  }));
  const containerRef = React.useRef(null);
  const currentIdx = React.useRef(props.index || 0);
  useEffect(() => {
    if (closeButtonRef && !isMobile) {
      setTimeout(() => {
        closeButtonRef.focus();
      }, 0);
    }
  }, [closeButtonRef]);
  const toggleFullscreenMode = () => {
    const element = document.body;
    if (document.fullscreenEnabled) {
      if (isInFullscreen) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      } else if (element.requestFullscreen) {
        element.requestFullscreen();
      }
    }
  };
  const onClose = () => {
    if (isInFullscreen) {
      toggleFullscreenMode();
    }
    props.onClose();
  };
  React.useEffect(() => {
    pauseChildNodesVideos(document);
    const onEsc = (event) => {
      if (event.key === "Escape") {
        onClose();
      }
    };
    const onWindowResize = () => setSize(getDimensions(containerRef.current));
    const onFullscreenChange = () => setIsInFullscreen(!!document.fullscreenElement);
    document.addEventListener("keydown", onEsc);
    window.addEventListener("resize", onWindowResize);
    if (document.fullscreenEnabled) {
      document.addEventListener("fullscreenchange", onFullscreenChange);
    }
    setSize(getDimensions(containerRef.current));
    return () => {
      document.removeEventListener("keydown", onEsc);
      window.removeEventListener("resize", onWindowResize);
      if (document.fullscreenEnabled) {
        document.removeEventListener("fullscreenchange", onFullscreenChange);
      }
    };
  }, []);
  const { width, height } = size;
  const isHorizontalView = width > height;
  const { arrowsPosition, slideshowInfoSize } = getStyleParams({
    isHorizontalView,
    isMobile,
    isInFullscreen
  });
  const infoElement = (itemProps) => {
    return itemProps.title ? /* @__PURE__ */ React.createElement("div", { className: styles.info_container }, /* @__PURE__ */ React.createElement("div", { title: itemProps.title, style: { color: foregroundColor }, className: styles.title }, itemProps.title)) : null;
  };
  const handleGalleryEvents = (name, data) => {
    if (name === "CURRENT_ITEM_CHANGED") {
      const previousItem = items[currentIdx.current];
      if (previousItem?.metaData?.type === "video") {
        pauseChildNodesVideos(
          document.querySelector(`[data-id='${previousItem.itemId}']`)
        );
      }
      currentIdx.current = data.idx;
    }
  };
  const closeButton = /* @__PURE__ */ React.createElement(
    "button",
    {
      ref: setCloseButtonRef,
      type: "button",
      className: styles.close,
      onClick: onClose,
      onKeyDown: applyOnEnterKeyPress(onClose),
      "aria-label": t("Fullscreen_Close_Button_AriaLabel"),
      "data-hook": FULLSCREEN_CLOSE_BUTTON
    },
    /* @__PURE__ */ React.createElement(CloseIcon, { backgroundColor, foregroundColor })
  );
  return /* @__PURE__ */ React.createElement(FocusManager, { jsdomMode: props.jsdomMode }, /* @__PURE__ */ React.createElement(
    "div",
    {
      style: { background: backgroundColor },
      dir: "ltr",
      "data-hook": FULLSCREEN_ROOT,
      className: isInFullscreen || isMobile && isHorizontalView ? styles.fullscreen_mode : styles.expand_mode,
      ref: containerRef,
      onContextMenu: (e) => items[currentIdx.current].disableDownload && e.preventDefault(),
      role: "none"
    },
    /* @__PURE__ */ React.createElement("div", { "aria-label": `Gallery with ${items.length} items`, style: { height: "100%" } }, !isMobile && /* @__PURE__ */ React.createElement(
      FullscreenToggleButton,
      {
        isInFullscreen,
        backgroundColor,
        foregroundColor,
        onToggleFullscreen: toggleFullscreenMode,
        t
      }
    ), closeButton, /* @__PURE__ */ React.createElement(
      ProGallery,
      {
        id: "ricos-fullscreen",
        scrollingElement: window,
        items,
        activeIndex: currentIdx.current,
        eventsListener: handleGalleryEvents,
        createMediaUrl: fullscreenResizeMediaUrl,
        container: { width, height: isMobile ? height : height - 80 },
        options: {
          ...migrateOptions({
            ...fixedOptions,
            showArrows: !isMobile,
            arrowsPosition,
            slideshowInfoSize,
            behaviourParams_item_overlay_hoveringBehaviour: "NEVER_SHOW"
          }),
          layoutParams_info_height: 60
        },
        customComponents: {
          customImageRenderer,
          customInfoRenderer: !isInFullscreen ? infoElement : void 0
        },
        totalItemsCount: items.length,
        settings: { isAccessible: true },
        disableItemFocus: items.length === 1
      }
    ))
  ));
};
const getDimensions = (element) => {
  const container = element?.getBoundingClientRect?.();
  const width = container?.width || 0;
  const height = container?.height || 0;
  return { width, height };
};
const customImageRenderer = (itemProps) => {
  const {
    style,
    className,
    alt,
    tabIndex: _tabIndex,
    ...rest
  } = itemProps;
  return /* @__PURE__ */ React.createElement("div", { className, style, "data-hook": FULLSCREEN_IMAGE_ITEM }, /* @__PURE__ */ React.createElement("img", { className, alt, style, ...rest }));
};
const applyOnEnterKeyPress = (callback) => (e) => {
  if (e.key === "Enter") {
    callback();
  }
};
const FullscreenToggleButton = ({
  isInFullscreen,
  backgroundColor,
  foregroundColor,
  onToggleFullscreen,
  t
}) => {
  const Icon = isInFullscreen ? ShrinkIcon : ExpandIcon;
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      className: styles.expand_button,
      onClick: onToggleFullscreen,
      onKeyDown: applyOnEnterKeyPress(onToggleFullscreen),
      "aria-label": isInFullscreen ? t("Fullscreen_Shrink_Button_AriaLabel") : t("Fullscreen_Expand_Button_AriaLabel"),
      "data-hook": FULLSCREEN_TOGGLE_BUTTON
    },
    /* @__PURE__ */ React.createElement(Icon, { backgroundColor, foregroundColor })
  );
};
const pauseChildNodesVideos = (element) => Array.from(element.getElementsByTagName("video"))?.forEach((video) => video.pause());
const getStyleParams = ({
  isHorizontalView,
  isMobile,
  isInFullscreen
}) => {
  let arrowsPosition = 0;
  let slideshowInfoSize = 0;
  if (isMobile) {
    slideshowInfoSize = isHorizontalView ? 0 : 80;
  } else if (!isInFullscreen) {
    arrowsPosition = 1;
    slideshowInfoSize = 142;
  }
  return { arrowsPosition, slideshowInfoSize };
};
const fixedOptions = {
  galleryLayout: 5,
  cubeType: "fit",
  scrollSnap: true,
  videoPlay: "CLICK",
  videoLoop: false,
  videoSound: true,
  hidePlay: false,
  showVideoControls: true,
  showVideoPlayButton: true,
  allowSocial: false,
  loveButton: false,
  allowTitle: true,
  defaultShowInfoExpand: 1,
  floatingImages: 0,
  allowContextMenu: true
};
const CloseIcon = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "60", height: "60", viewBox: "0 0 60 60" }, /* @__PURE__ */ React.createElement("g", { fill: "none", fillRule: "evenodd" }, /* @__PURE__ */ React.createElement("path", { fill: props.backgroundColor, d: "M0 0H60V60H0z" }), /* @__PURE__ */ React.createElement(
  "path",
  {
    fill: props.foregroundColor,
    d: "M42.188 17l.812.813L30.812 30 43 42.188l-.813.812L30 30.812 17.812 43 17 42.187 29.187 30 17 17.812l.813-.812L30 29.187 42.188 17z"
  }
)));
const ExpandIcon = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "60", height: "60", viewBox: "0 0 60 60" }, /* @__PURE__ */ React.createElement("g", { fill: "none", fillRule: "evenodd" }, /* @__PURE__ */ React.createElement("path", { fill: props.backgroundColor, d: "M0 0H60V60H0z" }), /* @__PURE__ */ React.createElement("g", { fill: props.foregroundColor }, /* @__PURE__ */ React.createElement(
  "path",
  {
    d: "M4.333 15.167H5.413V27.084H4.333z",
    transform: "translate(17 17) rotate(45 4.873 21.125)"
  }
), /* @__PURE__ */ React.createElement("path", { d: "M26 8h-1V1h-7V0h8v8z", transform: "translate(17 17)" }), /* @__PURE__ */ React.createElement(
  "path",
  {
    d: "M20.583 -1.083H21.665999999999997V10.834H20.583z",
    transform: "translate(17 17) rotate(45 21.125 4.875)"
  }
), /* @__PURE__ */ React.createElement("path", { d: "M0 26v-8h1v7h7v1H0z", transform: "translate(17 17)" }))));
const ShrinkIcon = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "60", height: "60", viewBox: "0 0 60 60" }, /* @__PURE__ */ React.createElement("g", { fill: "none", fillRule: "evenodd" }, /* @__PURE__ */ React.createElement("path", { fill: props.backgroundColor, d: "M0 0H60V60H0z" }), /* @__PURE__ */ React.createElement("g", { fill: props.foregroundColor }, /* @__PURE__ */ React.createElement(
  "path",
  {
    d: "M4.055 16.447H5.135V28.363999999999997H4.055z",
    transform: "translate(17 16) rotate(-135 4.595 22.405)"
  }
), /* @__PURE__ */ React.createElement("g", null, /* @__PURE__ */ React.createElement("path", { d: "M10 8.083H9v-7H2v-1h8v8z", transform: "translate(17 16) rotate(-180 13 5.458)" }), /* @__PURE__ */ React.createElement(
  "path",
  {
    d: "M4.583 -1H5.666V10.917H4.583z",
    transform: "translate(17 16) rotate(-180 13 5.458) rotate(45 5.125 4.958)"
  }
)), /* @__PURE__ */ React.createElement("path", { d: "M9.468 17.53v8h-1v-7h-7v-1h8z", transform: "translate(17 16)" }))));
var fullscreen_modal_default = FullscreenModal;
export {
  FullscreenModal,
  fullscreen_modal_default as default
};
//# sourceMappingURL=fullscreen-modal.js.map
