import { forwardRef, useContext, useState, useRef, useMemo, useImperativeHandle, useCallback, useEffect } from "react";
import { findDOMNode } from "react-dom";
import useMergeProps from "../_util/hooks/useMergeProps.js";
import useMergeValue from "../_util/hooks/useMergeValue.js";
import cs from "../_util/classNames.js";
import { isServerRendering, on, off } from "../_util/dom.js";
import ResizeObserver from "../_util/resizeObserver.js";
import IconLoading from "../../icon/react-icon/IconLoading/index.js";
import IconZoomOut from "../../icon/react-icon/IconZoomOut/index.js";
import IconZoomIn from "../../icon/react-icon/IconZoomIn/index.js";
import IconFullscreen from "../../icon/react-icon/IconFullscreen/index.js";
import IconClose from "../../icon/react-icon/IconClose/index.js";
import IconRotateLeft from "../../icon/react-icon/IconRotateLeft/index.js";
import IconRotateRight from "../../icon/react-icon/IconRotateRight/index.js";
import IconOriginalSize from "../../icon/react-icon/IconOriginalSize/index.js";
import ConfigProvider, { ConfigContext } from "../ConfigProvider/index.js";
import useImageStatus from "./utils/hooks/useImageStatus.js";
import PreviewScales, { defaultScales } from "./utils/getScale.js";
import getFixTranslate from "./utils/getFixTranslate.js";
import ImagePreviewToolbar from "./image-preview-toolbar.js";
import Portal from "../Portal/index.js";
import { PreviewGroupContext } from "./previewGroupContext.js";
import ImagePreviewArrow from "./image-preview-arrow.js";
import useOverflowHidden from "../_util/hooks/useOverflowHidden.js";
import { Esc } from "../_util/keycode.js";
import useUpdate from "../_util/hooks/useUpdate.js";
import { isUndefined } from "../_util/is.js";
import { jsx, jsxs } from "../../../../../../@emotion_react@11.10.4_3toe27fv7etiytxb5kxc7fxaw4/node_modules/@emotion/react/jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js";
import CSSTransition from "../../../../../../react-transition-group@4.4.5_biqbaboplfbrettd7655fr4n2y/node_modules/react-transition-group/esm/CSSTransition.js";
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __rest = globalThis && globalThis.__rest || function(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
var __read = globalThis && globalThis.__read || function(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = {
      error
    };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
};
var ROTATE_STEP = 90;
var defaultProps = {
  maskClosable: true,
  closable: true,
  breakPoint: 316,
  actionsLayout: ["fullScreen", "rotateRight", "rotateLeft", "zoomIn", "zoomOut", "originalSize", "extra"],
  getPopupContainer: function() {
    return document.body;
  },
  escToExit: true,
  scales: defaultScales
};
function Preview(baseProps, ref) {
  var _a, _b;
  var _c = useContext(PreviewGroupContext), previewGroup = _c.previewGroup, previewUrlMap = _c.previewUrlMap, currentIndex = _c.currentIndex, setCurrentIndex = _c.setCurrentIndex, infinite = _c.infinite, previewPropsMap = _c.previewPropsMap;
  var mergedPreviewProps = previewGroup ? previewPropsMap.get(currentIndex) : {};
  var mergedProps = useMergeProps(baseProps, defaultProps, mergedPreviewProps);
  var className = mergedProps.className, style = mergedProps.style, src = mergedProps.src, defaultVisible = mergedProps.defaultVisible, maskClosable = mergedProps.maskClosable, closable = mergedProps.closable, breakPoint = mergedProps.breakPoint, actions = mergedProps.actions, actionsLayout = mergedProps.actionsLayout, getPopupContainer = mergedProps.getPopupContainer, onVisibleChange = mergedProps.onVisibleChange, scales = mergedProps.scales, escToExit = mergedProps.escToExit, _d = mergedProps.imgAttributes, imgAttributes = _d === void 0 ? {} : _d;
  var mergedSrc = previewGroup ? previewUrlMap.get(currentIndex) : src;
  var _e = __read(useState(mergedSrc), 2), previewImgSrc = _e[0], setPreviewImgSrc = _e[1];
  var _f = __read(useMergeValue(false, {
    defaultValue: defaultVisible,
    value: mergedProps.visible
  }), 2), visible = _f[0], setVisible = _f[1];
  var globalContext = useContext(ConfigContext);
  var getPrefixCls = globalContext.getPrefixCls, locale = globalContext.locale, rtl = globalContext.rtl;
  var prefixCls = getPrefixCls("image");
  var previewPrefixCls = prefixCls + "-preview";
  var classNames = cs(previewPrefixCls, (_a = {}, _a[previewPrefixCls + "-hide"] = !visible, _a[previewPrefixCls + "-rtl"] = rtl, _a), className);
  var refImage = useRef();
  var refImageContainer = useRef();
  var refWrapper = useRef();
  var keyboardEventOn = useRef(false);
  var refMoveData = useRef({
    pageX: 0,
    pageY: 0,
    originX: 0,
    originY: 0
  });
  var _g = useImageStatus("loading"), isLoading = _g.isLoading, isLoaded = _g.isLoaded, setStatus = _g.setStatus;
  var _h = __read(useState(false), 2), toolbarSimple = _h[0], setToolbarSimple = _h[1];
  var _j = __read(useState({
    x: 0,
    y: 0
  }), 2), translate = _j[0], setTranslate = _j[1];
  var _k = __read(useState(1), 2), scale = _k[0], setScale = _k[1];
  var _l = __read(useState(false), 2), scaleValueVisible = _l[0], setScaleValueVisible = _l[1];
  var _m = __read(useState(0), 2), rotate = _m[0], setRotate = _m[1];
  var _o = __read(useState(false), 2), moving = _o[0], setMoving = _o[1];
  var previewScales = useMemo(function() {
    return new PreviewScales(scales);
  }, []);
  var onLoad = imgAttributes.onLoad, onError = imgAttributes.onError, onMouseDown = imgAttributes.onMouseDown, imgStyle = imgAttributes.style, imgClassName = imgAttributes.className, restImgAttributes = __rest(imgAttributes, ["onLoad", "onError", "onMouseDown", "style", "className"]);
  function reset() {
    setTranslate({
      x: 0,
      y: 0
    });
    setScale(1);
    setRotate(0);
  }
  useImperativeHandle(ref, function() {
    return {
      reset
    };
  });
  var _p = __read(useState(), 2), container = _p[0], setContainer = _p[1];
  var getContainer = useCallback(function() {
    return container;
  }, [container]);
  useEffect(function() {
    var container2 = getPopupContainer && getPopupContainer();
    var containerDom = findDOMNode(container2) || document.body;
    setContainer(containerDom);
  }, [getPopupContainer]);
  useOverflowHidden(getContainer, {
    hidden: visible
  });
  var isFixed = useMemo(function() {
    return !isServerRendering && container === document.body;
  }, [container]);
  function jumpTo(index) {
    var previewListLen = previewUrlMap.size;
    if (infinite) {
      index %= previewListLen;
      if (index < 0)
        index = previewListLen - Math.abs(index);
    }
    if (index !== currentIndex && index >= 0 && index <= previewListLen - 1) {
      setCurrentIndex(index);
    }
  }
  function onPrev() {
    jumpTo(currentIndex - 1);
  }
  function onNext() {
    jumpTo(currentIndex + 1);
  }
  function onRotateLeft() {
    setRotate(rotate === 0 ? 360 - ROTATE_STEP : rotate - ROTATE_STEP);
  }
  function onRotateRight() {
    setRotate((rotate + ROTATE_STEP) % 360);
  }
  var hideScaleTimer = useRef(null);
  var showScaleValue = function() {
    !scaleValueVisible && setScaleValueVisible(true);
    hideScaleTimer.current && clearTimeout(hideScaleTimer.current);
    hideScaleTimer.current = setTimeout(function() {
      setScaleValueVisible(false);
    }, 1e3);
  };
  var onScaleChange = function(newScale) {
    if (scale !== newScale) {
      setScale(newScale);
      showScaleValue();
    }
  };
  function onZoomIn() {
    var newScale = previewScales.getNextScale(scale, "zoomIn");
    onScaleChange(newScale);
  }
  function onZoomOut() {
    var newScale = previewScales.getNextScale(scale, "zoomOut");
    onScaleChange(newScale);
  }
  function onResetScale() {
    onScaleChange(1);
  }
  function onFullScreen() {
    var wrapperRect = refWrapper.current.getBoundingClientRect();
    var imgRect = refImage.current.getBoundingClientRect();
    var newHeightScale = wrapperRect.height / (imgRect.height / scale);
    var newWidthScale = wrapperRect.width / (imgRect.width / scale);
    var newScale = Math.max(newHeightScale, newWidthScale);
    onScaleChange(newScale);
  }
  function onOutsideImgClick(e) {
    if (e.target === e.currentTarget && maskClosable) {
      close();
    }
  }
  function onCloseClick() {
    close();
  }
  function close() {
    if (visible) {
      onVisibleChange && onVisibleChange(false, visible);
      isUndefined(mergedProps.visible) && setVisible(false);
    }
  }
  function onWrapperResize(entry) {
    if (entry && entry.length) {
      var wrapperRect = entry[0].contentRect;
      var nextSimple = wrapperRect.width < breakPoint;
      setToolbarSimple(nextSimple);
    }
  }
  var checkAndFixTranslate = function() {
    if (!refWrapper.current || !refImage.current)
      return;
    var wrapperRect = refWrapper.current.getBoundingClientRect();
    var imgRect = refImage.current.getBoundingClientRect();
    var _a2 = __read(getFixTranslate(wrapperRect, imgRect, translate.x, translate.y, scale), 2), x = _a2[0], y = _a2[1];
    if (x !== translate.x || y !== translate.y) {
      setTranslate({
        x,
        y
      });
    }
  };
  var onMoving = function(e) {
    if (visible && moving) {
      e.preventDefault && e.preventDefault();
      var _a2 = refMoveData.current, originX = _a2.originX, originY = _a2.originY, pageX = _a2.pageX, pageY = _a2.pageY;
      var nextX = originX + (e.pageX - pageX) / scale;
      var nextY = originY + (e.pageY - pageY) / scale;
      setTranslate({
        x: nextX,
        y: nextY
      });
    }
  };
  var onMoveEnd = function(e) {
    e.preventDefault && e.preventDefault();
    setMoving(false);
  };
  function onImgLoaded(e) {
    setStatus("loaded");
    onLoad && onLoad(e);
  }
  function onImgLoadError(e) {
    setStatus("error");
    onError && onError(e);
  }
  var onMoveStart = function(e) {
    e.preventDefault && e.preventDefault();
    setMoving(true);
    var ev = e.type === "touchstart" ? e.touches[0] : e;
    refMoveData.current.pageX = ev.pageX;
    refMoveData.current.pageY = ev.pageY;
    refMoveData.current.originX = translate.x;
    refMoveData.current.originY = translate.y;
    onMouseDown && onMouseDown(e);
  };
  useEffect(function() {
    if (visible && moving) {
      on(document, "mousemove", onMoving, false);
      on(document, "mouseup", onMoveEnd, false);
    }
    return function() {
      off(document, "mousemove", onMoving, false);
      off(document, "mouseup", onMoveEnd, false);
    };
  }, [visible, moving]);
  useEffect(function() {
    if (!moving) {
      checkAndFixTranslate();
    }
  }, [moving, translate]);
  useEffect(function() {
    checkAndFixTranslate();
  }, [scale]);
  useEffect(function() {
    if (visible) {
      reset();
    }
  }, [visible]);
  useEffect(function() {
    setPreviewImgSrc(mergedSrc);
    setStatus(mergedSrc ? "loading" : "loaded");
    reset();
  }, [mergedSrc]);
  useUpdate(function() {
    previewScales.updateScale(scales);
    setScale(1);
  }, [scales]);
  useEffect(function() {
    var onKeyDown = function(e) {
      if (escToExit && e && e.key === Esc.key) {
        close();
      }
    };
    if (visible && !moving && !keyboardEventOn.current) {
      keyboardEventOn.current = true;
      on(document, "keydown", onKeyDown);
    }
    return function() {
      keyboardEventOn.current = false;
      off(document, "keydown", onKeyDown);
    };
  }, [visible, escToExit, moving]);
  var defaultActions = [{
    key: "fullScreen",
    name: locale.ImagePreview.fullScreen,
    content: /* @__PURE__ */ jsx(IconFullscreen, {}),
    onClick: onFullScreen
  }, {
    key: "rotateRight",
    name: locale.ImagePreview.rotateRight,
    content: /* @__PURE__ */ jsx(IconRotateRight, {}),
    onClick: onRotateRight
  }, {
    key: "rotateLeft",
    name: locale.ImagePreview.rotateLeft,
    content: /* @__PURE__ */ jsx(IconRotateLeft, {}),
    onClick: onRotateLeft
  }, {
    key: "zoomIn",
    name: locale.ImagePreview.zoomIn,
    content: /* @__PURE__ */ jsx(IconZoomIn, {}),
    onClick: onZoomIn,
    disabled: scale === previewScales.maxScale
  }, {
    key: "zoomOut",
    name: locale.ImagePreview.zoomOut,
    content: /* @__PURE__ */ jsx(IconZoomOut, {}),
    onClick: onZoomOut,
    disabled: scale === previewScales.minScale
  }, {
    key: "originalSize",
    name: locale.ImagePreview.originalSize,
    content: /* @__PURE__ */ jsx(IconOriginalSize, {}),
    onClick: onResetScale
  }];
  return /* @__PURE__ */ jsx(Portal, {
    visible,
    forceRender: false,
    getContainer,
    children: /* @__PURE__ */ jsx(ConfigProvider, {
      ...__assign({}, globalContext, {
        getPopupContainer: function() {
          return refWrapper.current;
        }
      }),
      children: /* @__PURE__ */ jsxs("div", {
        className: classNames,
        style: __assign(__assign({}, style || {}), isFixed ? {} : {
          zIndex: "inherit",
          position: "absolute"
        }),
        children: [/* @__PURE__ */ jsx(CSSTransition, {
          in: visible,
          timeout: 400,
          appear: true,
          classNames: "fadeImage",
          mountOnEnter: true,
          unmountOnExit: false,
          onEnter: function(e) {
            e.parentNode.style.display = "block";
            e.style.display = "block";
          },
          onExited: function(e) {
            e.parentNode.style.display = "";
            e.style.display = "none";
          },
          children: /* @__PURE__ */ jsx("div", {
            className: previewPrefixCls + "-mask"
          })
        }), visible && /* @__PURE__ */ jsx(ResizeObserver, {
          onResize: onWrapperResize,
          children: /* @__PURE__ */ jsxs("div", {
            ref: refWrapper,
            className: previewPrefixCls + "-wrapper",
            onClick: onOutsideImgClick,
            children: [/* @__PURE__ */ jsxs("div", {
              ref: refImageContainer,
              className: previewPrefixCls + "-img-container",
              style: {
                transform: "scale(" + scale + ", " + scale + ")"
              },
              onClick: onOutsideImgClick,
              children: [/* @__PURE__ */ jsx("img", {
                ...__assign({
                  ref: refImage,
                  className: cs(imgClassName, previewPrefixCls + "-img", (_b = {}, _b[previewPrefixCls + "-img-moving"] = moving, _b)),
                  style: __assign(__assign({}, imgStyle), {
                    transform: "translate(" + translate.x + "px, " + translate.y + "px) rotate(" + rotate + "deg)"
                  })
                }, restImgAttributes, {
                  onLoad: onImgLoaded,
                  onError: onImgLoadError,
                  onMouseDown: onMoveStart,
                  key: previewImgSrc,
                  src: previewImgSrc
                })
              }), isLoading && /* @__PURE__ */ jsx("div", {
                className: previewPrefixCls + "-loading",
                children: /* @__PURE__ */ jsx(IconLoading, {})
              })]
            }), /* @__PURE__ */ jsx(CSSTransition, {
              in: scaleValueVisible,
              timeout: 400,
              appear: true,
              classNames: "fadeImage",
              unmountOnExit: true,
              children: /* @__PURE__ */ jsxs("div", {
                className: previewPrefixCls + "-scale-value",
                children: [(scale * 100).toFixed(0), "%"]
              })
            }), isLoaded && /* @__PURE__ */ jsx(ImagePreviewToolbar, {
              prefixCls,
              previewPrefixCls,
              actions,
              actionsLayout,
              defaultActions,
              simple: toolbarSimple
            }), closable && /* @__PURE__ */ jsx("div", {
              className: previewPrefixCls + "-close-btn",
              onClick: onCloseClick,
              children: /* @__PURE__ */ jsx(IconClose, {})
            }), previewGroup && /* @__PURE__ */ jsx(ImagePreviewArrow, {
              previewCount: previewUrlMap.size,
              current: currentIndex,
              infinite,
              onPrev,
              onNext
            })]
          })
        })]
      })
    })
  });
}
var PreviewComponent = forwardRef(Preview);
PreviewComponent.displayName = "ImagePreview";
const ImagePreview = PreviewComponent;
export {
  ImagePreview as default
};
//# sourceMappingURL=image-preview.js.map
