import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { useCallback, useMemo, } from "react";
import { e } from "./treeviewBem.js";
import { convertPathToKey, makeItemId } from "./utils.js";
/**
 * @internal
 */
export function UITreeviewItem(props) {
    const { getState, focusedItem, selectedItemId, itemDataTestId, onSelect, onHover, ItemComponent, isCompact, isDisabledFocusable, itemsRef, treeViewId, path, } = props;
    const [state, { toggle }] = getState(props.path);
    const { item, children } = props.item;
    const childCount = children?.length ?? 0;
    const level = props.path.length;
    const id = makeItemId(treeViewId, path);
    const isFocused = item === focusedItem?.item;
    const isSelected = item.id === selectedItemId;
    const isExpanded = childCount > 0 ? state?.expanded : undefined;
    const isDisabled = !isDisabledFocusable && item.isDisabled;
    const ariaAttributes = useMemo(() => ({
        id,
        role: "treeitem",
        "aria-level": level,
        "aria-expanded": isExpanded,
        "aria-selected": isFocused,
        "aria-disabled": isDisabled,
    }), [id, level, isExpanded, isFocused, isDisabled]);
    const handleToggle = useCallback((event, expanded) => {
        toggle(expanded);
        event.stopPropagation();
        event.preventDefault();
    }, [toggle]);
    const handleSelect = useCallback((event) => {
        onSelect(event, props.path, props.item);
    }, [props.item, props.path, onSelect]);
    const handleHover = useCallback(() => {
        onHover(props.path);
    }, [props.path, onHover]);
    return (_jsxs("div", { className: e("treeitem"), children: [
            _jsx("div", { className: e("treeitem__container"), "data-testid": itemDataTestId, ref: (node) => {
                    itemsRef.current[convertPathToKey(path)] = node;
                }, children: _jsx(ItemComponent, { item: item, type: childCount ? "group" : "leaf", childCount: childCount, isCompact: isCompact, isFocused: isFocused, isSelected: isSelected, isExpanded: isExpanded, level: level, onSelect: handleSelect, onToggle: handleToggle, onHover: handleHover, ariaAttributes: ariaAttributes }) }), children?.length && isExpanded ? (_jsx("div", { role: "group", className: e("treeitem__children"), children: children.map((child, i) => (_jsx(UITreeviewItem, { ItemComponent: ItemComponent, itemsRef: itemsRef, onSelect: onSelect, onHover: onHover, getState: getState, focusedItem: focusedItem, selectedItemId: selectedItemId, itemDataTestId: itemDataTestId, isCompact: isCompact, isDisabledFocusable: isDisabledFocusable, item: child, treeViewId: treeViewId, path: [...props.path, i] }, i))) })) : null] }));
}
