import { jsx as _jsx } from "react/jsx-runtime";
import { coreNotificationRoutes } from "./notificationRoutes";
import { RichTextEditor } from "../editor/field-types/RichTextEditor";
import { createRichTextContextMenu } from "../editor/field-types/richtext/contextMenuFactory";
import { createTextContextMenu } from "../editor/field-types/textContextMenuFactory";
import { LinkFieldEditor } from "../editor/field-types/LinkFieldEditor";
import { PictureFieldEditor } from "../editor/field-types/PictureFieldEditor";
import { InternalLinkFieldEditor } from "../editor/field-types/InternalLinkFieldEditor";
import TreeListEditor from "../editor/field-types/TreeListEditor";
import { SingleLineText } from "../editor/field-types/SingleLineText";
import { MultiLineText } from "../editor/field-types/MultiLineText";
import { DropLinkEditor } from "../editor/field-types/DropLinkEditor";
import { DropListEditor } from "../editor/field-types/DropListEditor";
import { RawEditor } from "../editor/field-types/RawEditor";
import { CheckboxEditor } from "../editor/field-types/CheckboxEditor";
import { DateFieldEditor } from "../editor/field-types/DateFieldEditor";
import { DateTimeFieldEditor } from "../editor/field-types/DateTimeFieldEditor";
import { NameValueListEditor } from "../editor/field-types/NameValueListEditor";
import { ItemLocked } from "../editor/editor-warnings/ItemLocked";
import { NoWriteAccess } from "../editor/editor-warnings/NoWriteAccess";
import { ValidationErrors } from "../editor/editor-warnings/ValidationErrors";
import { ComponentTree } from "../editor/sidebar/ComponentTree";
import { EditHistory } from "../editor/sidebar/EditHistory";
import { Favorites } from "../editor/sidebar/Favorites";
import { Sessions } from "../editor/sidebar/Sessions";
import { Workbox } from "../editor/sidebar/Workbox";
import { DictionaryEditor } from "../editor/sidebar/DictionaryEditor";
import { ParheliaAgentIcon } from "../editor/ui/Icons";
import { waitForSelectorAnimations } from "../editor/ui/animationSettle";
import { ModernSplashScreen } from "../splash-screen/ModernSplashScreen";
import { NewPageDialog } from "../splash-screen/DialogWrappers";
import { dispatchManualFieldActionVisibility, getFieldIdsForManualTarget, } from "../editor/manualActionEvents";
import { Titlebar } from "../editor/Titlebar";
import { NoWriteLanguageAccess } from "../editor/editor-warnings/NoLanguageWriteAccess";
import { NoWorkflowWriteAccess } from "../editor/editor-warnings/NoWorkflowWriteAccess";
import { FinalWorkflowStateReadOnly } from "../editor/editor-warnings/FinalWorkflowStateReadOnly";
import { AgentsWorkspaceView } from "../agents-view/AgentsWorkspaceView";
import { AgentsTitlebar } from "../agents-view/AgentsTitlebar";
import { TaskBoardWorkspace } from "../task-board/TaskBoardWorkspace";
import { TaskBoardTitlebar } from "../task-board/components/TaskBoardTitlebar";
import { TaskBoardProjectListSidebar } from "../task-board/components/TaskBoardProjectListSidebar";
import { TaskBoardMyTasksSidebar } from "../task-board/components/TaskBoardMyTasksSidebar";
import { createEditToolbar } from "../editor/menubar/ToolbarFactory";
import { LicenseFeatures, hasFeature } from "../licensing";
import { Validation } from "../editor/sidebar/Validation";
import { deleteItemCommand, insertItemCommand, moveItemsCommand, copyItemsCommand, cloneItemsCommand, renameItemCommand, duplicateItemCommand, uncloneItemCommand, exportItemsCommand, importItemsCommand, addStandardValuesCommand, publishItemCommand, publishRestrictionsCommand, reviewItemsCommand, } from "../editor/commands/itemCommands";
import { createTemplateItemCommand } from "../editor/commands/templateBuilderCommands";
import { loadInsertOptions } from "../editor/services/editService";
import { getDefaultTourSteps } from "../tour/default-tour";
import { EditView } from "../editor/views/EditView";
import { InsertMenuTemplate } from "../editor/context-menu/InsertMenu";
import { SettingsView } from "../editor/settings/SettingsView";
import { SettingsTitlebar } from "../editor/settings/SettingsTitlebar";
import { IndexOverview } from "../editor/settings/IndexOverview";
import { QuotaInfo } from "../editor/settings/QuotaInfo";
import { About } from "../editor/settings/About";
import { AgentsPanel, JavaScriptToolsPanel, ProjectTemplatesPanel, PersistentLogsPanel, ProvidersPanel, McpToolsPanel, ModelsPanel, SearchConfigPanel, StatusPanel, ClusterInstancesPanel, FieldTypeSerializersPanel, AgentToolsPanel, UserPreferencesPanel, NotificationSubscriptionsPanel, SystemSettingsPanel, } from "../editor/settings/panels";
import { coreStatusChecks } from "../editor/settings/status/index";
import { MainContentTree } from "../editor/sidebar/MainContentTree";
import { CONTENT_TREE_SIDEBAR_ID } from "../editor/sidebar/contentTreeConstants";
import { AttachmentEditor } from "../editor/field-types/AttachmentEditor";
import { replaceMediaItemWithFile } from "../editor/media-selector/mediaUpload";
import { Reviews } from "../editor/reviews/Reviews";
import { rejectReviewCommand } from "../editor/reviews/reviewCommands";
import { approveReviewCommand } from "../editor/reviews/reviewCommands";
import { agentCommandHandler } from "../editor/commands/handlers/agentHandler";
import { openDialogCommandHandler, openItemCommandHandler, openStatusPanelCommandHandler, openUrlCommandHandler, startTourCommandHandler, switchWorkspaceCommandHandler, } from "../editor/commands/handlers/uiActionHandlers";
import { getPreviewTourSteps } from "../tour/preview-tour";
import { ImageFieldEditor } from "../editor/field-types/ImageFieldEditor";
import { ReviewCommands } from "../editor/menubar/toolbar-sections/ReviewCommands";
import { Activity, Bell, BookA, History, FolderTreeIcon, InboxIcon, Layers, Settings, SlidersHorizontal, Star, Users, WandSparkles, ClipboardCheck, ShieldCheck, Info as InfoIcon, BarChart3, Search, Home, File, ExternalLink, Image as ImageIcon, Video, X, Crop, Download, Paperclip, Server, Sparkles, Bug, FileCode2, Wrench, ListTodo, TrendingUpDown, GitBranch, SquarePen, DatabaseZap, Network, } from "lucide-react";
import { Completions } from "../editor/sidebar/Completions";
import { createComponentThumbnailCommandProvider, openRenderingItemComponentCommandProvider, } from "../editor/commands/componentCommands";
import { openPlaceholderSettingsCommandProvider } from "../editor/commands/placeholderCommands";
import { GenericToolbar } from "../editor/menubar/GenericToolbar";
import { EditControls, UtilityControls, } from "../editor/menubar/toolbar-sections";
import { Agents } from "../editor/ai/Agents";
import { ComponentTypeSelectorInline, QuestionnaireInline, } from "../editor/ai/dialogs";
import { openCommentsFeedback } from "../editor/reviews/openCommentsFeedback";
import { cleanId } from "../editor/utils/id-helper";
import { getRedoCommand, getUndoCommand } from "../editor/commands/undo";
import { favoriteHistoryBackCommand, favoriteHistoryForwardCommand, historyBackCommand, historyForwardCommand, moveComponentDownCommand, moveComponentUpCommand, toggleInsertModeCommand, } from "../editor/commands/keyboardCommands";
export const contentItemId = "0DE95AE4-41AB-4D01-9EB0-67441B7C2450";
export const templatesRootItemId = "3c1715fe-6a13-4fcf-845f-de308ba9741d";
export const rootItemId = "11111111-1111-1111-1111-111111111111";
const newTemplateInsertOptionTypeId = "78cf88ba-6957-4366-8368-12f3ced0184f";
const commandTemplatesByTypeId = {
    // The generic masters processor emits the insert option master's item ID as
    // typeId, so "New Template" must be matched by that insert option typeId.
    [newTemplateInsertOptionTypeId]: {
        commandId: "createTemplateItem",
        optionName: "New Template",
        parentPathPrefix: "/sitecore/templates",
    },
};
const openTargetActionButton = {
    label: "Open target item",
    icon: (_jsx(ExternalLink, { strokeWidth: 1, size: 16 })),
    isDisabled: ({ field }) => {
        const fieldValue = field.value;
        return !fieldValue?.targetItemId;
    },
    clientAction: ({ field, editContext, event }) => {
        const fieldValue = field.value;
        if (!fieldValue?.targetItemId)
            return;
        const openInNewSlot = !!event?.altKey;
        editContext.loadItem({
            id: fieldValue.targetItemId,
            language: field.descriptor.item.language,
            version: 0,
        }, { openInNewSlot });
    },
    isGenerator: false,
    id: "open-target-in-content-editor",
    description: "Opens the target item in the content/page editor",
};
const toggleFieldActionsVisibility = (mode) => ({ runId, elements }) => {
    const fieldIds = getFieldIdsForManualTarget(elements);
    if (fieldIds.length === 0)
        return;
    dispatchManualFieldActionVisibility({
        mode,
        runId,
        fieldIds,
    });
};
const openMoreSidebarsPanel = async ({ selectorDef, resolveElements, }) => {
    // Prefer the actual highlight target: the anchor (availabilitySelector) is
    // often the More-panels trigger itself, which is always present and would
    // otherwise short-circuit opening the panel.
    const targetSelector = selectorDef.selector || selectorDef.availabilitySelector;
    if (hasVisibleManualTarget(resolveElements, targetSelector)) {
        return;
    }
    if (document.querySelector('[data-testid="more-sidebars-button"][aria-expanded="true"]')) {
        return;
    }
    const trigger = document.querySelector('[data-testid="more-sidebars-button"]');
    if (!trigger)
        return;
    trigger.click();
    // Wait for the Radix popover's open animation to finish (mounts on open).
    await waitForSelectorAnimations('[data-testid="more-sidebars-panel"]');
};
const openVersionSelector = async ({ selectorDef, resolveElements, }) => {
    const targetSelector = selectorDef.selector || selectorDef.availabilitySelector;
    if (hasVisibleManualTarget(resolveElements, targetSelector)) {
        return;
    }
    if (document.querySelector('[data-testid="version-selector"][aria-expanded="true"]')) {
        return;
    }
    const trigger = document.querySelector('[data-testid="version-selector"]');
    if (!trigger)
        return;
    trigger.click();
    // Wait for the Radix popover's open animation to finish (mounts on open).
    await waitForSelectorAnimations('[data-testid="version-selector-list"]');
};
const openNotificationCenter = async ({ selectorDef, resolveElements, }) => {
    const targetSelector = selectorDef.selector || selectorDef.availabilitySelector;
    if (hasVisibleManualTarget(resolveElements, targetSelector)) {
        return;
    }
    if (document.querySelector('[data-testid="notification-center-trigger"][aria-expanded="true"]')) {
        return;
    }
    const trigger = document.querySelector('[data-testid="notification-center-trigger"]');
    if (!trigger)
        return;
    trigger.click();
    await waitForSelectorAnimations('[data-testid="notification-center-list"]');
};
function isManualTargetVisible(element) {
    if (element.closest('[aria-hidden="true"]'))
        return false;
    const candidate = element;
    if (typeof candidate.checkVisibility === "function") {
        if (!candidate.checkVisibility({
            checkOpacity: true,
            checkVisibilityCSS: true,
        })) {
            return false;
        }
    }
    const style = window.getComputedStyle(element);
    if (style.display === "none" ||
        style.visibility === "hidden" ||
        style.visibility === "collapse") {
        return false;
    }
    const rect = element.getBoundingClientRect();
    return rect.width > 0 && rect.height > 0;
}
function hasVisibleManualTarget(resolveElements, selector) {
    return !!selector && resolveElements(selector).some(isManualTargetVisible);
}
// Open the Agents panel sidebar so targets that live inside it (chat input,
// send/stop button, settings trigger, mode selector, cost display, etc.) become
// present and can be highlighted. Keeps any other open sidebars (e.g. the Manual
// browser) in place.
const openAgentsPanel = async ({ editContext, selectorDef, resolveElements, }) => {
    const targetSelector = selectorDef.selector;
    const isAgentsPanelOpen = () => {
        const trigger = document.querySelector('[data-testid="agents-panel-button"]');
        const sidebarPanel = resolveElements("@sidebar-panel-agents-panel").find(isManualTargetVisible);
        return trigger?.getAttribute("aria-pressed") === "true" || !!sidebarPanel;
    };
    if (hasVisibleManualTarget(resolveElements, targetSelector)) {
        return;
    }
    // Already open (shared-surface fast path): nothing to animate, don't wait.
    if (isAgentsPanelOpen()) {
        return;
    }
    // The surface key to await depends on which surface actually animates:
    // - Desktop opens the dedicated far-right agents panel ("agents-panel").
    // - Mobile (and any setShowAgentsPanel-less context) opens it as a left
    //   sidebar stack, which MainLayout reports as "sidebar:agents-panel".
    // Awaiting the wrong key means the event-driven settle never fires and we
    // fall back to the 1.5s safety timeout, making Show-me needlessly slow.
    let surfaceKey = "agents-panel";
    if (!editContext.isMobile &&
        typeof editContext.setShowAgentsPanel === "function") {
        editContext.setShowAgentsPanel(true);
    }
    else if (typeof editContext.openSidebar === "function") {
        editContext.openSidebar("agents-panel", { preserveOpenSidebars: true });
        surfaceKey = "sidebar:agents-panel";
    }
    // Wait for the panel's open animation to finish before the caller highlights.
    await editContext.waitForSurfaceSettled?.(surfaceKey);
};
// Open the agent settings popover (which itself lives inside the Agents panel)
// so targets rendered only inside it (model picker, profile selector) become
// present. Opens the Agents panel first when needed.
const openAgentSettings = async (props) => {
    const { selectorDef, resolveElements } = props;
    const targetSelector = selectorDef.selector;
    if (hasVisibleManualTarget(resolveElements, targetSelector)) {
        return;
    }
    // Make sure the Agents panel (and therefore the settings trigger) is visible.
    await openAgentsPanel({
        ...props,
        selectorDef: {
            ...selectorDef,
            selector: "@agent-settings-popover-trigger",
        },
    });
    if (hasVisibleManualTarget(resolveElements, targetSelector)) {
        return;
    }
    const trigger = document.querySelector('[data-testid="agent-settings-popover-trigger"]');
    if (!trigger)
        return;
    trigger.click();
    // Wait for the settings popover's open animation to finish (mounts on open).
    await waitForSelectorAnimations('[data-testid="agent-settings-popover-content"]');
};
const coreManualActions = {
    "show-field-actions": toggleFieldActionsVisibility("show"),
    "hide-field-actions": toggleFieldActionsVisibility("hide"),
    "open-more-sidebars": openMoreSidebarsPanel,
    "open-version-selector": openVersionSelector,
    "open-notification-center": openNotificationCenter,
    "open-agents-panel": openAgentsPanel,
    "open-agent-settings": openAgentSettings,
};
// Picture variant buttons - these will be exported for external packages
const selectImageButton = {
    label: "Select",
    icon: (_jsx(ImageIcon, { strokeWidth: 1, size: 16 })),
    isPimaryAction: true, // Primary action - appears outside menu but show nontheless in the menu
    clientAction: async (props) => {
        const { field, editContext, variantName, variantData } = props;
        if (!variantName)
            return;
        const variant = variantData ||
            field.value?.variants?.find((v) => v.name === variantName);
        const selectedImageId = await editContext?.selectMedia({
            selectedIdPath: variant?.idPath || "",
            mode: "images",
        });
        if (selectedImageId) {
            const raw = (() => {
                try {
                    return field?.rawValue && field?.rawValue[0] === "{"
                        ? JSON.parse(field?.rawValue)
                        : { Variants: [] };
                }
                catch (error) {
                    console.warn("Failed to parse picture field raw value:", error);
                    return { Variants: [] };
                }
            })();
            const selected = raw.Variants?.find((x) => x.Name == variantName);
            if (!selected) {
                if (!raw.Variants)
                    raw.Variants = [];
                raw.Variants.push({
                    Name: variantName,
                    MediaId: selectedImageId,
                });
            }
            else {
                selected.MediaId = selectedImageId;
            }
            await editContext.operations.editField({
                field: field.descriptor,
                rawValue: JSON.stringify(raw),
                refresh: "immediate",
            });
        }
    },
    isGenerator: false,
    id: "select-image",
    description: "Select an image from the media library",
};
const selectVideoButton = {
    label: "Video",
    icon: (_jsx(Video, { strokeWidth: 1, size: 16 })),
    visible: ({ field }) => field.value?.allowVideos ?? false,
    clientAction: async (props) => {
        const { field, editContext, variantName, variantData } = props;
        if (!variantName)
            return;
        const variant = variantData ||
            field.value?.variants?.find((v) => v.name === variantName);
        const selectedVideoId = await editContext?.selectMedia({
            selectedIdPath: variant?.idPath || "",
            mode: "video",
        });
        if (selectedVideoId) {
            const raw = (() => {
                try {
                    return field?.rawValue && field?.rawValue[0] === "{"
                        ? JSON.parse(field?.rawValue)
                        : { Variants: [] };
                }
                catch (error) {
                    console.warn("Failed to parse picture field raw value:", error);
                    return { Variants: [] };
                }
            })();
            const selected = raw.Variants?.find((x) => x.Name == variantName);
            if (!selected) {
                if (!raw.Variants)
                    raw.Variants = [];
                raw.Variants.push({
                    Name: variantName,
                    VideoId: selectedVideoId,
                });
            }
            else {
                selected.VideoId = selectedVideoId;
            }
            await editContext.operations.editField({
                field: field.descriptor,
                rawValue: JSON.stringify(raw),
                refresh: "immediate",
            });
        }
    },
    isGenerator: false,
    id: "select-video",
    description: "Select a video from the media library",
};
const resetVariantButton = {
    label: "Reset",
    icon: (_jsx(X, { strokeWidth: 1, size: 16 })),
    visible: ({ rawVariant }) => !!rawVariant,
    clientAction: async (props) => {
        const { field, editContext, variantName } = props;
        if (!variantName)
            return;
        const raw = (() => {
            try {
                return field?.rawValue && field?.rawValue[0] === "{"
                    ? JSON.parse(field?.rawValue)
                    : { Variants: [] };
            }
            catch (error) {
                console.warn("Failed to parse picture field raw value:", error);
                return { Variants: [] };
            }
        })();
        raw.Variants = raw.Variants.filter((x) => x.Name !== variantName);
        await editContext.operations.editField({
            field: field.descriptor,
            rawValue: JSON.stringify(raw),
            refresh: "immediate",
        });
    },
    isGenerator: false,
    id: "reset-variant",
    description: "Reset the variant to default state",
};
const cropVariantButton = {
    label: "Crop",
    icon: (_jsx(Crop, { strokeWidth: 1, size: 16 })),
    visible: ({ variantData }) => !!variantData?.mediaId,
    componentAction: "open-cropper",
    isGenerator: false,
    id: "crop-variant",
    description: "Crop the image variant",
};
const openPictureMediaItemButton = {
    label: "Open media item",
    icon: (_jsx(ExternalLink, { strokeWidth: 1, size: 16 })),
    visible: ({ variantData }) => !!variantData?.mediaId,
    clientAction: (props) => {
        const { field, editContext, variantData, event } = props;
        const mediaId = variantData?.mediaId;
        if (mediaId) {
            const openInNewSlot = !!event?.altKey;
            editContext.loadItem({
                id: mediaId,
                language: field.descriptor.item.language,
                version: 0,
            }, { openInNewSlot });
        }
    },
    isGenerator: false,
    id: "open-picture-media-item",
    description: "Opens the media item in the content editor",
};
const openImageMediaItemButton = {
    label: "Open media item",
    icon: (_jsx(ExternalLink, { strokeWidth: 1, size: 16 })),
    clientAction: ({ field, editContext, event }) => {
        // Extract mediaId from XML rawValue: <image mediaid="{GUID}" />
        const rawValue = field.rawValue || "";
        const mediaIdMatch = rawValue.match(/mediaid="[{]?([0-9a-fA-F-]+)[}]?"/i);
        if (mediaIdMatch && mediaIdMatch[1]) {
            const openInNewSlot = !!event?.altKey;
            editContext.loadItem({
                id: mediaIdMatch[1],
                language: field.descriptor.item.language,
                version: 0,
            }, { openInNewSlot });
        }
    },
    isGenerator: false,
    id: "open-image-media-item",
    description: "Opens the media item in the content editor",
};
const openAttachmentButton = {
    label: "Open",
    icon: (_jsx(ExternalLink, { strokeWidth: 1, size: 16 })),
    visible: ({ field }) => !!field.value?.src,
    clientAction: ({ field }) => {
        const src = field.value?.src;
        if (src) {
            window.open(src, "_blank", "noopener,noreferrer");
        }
    },
    isGenerator: false,
    id: "open-attachment",
    description: "Opens the attachment in a new tab",
};
const selectLocalFile = (accept = "*/*") => new Promise((resolve) => {
    if (typeof document === "undefined") {
        resolve(undefined);
        return;
    }
    const input = document.createElement("input");
    input.type = "file";
    input.accept = accept;
    input.style.display = "none";
    let resolved = false;
    const cleanup = () => {
        input.removeEventListener("change", handleChange);
        input.removeEventListener("cancel", handleCancel);
        window.removeEventListener("focus", handleWindowFocus);
        input.remove();
    };
    const finish = (file) => {
        if (resolved)
            return;
        resolved = true;
        cleanup();
        resolve(file);
    };
    const handleChange = () => {
        finish(input.files?.[0]);
    };
    const handleCancel = () => {
        finish(undefined);
    };
    const handleWindowFocus = () => {
        window.setTimeout(() => {
            if (!input.files?.length) {
                finish(undefined);
            }
        }, 500);
    };
    input.addEventListener("change", handleChange);
    input.addEventListener("cancel", handleCancel);
    window.setTimeout(() => {
        window.addEventListener("focus", handleWindowFocus, { once: true });
    }, 0);
    document.body.appendChild(input);
    input.click();
});
const attachAttachmentButton = {
    label: "Attach",
    icon: (_jsx(Paperclip, { strokeWidth: 1, size: 16 })),
    clientAction: async ({ field, editContext }) => {
        const file = await selectLocalFile();
        if (!file)
            return;
        const value = field.value;
        const mediaItemName = field.descriptor.item.displayName ??
            field.descriptor.item.name ??
            value?.fileName ??
            field.displayName ??
            "media item";
        await replaceMediaItemWithFile({
            file,
            mediaItem: {
                id: field.descriptor.item.id,
                name: mediaItemName,
            },
            editContext,
            language: field.descriptor.item.language,
            itemDescriptor: field.descriptor.item,
            refreshFields: [field.id],
            skipConfirmation: !value?.src,
        });
    },
    isDisabled: ({ field }) => field.canWrite === false,
    isGenerator: false,
    id: "attach-attachment",
    description: "Attaches a file to the media item",
};
const downloadAttachmentButton = {
    label: "Download",
    icon: (_jsx(Download, { strokeWidth: 1, size: 16 })),
    visible: ({ field }) => !!field.value?.src,
    clientAction: ({ field }) => {
        const src = field.value?.src;
        const fileName = field.value?.fileName;
        const mimeType = field.value?.mimeType;
        if (src) {
            const link = document.createElement("a");
            link.href = src;
            link.download = fileName || "";
            if (mimeType) {
                link.type = mimeType;
            }
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    },
    isGenerator: false,
    id: "download-attachment",
    description: "Downloads the attachment file",
};
// ============================================================================
// WORKSPACE DEFINITIONS
// Workspaces are fundamentally different UI experiences
// ============================================================================
const editView = _jsx(EditView, {});
const editorKeyboardCommandIds = [
    "renameItem",
    "deleteItem",
    "toggleInsertMode",
    "undo",
    "redo",
    "historyBack",
    "historyForward",
    "favoriteHistoryBack",
    "favoriteHistoryForward",
    "moveComponentUp",
    "moveComponentDown",
];
const undoCommand = getUndoCommand();
const redoCommand = getRedoCommand();
const coreKeyboardCommands = [
    renameItemCommand,
    deleteItemCommand,
    toggleInsertModeCommand,
    undoCommand,
    redoCommand,
    historyBackCommand,
    historyForwardCommand,
    favoriteHistoryBackCommand,
    favoriteHistoryForwardCommand,
    moveComponentUpCommand,
    moveComponentDownCommand,
];
/**
 * Core workspace definitions.
 * These are the main application modes: Home, Editor, Settings, Agents
 */
export const coreWorkspaces = [
    {
        id: "home",
        title: "Home",
        icon: _jsx(Home, { strokeWidth: 1 }),
        component: _jsx(ModernSplashScreen, {}),
        supportsSidebars: false,
    },
    {
        id: "editor",
        title: "Editor",
        icon: _jsx(SquarePen, { strokeWidth: 1 }),
        component: editView,
        toolbarFactory: createEditToolbar,
        titlebar: _jsx(Titlebar, {}),
        supportsSidebars: true,
        keyboardCommandIds: editorKeyboardCommandIds,
        defaultSidebars: [CONTENT_TREE_SIDEBAR_ID],
        sortOrder: 10,
    },
    {
        id: "agents",
        title: "AI Agents",
        icon: _jsx(ParheliaAgentIcon, { size: 20, strokeWidth: 1 }),
        component: _jsx(AgentsWorkspaceView, {}),
        titlebar: _jsx(AgentsTitlebar, {}),
        supportsSidebars: false,
        sortOrder: 20,
    },
    {
        id: "taskboard",
        title: "Workflow Projects",
        icon: _jsx(TrendingUpDown, { strokeWidth: 1 }),
        component: _jsx(TaskBoardWorkspace, {}),
        titlebar: _jsx(TaskBoardTitlebar, {}),
        supportsSidebars: true,
        defaultSidebars: ["taskboard-project-list"],
        sortOrder: 30,
    },
    {
        id: "settings",
        title: "Settings",
        icon: _jsx(Settings, { strokeWidth: 1 }),
        component: _jsx(SettingsView, {}),
        titlebar: _jsx(SettingsTitlebar, {}),
        supportsSidebars: false,
        sortOrder: 40,
    },
];
// ============================================================================
// SIDEBAR DEFINITIONS
// Sidebars are panels that can be opened within the Editor workspace
// ============================================================================
/**
 * Core sidebar definitions for the Editor workspace.
 */
export const coreSidebars = (isMobile) => [
    // Left sidebars
    {
        id: CONTENT_TREE_SIDEBAR_ID,
        title: "Content Tree",
        icon: _jsx(FolderTreeIcon, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 10,
        defaultWidth: 400,
        // Desktop renders this through MainLayout's dedicated content-tree panel.
        // Keep the sidebar definition for URL state, mobile, and programmatic opens.
        hidden: true,
        panels: [
            {
                name: "tree",
                title: "Content Tree",
                content: _jsx(MainContentTree, { mode: "normal", hideRootNodes: true }),
                initialSize: 100,
            },
        ],
    },
    {
        id: "favorites",
        title: "Favorites",
        icon: _jsx(Star, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 15,
        panels: [
            {
                name: "favorites",
                title: "Favorites",
                content: _jsx(Favorites, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "history",
        title: "History",
        icon: _jsx(History, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 20,
        panels: [
            {
                name: "history",
                title: "History",
                content: _jsx(EditHistory, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "completions",
        title: "Completions",
        icon: _jsx(WandSparkles, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 25,
        panels: [
            {
                name: "completions",
                title: "Completions",
                content: _jsx(Completions, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "reviews",
        title: "Reviews",
        icon: _jsx(ClipboardCheck, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 35,
        defaultWidth: 500,
        panels: [
            {
                name: "reviews",
                title: "Reviews",
                content: _jsx(Reviews, {}),
                initialSize: 100,
                noOverflow: true,
            },
        ],
    },
    {
        id: "validation",
        title: "Validation",
        icon: _jsx(ShieldCheck, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 40,
        panels: [
            {
                name: "validation",
                title: "Validation",
                content: _jsx(Validation, {}),
                initialSize: 100,
                noOverflow: true,
            },
        ],
    },
    {
        id: "workbox",
        title: "Workbox",
        icon: _jsx(InboxIcon, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 50,
        panels: [
            {
                name: "workbox",
                title: "Workbox",
                content: _jsx(Workbox, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "dictionary",
        title: "Dictionary",
        icon: _jsx(BookA, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 60,
        panels: [
            {
                name: "dictionary",
                title: "Dictionary",
                content: _jsx(DictionaryEditor, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "sessions",
        title: "Sessions",
        icon: _jsx(Users, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 70,
        panels: [
            {
                name: "sessions",
                title: "Sessions",
                content: _jsx(Sessions, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "taskboard-project-list",
        title: "Project List",
        icon: _jsx(Layers, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 110,
        defaultWidth: 368,
        panels: [
            {
                name: "taskboard-project-list",
                title: "Projects",
                hideHeaderIcon: true,
                content: _jsx(TaskBoardProjectListSidebar, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "taskboard-my-tasks",
        title: "My Tasks",
        icon: _jsx(ListTodo, { strokeWidth: 1 }),
        position: "left",
        sortOrder: 111,
        defaultWidth: 320,
        panels: [
            {
                name: "taskboard-my-tasks",
                title: "My Tasks",
                content: _jsx(TaskBoardMyTasksSidebar, {}),
                initialSize: 100,
            },
        ],
    },
    // Right sidebars
    {
        id: "component-navigator",
        title: "Component Navigator",
        icon: _jsx(Layers, { strokeWidth: 1 }),
        position: "right",
        sortOrder: 10,
        requiresLayout: true,
        panels: [
            {
                name: "component-tree",
                icon: _jsx(Layers, { strokeWidth: 1, size: 14 }),
                title: "Component Navigator",
                content: _jsx(ComponentTree, {}),
                initialSize: 100,
            },
        ],
    },
    {
        id: "agents-panel",
        title: "Agents",
        icon: _jsx(ParheliaAgentIcon, { size: 16, strokeWidth: 1 }),
        position: "right",
        sortOrder: 20,
        defaultWidth: 600,
        panels: [
            {
                name: "agents",
                title: "Agents",
                content: _jsx(Agents, {}),
                initialSize: 100,
                hideHeader: true,
                noOverflow: true,
            },
        ],
    },
];
// Reusable paste configs to avoid redundancy per field type
const textPaste = {
    enabled: () => true,
    kind: { type: "text" },
    hideIfInvalidClipboard: true,
    target: "value",
};
const guidPaste = {
    enabled: () => true,
    kind: { type: "guid" },
    hideIfInvalidClipboard: true,
    target: "rawValue",
};
const guidListPaste = {
    enabled: () => true,
    kind: { type: "guid-list", separator: "|" },
    hideIfInvalidClipboard: true,
    target: "rawValue",
};
export const getConfiguration = (isMobile = false) => {
    const defaultPictureVariantButtons = [
        selectImageButton,
        selectVideoButton,
        cropVariantButton,
        openPictureMediaItemButton,
        resetVariantButton,
    ];
    // Note: forceFullscreen is intended for embedding scenarios where fullscreen mode
    // should be permanently enforced (e.g., when embedded in another application).
    // The URL parameter ?fullscreen=true initializes fullscreen state in EditorShell
    // but should NOT set forceFullscreen - users should still be able to exit.
    return {
        extensions: {},
        statusChecks: coreStatusChecks,
        forceFullscreen: false,
        tours: {
            default: {
                getSteps: (params) => getDefaultTourSteps(params, {
                    firstComponentTemplateId: "39593ec8-0d85-46f2-9573-c368ef7e4ae3",
                    firstComponentTemplateName: "Section",
                    firstComponentTextFieldName: "Title",
                    firstComponentTextFieldId: "f352f51f-062c-4874-a561-6283f8679583",
                    firstComponentRichTextFieldName: "Introduction",
                    firstComponentRichTextFieldId: "b44b547b-33f5-4379-8ac3-c57ccea2d407",
                    tourTemplateName: "Article",
                }),
            },
            preview: {
                getSteps: (params) => getPreviewTourSteps(params),
            },
        },
        activeTour: "",
        commands: {
            renameItem: renameItemCommand,
            deleteItem: deleteItemCommand,
            insertItem: insertItemCommand,
            createTemplateItem: createTemplateItemCommand,
            moveItems: moveItemsCommand,
            copyItems: copyItemsCommand,
            keyboardCommands: coreKeyboardCommands,
            allItemCommands: [
                renameItemCommand,
                deleteItemCommand,
                duplicateItemCommand,
                copyItemsCommand,
                cloneItemsCommand,
                uncloneItemCommand,
                moveItemsCommand,
                exportItemsCommand,
                importItemsCommand,
                addStandardValuesCommand,
                publishItemCommand,
                publishRestrictionsCommand,
                reviewItemsCommand,
            ],
            reviewcommands: [approveReviewCommand, rejectReviewCommand],
        },
        commandTemplates: {
            byTypeId: commandTemplatesByTypeId,
        },
        customCommands: {
            handlers: [
                agentCommandHandler,
                openDialogCommandHandler,
                switchWorkspaceCommandHandler,
                openUrlCommandHandler,
                startTourCommandHandler,
                openStatusPanelCommandHandler,
                openItemCommandHandler,
            ],
        },
        componentCommands: {
            providers: [
                openRenderingItemComponentCommandProvider,
                createComponentThumbnailCommandProvider,
            ],
        },
        placeholderCommands: {
            providers: [openPlaceholderSettingsCommandProvider],
        },
        events: {},
        services: {
            aiService: {
                endpoint: "/parhelia/ai",
            },
        },
        fieldTypes: {
            raw: {
                editor: RawEditor,
            },
            "single-line text": {
                editor: SingleLineText,
                paste: textPaste,
                contextMenuFactory: createTextContextMenu,
            },
            "multi-line text": {
                editor: MultiLineText,
                paste: textPaste,
                contextMenuFactory: createTextContextMenu,
            },
            memo: {
                editor: MultiLineText,
                paste: textPaste,
                contextMenuFactory: createTextContextMenu,
            },
            "rich text": {
                editor: RichTextEditor,
                contextMenuFactory: createRichTextContextMenu,
            },
            "general link": {
                editor: LinkFieldEditor,
            },
            picture: {
                editor: PictureFieldEditor,
                variantButtons: defaultPictureVariantButtons,
                aiImageEdit: true,
            },
            image: {
                editor: ImageFieldEditor,
                buttons: [openImageMediaItemButton],
                aiImageEdit: true,
            },
            thumbnail: {
                editor: ImageFieldEditor,
                buttons: [openImageMediaItemButton],
                aiImageEdit: true,
            },
            thumbnaili: {
                editor: ImageFieldEditor,
                buttons: [openImageMediaItemButton],
                aiImageEdit: true,
            },
            droplink: {
                editor: DropLinkEditor,
                buttons: [openTargetActionButton],
                paste: guidPaste,
            },
            "enhanced droplink": {
                editor: DropLinkEditor,
                buttons: [openTargetActionButton],
                paste: guidPaste,
            },
            "enhanced internal link": {
                editor: InternalLinkFieldEditor,
                buttons: [openTargetActionButton],
                paste: guidPaste,
            },
            droplist: {
                editor: DropListEditor,
            },
            "enhanced droplist": {
                editor: DropListEditor,
            },
            treelistex: {
                editor: TreeListEditor,
                paste: guidListPaste,
            },
            treelist: {
                editor: TreeListEditor,
                paste: guidListPaste,
            },
            "enhanced treelist": {
                editor: TreeListEditor,
                paste: guidListPaste,
            },
            "tree list": {
                editor: TreeListEditor,
                paste: guidListPaste,
            },
            "tag treelist": {
                editor: TreeListEditor,
                paste: guidListPaste,
            },
            multilist: {
                editor: TreeListEditor,
                paste: guidListPaste,
            },
            "multiroot treelist": {
                editor: TreeListEditor,
                paste: guidListPaste,
            },
            checkbox: {
                editor: CheckboxEditor,
            },
            date: {
                editor: DateFieldEditor,
            },
            datetime: {
                editor: DateTimeFieldEditor,
            },
            "name value list": {
                editor: NameValueListEditor,
            },
            "enhanced name value list": {
                editor: NameValueListEditor,
            },
            droptree: {
                editor: InternalLinkFieldEditor,
                buttons: [openTargetActionButton],
                paste: {
                    enabled: () => true,
                    isValid: (text) => /[\{\(]?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}[\}\)]?/.test(text?.trim() ?? ""),
                    transform: (text) => {
                        const match = text
                            ?.trim()
                            .match(/[\{\(]?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}[\}\)]?/);
                        const id = match?.[0]?.replace(/[{}()]/g, "");
                        return id ? `{${id.toUpperCase()}}` : undefined;
                    },
                    hideIfInvalidClipboard: true,
                    target: "rawValue",
                },
            },
            attachment: {
                editor: AttachmentEditor,
                buttons: [
                    attachAttachmentButton,
                    openAttachmentButton,
                    downloadAttachmentButton,
                ],
            },
        },
        editorWarnings: [
            NoWriteAccess,
            NoWriteLanguageAccess,
            FinalWorkflowStateReadOnly,
            NoWorkflowWriteAccess,
            ItemLocked,
            ValidationErrors,
        ],
        outline: {
            width: 100,
        },
        debounceFieldEditsInterval: 250,
        devices: [
            // The first device is the default selected by the "Mobile" viewport
            // switcher option (see DeviceSwitchToolbar). Keep
            // iPhone 14 Pro Max first so the default mobile viewport width stays stable
            // when new presets are added to the dropdown.
            { name: "iPhone 14 Pro Max", width: 430, height: 932 },
            { name: "iPhone 17 Pro Max", width: 440, height: 956 },
            { name: "Galaxy S26 Ultra", width: 412, height: 891 },
            { name: "iPhone SE", width: 375, height: 667 },
            { name: "Pixel 7", width: 412, height: 915 },
            { name: "iPad Mini", width: 768, height: 1024 },
            { name: "iPad Pro", width: 1024, height: 1366 },
            { name: "Responsive", width: undefined, height: undefined },
        ],
        settings: {
            subtitle: "Parhelia settings",
            groups: [
                {
                    title: "Personal",
                    icon: _jsx(Users, { strokeWidth: 1 }),
                    panels: [
                        {
                            id: "user-preferences",
                            title: "User Preferences",
                            subtitle: "Configure personal editor preferences",
                            icon: _jsx(SlidersHorizontal, { strokeWidth: 1 }),
                            content: _jsx(UserPreferencesPanel, {}),
                        },
                        {
                            id: "notification-subscriptions",
                            title: "Notification Subscriptions",
                            subtitle: "Review and manage what you're watching",
                            icon: _jsx(Bell, { strokeWidth: 1 }),
                            content: _jsx(NotificationSubscriptionsPanel, {}),
                        },
                    ],
                },
                {
                    title: "AI",
                    icon: _jsx(Sparkles, { strokeWidth: 1 }),
                    panels: [
                        {
                            id: "ai-providers",
                            title: "Providers",
                            subtitle: "Configure AI providers",
                            icon: _jsx(Server, { strokeWidth: 1 }),
                            content: _jsx(ProvidersPanel, {}),
                        },
                        {
                            id: "ai-models",
                            title: "Models",
                            subtitle: "Install and configure AI models",
                            icon: _jsx(Sparkles, { strokeWidth: 1 }),
                            content: _jsx(ModelsPanel, {}),
                        },
                        {
                            id: "ai-agents",
                            title: "Agent Profiles",
                            subtitle: "Browse installed agent profiles and edit their core settings",
                            icon: _jsx(ParheliaAgentIcon, { size: 16, strokeWidth: 1 }),
                            content: _jsx(AgentsPanel, {}),
                        },
                        {
                            id: "javascript-tools",
                            title: "JavaScript Tools",
                            subtitle: "Create custom JavaScript-backed tools",
                            icon: _jsx(FileCode2, { strokeWidth: 1 }),
                            content: _jsx(JavaScriptToolsPanel, {}),
                        },
                        {
                            id: "mcp-tools",
                            title: "MCP Tools",
                            subtitle: "View installed MCP tool functions",
                            icon: _jsx(Wrench, { strokeWidth: 1 }),
                            content: _jsx(McpToolsPanel, {}),
                        },
                        {
                            id: "ai-quota",
                            title: "Usage & Quota",
                            subtitle: "View AI usage statistics and quota information",
                            icon: _jsx(BarChart3, { strokeWidth: 1 }),
                            content: _jsx(QuotaInfo, {}),
                        },
                        {
                            id: "project-templates",
                            title: "Workflow Project Templates",
                            subtitle: "Create project templates",
                            icon: _jsx(GitBranch, { strokeWidth: 1 }),
                            content: _jsx(ProjectTemplatesPanel, {}),
                        },
                        {
                            id: "agent-taskboard-logs",
                            title: "Agent and Taskboard Logs",
                            subtitle: "Filter and purge agent and taskboard execution logs",
                            icon: _jsx(Bug, { strokeWidth: 1 }),
                            content: _jsx(PersistentLogsPanel, {}),
                        },
                    ],
                },
                {
                    title: "Search",
                    icon: _jsx(Search, { strokeWidth: 1 }),
                    panels: [
                        {
                            id: "search-config",
                            title: "Search Index Configuration",
                            subtitle: "Configure search index and embeddings models",
                            icon: _jsx(Settings, { strokeWidth: 1 }),
                            content: _jsx(SearchConfigPanel, {}),
                        },
                        {
                            id: "search-index",
                            title: "Index Status",
                            subtitle: "View search index status and rebuild progress",
                            icon: _jsx(Search, { strokeWidth: 1 }),
                            content: _jsx(IndexOverview, {}),
                        },
                    ],
                },
                {
                    title: "System",
                    icon: _jsx(Server, { strokeWidth: 1 }),
                    panels: [
                        {
                            id: "system-settings",
                            title: "System Settings",
                            subtitle: "Realtime transport and other system-wide options",
                            icon: _jsx(Network, { strokeWidth: 1 }),
                            content: _jsx(SystemSettingsPanel, {}),
                        },
                        {
                            id: "status",
                            title: "System Status",
                            subtitle: "Overview of system health and configuration issues",
                            icon: _jsx(Activity, { strokeWidth: 1 }),
                            content: _jsx(StatusPanel, {}),
                        },
                        {
                            id: "cluster-instances",
                            title: "Cluster Instances",
                            subtitle: "View registered Sitecore CM instances and internal routing configuration",
                            icon: _jsx(Server, { strokeWidth: 1 }),
                            content: _jsx(ClusterInstancesPanel, {}),
                        },
                        {
                            id: "field-type-serializers",
                            title: "Field Type Serializers",
                            subtitle: "View Sitecore field types and their Parhelia serializer mappings",
                            icon: _jsx(DatabaseZap, { strokeWidth: 1 }),
                            content: _jsx(FieldTypeSerializersPanel, {}),
                        },
                        {
                            id: "agent-tools",
                            title: "Agent Tools",
                            subtitle: "Registered agent tool keys and signatures",
                            icon: _jsx(Wrench, { strokeWidth: 1 }),
                            content: _jsx(AgentToolsPanel, {}),
                        },
                    ],
                },
                {
                    title: "About",
                    icon: _jsx(InfoIcon, { strokeWidth: 1 }),
                    panels: [
                        {
                            id: "about",
                            title: "About Parhelia",
                            subtitle: "Version information and system details",
                            icon: _jsx(InfoIcon, { strokeWidth: 1 }),
                            content: _jsx(About, {}),
                        },
                    ],
                },
            ],
        },
        editor: {
            defaultPanelSizes: [400, 300],
            dialogs: {
                newPage: {
                    expandTreeNode: "bafb88a1-506a-4671-b47b-1947730d25f6",
                },
            },
            // New workspace/sidebar architecture
            workspaces: coreWorkspaces,
            sidebars: coreSidebars(isMobile),
            defaultWorkspace: "home",
            defaultOpenSidebars: [CONTENT_TREE_SIDEBAR_ID],
            manualActions: coreManualActions,
            // Agent dialog function components
            agentDialogs: [
                {
                    dialogType: "component-type-selector",
                    component: ComponentTypeSelectorInline,
                },
                {
                    dialogType: "questionnaire",
                    component: QuestionnaireInline,
                },
            ],
            notificationRoutes: coreNotificationRoutes,
            itemActionsMenu: {
                itemsFactory: (editContext) => {
                    const groups = [];
                    if (!editContext.item)
                        return [];
                    const items = [editContext.item];
                    const generateItems = (commands) => commands.map((command) => {
                        if (typeof command === "string") {
                            return {
                                id: "separator",
                                separator: true,
                                label: "",
                                icon: undefined,
                            };
                        }
                        return {
                            id: command.id,
                            label: command.label,
                            icon: command.icon,
                            disabled: editContext.isCommandDisabled({
                                command: command,
                                data: { items },
                            }),
                            command: async (event) => {
                                await editContext.executeCommand({
                                    command: command,
                                    event: event,
                                    data: { items },
                                });
                            },
                        };
                    });
                    groups.push({
                        id: "review",
                        label: "Review",
                        items: generateItems(editContext.configuration.commands.reviewcommands),
                    });
                    groups.push({
                        id: "all-item-commands",
                        label: "All Item Commands",
                        items: generateItems(editContext.configuration.commands.allItemCommands),
                    });
                    groups.push({
                        id: "new",
                        label: "New",
                        items: [
                            {
                                id: "new-page",
                                label: "New Page",
                                icon: _jsx(File, { strokeWidth: 1 }),
                                command: async () => {
                                    editContext.openDialog(NewPageDialog, {});
                                },
                            },
                        ],
                    });
                    // groups.push({
                    //   id: "about",
                    //   label: "About",
                    //   items: [
                    //     {
                    //       id: "about",
                    //       label: "About",
                    //       icon: "",
                    //       command: async () => {
                    //         editContext.openDialog(AboutDialog, {});
                    //       },
                    //     },
                    //   ],
                    // });
                    // groups.push({
                    //   id: "account",
                    //   label: "Account",
                    //   items: [
                    //     {
                    //       id: "logout",
                    //       label: "Log Out",
                    //       icon: "",
                    //       command: async () => {
                    //         // Redirect to Sitecore logout endpoint
                    //         window.location.href = "/sitecore/login?action=logout";
                    //       },
                    //     },
                    //   ],
                    // });
                    return groups;
                },
            },
            contentTree: {
                indicatorActions: {
                    validation: {
                        onClick: async (editContext, context) => {
                            const currentItem = editContext.currentItemDescriptor;
                            const isCurrentItem = cleanId(currentItem?.id) === cleanId(context.itemId) &&
                                currentItem?.language === context.itemLanguage;
                            if (!isCurrentItem) {
                                const loaded = await editContext.loadItem({
                                    id: context.itemId,
                                    language: context.itemLanguage,
                                    version: 0,
                                });
                                if (!loaded)
                                    return;
                            }
                            editContext.openSidebar("validation", {
                                preserveOpenSidebars: true,
                            });
                        },
                    },
                    feedback: {
                        onClick: async (editContext, context) => {
                            const currentItem = editContext.currentItemDescriptor;
                            const isCurrentItem = cleanId(currentItem?.id) === cleanId(context.itemId) &&
                                currentItem?.language === context.itemLanguage;
                            if (!isCurrentItem) {
                                const loaded = await editContext.loadItem({
                                    id: context.itemId,
                                    language: context.itemLanguage,
                                    version: 0,
                                });
                                if (!loaded)
                                    return;
                            }
                            openCommentsFeedback(editContext);
                        },
                    },
                },
                contextMenu: {
                    factory: async (props) => {
                        const editContext = props.editContext;
                        if (!props.items)
                            return;
                        const menuItems = props.editContext.configuration.commands.allItemCommands
                            ?.filter((x) => {
                            // Filter out commands that are not visible
                            const commandData = {
                                items: props.items,
                            };
                            if (x.visible) {
                                return x.visible({
                                    editContext,
                                    data: commandData,
                                });
                            }
                            return true; // If no visible property, show the command
                        })
                            .map((x) => {
                            const commandData = {
                                items: props.items,
                            };
                            return {
                                id: x.id,
                                label: x.label,
                                icon: x.icon,
                                command: async (triggerEvent) => {
                                    const result = await editContext?.executeCommand({
                                        command: x,
                                        data: commandData,
                                        event: triggerEvent,
                                    });
                                    if (props.commandCallback)
                                        props.commandCallback(x, result);
                                },
                                disabled: editContext?.isCommandDisabled({
                                    command: x,
                                    data: commandData,
                                }),
                            };
                        }) || [];
                        if (props.items.length > 1)
                            return menuItems;
                        const item = props.items[0];
                        if (!item)
                            return menuItems;
                        const insertOptions = await loadInsertOptions(item.descriptor);
                        const insertMenuItem = {
                            label: "Insert",
                            id: "insert",
                            disabled: insertOptions.length == 0,
                            template: (_jsx(InsertMenuTemplate, { insertOptions: insertOptions, item: item, commandCallback: props.commandCallback, mode: "overlay" })),
                        };
                        return [insertMenuItem, ...menuItems];
                    },
                },
            },
        },
    };
};
export function configureForUser(configuration, user) {
    if (user.isLimitedPreviewUser) {
        const previewToolbar = (editContext) => (_jsx(GenericToolbar, { left: [{ key: "review-commands", component: _jsx(ReviewCommands, {}) }], center: [{ key: "edit-mode", component: _jsx(EditControls, {}) }], right: [
                {
                    key: "utility-controls",
                    component: _jsx(UtilityControls, {}),
                },
            ] }));
        // For limited preview users, only allow review sidebars and override the
        // editor workspace toolbar. Comments are exposed through the editor's
        // right-side comments panel rather than a generic sidebar.
        const limitedSidebars = (configuration.editor.sidebars ?? []).filter((s) => s.id === "reviews");
        const limitedWorkspaces = (configuration.editor.workspaces ?? [])
            .map((w) => {
            if (w.id === "editor") {
                return {
                    ...w,
                    toolbarFactory: previewToolbar,
                    defaultSidebars: ["reviews"],
                };
            }
            return w;
        })
            .filter((w) => w.id === "editor"); // Only allow editor workspace
        return {
            ...configuration,
            activeTour: "",
            editor: {
                ...configuration.editor,
                workspaces: limitedWorkspaces,
                sidebars: limitedSidebars,
                defaultOpenSidebars: ["reviews"],
            },
        };
    }
    // Filter settings for non-admin users
    if (!user.isAdministrator) {
        const filteredSettings = {
            groups: configuration.settings.groups
                // Remove admin-only infrastructure groups for non-admins
                .filter((group) => group.title !== "Search" && group.title !== "System")
                .map((group) => {
                // For AI group, only show Usage & Quota
                if (group.title === "AI") {
                    return {
                        ...group,
                        panels: group.panels.filter((panel) => panel.id === "ai-quota"),
                    };
                }
                return group;
            }),
        };
        return {
            ...configuration,
            settings: filteredSettings,
        };
    }
    return configuration;
}
export function configureForLicense(configuration, licenseStatus) {
    if (licenseStatus && hasFeature(licenseStatus.features, LicenseFeatures.AI)) {
        return {
            ...configuration,
            hasAiLicense: true,
        };
    }
    const filteredSettings = {
        groups: configuration.settings.groups.filter((group) => group.title !== "AI" && group.title !== "Search"),
    };
    const filteredWorkspaces = (configuration.editor.workspaces ?? []).filter((workspace) => workspace.id !== "agents" && workspace.id !== "taskboard");
    const filteredSidebars = (configuration.editor.sidebars ?? []).filter((sidebar) => sidebar.id !== "agents-panel" &&
        sidebar.id !== "completions" &&
        sidebar.id !== "taskboard-project-list" &&
        sidebar.id !== "taskboard-my-tasks");
    const filteredDefaultOpenSidebars = (configuration.editor.defaultOpenSidebars ?? []).filter((sidebarId) => sidebarId !== "agents-panel" &&
        sidebarId !== "completions" &&
        sidebarId !== "taskboard-project-list" &&
        sidebarId !== "taskboard-my-tasks");
    const filteredCustomCommandHandlers = configuration.customCommands?.handlers?.filter((handler) => handler.type !== agentCommandHandler.type) ?? [];
    return {
        ...configuration,
        hasAiLicense: false,
        settings: filteredSettings,
        customCommands: {
            ...configuration.customCommands,
            handlers: filteredCustomCommandHandlers,
        },
        editor: {
            ...configuration.editor,
            workspaces: filteredWorkspaces,
            sidebars: filteredSidebars,
            defaultOpenSidebars: filteredDefaultOpenSidebars,
            agentDialogs: [],
        },
    };
}
export function configureTour(configuration, tourConfig) {
    if (configuration.tours?.default) {
        return {
            ...configuration,
            tours: {
                ...configuration.tours,
                default: {
                    ...configuration.tours.default,
                    getSteps: (params) => getDefaultTourSteps(params, tourConfig),
                },
            },
        };
    }
    return configuration;
}
//# sourceMappingURL=config.js.map