// (C) 2026 GoodData Corporation
import { useCallback, useEffect, useMemo } from "react";
/**
 * Hook to manage catalog item picker event handlers.
 *
 * @internal
 */
export function useCatalogItemPickerHandlers({ selectionMode, selectedIds, setSelectedIds, listboxItems, onClose, onAdd, onSelect, handleItemSelect, setActiveType, resetSelection, }) {
    // Item lookup map
    const itemById = useMemo(() => {
        const map = new Map();
        listboxItems.forEach((item) => {
            if (item.type === "interactive") {
                const interactiveItem = item;
                map.set(interactiveItem.id, interactiveItem.data.item);
            }
        });
        return map;
    }, [listboxItems]);
    // Sync selected IDs with available items
    useEffect(() => {
        setSelectedIds((prev) => {
            const next = new Set();
            prev.forEach((id) => {
                if (itemById.has(id)) {
                    next.add(id);
                }
            });
            if (next.size !== prev.size) {
                return next;
            }
            for (const id of next) {
                if (!prev.has(id)) {
                    return next;
                }
            }
            return prev;
        });
    }, [itemById, setSelectedIds]);
    const handleListboxSelect = useCallback((item) => {
        if (selectionMode === "single") {
            onSelect?.(item.data.item.payload);
            onClose();
            return;
        }
        handleItemSelect(item.id);
    }, [handleItemSelect, onClose, onSelect, selectionMode]);
    const handleAdd = useCallback(() => {
        const selectedItems = Array.from(selectedIds)
            .map((id) => itemById.get(id))
            .filter((item) => !!item)
            .map((item) => item.payload);
        onAdd?.(selectedItems);
    }, [itemById, onAdd, selectedIds]);
    const handleTabChange = useCallback((type) => {
        setActiveType(type);
        resetSelection();
    }, [resetSelection, setActiveType]);
    return {
        itemById,
        handleListboxSelect,
        handleAdd,
        handleTabChange,
    };
}
