import _pt from "prop-types";

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import React, { useState } from 'react';
import VerticalNav from './VerticalNav';
import VerticalNavItemLabel from './VerticalNavItemLabel';
import classNames from 'classnames';
import uniqueId from 'lodash/uniqueId';
export var VerticalNavItem = function VerticalNavItem(props) {
  var id = props.id || uniqueId('VerticalNavItem_');
  var subnavId = "".concat(id, "__subnav");

  var _useState = useState(props.defaultCollapsed),
      _useState2 = _slicedToArray(_useState, 2),
      collapsed = _useState2[0],
      setCollapsed = _useState2[1];
  /**
   * Note: This event handler will only get called when the VerticalNavItemLabel
   * is a link or plain text
   */


  var handleClick = function handleClick(evt) {
    if (props.onClick) {
      props.onClick(evt, id, props.url);
    }
  };

  var handleToggleClick = function handleToggleClick() {
    setCollapsed(!collapsed);

    if (props.onSubnavToggle) {
      props.onSubnavToggle(props.id, collapsed);
    }
  };

  var hasSubnav = function hasSubnav() {
    return Boolean(props.items && props.items.length > 0);
  };
  /**
   * Called when VerticalNavItemLabel is clicked. Since the "label" could be
   * a link, subnav toggle button, or plain text, we use this method to
   * determine what action to take and which event to actually fire.
   * @param {Object} SyntheticEvent
   */


  var handleLabelClick = function handleLabelClick(evt) {
    if (hasSubnav()) {
      return handleToggleClick();
    }

    return handleClick(evt);
  };
  /**
   * Checks if a descendant is selected
   * @param {Array} children - The nested items
   * @return {Boolean}
   */


  var childIsSelected = function childIsSelected(children) {
    if (children && children.length) {
      return children.some(function (child) {
        return child.id === props._selectedId || childIsSelected(child.items);
      });
    }

    return false;
  };
  /**
   * Check if this item is selected or if it is a parent of a selected item
   * @return {Boolean}
   */


  var isSelected = function isSelected() {
    if (props.selected) return props.selected;

    if (props._selectedId && hasSubnav()) {
      return childIsSelected(props.items);
    }

    return false;
  };

  var subnavItems = function subnavItems() {
    if (props.url) {
      // Since the VerticalNavItemLabel will just toggle the subnav, we
      // add a link to the top of the subnav for this item. Otherwise there
      // wouldn't be a way to actually visit its URL
      var item = _extends({}, props);

      delete item.items;
      return [item].concat(props.items);
    }

    return props.items;
  };

  var classes = classNames('ds-c-vertical-nav__item', props.className);
  return /*#__PURE__*/React.createElement("li", {
    className: classes
  }, /*#__PURE__*/React.createElement(VerticalNavItemLabel, {
    ariaCollapsedStateButtonLabel: props.ariaCollapsedStateButtonLabel,
    ariaExpandedStateButtonLabel: props.ariaExpandedStateButtonLabel,
    collapsed: collapsed,
    component: props.component,
    label: props.label,
    hasSubnav: hasSubnav(),
    onClick: handleLabelClick,
    selected: isSelected(),
    subnavId: subnavId,
    url: props.url
  }), hasSubnav() && /*#__PURE__*/React.createElement(VerticalNav, {
    selectedId: props._selectedId,
    collapsed: collapsed,
    id: subnavId,
    items: subnavItems(),
    component: props.component,
    nested: true
  }));
};
VerticalNavItem.propTypes = {
  /**
     * @hide-prop This gets passed through from the parent VerticalNav to a nested VerticalNav
     */
  _selectedId: _pt.string,

  /**
     * Aria label for the toggle button when the sub-navigation is collapsed
     */
  ariaCollapsedStateButtonLabel: _pt.string,

  /**
     * Aria label for the toggle button when the sub-navigation is expanded
     */
  ariaExpandedStateButtonLabel: _pt.string,

  /**
     * Additional classes to be added to the root element
     */
  className: _pt.string,

  /**
     * When provided, this will render the passed in component. This is useful when
     * integrating with React Router's `<Link>` or using your own custom component.
     */
  component: _pt.any,

  /**
     * Whether or not the item's sub-navigation is in a collapsed state by default
     */
  defaultCollapsed: _pt.bool,

  /**
     * Called when the link is clicked, with the following arguments:
     * [`SyntheticEvent`](https://facebook.github.io/react/docs/events.html),
     * `id`, `url`.
     * This takes precedence over the `VerticalNav` `onLinkClick` prop
     */
  onClick: _pt.func,

  /**
     * Called when this item's subnav is collapsed or expanded, with the
     * following arguments: `id`, `collapsed`
     */
  onSubnavToggle: _pt.func,

  /**
     * Optional identifier. This can be handy if you're passing in an
     * `onClick` handler. A unique ID will be generated if one isn't provided.
     */
  id: _pt.string,

  /**
     * An array of nested `VerticalNavItem` data objects to be rendered in a
     * sub-navigation list.
     */
  items: _pt.arrayOf(_pt.any),

  /**
     * Text to render for this nav item
     */
  label: _pt.node.isRequired,

  /**
     * A URL to navigate to if this item is a link
     */
  url: _pt.string,

  /**
     * If this item is currently selected
     */
  selected: _pt.bool
};
VerticalNavItem.defaultProps = {
  // Unfortunately, we're defining these default ARIA props here and in
  // VerticalNavItemLabel. We define them here so they show in the docs.
  // TODO(sawyer): Update react-docgen so we don't have to do this
  ariaCollapsedStateButtonLabel: 'Expand sub-navigation',
  ariaExpandedStateButtonLabel: 'Collapse sub-navigation',
  defaultCollapsed: false
};
export default VerticalNavItem;