"use strict";

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

/**
 * `Subnav` component is used when you need a second level navigation under [Tabs](#!/Tabs) on the screen.
 * @since 0.0.42
 */
const Subnav = _ref => {
  let {
    className,
    children,
    onKeyDown,
    baseClassName = `${_constants.CLS_PREFIX}subnav`,
    ...props
  } = _ref;
  const rootRef = (0, _react.useRef)(null);
  const {
    focusNext,
    focusPrev,
    focusFirst,
    focusLast
  } = (0, _react.useMemo)(() => (0, _utils.createFocusManager)(rootRef), []);
  const handleKeyDown = e => {
    switch (e.key) {
      case 'ArrowLeft':
        e.preventDefault();
        focusPrev();
        break;
      case 'ArrowRight':
        e.preventDefault();
        focusNext();
        break;
      case 'Home':
      case 'PageUp':
        e.preventDefault();
        focusFirst();
        break;
      case 'End':
      case 'PageDown':
        e.preventDefault();
        focusLast();
        break;
      case 'Enter':
        e.preventDefault();
        if (e.target instanceof HTMLElement) {
          e.target.click();
        }
        break;
    }
    (0, _utils.safeInvoke)(onKeyDown, e);
  };
  let itemIndex = -1;
  _react.Children.toArray(children).every((child, index) => {
    if (! /*#__PURE__*/(0, _react.isValidElement)(child)) {
      return true;
    }
    if (child.props.active) {
      itemIndex = index;
      return false;
    } else if (itemIndex === -1) {
      itemIndex = index;
    }
    return true;
  });
  const items = _react.Children.map(children, (child, index) => {
    if (itemIndex === index) {
      if (! /*#__PURE__*/(0, _react.isValidElement)(child)) {
        return child;
      }
      return /*#__PURE__*/(0, _react.cloneElement)(child, {
        tabIndex: 0
      });
    }
    return child;
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: (0, _classnames.default)(baseClassName, className),
    ...props,
    onKeyDown: handleKeyDown,
    ref: rootRef,
    children: items
  });
};
/**
 * SubnavItem component.
 */
const SubnavItem = _ref2 => {
  let {
    className,
    active,
    children,
    baseClassName = `${_constants.CLS_PREFIX}subnav__item`,
    ...props
  } = _ref2;
  return /*#__PURE__*/(0, _react.cloneElement)(children, {
    className: (0, _classnames.default)(baseClassName, active && `${baseClassName}--active`, className),
    tabIndex: -1,
    ...props
  });
};
exports.SubnavItem = SubnavItem;
var _default = exports.default = Subnav;