import { jsx as _jsx } from "react/jsx-runtime";
import uuid from "react-uuid";
import { Copy, ImagePlus, LayoutTemplate, MessageCirclePlus, Palette, PenLine, Plus, RefreshCcw, Share2, UsersRound, } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { showCommentPopoverAt } from "../reviews/CommentPopover";
import { enterSuggestionsMode, isSuggestionsModeAvailable, } from "../reviews/openCommentsFeedback";
import { loadCustomCommands } from "../services/customCommandsService";
import { getCustomComponentCommands } from "./customCommandConverter";
import { checkItemReferences, createComponentThumbnail, getSharedComponentTarget, loadInsertOptions, } from "../services/editService";
import { cleanId } from "../utils/id-helper";
import { RemoveComponentsConfirmMessage } from "../ui/RemoveComponentsConfirmMessage";
import { SharedFolderSelectorDialog, } from "../ui/SharedFolderSelectorDialog";
import { captureScreenshotFromBridgeSource } from "../ai/dialogs/capturePageScreenshot";
import { ComponentThumbnailDialog, } from "../ui/ComponentThumbnailDialog";
function getDataUrlContentType(dataUrl) {
    return dataUrl.match(/^data:([^;,]+)/)?.[1] ?? "image/png";
}
function getDataUrlApproximateSize(dataUrl) {
    const commaIndex = dataUrl.indexOf(",");
    if (commaIndex < 0)
        return dataUrl.length;
    const payload = dataUrl.slice(commaIndex + 1);
    if (dataUrl.slice(0, commaIndex).includes(";base64")) {
        return Math.floor((payload.length * 3) / 4);
    }
    return decodeURIComponent(payload).length;
}
async function captureLiveComponentThumbnail(pageViewContext, componentId) {
    if (!pageViewContext.requestBridgeComponentSnapshot)
        return null;
    try {
        const snapshot = await pageViewContext.requestBridgeComponentSnapshot({
            componentId,
            maxDimension: 1280,
        });
        if (snapshot.error || !snapshot.dataUrl)
            return null;
        return {
            success: true,
            image: {
                dataUrl: snapshot.dataUrl,
                fileName: `component-thumbnail-${componentId}.png`,
                fileSize: getDataUrlApproximateSize(snapshot.dataUrl),
                contentType: getDataUrlContentType(snapshot.dataUrl),
            },
            imageWidth: Math.max(1, snapshot.width ?? 0),
            imageHeight: Math.max(1, snapshot.height ?? 0),
        };
    }
    catch {
        return null;
    }
}
const isPlaceholder = (x) => x.components !== undefined;
const defaultIconSize = 16;
function normalizeGuid(value) {
    if (!value)
        return "";
    return value.replace(/[{}]/g, "").toLowerCase();
}
function normalizeText(value) {
    return (value || "").trim().toLowerCase();
}
async function isTemplateAllowedInTargetFolder(targetFolder, templateId, componentTypeId, templateName) {
    if (!templateId)
        return true;
    const insertOptions = await loadInsertOptions(targetFolder);
    const normalizedTemplateId = normalizeGuid(templateId);
    const normalizedComponentTypeId = normalizeGuid(componentTypeId);
    const normalizedTemplateName = normalizeText(templateName);
    const matchedByTemplateId = insertOptions.filter((option) => normalizeGuid(option.templateId) === normalizedTemplateId);
    const matchedByTypeId = insertOptions.filter((option) => normalizeGuid(option.typeId) === normalizedTemplateId);
    const matchedByCompatibleTypeIds = insertOptions.filter((option) => (option.compatibleTypeIds || []).some((id) => normalizeGuid(id) === normalizedTemplateId));
    const matchedByComponentTypeId = insertOptions.filter((option) => normalizeGuid(option.typeId) === normalizedComponentTypeId);
    const matchedByName = insertOptions.filter((option) => normalizeText(option.name) === normalizedTemplateName);
    return (matchedByTemplateId.length > 0 ||
        matchedByTypeId.length > 0 ||
        matchedByCompatibleTypeIds.length > 0 ||
        matchedByComponentTypeId.length > 0 ||
        matchedByName.length > 0);
}
// export function getSelectedComponentCommands(editContext: EditContextType) {
//   const selection = editContext.selection;
//   const selectedComponents = selection
//     .map((x) => getComponentById(x, editContext.page!))
//     .filter((x) => x) as Component[];
//   const componentCommands = getComponentCommands(
//     selectedComponents,
//     editContext,
//   );
//   const componentCommandMenuItems = componentCommands.filter(
//     (x) => x.visibilityScopes.indexOf("menu") >= 0,
//   );
//   return componentCommandMenuItems;
// }
export async function getComponentCommands(entities, editContext, providerContext) {
    const components = entities.filter((x) => x && !isPlaceholder(x));
    // Load custom commands from backend (e.g., AI commands configured in Sitecore)
    const customCommands = await getCustomComponentCommands(components, editContext, () => loadCustomCommands("frameMenu"), ["editFrame", "contextMenu"]);
    const externalCommands = (await Promise.all((editContext.configuration.componentCommands?.providers ?? []).map((provider) => provider(components, editContext, providerContext)))).flat();
    const commands = [
        await getCreateCommentCommand(components, editContext, providerContext),
        await getSuggestionsModeCommand(components, editContext),
        await getInsertCommand(components, editContext),
        await getDeleteCommand(components, editContext),
        await getDuplicateCommand(components, editContext),
        await getSyncCommand(entities, editContext),
        ...customCommands,
        await getDesignCommand(components, editContext),
        await getPersonalizeCommand(components, editContext),
        await getConvertToSharedCommand(components, editContext),
        ...externalCommands,
    ];
    return commands.filter((x) => x !== null);
}
export function openRenderingItemComponentCommandProvider(components, editContext, providerContext) {
    if (providerContext?.surface !== "componentTree")
        return [];
    if (editContext.isMobile)
        return [];
    const component = providerContext.targetComponent ??
        (components.length === 1 ? components[0] : undefined);
    if (!component?.typeId)
        return [];
    const pageItem = providerContext.pageItem ??
        editContext.currentItemDescriptor ??
        editContext.page?.item;
    const language = providerContext.language ??
        pageItem?.language ??
        editContext.page?.item.language ??
        "en";
    return [
        {
            id: "open-rendering-item",
            label: "Open rendering item",
            icon: _jsx(LayoutTemplate, { strokeWidth: 1, size: defaultIconSize }),
            disabled: () => false,
            visibilityScopes: ["componentTree"],
            execute: async (context) => {
                await context.editContext.loadItem({
                    id: component.typeId,
                    language,
                    version: 0,
                    database: pageItem?.database,
                    name: component.type,
                }, { openInNewSlot: true });
            },
        },
    ];
}
export function createComponentThumbnailCommandProvider(components, editContext, providerContext) {
    if (providerContext?.surface !== "contextMenu")
        return [];
    if (components.length !== 1)
        return [];
    if (editContext.mode !== "edit" || editContext.readonly)
        return [];
    const component = providerContext.targetComponent ?? components[0];
    if (!component?.typeId || component.editable === false)
        return [];
    if (component.layoutId && !editContext.showLayoutComponents)
        return [];
    return [
        {
            id: "create-component-thumbnail",
            label: "Create thumbnail",
            icon: _jsx(ImagePlus, { strokeWidth: 1, size: defaultIconSize }),
            disabled: (context) => {
                const pageViewContext = context.editContext.getActiveSlotContext()?.primaryPageViewContext;
                const pageItem = providerContext?.pageItem ??
                    pageViewContext?.page?.item?.descriptor ??
                    context.editContext.currentItemDescriptor ??
                    context.editContext.page?.item?.descriptor;
                return !pageItem || !pageViewContext?.bridgeReady;
            },
            visibilityScopes: ["contextMenu"],
            execute: async (context) => {
                const pageViewContext = context.editContext.getActiveSlotContext()?.primaryPageViewContext;
                const pageItem = providerContext?.pageItem ??
                    pageViewContext?.page?.item?.descriptor ??
                    context.editContext.currentItemDescriptor ??
                    context.editContext.page?.item?.descriptor;
                if (!pageItem || !pageViewContext?.bridgeReady) {
                    context.editContext.showErrorToast({
                        summary: "Cannot capture thumbnail",
                        details: "The page preview is not ready.",
                    });
                    return;
                }
                const captureThumbnail = async () => {
                    let capture;
                    try {
                        capture = await captureLiveComponentThumbnail(pageViewContext, component.id);
                        if (!capture) {
                            capture = await captureScreenshotFromBridgeSource(pageViewContext, {
                                scope: "component",
                                fromComponentId: component.id,
                                padding: 8,
                            }, [component.id], "component");
                        }
                    }
                    catch (error) {
                        throw new Error(error instanceof Error
                            ? error.message
                            : "Could not capture the selected component thumbnail.");
                    }
                    if (!capture?.success || !capture.image?.dataUrl) {
                        throw new Error(capture?.error ??
                            "Could not capture the selected component thumbnail.");
                    }
                    return {
                        imageDataUrl: capture.image.dataUrl,
                        imageWidth: capture.imageWidth,
                        imageHeight: capture.imageHeight,
                    };
                };
                const capture = await context.openDialog(ComponentThumbnailDialog, {
                    componentName: component.name,
                    captureThumbnail,
                });
                if (!capture)
                    return;
                const result = await createComponentThumbnail({
                    pageItem,
                    componentId: component.id,
                    imageDataUrl: capture.imageDataUrl,
                    imageWidth: capture.imageWidth ?? 0,
                    imageHeight: capture.imageHeight ?? 0,
                });
                if (result.type !== "success" || !result.data?.success) {
                    context.editContext.showErrorToast({
                        summary: result.summary ?? "Thumbnail not saved",
                        details: result.details ?? "The component thumbnail could not be saved.",
                    });
                    return;
                }
                pageViewContext.invalidateInsertOptionsCache();
                context.editContext.requestRefresh("immediate");
                context.editContext.showInfoToast({
                    summary: "Thumbnail saved",
                    details: `${component.name} now has a palette thumbnail.`,
                });
            },
        },
    ];
}
function getInsertCommand(components, editContext) {
    if (components.length !== 1 || isPlaceholder(components[0]))
        return null;
    const item = components[0];
    if (!item)
        return null;
    if (!item.placeholders || item.placeholders.length === 0)
        return null;
    if (editContext.mode === "suggestions")
        return null;
    // Don't show insert for layout components when showLayoutComponents is disabled
    if (item.layoutId && !editContext.showLayoutComponents)
        return null;
    return {
        id: "insert",
        icon: _jsx(Plus, { strokeWidth: 1, size: defaultIconSize }),
        label: "Insert component",
        disabled: (context) => !context.editContext.page?.item.canWriteItem,
        visibilityScopes: ["editFrame"],
        execute: async () => {
            editContext.setSelectedForInsertion(item.id);
        },
    };
}
function getDuplicateCommand(components, editContext) {
    if (components.length !== 1)
        return null;
    if (editContext.mode === "suggestions")
        return null;
    const component = components[0];
    if (!component)
        return null;
    // Don't show duplicate for layout components when showLayoutComponents is disabled
    if (component.layoutId && !editContext.showLayoutComponents)
        return null;
    return {
        id: "duplicate",
        icon: _jsx(Copy, { strokeWidth: 1, size: defaultIconSize }),
        label: "Duplicate component",
        visibilityScopes: ["contextMenu", "menu"],
        disabled: (c) => !(c.editContext.page?.item.canWriteItem || false),
        execute: async (context) => {
            // if (!components[0].parentPlaceholder?.parentComponent.datasourceItem)
            //   return;
            editContext.operations.duplicateComponents({
                componentIds: components.map((x) => x.id),
            });
        },
    };
}
async function getDesignCommand(components, editContext) {
    if (components.length !== 1 || isPlaceholder(components[0]))
        return null;
    const component = components[0];
    if (!component || !component.datasourceItem)
        return null;
    // Don't show design for layout components when showLayoutComponents is disabled
    if (component.layoutId && !editContext.showLayoutComponents)
        return null;
    const item = await editContext.itemsRepository.getItem(component.datasourceItem);
    if (!item)
        return null;
    if (!Object.values(item.fields).find((x) => x.section === "Design"))
        return null;
    return {
        id: "design",
        icon: _jsx(Palette, { strokeWidth: 1, size: defaultIconSize }),
        label: "Open design options",
        disabled: () => false,
        execute: async (context) => {
            const activeSlotId = editContext.getActiveSlotId();
            editContext.setEditorFormHiddenForSlot(activeSlotId, false);
            // Switch to the design tab
            editContext.setActiveEditorTab("design");
        },
        visibilityScopes: ["editFrame", "contextMenu"],
    };
}
async function getPersonalizeCommand(components, editContext) {
    if (components.length !== 1 || isPlaceholder(components[0]))
        return null;
    const component = components[0];
    if (!component)
        return null;
    // Don't show for layout components when showLayoutComponents is disabled
    if (component.layoutId && !editContext.showLayoutComponents)
        return null;
    // Personalize tab is not shown for the root component
    const rootComponentId = editContext.page?.rootComponent?.id;
    if (rootComponentId && component.id === rootComponentId)
        return null;
    // Personalize tab requires the active page view to support personalization
    const slotContext = editContext.getActiveSlotContext();
    const supportsPersonalization = !!slotContext?.primaryPageViewContext?.componentsProviderSettings
        ?.supportsPersonalization;
    if (!supportsPersonalization)
        return null;
    return {
        id: "personalize",
        icon: _jsx(UsersRound, { strokeWidth: 1, size: defaultIconSize }),
        label: "Personalize",
        disabled: () => false,
        execute: async () => {
            const activeSlotId = editContext.getActiveSlotId();
            editContext.setEditorFormHiddenForSlot(activeSlotId, false);
            editContext.setActiveEditorTab("personalize");
        },
        visibilityScopes: ["editFrame", "contextMenu"],
    };
}
async function getConvertToSharedCommand(components, editContext) {
    // Only show for single component
    if (components.length !== 1 || isPlaceholder(components[0]))
        return null;
    const component = components[0];
    if (!component || !component.datasourceItem)
        return null;
    // Don't show for layout components when showLayoutComponents is disabled
    if (component.layoutId && !editContext.showLayoutComponents)
        return null;
    // Don't show if already shared
    if (component.isShared)
        return null;
    // Don't show in suggestions mode
    if (editContext.mode === "suggestions")
        return null;
    return {
        id: "convertToShared",
        icon: _jsx(Share2, { strokeWidth: 1, size: defaultIconSize }),
        label: "Convert to shared",
        disabled: (context) => !context.editContext.page?.item.canWriteItem,
        visibilityScopes: ["contextMenu", "menu"],
        execute: async (context) => {
            if (!editContext.page?.item.descriptor)
                return;
            // Get the shared component target info from the backend
            const targetInfo = await getSharedComponentTarget(editContext.page.item.descriptor, component.id);
            if (!targetInfo.supported) {
                editContext.showErrorToast({
                    summary: "Not supported",
                    details: "Converting to shared component is not supported for this page.",
                });
                return;
            }
            let targetFolderId = targetInfo.rootFolderId;
            let targetFolderPath = targetInfo.rootFolderPath;
            const askProceedDespiteInsertOptions = async () => await new Promise((resolve) => {
                editContext.confirm({
                    showCancel: true,
                    message: `The selected folder does not list template "${component.datasourceItem?.templateName || component.datasourceItem?.templateId}" in its insert options. Move "${component.name}" anyway?`,
                    header: "Template not allowed in target folder",
                    accept: () => resolve(true),
                    reject: () => resolve(false),
                });
            });
            if (targetInfo.allowUserSelection && targetInfo.rootFolderId) {
                while (true) {
                    const selectedFolder = await context.openDialog(SharedFolderSelectorDialog, {
                        editContext,
                        language: component.datasourceItem?.language ??
                            editContext.page.item.language,
                        initialFolderId: targetInfo.rootFolderId,
                        header: "Select Shared Component Folder",
                        label: "Move here",
                    });
                    if (!selectedFolder) {
                        return;
                    }
                    targetFolderId = selectedFolder.id;
                    const selectedFolderItem = await editContext.itemsRepository.getItem(selectedFolder);
                    targetFolderPath = selectedFolderItem?.path ?? targetFolderPath;
                    const selectedFolderDescriptor = {
                        id: targetFolderId,
                        language: component.datasourceItem?.language ??
                            editContext.page.item.language,
                        version: 0,
                        ...(editContext.page.item.descriptor.database
                            ? { database: editContext.page.item.descriptor.database }
                            : {}),
                    };
                    let isAllowedByInsertOptions = true;
                    try {
                        isAllowedByInsertOptions = await isTemplateAllowedInTargetFolder(selectedFolderDescriptor, component.datasourceItem?.templateId, component.typeId, component.datasourceItem?.templateName);
                    }
                    catch (error) {
                        console.warn("Failed to verify target folder insert options:", error);
                    }
                    if (isAllowedByInsertOptions)
                        break;
                    const continueAfterWarning = await askProceedDespiteInsertOptions();
                    if (continueAfterWarning)
                        break;
                    // User canceled the warning; return to folder selection dialog.
                }
            }
            if (!targetFolderId) {
                editContext.showErrorToast({
                    summary: "No target folder",
                    details: "Could not determine shared component target folder.",
                });
                return;
            }
            // Root-folder mode: validate once and allow user to proceed or cancel.
            if (!targetInfo.allowUserSelection) {
                const targetFolderDescriptor = {
                    id: targetFolderId,
                    language: component.datasourceItem?.language ??
                        editContext.page.item.language,
                    version: 0,
                    ...(editContext.page.item.descriptor.database
                        ? { database: editContext.page.item.descriptor.database }
                        : {}),
                };
                let isAllowedByInsertOptions = true;
                try {
                    isAllowedByInsertOptions = await isTemplateAllowedInTargetFolder(targetFolderDescriptor, component.datasourceItem?.templateId, component.typeId, component.datasourceItem?.templateName);
                }
                catch (error) {
                    console.warn("Failed to verify target folder insert options:", error);
                }
                if (!isAllowedByInsertOptions) {
                    const continueAfterWarning = await askProceedDespiteInsertOptions();
                    if (!continueAfterWarning)
                        return;
                }
            }
            // Confirm with user
            editContext.confirm({
                showCancel: true,
                message: `Move "${component.name}" to shared location at "${targetFolderPath}"? This will make the component available for use on other pages.`,
                header: "Convert to Shared Component",
                accept: () => {
                    const op = {
                        type: "convert-to-shared",
                        date: new Date().toISOString(),
                        id: uuid(),
                        componentId: component.id,
                        targetFolderId: targetFolderId,
                        mainItem: editContext.page.item.descriptor,
                        title: `Convert to shared: ${component.name}`,
                    };
                    editContext.operations.executeEditOperation(op);
                },
            });
        },
    };
}
function isLocked(c, editContext) {
    if (editContext.activeSessions.find((x) => x.fieldLock?.item.id === c.id &&
        x.fieldLock.item.language == c.datasourceItem?.language &&
        x.fieldLock.item.version === c.datasourceItem?.version &&
        x.sessionId !== editContext.sessionId) !== undefined) {
        return true;
    }
    else
        return (c.placeholders?.find((x) => x.components.find((child) => isLocked(child, editContext)) !==
            undefined) !== undefined);
}
function getDeleteCommand(components, editContext) {
    if (editContext.mode === "suggestions" || editContext.mode === "preview")
        return null;
    const applicableComponents = components.filter((c) => ((!isPlaceholder(c) && !c.layoutId) ||
        c.layoutId === editContext.page?.item.id) &&
        !isLocked(c, editContext) &&
        editContext.page?.item.canWriteItem &&
        // When showLayoutComponents is disabled, layout components should not be editable
        (editContext.showLayoutComponents || !c.layoutId));
    if (applicableComponents.length === 0)
        return null;
    return {
        id: "delete",
        label: applicableComponents.length > 1
            ? "Remove components"
            : "Remove component",
        icon: _jsx(DeleteIcon, { size: "md" }),
        execute: async (context) => deleteComponents(applicableComponents, context.editContext),
        disabled: () => applicableComponents.length === 0 ||
            applicableComponents.length !== components.length,
        visibilityScopes: ["editFrame", "menu", "contextMenu"],
    };
}
function canSynchronize(placeholderData) {
    if (placeholderData.canSynchronize)
        return true;
    placeholderData.components.forEach((c) => {
        if (c.placeholders?.find((x) => canSynchronize(x)))
            return true;
    });
    return false;
}
function getSyncCommand(components, editContext) {
    const placeholders = [];
    for (const component of components) {
        if (isPlaceholder(component) && canSynchronize(component)) {
            placeholders.push({
                item: component.parentComponent
                    ? getItemDescriptor(component.parentComponent, editContext)
                    : undefined,
            });
        }
        else {
            if (component.placeholders?.find((x) => canSynchronize(x))) {
                placeholders.push({
                    item: getItemDescriptor(component, editContext),
                });
            }
        }
    }
    const canSync = placeholders.length > 0 ||
        (components.length === 0 &&
            editContext.page?.rootComponent.placeholders.find((x) => canSynchronize(x)));
    return {
        id: "synchronize",
        label: "Synchronize",
        icon: _jsx(RefreshCcw, { strokeWidth: 1, size: 14 }),
        disabled: () => !canSync,
        visibilityScopes: ["menu", "editFrame", "contextMenu"],
        execute: async () => {
            const op = {
                mainItem: editContext.page.item.descriptor,
                type: "synchronize-components",
                date: new Date().toISOString(),
                delete: false,
                id: uuid(),
                placeholders: placeholders,
                title: "Synchronize components",
            };
            editContext.operations.executeEditOperation(op);
        },
    };
}
async function deleteComponents(components, editContext) {
    if (!components.length)
        return;
    // Shared datasource items used by the selection, deduped (several selected
    // components may render the same shared item).
    const sharedDatasources = components
        .filter((c) => c.isShared && c.datasourceItem)
        .map((c) => c.datasourceItem)
        .filter((item, index, all) => all.findIndex((x) => cleanId(x.id) === cleanId(item.id)) === index);
    let sharedReferences = [];
    if (sharedDatasources.length > 0) {
        try {
            const result = await checkItemReferences(sharedDatasources);
            if (result.type === "success" && result.data) {
                // The current page's own layout references the datasource; only other
                // referrers matter for the warning.
                const pageId = cleanId(editContext.page?.item.id);
                sharedReferences = result.data.map((ref) => {
                    const otherReferrers = ref.referencingItems.filter((r) => cleanId(r.id) !== pageId);
                    const unfetchedCount = Math.max(0, ref.totalReferenceCount - ref.referencingItems.length);
                    return {
                        ...ref,
                        referencingItems: otherReferrers,
                        totalReferenceCount: otherReferrers.length + unfetchedCount,
                    };
                });
            }
        }
        catch (error) {
            console.error("Failed to check datasource references:", error);
            // Show the dialog without referrer info rather than blocking removal.
        }
    }
    const deleteSharedCheckboxId = `remove-delete-shared-${Date.now()}`;
    editContext.confirm({
        showCancel: true,
        message: (_jsx(RemoveComponentsConfirmMessage, { componentNames: components.map((x) => x.name), sharedDatasourceNames: sharedDatasources.map((x) => x.displayName || x.name), sharedReferences: sharedReferences, deleteSharedCheckboxId: deleteSharedCheckboxId })),
        header: components.length > 1 ? "Remove components" : "Remove component",
        acceptLabel: "Yes, remove",
        accept: () => {
            if (!editContext.page?.item.descriptor)
                return;
            const deleteSharedDatasources = sharedDatasources.length > 0 &&
                (document.getElementById(deleteSharedCheckboxId)?.checked ??
                    false);
            console.log("Remove components", components);
            const op = {
                type: "remove-component",
                date: new Date().toISOString(),
                id: uuid(),
                componentIds: components.map((x) => x.id),
                mainItem: editContext.page.item.descriptor,
                title: "Remove components: " + components.map((x) => x.name).join(", "),
                deleteSharedDatasources,
            };
            editContext.operations.executeEditOperation(op);
        },
    });
}
function getCreateCommentCommand(components, editContext, providerContext) {
    if (components.length !== 1 || isPlaceholder(components[0]))
        return null;
    return {
        id: "addComment",
        label: "Add comment",
        icon: _jsx(MessageCirclePlus, { size: 14, strokeWidth: 1 }),
        disabled: () => false,
        visibilityScopes: ["contextMenu"],
        execute: async (context) => {
            const ev = context.event;
            if (ev?.preventDefault)
                ev.preventDefault();
            if (ev?.stopPropagation)
                ev.stopPropagation();
            if (ev?.nativeEvent?.stopImmediatePropagation)
                ev.nativeEvent.stopImmediatePropagation();
            const x = ev?.clientX ?? ev?.pageX ?? window.innerWidth / 2;
            const y = ev?.clientY ?? ev?.pageY ?? window.innerHeight / 2;
            setTimeout(() => {
                requestAnimationFrame(() => {
                    // Prefer the field that was right-clicked (bridge context menus resolve
                    // it from the pointer position); focusedField is only a fallback since
                    // right-clicking does not focus a field.
                    const snapshotField = providerContext?.targetField ?? context.editContext.focusedField;
                    const snapshotRange = context.editContext.selectedRange;
                    showCommentPopoverAt({ x, y }, context.editContext, {
                        field: snapshotField,
                        range: snapshotRange,
                    });
                });
            }, 0);
        },
    };
}
function getSuggestionsModeCommand(components, editContext) {
    if (components.length !== 1 || isPlaceholder(components[0]))
        return null;
    // Sits beside "Add Comment" as the other way to give feedback. Only offered
    // where suggestions mode works (WYSIWYG canvas) and when it is not already on.
    if (!isSuggestionsModeAvailable(editContext))
        return null;
    if (editContext.mode === "suggestions")
        return null;
    return {
        id: "activateSuggestionsMode",
        label: "Activate suggestions mode",
        icon: _jsx(PenLine, { size: 14, strokeWidth: 1 }),
        disabled: () => false,
        visibilityScopes: ["contextMenu"],
        execute: async (context) => {
            const ev = context.event;
            if (ev?.preventDefault)
                ev.preventDefault();
            if (ev?.stopPropagation)
                ev.stopPropagation();
            if (ev?.nativeEvent?.stopImmediatePropagation)
                ev.nativeEvent.stopImmediatePropagation();
            enterSuggestionsMode(context.editContext, { reason: "context-menu" });
        },
    };
}
function getItemDescriptor(component, editContext) {
    return {
        id: component.id,
        language: component.datasourceItem?.language || editContext.page.item.language,
        version: component.datasourceItem?.version || editContext.page.item.version,
    };
}
//# sourceMappingURL=componentCommands.js.map