"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _utils = require("../../utils");
var _react = require("react");
var _utils2 = require("../utils");
var _classnames = _interopRequireDefault(require("classnames"));
var _constants = require("../../constants");
var _Layer = _interopRequireDefault(require("../Layer"));
var _FocusTrap = _interopRequireDefault(require("../FocusTrap"));
var _jsxRuntime = require("react/jsx-runtime");
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

/**
 * `Overlay` component.
 */

let overlaysCount = 0;
const OverlayCore = _ref => {
  let {
    baseClassName = `${_constants.CLS_PREFIX}overlay`,
    className,
    children = null,
    isOpen: externalIsOpen,
    placement = 'center',
    size = 'md',
    sideBanner,
    sideBannerContainer,
    onClose,
    canCloseOnBackdropClick = true,
    canCloseOnEscapePress = true,
    style = {},
    onAnimationExited,
    ...props
  } = _ref;
  const animationTimeoutRef = (0, _react.useRef)();
  const contentRef = (0, _react.useRef)(null);
  const prevIsOpen = (0, _react.useRef)(externalIsOpen);
  if (prevIsOpen.current !== externalIsOpen) {
    prevIsOpen.current = externalIsOpen;
    if (externalIsOpen) {
      clearTimeout(animationTimeoutRef.current);
    } else {
      animationTimeoutRef.current = window.setTimeout(onAnimationExited, 300);
    }
  }
  (0, _react.useEffect)(() => () => clearTimeout(animationTimeoutRef.current), []);
  const [isOpen, setIsOpen] = (0, _react.useState)(false);
  (0, _react.useEffect)(() => setIsOpen(externalIsOpen), [externalIsOpen]);
  const focus = () => {
    if (contentRef.current === null || document.activeElement === null) {
      return;
    }
    const isFocusOutside = !contentRef.current.contains(document.activeElement);
    if (isFocusOutside) {
      const autofocusElement = contentRef.current.querySelector('[autofocus]');
      if (autofocusElement instanceof HTMLElement) {
        autofocusElement.focus();
      } else {
        contentRef.current.focus();
      }
    }
  };
  (0, _react.useLayoutEffect)(() => {
    if (isOpen) focus();
  }, [isOpen]);
  const handleBackdropClick = () => {
    if (canCloseOnBackdropClick) {
      (0, _utils2.safeInvoke)(onClose);
    } else if (isOpen) {
      focus();
    }
  };
  const handleContentKeyUp = e => {
    if (!e.isDefaultPrevented() && e.key === 'Escape') {
      (0, _utils2.safeInvoke)(onClose);
      e.preventDefault();
    }
  };
  const renderImage = sideBanner => {
    const classPrefix = `${baseClassName}__side`;
    let element = null;
    if ( /*#__PURE__*/(0, _react.isValidElement)(sideBanner)) {
      element = sideBanner;
    } else if (typeof sideBanner === 'string') {
      element = /*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
        className: `${classPrefix}-image`,
        src: sideBanner,
        alt: ""
      });
    } else {
      element = /*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
        className: `${classPrefix}-image`,
        ...sideBanner
      });
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: classPrefix,
      children: element
    });
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layer.default, {
    level: _constants.Z_INDEX_OVERLAY,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: (0, _classnames.default)(baseClassName, `${baseClassName}--${placement}`, `${baseClassName}--${size}`, sideBanner && `${baseClassName}--side`, isOpen && `${baseClassName}--open`, className),
      style: {
        '--overlay-side-banner-background': sideBannerContainer?.background,
        '--overlay-side-banner-align': sideBannerContainer?.align,
        ...style
      },
      ...props,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${baseClassName}__backdrop`,
        onClick: handleBackdropClick
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_FocusTrap.default, {
        className: `${baseClassName}__content`,
        onKeyUp: canCloseOnEscapePress ? handleContentKeyUp : undefined,
        ref: contentRef,
        role: "dialog",
        "aria-modal": "true",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: `${baseClassName}__body`,
          children: children
        }), sideBanner && renderImage(sideBanner)]
      })]
    })
  });
};
const Overlay = _ref2 => {
  let {
    isOpen = false,
    ...props
  } = _ref2;
  const isOpenRef = (0, _react.useRef)(false);
  const [isExist, setIsExist] = (0, _react.useState)(false);
  const prevFocusElementRef = (0, _react.useRef)(null);
  const handleClose = (0, _react.useCallback)(() => {
    if (!isOpenRef.current) return;
    isOpenRef.current = false;
    if (--overlaysCount === 0) (0, _utils.enableDocumentScroll)();
    prevFocusElementRef.current?.focus();
  }, []);
  (0, _react.useEffect)(() => {
    if (isOpen) {
      isOpenRef.current = true;
      (0, _utils.disableDocumentScroll)();
      overlaysCount++;
      if (document.activeElement instanceof HTMLElement) {
        prevFocusElementRef.current = document.activeElement;
      }
      setIsExist(true);
    } else {
      handleClose();
    }
  }, [isOpen, handleClose]);
  (0, _react.useEffect)(() => () => handleClose(), [handleClose]);
  if (!isExist) return null;
  const handleExited = () => {
    setIsExist(false);
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(OverlayCore, {
    isOpen: isOpen,
    onAnimationExited: handleExited,
    ...props
  });
};
var _default = exports.default = Overlay;