import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useState } from "react";
import { useEditContext } from "../client/editContext";
import { Button } from "../../components/ui/button";
import { FileText, Puzzle, Type, Plus, Code2, ChevronDown, ChevronUp, X, Target, ArrowRight, RefreshCw, } from "lucide-react";
import { getComponentById } from "../componentTreeHelper";
import { updateAgentContext, } from "../services/agentService";
import { ContentInspectorPopover } from "./ContentInspectorPopover";
export function ContextInfoBar({ agent, agentMetadata, setAgentMetadata, setAgent, resolvedPageName, resolvedComponentName, resolvedFieldName, isLiveEditorContextMode, omitEditorContext, onRefreshContext, }) {
    const editContext = useEditContext();
    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 addPagesToContext = async () => {
        if (!agent?.id || !editContext?.currentItemDescriptor)
            return;
        const item = editContext.currentItemDescriptor;
        const pageToAdd = {
            id: item.id,
            language: item.language,
            version: item.version,
            name: editContext.item?.name,
            path: editContext.item?.path,
        };
        const current = agentMetadata || {};
        const currentPages = current.items || [];
        const existingPageIds = new Set(currentPages.map((p) => `${p.id}-${p.language}-${p.version}`));
        if (existingPageIds.has(`${pageToAdd.id}-${pageToAdd.language}-${pageToAdd.version}`)) {
            return;
        }
        const next = {
            ...current,
            items: [...currentPages, pageToAdd],
            currentItemId: pageToAdd.id, // Set the newly added item as the current item
        };
        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 pages)", e);
        }
    };
    const addSelectedComponentsToContext = async () => {
        if (!agent?.id || !editContext?.selection?.length)
            return;
        const current = agentMetadata || {};
        const currentComponents = current.components || [];
        const existingIds = new Set(currentComponents.map((c) => c.componentId));
        const newComponentIds = editContext.selection.filter((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 addComponentIdsToContext = async (ids) => {
        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 (!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) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = "copy";
        if (!isDragOver)
            setIsDragOver(true);
    };
    const handleDragLeave = () => {
        setIsDragOver(false);
    };
    const handleDrop = async (e) => {
        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 dynamicContext = React.useMemo(() => {
        if (!isLiveEditorContextMode || !editContext?.currentItemDescriptor) {
            return undefined;
        }
        const item = editContext.currentItemDescriptor;
        return {
            items: [
                {
                    id: item.id,
                    language: item.language,
                    version: item.version,
                    name: editContext.item?.name,
                    path: editContext.item?.path,
                },
            ],
            currentItemId: item.id,
            components: editContext.selection && editContext.selection.length > 0
                ? editContext.selection.map((componentId) => ({
                    componentId,
                    pageItem: {
                        id: item.id,
                        language: item.language,
                        version: item.version,
                        name: editContext.item?.name,
                        path: editContext.item?.path,
                    },
                }))
                : undefined,
        };
    }, [
        isLiveEditorContextMode,
        editContext?.currentItemDescriptor?.id,
        editContext?.currentItemDescriptor?.language,
        editContext?.currentItemDescriptor?.version,
        editContext?.item?.name,
        editContext?.item?.path,
        editContext?.selection,
    ]);
    // In live editor-context mode, derive the visible context directly
    // from the current editor state so UI always follows navigation.
    const ctx = React.useMemo(() => {
        if (!isLiveEditorContextMode || !editContext?.currentItemDescriptor) {
            return rawCtx;
        }
        const item = editContext.currentItemDescriptor;
        const liveItem = {
            id: item.id,
            language: item.language,
            version: item.version,
            name: editContext.item?.name,
            path: editContext.item?.path,
        };
        const liveComponents = editContext.selection && editContext.selection.length > 0
            ? editContext.selection.map((componentId) => ({
                componentId,
                pageItem: {
                    id: item.id,
                    language: item.language,
                    version: item.version,
                    name: editContext.item?.name,
                },
            }))
            : undefined;
        const base = (rawCtx || {});
        return {
            ...base,
            // In live mode, always show the current page as the only page context
            items: [liveItem],
            // ID of the currently loaded item the user is viewing
            currentItemId: item.id,
            // In live mode, components strictly follow the current selection;
            // if nothing is selected, previous component context is cleared.
            components: liveComponents,
            // Preserve any existing field/comment/additionalData from metadata;
            // live updates for field are handled via agentMetadata.
            field: base.field,
        };
    }, [
        isLiveEditorContextMode,
        rawCtx,
        editContext?.currentItemDescriptor?.id,
        editContext?.currentItemDescriptor?.language,
        editContext?.currentItemDescriptor?.version,
        editContext?.item?.name,
        editContext?.selection,
    ]);
    // // Debug logging to verify what context the UI receives
    // try {
    //   // eslint-disable-next-line no-console
    //   console.log("[ContextInfoBar] Render", {
    //     items: ctx?.items?.map((p) => ({
    //       id: p.id,
    //       language: p.language,
    //       version: p.version,
    //       name: p.name,
    //     })),
    //     components: ctx?.components?.map((c) => ({
    //       componentId: c.componentId,
    //       pageItem: c.pageItem
    //         ? {
    //             id: c.pageItem.id,
    //             language: c.pageItem.language,
    //             version: c.pageItem.version,
    //             name: c.pageItem.name,
    //           }
    //         : undefined,
    //     })),
    //     field: ctx?.field
    //       ? {
    //           fieldId: ctx.field.fieldId,
    //           fieldName: ctx.field.fieldName,
    //           item: ctx.field.item,
    //         }
    //       : undefined,
    //   });
    // } catch {
    //   // ignore logging errors
    // }
    const hasContext = !!ctx && !!(ctx.items?.length || ctx.components?.length || ctx.field);
    const rawContextSections = React.useMemo(() => [
        {
            title: "Stored context",
            content: JSON.stringify(rawCtx ?? null, null, 2),
        },
        {
            title: "Dynamic context",
            content: JSON.stringify(dynamicContext ?? null, null, 2),
        },
        {
            title: "Effective context",
            content: JSON.stringify(ctx ?? null, null, 2),
        },
    ], [ctx, dynamicContext, rawCtx]);
    const currentPageAlreadyAdded = editContext?.currentItemDescriptor &&
        !!ctx?.items?.some((page) => page.id === editContext.currentItemDescriptor?.id &&
            page.language === editContext.currentItemDescriptor?.language &&
            page.version === editContext.currentItemDescriptor?.version);
    const selectedComponentsAlreadyAdded = !!editContext?.selection?.length &&
        !!editContext.selection?.every((selectedId) => ctx?.components?.some((c) => c.componentId === selectedId));
    const canAddPage = !!editContext?.currentItemDescriptor && !currentPageAlreadyAdded;
    const canAddSelection = !!editContext?.selection?.length && !selectedComponentsAlreadyAdded;
    if (omitEditorContext) {
        return null;
    }
    if (!hasContext && !canAddPage && !canAddSelection) {
        return null;
    }
    const Chip = ({ icon, label, onRemove, onLoad, showRemove = true, isActive = false, }) => (_jsxs("span", { className: `inline-flex h-4 items-center gap-1 rounded-full border px-1.5 py-0.5 text-[11px] leading-none ${isActive
            ? "border-green-300 bg-green-100 text-green-700"
            : "border-gray-200 bg-gray-100 text-gray-700"}`, children: [icon, _jsx("span", { className: "max-w-[240px] truncate leading-none", title: label, children: label }), !isActive && onLoad && (_jsx("button", { onClick: onLoad, className: `ml-0.5 rounded p-0.5 hover:bg-gray-200`, "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-green-200" : "hover:bg-gray-200"}`, "aria-label": "Remove context", children: _jsx(X, { className: "h-3 w-3", strokeWidth: 1 }) }))] }));
    const chips = [];
    if (ctx?.items && ctx.items.length > 0) {
        ctx.items.forEach((page, index) => {
            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: "h-3 w-3 text-gray-500", strokeWidth: 1 }), label: pageLabel, onRemove: () => removeContextKey("items", index), onLoad: !isActive && editContext?.loadItem
                    ? () => editContext.loadItem(page)
                    : undefined, isActive: isActive }, `page-${index}`));
        });
    }
    if (ctx?.components && ctx.components.length > 0) {
        ctx.components.forEach((component, index) => {
            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 = !!editContext?.selection && editContext.selection.includes(componentId);
            chips.push(_jsx(Chip, { icon: _jsx(Puzzle, { className: "h-3 w-3 text-gray-500", strokeWidth: 1 }), label: label, onRemove: () => removeContextKey("components", index), 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, 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: "h-3 w-3 text-gray-500", strokeWidth: 1 }), label: fieldLabel, onRemove: () => removeContextKey("field"), isActive: isActive }, "field"));
    }
    // Build summary chips for collapsed view
    const summaryChips = [];
    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: "h-3 w-3 text-gray-500", 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 = !!editContext?.selection && editContext.selection.includes(firstId);
        summaryChips.push(_jsx(Chip, { icon: _jsx(Puzzle, { className: "h-3 w-3 text-gray-500", 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: "h-3 w-3 text-gray-500", 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: "h-3 w-3 text-gray-500", strokeWidth: 1 }), label: `"${trimmed}"`, onRemove: () => { }, showRemove: false }, "summary-comment"));
    }
    return (_jsxs("div", { className: "border-t border-gray-200 bg-gray-50", 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 flex w-full cursor-pointer items-center justify-between px-4 py-2 text-left transition-colors hover:bg-gray-100", "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: "h-4 w-4 text-gray-500", strokeWidth: 1 }), _jsx("span", { className: "text-xs leading-none font-normal text-gray-700", 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: "h-4 px-1.5 text-gray-500 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-gray-200 hover:text-gray-700", title: "Show raw context", "aria-label": "Show raw context", children: _jsx(Code2, { className: "h-3 w-3", strokeWidth: 1.5 }) }) }), isCollapsed && !isLiveEditorContextMode && onRefreshContext && (_jsxs(Button, { size: "xs", variant: "ghost", onClick: (e) => {
                                    e.stopPropagation();
                                    void onRefreshContext?.();
                                }, className: "h-4 px-2 text-blue-600 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-blue-50 hover:text-blue-700", title: "Update context to current page/selection", children: [_jsx(RefreshCw, { className: "mr-1 h-3 w-3", strokeWidth: 1 }), " Sync"] })), isCollapsed ? (_jsx(ChevronDown, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 })) : (_jsx(ChevronUp, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 }))] })] }), !isCollapsed && (_jsxs("div", { className: "px-4 pb-3", children: [_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 }), _jsxs("div", { className: "flex items-center gap-1", children: [!isLiveEditorContextMode && onRefreshContext && (_jsxs(Button, { size: "xs", variant: "ghost", onClick: () => void onRefreshContext?.(), className: "text-blue-600 hover:bg-blue-50 hover:text-blue-700", title: "Update context to current page/selection", children: [_jsx(RefreshCw, { className: "mr-1 h-2 w-2", strokeWidth: 1 }), " Sync"] })), hasContext && !isLiveEditorContextMode && (_jsxs(Button, { size: "xs", variant: "ghost", onClick: removeAllContext, className: "text-red-600 hover:bg-red-50 hover:text-red-700", "data-testid": "remove-all-context", children: [_jsx(X, { className: "mr-1 h-3 w-3", strokeWidth: 1 }), " Clear All"] }))] })] }), (canAddPage || canAddSelection) && (_jsxs("div", { className: "flex flex-col items-start gap-1 pb-2", children: [canAddPage && (_jsxs(Button, { size: "xs", variant: "outline", onClick: addPagesToContext, "data-testid": "add-current-item", children: [_jsx(Plus, { className: "mr-1 h-3 w-3", strokeWidth: 1 }), " Add current item"] })), canAddSelection && (_jsxs(Button, { size: "xs", variant: "outline", onClick: addSelectedComponentsToContext, children: [_jsx(Plus, { className: "mr-1 h-3 w-3", strokeWidth: 1 }), " Add selected components"] }))] })), (canAddPage || canAddSelection) && (_jsx("div", { className: "text-xs text-gray-500", children: "Tip: Drag items or components here to add them" }))] }))] }));
}
//# sourceMappingURL=ContextInfoBar.js.map