import { useWixPatternsContainer } from '@wix/bex-core/react';
import React, { useCallback } from 'react';
import { accordionSectionItemBuilder, } from '@wix/design-system';
import { CollectionFilter } from '../components/CollectionFilter';
import { FilterAccordionTitle } from '../components/FiltersPanel/FilterAccordionTitle';
function useBuildAccordionItem(state) {
    return useCallback((filterElement) => {
        const { type: Component, props: filterProps } = filterElement;
        const { filter, initiallyOpen, popoverProps, accordionItemProps } = filterProps;
        const clonedElement = (React.createElement(Component, { ...filterProps, popoverProps: { appendTo: 'window', ...popoverProps } }));
        return {
            title: (React.createElement(FilterAccordionTitle, { state: state.toolbar, filter: filter, filterProps: filterProps })),
            children: filterProps.filter ? (React.createElement(CollectionFilter, { filter: filterProps.filter, state: state }, clonedElement)) : (clonedElement),
            initiallyOpen,
            ...accordionItemProps,
        };
    }, []);
}
export function useBuildAccordionItems(state) {
    const { translate: t } = useWixPatternsContainer();
    const buildAccordionItem = useBuildAccordionItem(state);
    const { panelFilterElements } = state;
    const defaultSectionTitle = t('cairo.filtersPanel.sections.default.title');
    const { groups, defaultGroup } = panelFilterElements.reduce((accumulator, item) => {
        const sectionTitle = item.props?.sectionTitle;
        if (!sectionTitle) {
            return {
                ...accumulator,
                defaultGroup: [...accumulator.defaultGroup, buildAccordionItem(item)],
            };
        }
        const groupItems = accumulator.groups[sectionTitle]
            ? [...accumulator.groups[sectionTitle], buildAccordionItem(item)]
            : [
                accordionSectionItemBuilder({ title: sectionTitle }),
                buildAccordionItem(item),
            ];
        return {
            ...accumulator,
            groups: {
                ...accumulator.groups,
                [sectionTitle]: groupItems,
            },
        };
    }, {
        groups: {},
        defaultGroup: [],
    });
    const items = Object.values(groups).flat();
    if (!items.length) {
        return defaultGroup;
    }
    return [
        ...items,
        ...(defaultGroup.length
            ? [
                accordionSectionItemBuilder({ title: defaultSectionTitle }),
                ...defaultGroup,
            ]
            : []),
    ];
}
//# sourceMappingURL=useBuildAccordionItems.js.map