import { Children } from 'react';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
function hasFilter(e, index) {
    const filter = e?.props?.filter;
    if (process.env.NODE_ENV !== 'production') {
        if (filter == null) {
            console.warn(`filter component must pass \`filter\` prop directly, missing from CollectionToolbarFilters.children[${index}].props`);
        }
    }
    return filter != null;
}
function flattenChildren(children) {
    const currentChildren = [];
    if (Array.isArray(children)) {
        currentChildren.push(...children);
    }
    else {
        currentChildren.push(children);
    }
    return currentChildren;
}
function filterValidChildren(children) {
    return Children.toArray(children).filter(hasFilter);
}
function addTagsFilter(children, state) {
    const tagsFilter = state.tagsCollectionState?.buildTagsFilterWrapper();
    if (tagsFilter &&
        !children.some((child) => child.props.filter.name === tagsFilter.props.filter.name)) {
        return [...children, tagsFilter];
    }
    return children;
}
function addCustomFieldFilters(children, state) {
    const customFieldFilters = state.collectionDataExtension?.dataExtension.filterableCustomFields
        .map((customField) => {
        if (children.some((child) => child.props.filter.name === customField.id)) {
            return null;
        }
        return state.collectionDataExtension?.buildCustomFieldFilterWrapper(customField);
    })
        .filter(Boolean);
    if (customFieldFilters) {
        return [...children, ...customFieldFilters];
    }
    return children;
}
export const useFiltersSyncProps = (children) => {
    const state = useToolbarCollectionContext();
    const allChildren = flattenChildren(children);
    const filteredChildren = filterValidChildren(allChildren);
    const childrenWithTagsFilter = addTagsFilter(filteredChildren, state);
    const finalChildren = addCustomFieldFilters(childrenWithTagsFilter, state);
    return finalChildren;
};
//# sourceMappingURL=useFiltersSyncProps.js.map