// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { isRtl } from '../../utils';
import { cloneElement, isValidElement, useState, useEffect, useRef } from 'react';
import { wrapFunction } from '../utils';
import classNames from 'classnames';
import { CLS_PREFIX, Z_INDEX_DROPDOWN, Z_INDEX_OVERLAY } from '../../constants';
import Button from '../Button';
import AutoClosable from '../AutoClosable';
import Popper from '../Popper';
import Layer from '../Layer';
import { MenuItem, MenuDivider } from '../Menu';
import Translate from '../Translate';
import localeFallback from './locale/en-US';
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const createTarget = (node, _ref) => {
  let {
    onToggle,
    targetRef
  } = _ref;
  if (!( /*#__PURE__*/isValidElement(node) && node.type !== Translate)) {
    node = /*#__PURE__*/_jsx(Button, {
      caret: true,
      children: node
    });
  }
  let isKeyboardEvent = false;
  return /*#__PURE__*/cloneElement(node, {
    onKeyDown: wrapFunction(node.props.onKeyDown, e => {
      isKeyboardEvent = e.key === ' ' || e.key === 'Enter';
    }),
    onClick: wrapFunction(node.props.onClick, e => {
      targetRef.current = e.currentTarget;
      onToggle(isKeyboardEvent);
      isKeyboardEvent = false;
    }),
    'aria-haspopup': true
  });
};
const computePlacement = placement => {
  const [side, align] = placement.split('-');
  if (align && isRtl() && ['top', 'bottom'].indexOf(side) !== -1) {
    return `${side}-${align === 'start' ? 'end' : 'start'}`;
  }
  return placement;
};
const useEnhancedMenu = (menu, _ref2) => {
  let {
    baseClassName,
    onClose,
    overlay,
    locale,
    autoFocus
  } = _ref2;
  const menuRef = useRef();
  const triggerRef = useRef();
  useEffect(() => {
    if (menuRef.current && !overlay) {
      triggerRef.current = document.activeElement;
      setTimeout(() => {
        if (menuRef.current) {
          menuRef.current.focus();
        }
      });
    }
  });
  const handleClose = () => {
    if (triggerRef.current) {
      triggerRef.current.focus();
    }
    onClose();
  };
  const handleKeyDown = e => {
    e.stopPropagation();
    switch (e.key) {
      case 'Enter':
        e.preventDefault();
        document.activeElement.click();
        break;
      case 'Escape':
        e.preventDefault();
        handleClose();
        break;
      case 'Tab':
        handleClose();
        break;
    }
  };
  let {
    children
  } = menu.props;
  if (overlay) {
    children = [...menu.props.children, /*#__PURE__*/_jsx(MenuDivider, {
      className: `${baseClassName}__overlay-menu-divider`
    }, "divider"), /*#__PURE__*/_jsx(MenuItem, {
      onClick: handleClose,
      children: /*#__PURE__*/_jsx(Translate, {
        namespace: "Dropdown",
        content: "close",
        translators: locale,
        fallback: localeFallback.close
      })
    }, "close")];
  }
  const clone = /*#__PURE__*/cloneElement(menu, {
    onItemClick: wrapFunction(menu.props.onItemClick, handleClose),
    className: classNames(`${baseClassName}__menu`, menu.props.className),
    overlay,
    ref: menuRef,
    children,
    onKeyDown: handleKeyDown,
    autoFocus
  });
  return {
    enhancedMenu: clone,
    menuRef
  };
};

/**
 * `Dropdown` component is a [Button](#!/Button) that opens a drop-down (nested) [Menu](#!/Menu).
 * Use dropdown for grouping actions that are not used often or are less important than others -- in other words,
 * for stuff that you don't want to show users all the time, especially if you have limited screen space.
 * @since 0.0.57
 */
const Dropdown = _ref3 => {
  let {
    baseClassName,
    className,
    children,
    menu,
    menuPlacement,
    overlay,
    locale,
    ...props
  } = _ref3;
  const [opened, setOpened] = useState(false);
  const [autoFocus, setAutoFocus] = useState(false);
  const closeTimerRef = useRef();
  useEffect(() => () => {
    clearTimeout(closeTimerRef.current);
  }, []);
  const handleOpen = isKeyboardEvent => {
    setAutoFocus(isKeyboardEvent);
    setOpened(true);
  };
  const handleClose = () => {
    closeTimerRef.current = setTimeout(() => {
      setOpened(false);
    }, 0);
  };
  const {
    enhancedMenu,
    menuRef
  } = useEnhancedMenu(menu, {
    baseClassName,
    onClose: handleClose,
    overlay,
    locale,
    autoFocus
  });
  const targetRef = useRef();
  const target = createTarget(children, {
    onToggle: handleOpen,
    targetRef
  });
  return /*#__PURE__*/_jsx("div", {
    className: classNames(baseClassName, {
      [`${baseClassName}--opened`]: opened
    }, className),
    ...props,
    children: overlay ? /*#__PURE__*/_jsxs(_Fragment, {
      children: [target, opened && /*#__PURE__*/_jsx(Layer, {
        level: Z_INDEX_OVERLAY,
        children: /*#__PURE__*/_jsx("div", {
          className: `${baseClassName}__overlay`,
          children: /*#__PURE__*/_jsx(AutoClosable, {
            onClose: handleClose,
            nodeRef: menuRef,
            children: /*#__PURE__*/_jsx("div", {
              className: `${baseClassName}__overlay-menu`,
              children: enhancedMenu
            })
          })
        })
      })]
    }) : /*#__PURE__*/_jsx(Popper, {
      target: target,
      targetRef: targetRef,
      placement: computePlacement(menuPlacement),
      show: opened,
      className: `${baseClassName}__popper`,
      zIndex: Z_INDEX_DROPDOWN,
      children: /*#__PURE__*/_jsx(AutoClosable, {
        onClose: handleClose,
        nodeRef: menuRef,
        children: enhancedMenu
      })
    })
  });
};
Dropdown.defaultProps = {
  menuPlacement: 'bottom-start',
  children: undefined,
  overlay: false,
  className: undefined,
  baseClassName: `${CLS_PREFIX}dropdown`,
  locale: undefined
};
export default Dropdown;