import React__default, { useRef } from 'react';
import { ListWrapper, Ul } from '../../Dropdown.styles.js';
import { FloatingPopover } from '../../FloatingPopover.js';
import { safeUseId } from '../../../../utils/react.js';
import { getPlacement } from '../../utils/getPlacement.js';
import { Item } from './ui/Item/Item.js';

var Inner = function Inner(_ref) {
  var _item$items;
  var item = _ref.item,
    currentLevel = _ref.currentLevel,
    path = _ref.path,
    dispatchPath = _ref.dispatchPath,
    index = _ref.index,
    trigger = _ref.trigger,
    listWidth = _ref.listWidth,
    portal = _ref.portal;
  var handleToggle = function handleToggle(opened) {
    if (opened) {
      dispatchPath({
        type: 'changed_on_level',
        value: item.value.toString(),
        level: currentLevel + 1
      });
    } else {
      dispatchPath({
        type: 'cut_by_level',
        level: currentLevel + 1
      });
    }
  };
  var listWrapperRef = useRef(null);
  var isCurrentListOpen = path[currentLevel + 1] === item.value.toString();
  var treeId = safeUseId();
  var listId = "".concat(treeId, "_tree_level_").concat(currentLevel + 2);
  var nextLevel = currentLevel + 1;
  if (item !== null && item !== void 0 && (_item$items = item.items) !== null && _item$items !== void 0 && _item$items.length) {
    return /*#__PURE__*/React__default.createElement(FloatingPopover, {
      placement: getPlacement((item === null || item === void 0 ? void 0 : item.placement) || 'right'),
      opened: isCurrentListOpen,
      onToggle: handleToggle,
      trigger: item.trigger || trigger,
      target: /*#__PURE__*/React__default.createElement(Item, {
        item: item,
        index: index,
        path: path,
        currentLevel: currentLevel,
        ariaControls: listId,
        ariaExpanded: isCurrentListOpen,
        ariaLevel: nextLevel,
        ariaLabel: item.label
      }),
      isInner: true,
      portal: portal
    }, /*#__PURE__*/React__default.createElement(ListWrapper, {
      ref: listWrapperRef,
      listWidth: listWidth
    }, /*#__PURE__*/React__default.createElement(Ul, {
      id: listId,
      role: "group",
      listMaxHeight: item.listMaxHeight
    }, item.beforeList, item.items.map(function (innerItem, innerIndex) {
      return /*#__PURE__*/React__default.createElement(Inner, {
        key: "".concat(innerIndex, "/").concat(currentLevel),
        item: innerItem,
        currentLevel: nextLevel,
        path: path,
        dispatchPath: dispatchPath,
        index: innerIndex,
        trigger: trigger,
        listWidth: listWidth,
        portal: listWrapperRef
      });
    }))));
  }
  return /*#__PURE__*/React__default.createElement(Item, {
    item: item,
    path: path,
    index: index,
    currentLevel: currentLevel,
    ariaLevel: nextLevel
  });
};

export { Inner };
