import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, ContextMenuLabel, } from "../components/ui/context-menu";
import { cn } from "../lib/utils";
// export function getFieldContextMenu(
//   field: Field,
//   editContext: EditContextType,
//   customButtons: EditButton[] = []
// ) {
//   return (e: any) => {
//     e.preventDefault();
//     e.stopPropagation();
//     const menuItems: MenuItem[] = getComponentMenuItems(
//       editContext,
//       getComponentById(field._editor!.descriptor.item.id, editContext.page!)!
//     );
//     if (customButtons.length) {
//       if (menuItems.length)
//         menuItems.push({
//           separator: true,
//         });
//       customButtons.forEach((button) => {
//         menuItems.push({
//           label: button.label,
//           command: (ev) => button.onClick(ev.originalEvent as any),
//           icon: button.icon,
//         });
//       });
//     }
//     if (field._editor?.buttons?.length) {
//       if (menuItems.length)
//         menuItems.push({
//           separator: true,
//         });
//       field._editor?.buttons.forEach((button: FieldButton) => {
//         menuItems.push({
//           label: button.label,
//           command: () => {
//             editContext!.triggerFieldAction(field._editor!.descriptor, button);
//           },
//           icon: button.icon ? "pi " + button.icon : undefined,
//         });
//       });
//     }
//     if (!e.ctrlKey && !e.shiftKey && !e.altKey && menuItems.length) {
//       editContext.select([field._editor!.descriptor.item.id]);
//       editContext!.setFocusedField(field._editor!.descriptor, false);
//       editContext!.showContextMenu(e, menuItems);
//     }
//   };
// }
export async function buildComponentContextMenuItems(components, editContext, field, fieldButtons, onParameterizedAction) {
    const componentCommandMenuItems = await getComponentMenuItems(editContext, components);
    const menuItems = [...componentCommandMenuItems];
    // Only show field actions when a single component is selected
    if (!editContext.readonly &&
        field &&
        fieldButtons?.length &&
        components.length === 1) {
        if (menuItems.length)
            menuItems.push({
                id: "separator",
                separator: true,
            });
        fieldButtons.forEach((button) => {
            menuItems.push({
                id: button.id,
                label: button.label,
                command: async (event) => {
                    if (button.parameters && button.parameters.length > 0) {
                        if (onParameterizedAction) {
                            onParameterizedAction(field, button, fieldButtons, event);
                        }
                        else {
                            editContext.triggerFieldAction(field, button);
                        }
                    }
                    else {
                        editContext.triggerFieldAction(field, button);
                    }
                },
                icon: button.icon,
            });
        });
    }
    // Call field type context menu factory when a single component is selected and field is available
    if (!editContext.readonly && field) {
        const fieldFromRepository = await editContext.itemsRepository.getField(field);
        if (fieldFromRepository) {
            const fieldTypeConfig = editContext.configuration.fieldTypes[fieldFromRepository.type];
            if (fieldTypeConfig?.contextMenuFactory) {
                try {
                    const factoryMenuItems = await fieldTypeConfig.contextMenuFactory(fieldFromRepository, editContext);
                    if (factoryMenuItems && factoryMenuItems.length > 0) {
                        if (menuItems.length > 0) {
                            menuItems.push({
                                id: "factory-separator",
                                separator: true,
                            });
                        }
                        menuItems.push(...factoryMenuItems);
                    }
                }
                catch (error) {
                    console.error("Error calling field type context menu factory:", error);
                }
            }
        }
    }
    return menuItems;
}
export async function showComponentContextMenu(components, editContext, field, fieldButtons, onParameterizedAction) {
    const menuItems = await buildComponentContextMenuItems(components, editContext, field, fieldButtons, onParameterizedAction);
    return (e) => {
        if (!e.shiftKey && !e.altKey) {
            if (menuItems.length) {
                editContext.showContextMenu(e, menuItems);
            }
            return true;
        }
        return false;
    };
}
export const EditContextMenu = forwardRef((props, ref) => {
    const canvasRef = useRef(null);
    const [menuItems, setMenuItems] = useState([]);
    const closeMenu = () => {
        try {
            // Close Radix ContextMenu by sending Escape to the document
            document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
        }
        catch { }
    };
    // Helper function to render icon
    const renderIcon = (icon) => {
        if (!icon)
            return null;
        if (typeof icon === "string") {
            return _jsx("img", { src: icon, alt: "", className: "h-4 w-4" });
        }
        return icon;
    };
    if (!props)
        return;
    useImperativeHandle(ref, () => ({
        show: (e, items) => {
            if (!e.ctrlKey && !e.shiftKey && !e.altKey) {
                setMenuItems(items);
                e.preventDefault();
                triggerRightClick(canvasRef.current, {
                    position: { x: e.clientX, y: e.clientY },
                });
            }
        },
        update: (items) => {
            setMenuItems(items);
        },
        close: (event) => {
            closeMenu();
        },
    }));
    const triggerRightClick = (element, { position }) => {
        const event = new MouseEvent("contextmenu", {
            bubbles: true,
            cancelable: true,
            clientX: position.x,
            clientY: position.y,
        });
        element.dispatchEvent(event);
    };
    return (_jsxs(ContextMenu, { children: [_jsx(ContextMenuTrigger, { children: _jsx("span", { id: "contextmenu_canvas", ref: canvasRef }) }), _jsx(ContextMenuContent, { children: menuItems.map((item, index) => {
                    if (item.separator) {
                        return _jsx(ContextMenuSeparator, {}, index);
                    }
                    // Render custom template item as-is (used for Insert overlay template)
                    if (item.template) {
                        return (_jsx("div", { className: cn("hover:bg-gray-5 px-2 py-1.5", item.className), 
                            // Do not stop propagation during React capture phase:
                            // descendants (e.g. PerfectTree expand toggle uses onMouseDown) must still receive events.
                            // Bubble-phase stopPropagation is enough to prevent Radix from closing the menu.
                            onPointerDown: (e) => e.stopPropagation(), onMouseDown: (e) => e.stopPropagation(), onClick: (e) => {
                                e.stopPropagation();
                                e.preventDefault();
                            }, children: item.template }, index));
                    }
                    // Render disabled items without command as a label (useful for section headers)
                    if (item.disabled && !item.command && !item.items?.length) {
                        return (_jsxs(ContextMenuLabel, { className: cn("flex items-center gap-2", item.className), inset: false, children: [renderIcon(item.icon), item.label] }, index));
                    }
                    if (item.items && item.items.length > 0) {
                        return (_jsxs(ContextMenuSub, { children: [_jsxs(ContextMenuSubTrigger, { disabled: item.disabled, className: item.className, children: [renderIcon(item.icon), item.label] }), _jsx(ContextMenuSubContent, { children: item.items.map((subItem, subIndex) => {
                                        if (subItem.separator) {
                                            return _jsx(ContextMenuSeparator, {}, subIndex);
                                        }
                                        if (subItem.template) {
                                            return (_jsx("div", { className: cn("px-2 py-1.5", subItem.className), onClick: (e) => {
                                                    // prevent closing
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                }, onPointerDown: (e) => e.stopPropagation(), onMouseDown: (e) => e.stopPropagation(), children: subItem.template }, subIndex));
                                        }
                                        if (subItem.disabled &&
                                            !subItem.command &&
                                            !subItem.items?.length) {
                                            return (_jsxs(ContextMenuLabel, { className: cn("flex items-center gap-2", subItem.className), inset: false, children: [renderIcon(subItem.icon), subItem.label] }, subIndex));
                                        }
                                        if (subItem.items && subItem.items.length > 0) {
                                            // Nested submenu support if needed
                                            return (_jsxs(ContextMenuSub, { children: [_jsxs(ContextMenuSubTrigger, { disabled: subItem.disabled, className: subItem.className, children: [renderIcon(subItem.icon), subItem.label] }), _jsx(ContextMenuSubContent, { children: (subItem.items || []).map((nested, nestedIndex) => (_jsxs(ContextMenuItem, { onClick: (e) => {
                                                                closeMenu();
                                                                if (nested.command)
                                                                    nested.command(e);
                                                            }, disabled: nested.disabled, className: cn("cursor-pointer", nested.className), children: [renderIcon(nested.icon), nested.label] }, nestedIndex))) })] }, subIndex));
                                        }
                                        return (_jsxs(ContextMenuItem, { onClick: (e) => {
                                                closeMenu();
                                                if (subItem.command) {
                                                    subItem.command(e);
                                                }
                                            }, disabled: subItem.disabled, className: cn("cursor-pointer", subItem.className), children: [renderIcon(subItem.icon), subItem.label] }, subIndex));
                                    }) })] }, index));
                    }
                    return (_jsxs(ContextMenuItem, { onClick: (e) => {
                            closeMenu();
                            if (item.command) {
                                item.command(e);
                            }
                            // default Radix behavior closes menu on item click
                        }, disabled: item.disabled, className: cn("cursor-pointer", item.className), children: [renderIcon(item.icon), item.label] }, index));
                }) })] }));
    // return <ContextMenu model={menuItems} ref={cm} />;
});
async function getComponentMenuItems(editContext, components) {
    const componentCommands = await editContext.getComponentCommands(components);
    const componentCommandMenuItems = componentCommands.map((x) => {
        return {
            id: x.id,
            label: x.label,
            icon: x.icon,
            command: (ev) => editContext.executeCommand({
                command: x,
                event: ev,
            }),
            disabled: editContext.isCommandDisabled({ command: x }),
        };
    });
    return componentCommandMenuItems;
}
//# sourceMappingURL=ContextMenu.js.map