import { getComponentById } from "../componentTreeHelper";
/**
 * Collects insert options from placeholders in a page.
 * @param page The page to collect from
 * @param placeholderKeys If provided, only collect from these placeholders. If empty, collect from all placeholders.
 */
function collectInsertOptions(page, placeholderKeys) {
    const insertOptionsMap = new Map();
    function traverse(placeholders) {
        for (const placeholder of placeholders) {
            if (placeholder &&
                (placeholderKeys.length === 0 ||
                    placeholderKeys.includes(placeholder.key))) {
                for (const option of placeholder.insertOptions) {
                    insertOptionsMap.set(option.typeId, option);
                }
            }
            for (const component of placeholder.components) {
                if (component.placeholders)
                    traverse(component.placeholders);
            }
        }
    }
    traverse(page.rootComponent.placeholders);
    // Convert the map back into an array of objects
    const insertOptionsArray = Array.from(insertOptionsMap.values());
    insertOptionsArray.sort((a, b) => a.name.localeCompare(b.name));
    return insertOptionsArray;
}
/**
 * Gets insert options based on the current selection in the edit context.
 * Only returns options valid for the currently selected placeholder(s).
 */
export function getInsertOptionsForCurrentSelection(editContext) {
    const page = editContext.page;
    if (!page)
        return [];
    const insertingPlaceholderKeys = [editContext.selectedForInsertion]
        .map((x) => getComponentById(x, editContext.page))
        .filter((x) => x)
        .reduce((a, x) => a.concat(x.placeholders?.map((y) => y.key) || []), []);
    const selectedPlaceholderKeys = [
        //...selection.filter((x) => x.indexOf("_") > 0),
        ...insertingPlaceholderKeys,
    ];
    const currentInsertOptions = page
        ? collectInsertOptions(page, selectedPlaceholderKeys)
        : [];
    // console.log(currentInsertOptions, selectedPlaceholderKeys, page);
    return currentInsertOptions;
}
/**
 * Gets ALL insert options from ALL placeholders in the page.
 * Use this when you need to show all available component types regardless of selection.
 */
export function getAllInsertOptions(editContext) {
    const page = editContext.page;
    if (!page)
        return [];
    // Pass empty array to collect from all placeholders
    return collectInsertOptions(page, []);
}
//# sourceMappingURL=insertOptions.js.map