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

import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';
import { safeInvoke, createFocusManager } from '../utils';
import { cloneElement, Children, isValidElement, useRef, useMemo } from 'react';
import { jsx as _jsx } from "react/jsx-runtime";
/**
 * `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 = `${CLS_PREFIX}subnav`,
    ...props
  } = _ref;
  const rootRef = useRef(null);
  const {
    focusNext,
    focusPrev,
    focusFirst,
    focusLast
  } = useMemo(() => 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;
    }
    safeInvoke(onKeyDown, e);
  };
  let itemIndex = -1;
  Children.toArray(children).every((child, index) => {
    if (! /*#__PURE__*/isValidElement(child)) {
      return true;
    }
    if (child.props.active) {
      itemIndex = index;
      return false;
    } else if (itemIndex === -1) {
      itemIndex = index;
    }
    return true;
  });
  const items = Children.map(children, (child, index) => {
    if (itemIndex === index) {
      if (! /*#__PURE__*/isValidElement(child)) {
        return child;
      }
      return /*#__PURE__*/cloneElement(child, {
        tabIndex: 0
      });
    }
    return child;
  });
  return /*#__PURE__*/_jsx("div", {
    className: classNames(baseClassName, className),
    ...props,
    onKeyDown: handleKeyDown,
    ref: rootRef,
    children: items
  });
};
/**
 * SubnavItem component.
 */
const SubnavItem = _ref2 => {
  let {
    className,
    active,
    children,
    baseClassName = `${CLS_PREFIX}subnav__item`,
    ...props
  } = _ref2;
  return /*#__PURE__*/cloneElement(children, {
    className: classNames(baseClassName, active && `${baseClassName}--active`, className),
    tabIndex: -1,
    ...props
  });
};
export default Subnav;
export { SubnavItem };