import React, { useRef } from "react";
import { isEmpty, safeUseId } from "../../../../utils";
import { Ul, ListWrapper } from "../../Select.styles";
import { FloatingPopover } from "../../FloatingPopover";
import { Item } from "./ui/Item/Item";
export const Inner = ({ item, currentLevel, path, dispatchPath, index, listWidth, portal, shift, flip })=>{
    const 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
            });
        }
    };
    const listWrapperRef = useRef(null);
    const isCurrentListOpen = path[currentLevel + 1] === item.value.toString();
    const treeId = safeUseId();
    const listId = `${treeId}_tree_level_${currentLevel + 2}`;
    const nextLevel = currentLevel + 1;
    if (!isEmpty(item?.items)) {
        return /*#__PURE__*/ React.createElement(FloatingPopover, {
            placement: item?.placement || 'right',
            opened: isCurrentListOpen,
            onToggle: handleToggle,
            target: /*#__PURE__*/ React.createElement(Item, {
                item: item,
                path: path,
                currentLevel: currentLevel,
                index: index,
                ariaControls: listId,
                ariaExpanded: isCurrentListOpen,
                ariaLevel: nextLevel,
                ariaLabel: item.label
            }),
            isInner: true,
            portal: portal,
            shift: shift,
            flip: flip
        }, /*#__PURE__*/ React.createElement(ListWrapper, {
            listWidth: listWidth,
            ref: listWrapperRef
        }, /*#__PURE__*/ React.createElement(Ul, {
            role: "group",
            id: listId,
            virtual: false,
            listMaxHeight: item?.listMaxHeight
        }, item.items?.map((innerItem, innerIndex)=>/*#__PURE__*/ React.createElement(Inner, {
                key: `${innerIndex}/${currentLevel}`,
                item: innerItem,
                currentLevel: nextLevel,
                path: path,
                dispatchPath: dispatchPath,
                index: innerIndex,
                listWidth: listWidth,
                portal: listWrapperRef,
                shift: shift,
                flip: flip
            })))));
    }
    return /*#__PURE__*/ React.createElement(Item, {
        item: item,
        path: path,
        index: index,
        currentLevel: currentLevel,
        ariaLevel: nextLevel
    });
};
