import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useState } from "react";
import { createPortal } from "react-dom";
import { useCanvasSelection, useEditContext, } from "../../../client/editContext";
import { Button } from "../../../../components/ui/button";
import { FileText, Puzzle, Type, Plus, Code2, ChevronDown, ChevronUp, X, Target, ArrowRight, } from "lucide-react";
import { getComponentById } from "../../../componentTreeHelper";
import { updateAgentContext, } from "../../../services/agentService";
import { ContentInspectorPopover } from "../../ContentInspectorPopover";
import { getAgentContextComponentKey, getAgentContextItemKey, hasViewedContent, mergeViewedContext, } from "../agentContextMerge";
import { getProjectTemplateContextSummary } from "../projectTemplateContext";
function formatProjectTemplateCounts(input) {
    const parts = [];
    if (input.taskCount !== undefined) {
        parts.push(`${input.taskCount} task${input.taskCount === 1 ? "" : "s"}`);
    }
    if (input.goalCount !== undefined) {
        parts.push(`${input.goalCount} goal${input.goalCount === 1 ? "" : "s"}`);
    }
    return parts.length ? ` (${parts.join(", ")})` : "";
}
export function ContextInfoBar({ agent, agentMetadata, setAgentMetadata, setAgent, resolvedPageName, resolvedComponentName, resolvedFieldName, viewedContext, includeEditorContext = false, includeLiveEditorContext = false, captureEditorContextOnCreate = false, headerless, headerActionsContainer, }) {
    const editContext = useEditContext();
    const canvasSelection = useCanvasSelection();
    const [isCollapsed, setIsCollapsed] = useState(true);
    const [isDragOver, setIsDragOver] = useState(false);
    const removeContextKey = useCallback(async (key, index) => {
        if (!agent?.id)
            return;
        const current = agentMetadata || {};
        const next = { ...current };
        if (key === "items" && typeof index === "number" && next.items) {
            next.items = [...next.items];
            next.items.splice(index, 1);
            if (next.items.length === 0)
                delete next.items;
        }
        else if (key === "components" &&
            typeof index === "number" &&
            next.components) {
            next.components = [...next.components];
            next.components.splice(index, 1);
            if (next.components.length === 0)
                delete next.components;
        }
        else if (key === "field") {
            delete next.field;
        }
        else if (key === "comment") {
            delete next.comment;
        }
        try {
            if (agent.status === "new") {
                setAgentMetadata(next);
                return;
            }
            await updateAgentContext(agent.id, next);
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
        }
        catch (e) {
            console.error("Failed to update agent context", e);
        }
    }, [agent?.id, agent?.status, agentMetadata, setAgent, setAgentMetadata]);
    const removeAllContext = useCallback(async () => {
        if (!agent?.id)
            return;
        const current = agentMetadata || {};
        const next = { ...current };
        // Remove all context items
        delete next.items;
        delete next.components;
        delete next.field;
        delete next.comment;
        try {
            if (agent.status === "new") {
                setAgentMetadata(next);
                return;
            }
            await updateAgentContext(agent.id, next);
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
        }
        catch (e) {
            console.error("Failed to clear agent context", e);
        }
    }, [agent?.id, agent?.status, agentMetadata, setAgent, setAgentMetadata]);
    const persistContext = useCallback(async (next) => {
        if (!agent?.id)
            return;
        if (agent.status === "new") {
            setAgentMetadata(next);
            return;
        }
        await updateAgentContext(agent.id, next);
        setAgentMetadata(next);
        setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
    }, [agent?.id, agent?.status, setAgent, setAgentMetadata]);
    // Pin the current view into the persistent "Added" context so it survives
    // navigating away.
    const pinViewedContext = useCallback(async () => {
        if (!includeEditorContext || !hasViewedContent(viewedContext))
            return;
        const merged = mergeViewedContext(agentMetadata || null, viewedContext || null);
        if (!merged)
            return;
        try {
            await persistContext(merged);
        }
        catch (e) {
            console.error("Failed to add currently viewed context", e);
        }
    }, [agentMetadata, includeEditorContext, persistContext, viewedContext]);
    const addComponentIdsToContext = async (ids) => {
        if (!includeEditorContext)
            return;
        if (!agent?.id || !ids?.length)
            return;
        const current = agentMetadata || {};
        const currentComponents = current.components || [];
        const existingIds = new Set(currentComponents.map((c) => c.componentId));
        const newComponentIds = ids.filter((id) => !!id && !existingIds.has(id));
        if (newComponentIds.length === 0)
            return;
        // Get page item descriptor from edit context
        const pageItem = editContext?.currentItemDescriptor
            ? {
                id: editContext.currentItemDescriptor.id,
                language: editContext.currentItemDescriptor.language,
                version: editContext.currentItemDescriptor.version,
                name: editContext.item?.name,
                path: undefined,
            }
            : undefined;
        // Build new components with page info and component name
        const newComponents = newComponentIds.map((componentId) => {
            let componentName;
            if (editContext?.page) {
                try {
                    const comp = getComponentById(componentId, editContext.page);
                    componentName = comp?.name || undefined;
                }
                catch { }
            }
            return {
                componentId,
                componentName,
                pageItem: pageItem,
            };
        });
        const next = {
            ...current,
            components: [...currentComponents, ...newComponents],
        };
        try {
            if (agent.status === "new") {
                setAgentMetadata(next);
                return;
            }
            await updateAgentContext(agent.id, next);
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
        }
        catch (e) {
            console.error("Failed to update agent context (add components)", e);
        }
    };
    const addPagesToContextFromItems = async (items) => {
        if (!includeEditorContext)
            return;
        if (!agent?.id || !items?.length)
            return;
        const current = agentMetadata || {};
        const currentPages = current.items || [];
        const existingPageIds = new Set(currentPages.map((p) => `${p.id}-${p.language}-${p.version}`));
        const pagesToAdd = items
            .filter((it) => !!it?.id)
            .map((it) => {
            const anyIt = it;
            const page = {
                id: it.id,
                language: it.language,
                version: it.version,
            };
            const candidateName = anyIt?.displayName || anyIt?.name;
            if (candidateName)
                page.name = candidateName;
            if (anyIt?.path)
                page.path = anyIt.path;
            return page;
        })
            .filter((p) => !existingPageIds.has(`${p.id}-${p.language}-${p.version}`));
        if (pagesToAdd.length === 0)
            return;
        const next = {
            ...current,
            items: [...currentPages, ...pagesToAdd],
        };
        try {
            if (agent.status === "new") {
                setAgentMetadata(next);
                return;
            }
            await updateAgentContext(agent.id, next);
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
        }
        catch (e) {
            console.error("Failed to update agent context (add items/pages)", e);
        }
    };
    const handleDragOver = (e) => {
        if (!includeEditorContext)
            return;
        e.preventDefault();
        e.dataTransfer.dropEffect = "copy";
        if (!isDragOver)
            setIsDragOver(true);
    };
    const handleDragLeave = () => {
        setIsDragOver(false);
    };
    const handleDrop = async (e) => {
        if (!includeEditorContext)
            return;
        e.preventDefault();
        setIsDragOver(false);
        try {
            const dragObj = editContext?.dragObject;
            if (dragObj?.type === "component") {
                const idsFromComponents = (dragObj.components || [])
                    .map((c) => c.id)
                    .filter((x) => !!x);
                const idFromData = e.dataTransfer.getData("componentId");
                const allIds = Array.from(new Set([...idsFromComponents, idFromData].filter((x) => !!x)));
                if (allIds.length) {
                    await addComponentIdsToContext(allIds);
                    if (isCollapsed)
                        setIsCollapsed(false);
                    return;
                }
            }
            if (dragObj?.type === "items" && dragObj.items?.length) {
                await addPagesToContextFromItems(dragObj.items);
                if (isCollapsed)
                    setIsCollapsed(false);
                return;
            }
            // Fallbacks when no dragObj or different source
            const fallbackComponentId = e.dataTransfer.getData("componentId");
            if (fallbackComponentId) {
                await addComponentIdsToContext([fallbackComponentId]);
                if (isCollapsed)
                    setIsCollapsed(false);
                return;
            }
            try {
                const textData = e.dataTransfer.getData("text/plain");
                if (textData) {
                    const parsed = JSON.parse(textData);
                    if (Array.isArray(parsed)) {
                        await addPagesToContextFromItems(parsed);
                        if (isCollapsed)
                            setIsCollapsed(false);
                        return;
                    }
                    else if (parsed?.id) {
                        await addPagesToContextFromItems([parsed]);
                        if (isCollapsed)
                            setIsCollapsed(false);
                        return;
                    }
                }
            }
            catch { }
        }
        catch (err) {
            console.error("Context drop failed", err);
        }
    };
    const rawCtx = agentMetadata || undefined;
    const ctx = React.useMemo(() => {
        if (!rawCtx)
            return rawCtx;
        const filtered = { ...rawCtx };
        if (filtered.editorContext) {
            filtered.editorContext = { ...filtered.editorContext };
        }
        if (!includeEditorContext) {
            delete filtered.selectedText;
            delete filtered.items;
            delete filtered.currentItemId;
            delete filtered.components;
            delete filtered.field;
            delete filtered.activeWorkspace;
            delete filtered.hasPageLoaded;
            delete filtered.editorContext;
            return filtered;
        }
        if (!captureEditorContextOnCreate) {
            delete filtered.editorContext?.startedFrom;
        }
        if (!includeLiveEditorContext) {
            delete filtered.editorContext?.currentlyViewing;
        }
        if (filtered.editorContext &&
            !filtered.editorContext.startedFrom &&
            !filtered.editorContext.currentlyViewing) {
            delete filtered.editorContext;
        }
        return filtered;
    }, [
        captureEditorContextOnCreate,
        includeEditorContext,
        includeLiveEditorContext,
        rawCtx,
    ]);
    const showViewedSection = includeLiveEditorContext && hasViewedContent(viewedContext);
    // What is actually sent to the AI: stored context, plus the current view when
    // the profile includes editor context. Surfaced in the raw-context inspector
    // for clarity.
    const effectiveCtx = React.useMemo(() => {
        if (!includeLiveEditorContext || !showViewedSection)
            return ctx;
        return mergeViewedContext(rawCtx ?? null, viewedContext ?? null) ?? ctx;
    }, [ctx, includeLiveEditorContext, showViewedSection, rawCtx, viewedContext]);
    const hasStoredContext = !!ctx &&
        !!(ctx.items?.length || ctx.components?.length || ctx.field || ctx.comment);
    const projectTemplateContext = getProjectTemplateContextSummary(ctx);
    const hasContext = hasStoredContext || !!projectTemplateContext;
    const rawContextSections = React.useMemo(() => [
        {
            title: "Added context",
            content: JSON.stringify(rawCtx ?? null, null, 2),
        },
        {
            title: "Currently viewing",
            content: JSON.stringify(viewedContext ?? null, null, 2),
        },
        {
            title: includeEditorContext
                ? "Effective context (sent to AI)"
                : "Effective context (sent to AI) - editor context disabled",
            content: JSON.stringify(effectiveCtx ?? null, null, 2),
        },
    ], [effectiveCtx, includeEditorContext, rawCtx, viewedContext]);
    if (!headerless && !hasContext && !showViewedSection) {
        return null;
    }
    const Chip = ({ icon, label, onRemove, onLoad, showRemove = true, isActive = false, testId, }) => (_jsxs("span", { "data-testid": testId, className: `rounded-badge badge-pad-sm text-2xs inline-flex h-4 items-center gap-1 border leading-none ${isActive
            ? "border-feedback-green bg-feedback-green-light text-feedback-green"
            : "border-border-default bg-neutral-grey-5 text-neutral-grey-100"}`, children: [icon, _jsx("span", { className: "max-w-[240px] truncate leading-none", title: label, children: label }), !isActive && onLoad && (_jsx("button", { onClick: onLoad, className: `hover:bg-neutral-grey-10 ml-0.5 rounded p-0.5`, "aria-label": "Load item", children: _jsx(ArrowRight, { className: "h-3 w-3", strokeWidth: 1 }) })), showRemove && (_jsx("button", { onClick: onRemove, className: `ml-0.5 rounded p-0.5 ${isActive
                    ? "hover:bg-feedback-green-light"
                    : "hover:bg-neutral-grey-10"}`, "aria-label": "Remove context", children: _jsx(X, { className: "h-3 w-3", strokeWidth: 1 }) }))] }));
    const chips = [];
    if (projectTemplateContext) {
        const templateName = projectTemplateContext.name ||
            projectTemplateContext.id ||
            "Current template";
        const templateLabel = `Project template: ${templateName}${formatProjectTemplateCounts(projectTemplateContext)}`;
        chips.push(_jsx(Chip, { icon: _jsx(FileText, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: templateLabel, onRemove: () => { }, showRemove: false }, "project-template"));
        if (projectTemplateContext.selectedTaskTitle) {
            chips.push(_jsx(Chip, { icon: _jsx(ArrowRight, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: `Selected task: ${projectTemplateContext.selectedTaskTitle}`, onRemove: () => { }, showRemove: false }, "project-template-selected-task"));
        }
        if (projectTemplateContext.selectedGoalTitle) {
            chips.push(_jsx(Chip, { icon: _jsx(Target, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: `Selected goal: ${projectTemplateContext.selectedGoalTitle}`, onRemove: () => { }, showRemove: false }, "project-template-selected-goal"));
        }
    }
    if (ctx?.items && ctx.items.length > 0) {
        ctx.items.forEach((page, index) => {
            const storedIndex = rawCtx?.items?.findIndex((storedPage) => getAgentContextItemKey(storedPage) === getAgentContextItemKey(page)) ?? -1;
            const pageLabelName = page.name || resolvedPageName || undefined;
            const pageLabel = `${pageLabelName || page.path || page.id} (${page.language}/${page.version})`;
            const isActive = !!editContext?.currentItemDescriptor &&
                page.id === editContext.currentItemDescriptor.id &&
                page.language === editContext.currentItemDescriptor.language &&
                page.version === editContext.currentItemDescriptor.version;
            chips.push(_jsx(Chip, { icon: _jsx(FileText, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: pageLabel, onRemove: () => {
                    if (storedIndex >= 0)
                        removeContextKey("items", storedIndex);
                }, onLoad: !isActive && editContext?.loadItem
                    ? () => editContext.loadItem(page)
                    : undefined, showRemove: storedIndex >= 0, isActive: isActive }, `page-${index}`));
        });
    }
    if (ctx?.components && ctx.components.length > 0) {
        ctx.components.forEach((component, index) => {
            const storedIndex = rawCtx?.components?.findIndex((storedComponent) => getAgentContextComponentKey(storedComponent) ===
                getAgentContextComponentKey(component)) ?? -1;
            const componentId = component.componentId;
            // Check if component's page is currently loaded (for load button)
            const isPageLoaded = !!editContext?.currentItemDescriptor &&
                !!component.pageItem &&
                component.pageItem.id === editContext.currentItemDescriptor.id &&
                component.pageItem.language ===
                    editContext.currentItemDescriptor.language &&
                component.pageItem.version ===
                    editContext.currentItemDescriptor.version;
            // Get component name - try resolved name first, then from loaded page, then stored name
            let compLabel = component.componentName || componentId;
            if (index === 0 && resolvedComponentName) {
                compLabel = resolvedComponentName;
            }
            else if (isPageLoaded && editContext?.page) {
                try {
                    const comp = getComponentById(componentId, editContext.page);
                    compLabel =
                        comp?.name || component.componentName || componentId;
                }
                catch { }
            }
            // Build label: when page is loaded, show "ComponentName on PageName"
            // When page is not loaded, show "PageName / ComponentName"
            let label;
            if (isPageLoaded) {
                const pageInfo = component.pageItem
                    ? ` on ${component.pageItem.name || component.pageItem.path || component.pageItem.id}`
                    : "";
                label = `${compLabel}${pageInfo}`;
            }
            else {
                // Page not loaded - show page name and component name
                const pageName = component.pageItem
                    ? component.pageItem.name ||
                        component.pageItem.path ||
                        component.pageItem.id
                    : "Unknown Page";
                label = `${pageName} / ${compLabel}`;
            }
            // Check if component is currently selected
            const isActive = canvasSelection.includes(componentId);
            chips.push(_jsx(Chip, { icon: _jsx(Puzzle, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: label, onRemove: () => {
                    if (storedIndex >= 0) {
                        removeContextKey("components", storedIndex);
                    }
                }, onLoad: !isPageLoaded && editContext?.loadItem && component.pageItem
                    ? async () => {
                        await editContext.loadItem(component.pageItem);
                        // Select the component after loading the page
                        if (editContext.select) {
                            editContext.select([componentId]);
                        }
                    }
                    : undefined, showRemove: storedIndex >= 0, isActive: isActive }, `component-${index}`));
        });
    }
    if (ctx?.field) {
        const field = ctx.field;
        const fieldLabel = `${field.fieldName || resolvedFieldName || field.fieldId}`;
        // Check if field's item matches current item
        const isActive = !!editContext?.currentItemDescriptor &&
            !!field.item &&
            field.item.id === editContext.currentItemDescriptor.id &&
            field.item.language === editContext.currentItemDescriptor.language &&
            field.item.version === editContext.currentItemDescriptor.version;
        chips.push(_jsx(Chip, { icon: _jsx(Type, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: fieldLabel, onRemove: () => removeContextKey("field"), isActive: isActive }, "field"));
    }
    if (ctx?.comment) {
        const commentText = (ctx.comment.text || "").trim();
        const commentLabel = commentText.length > 48
            ? `${commentText.slice(0, 48)}...`
            : commentText || "Review comment";
        chips.push(_jsx(Chip, { icon: _jsx(Target, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: commentLabel, onRemove: () => removeContextKey("comment") }, "comment"));
    }
    // Build read-only chips for the currently viewed page/component/field.
    const viewedChips = [];
    if (showViewedSection) {
        viewedContext?.items?.forEach((page, index) => {
            const pageLabelName = page.name || resolvedPageName || undefined;
            const pageLabel = `${pageLabelName || page.path || page.id} (${page.language}/${page.version})`;
            viewedChips.push(_jsx(Chip, { icon: _jsx(FileText, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: pageLabel, onRemove: () => { }, showRemove: false, isActive: true }, `viewed-page-${index}`));
        });
        viewedContext?.components?.forEach((component, index) => {
            const componentId = component.componentId;
            let compLabel = component.componentName || componentId;
            if (editContext?.page) {
                try {
                    const comp = getComponentById(componentId, editContext.page);
                    compLabel =
                        comp?.name || component.componentName || componentId;
                }
                catch { }
            }
            viewedChips.push(_jsx(Chip, { icon: _jsx(Puzzle, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: compLabel, onRemove: () => { }, showRemove: false, isActive: true }, `viewed-component-${index}`));
        });
        if (viewedContext?.field) {
            const field = viewedContext.field;
            const fieldLabel = `${field.fieldName || resolvedFieldName || field.fieldId}`;
            viewedChips.push(_jsx(Chip, { testId: "viewed-field-chip", icon: _jsx(Type, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: fieldLabel, onRemove: () => { }, showRemove: false, isActive: true }, "viewed-field"));
        }
    }
    // Build summary chips for collapsed view
    const summaryChips = [];
    if (projectTemplateContext) {
        const templateName = projectTemplateContext.name ||
            projectTemplateContext.id ||
            "Current template";
        summaryChips.push(_jsx(Chip, { icon: _jsx(FileText, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: `Project template: ${templateName}`, onRemove: () => { }, showRemove: false }, "summary-project-template"));
    }
    if (ctx?.items && ctx.items.length > 0) {
        const first = ctx.items[0];
        const pageLabelName = first.name || resolvedPageName || undefined;
        const pageText = pageLabelName || first.path || first.id;
        const label = ctx.items.length > 1 ? `${ctx.items.length} pages` : pageText;
        // Check if any item matches current item (for summary, check first item)
        const isActive = !!editContext?.currentItemDescriptor &&
            first.id === editContext.currentItemDescriptor.id &&
            first.language === editContext.currentItemDescriptor.language &&
            first.version === editContext.currentItemDescriptor.version;
        summaryChips.push(_jsx(Chip, { icon: _jsx(FileText, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: label, onRemove: () => { }, onLoad: !isActive && editContext?.loadItem
                ? () => editContext.loadItem(first)
                : undefined, showRemove: false, isActive: isActive }, "summary-page"));
    }
    if (ctx?.components && ctx.components.length > 0) {
        const firstComponent = ctx.components[0];
        const firstId = firstComponent.componentId;
        // Check if component's page is currently loaded (for load button)
        const isPageLoaded = !!editContext?.currentItemDescriptor &&
            !!firstComponent.pageItem &&
            firstComponent.pageItem.id === editContext.currentItemDescriptor.id &&
            firstComponent.pageItem.language ===
                editContext.currentItemDescriptor.language &&
            firstComponent.pageItem.version ===
                editContext.currentItemDescriptor.version;
        // Get component name - try resolved name first, then from loaded page, then stored name
        let compLabel = firstComponent.componentName || firstId;
        if (resolvedComponentName)
            compLabel = resolvedComponentName;
        else if (isPageLoaded && editContext?.page) {
            try {
                const comp = getComponentById(firstId, editContext.page);
                compLabel =
                    comp?.name || firstComponent.componentName || firstId;
            }
            catch { }
        }
        // Build label: when page is loaded, show component name
        // When page is not loaded, show "PageName / ComponentName"
        let label;
        if (ctx.components.length > 1) {
            label = `${ctx.components.length} components`;
        }
        else if (isPageLoaded) {
            label = compLabel;
        }
        else {
            // Page not loaded - show page name and component name
            const pageName = firstComponent.pageItem
                ? firstComponent.pageItem.name ||
                    firstComponent.pageItem.path ||
                    firstComponent.pageItem.id
                : "Unknown Page";
            label = `${pageName} / ${compLabel}`;
        }
        // Check if first component is currently selected (for summary)
        const isActive = canvasSelection.includes(firstId);
        summaryChips.push(_jsx(Chip, { icon: _jsx(Puzzle, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: label, onRemove: () => { }, onLoad: !isPageLoaded && editContext?.loadItem && firstComponent.pageItem
                ? async () => {
                    await editContext.loadItem(firstComponent.pageItem);
                    // Select the component after loading the page
                    if (editContext.select) {
                        editContext.select([firstId]);
                    }
                }
                : undefined, showRemove: false, isActive: isActive }, "summary-component"));
    }
    if (ctx?.field) {
        const field = ctx.field;
        const fieldLabel = `${field.fieldName || resolvedFieldName || field.fieldId}`;
        // Check if field's item matches current item
        const isActive = !!editContext?.currentItemDescriptor &&
            !!field.item &&
            field.item.id === editContext.currentItemDescriptor.id &&
            field.item.language === editContext.currentItemDescriptor.language &&
            field.item.version === editContext.currentItemDescriptor.version;
        summaryChips.push(_jsx(Chip, { icon: _jsx(Type, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: fieldLabel, onRemove: () => { }, showRemove: false, isActive: isActive }, "summary-field"));
    }
    if (ctx?.comment?.selectedText) {
        const t = ctx.comment.selectedText || "";
        const trimmed = t.length > 20 ? `${t.slice(0, 20)}...` : t;
        summaryChips.push(_jsx(Chip, { icon: _jsx(Type, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: `"${trimmed}"`, onRemove: () => { }, showRemove: false }, "summary-comment"));
    }
    else if (ctx?.comment) {
        const commentText = (ctx.comment.text || "").trim();
        const label = commentText.length > 20
            ? `${commentText.slice(0, 20)}...`
            : commentText || "Review comment";
        summaryChips.push(_jsx(Chip, { icon: _jsx(Target, { className: "text-neutral-grey-50 h-3 w-3", strokeWidth: 1 }), label: label, onRemove: () => { }, showRemove: false }, "summary-comment"));
    }
    const inlineHeaderActions = hasStoredContext ? (_jsx("div", { className: "flex items-center gap-1", children: _jsxs(Button, { size: "xs", variant: "ghost", onClick: removeAllContext, className: "text-feedback-red hover:bg-feedback-red-light hover:text-feedback-red", "data-testid": "remove-all-context", children: [_jsx(X, { className: "mr-1 h-3 w-3", strokeWidth: 1 }), " Clear All"] }) })) : null;
    const useHeaderPortal = headerless && headerActionsContainer;
    const expandedBody = (_jsxs("div", { className: "px-4 pt-3 pb-3", children: [useHeaderPortal && inlineHeaderActions
                ? createPortal(inlineHeaderActions, headerActionsContainer)
                : null, _jsxs("div", { className: "flex items-start justify-between gap-2 pb-2", children: [_jsx("div", { className: "flex flex-1 flex-wrap items-center gap-2", children: chips.length > 0 ? (chips) : (_jsx("span", { className: "text-neutral-grey-50 text-xs", children: !includeEditorContext
                                ? "Editor context is disabled for this profile."
                                : captureEditorContextOnCreate && !includeLiveEditorContext
                                    ? "Editor context will be captured when this agent starts."
                                    : "No context added yet. Drag items or components here to add them." })) }), !useHeaderPortal && inlineHeaderActions] }), showViewedSection && (_jsxs("div", { className: "border-border-default mt-2 border-t pt-3", children: [_jsxs("div", { className: "flex items-center justify-between gap-2 pb-2", children: [_jsx("span", { className: "text-neutral-grey-100 text-xs", children: "Currently viewing" }), _jsxs(Button, { size: "xs", variant: "outline", onClick: () => void pinViewedContext(), "data-testid": "add-current-item", children: [_jsx(Plus, { className: "mr-1 h-3 w-3", strokeWidth: 1 }), " Add to context"] })] }), _jsx("div", { className: "flex flex-wrap items-center gap-2", children: viewedChips })] }))] }));
    if (headerless) {
        return (_jsx("div", { className: "bg-neutral-grey-5", onDragOver: handleDragOver, onDragEnter: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, children: expandedBody }));
    }
    return (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 border-t", onDragOver: handleDragOver, onDragEnter: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, children: [_jsxs("div", { role: "button", tabIndex: 0, onClick: (e) => {
                    // Don't toggle if clicking on an interactive element inside
                    if (e.target.closest("button, a, [role='button']") !==
                        e.currentTarget) {
                        return;
                    }
                    setIsCollapsed(!isCollapsed);
                }, onKeyDown: (e) => {
                    if (e.key === "Enter" || e.key === " ") {
                        e.preventDefault();
                        setIsCollapsed(!isCollapsed);
                    }
                }, className: "group hover:bg-neutral-grey-5 flex w-full cursor-pointer items-center justify-between px-4 py-2 text-left transition-colors", "aria-label": isCollapsed ? "Expand context" : "Collapse context", "aria-expanded": !isCollapsed, "data-testid": "context-toggle", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Target, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1 }), _jsx("span", { className: "text-neutral-grey-100 text-xs leading-none font-normal", children: "Context" }), isCollapsed && summaryChips.length > 0 && (_jsx("div", { className: "flex flex-wrap items-center gap-1", children: summaryChips }))] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(ContentInspectorPopover, { title: "Raw context", sections: rawContextSections, trigger: _jsx(Button, { size: "xs", variant: "ghost", onClick: (e) => e.stopPropagation(), className: "text-neutral-grey-50 hover:bg-neutral-grey-10 hover:text-neutral-grey-100 h-4 px-1.5 opacity-0 transition-opacity group-hover:opacity-100", title: "Show raw context", "aria-label": "Show raw context", children: _jsx(Code2, { className: "h-3 w-3", strokeWidth: 1.5 }) }) }), isCollapsed ? (_jsx(ChevronDown, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1 })) : (_jsx(ChevronUp, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1 }))] })] }), !isCollapsed && expandedBody] }));
}
//# sourceMappingURL=ContextInfoBar.js.map