import { jsx as _jsx } from "react/jsx-runtime";
import { getAbsoluteIconUrl } from "./utils";
const MIN_COMPONENTS_FOR_GROUPED_MENU = 9;
export function getVisibleInsertOptions(insertOptions) {
    return (insertOptions
        ?.filter((x) => !x.isHidden && !x.isInvalid)
        .sort((a, b) => a.name.localeCompare(b.name)) || []);
}
export function buildInsertMenuItems(insertOptions, onInsert) {
    if (!shouldUseGroupedInsertMenu(insertOptions)) {
        return insertOptions.map((x) => createInsertMenuItem(x, onInsert));
    }
    const grouped = groupInsertOptions(insertOptions);
    return grouped.map(([groupName, options]) => ({
        id: `group-${groupName}`,
        label: groupName,
        items: options.map((option) => createInsertMenuItem(option, onInsert)),
    }));
}
function shouldUseGroupedInsertMenu(insertOptions) {
    if (insertOptions.length < MIN_COMPONENTS_FOR_GROUPED_MENU)
        return false;
    const grouped = groupInsertOptions(insertOptions);
    if (grouped.length < 2)
        return false;
    const groupsWithMultipleItems = grouped.filter(([, options]) => options.length >= 2).length;
    // "Meaningful" grouping:
    // - at least two groups with multiple items, OR
    // - at least three distinct groups.
    return groupsWithMultipleItems >= 2 || grouped.length >= 3;
}
function groupInsertOptions(insertOptions) {
    const groups = new Map();
    for (const option of insertOptions) {
        const groupName = option.group && option.group.trim().length > 0
            ? option.group.trim()
            : "Other";
        if (!groups.has(groupName)) {
            groups.set(groupName, []);
        }
        groups.get(groupName).push(option);
    }
    return Array.from(groups.entries())
        .map(([groupName, options]) => [
        groupName,
        [...options].sort((a, b) => a.name.localeCompare(b.name)),
    ])
        .sort((a, b) => {
        if (a[0] === "Other")
            return 1;
        if (b[0] === "Other")
            return -1;
        return a[0].localeCompare(b[0]);
    });
}
function createInsertMenuItem(option, onInsert) {
    return {
        id: option.typeId,
        icon: (_jsx("div", { className: "bg-neutral-grey-5 flex h-5 w-5 items-center justify-center rounded transition-colors group-hover:bg-white", children: _jsx("img", { src: getAbsoluteIconUrl(option.icon), width: "14", height: "14", className: "shrink-0 opacity-80" }) })),
        label: option.name,
        command: async () => {
            await onInsert(option);
        },
    };
}
//# sourceMappingURL=insertMenuItems.js.map