import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { ChevronDown, ChevronRight, ChevronUp, Lightbulb, ListChecks, MessageSquare, } from "lucide-react";
import { cn } from "../../../../lib/utils";
import { buildActivityOverview, extractAgentFeedback, } from "../../agentActivitySummary";
import { useEditContext } from "../../../client/editContext";
import { OperationItem } from "../../../sidebar/OperationItem";
import { ActivitySummaryCell } from "./ActivitySummaryCell";
function leafOfPath(path) {
    if (!path)
        return undefined;
    const parts = path.split(/[\\/]/).filter(Boolean);
    return parts.length ? parts[parts.length - 1] : undefined;
}
function ActivityFeedbackRow({ feedback }) {
    const isSuggestion = feedback.kind === "suggested";
    const Icon = isSuggestion ? Lightbulb : MessageSquare;
    const title = isSuggestion
        ? `Suggested edit${feedback.fieldName ? ` · ${feedback.fieldName}` : ""}`
        : "Comment";
    return (_jsxs("div", { className: cn("border-border-default flex flex-col border-b border-l-[3px] p-2 text-xs font-light", isSuggestion ? "border-l-highlight-100" : "border-l-neutral-grey-15"), "data-testid": "activity-feedback-row", "data-feedback-kind": feedback.kind, children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(Icon, { className: cn("h-3.5 w-3.5 shrink-0", isSuggestion ? "text-highlight-100" : "text-neutral-grey-50"), strokeWidth: 1.75 }), _jsx("span", { className: "text-neutral-grey-100 truncate", children: title })] }), feedback.value && (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 line-clamp-2 text-[10px]", children: feedback.value }))] }));
}
function ActivityItemRow({ summary, expanded, onToggle }) {
    const editContext = useEditContext();
    const fullyUndone = summary.buckets.length === 0;
    const handleLoadItem = () => {
        if (summary.item?.id && editContext?.loadItem) {
            void editContext.loadItem(summary.item);
        }
    };
    return (_jsxs("div", { className: "border-border-default border-b last:border-b-0", children: [_jsxs("div", { role: "button", tabIndex: 0, onClick: handleLoadItem, onKeyDown: (event) => {
                    if (event.key === "Enter" || event.key === " ") {
                        event.preventDefault();
                        handleLoadItem();
                    }
                }, className: cn("hover:bg-neutral-grey-5 flex cursor-pointer items-center gap-2 px-4 py-2 text-xs transition-colors", fullyUndone && "opacity-60", summary.hasFailed && "bg-feedback-red-light/30"), "data-testid": "activity-item-row", "data-item-id": summary.itemId, title: "Open this item in the editor", children: [_jsx("button", { type: "button", onClick: (event) => {
                            event.stopPropagation();
                            onToggle();
                        }, onKeyDown: (event) => {
                            if (event.key === "Enter" || event.key === " ") {
                                event.stopPropagation();
                            }
                        }, className: "text-neutral-grey-50 hover:bg-neutral-grey-10 hover:text-neutral-grey-100 -ml-1 shrink-0 rounded p-0.5 transition-colors", "aria-label": expanded ? "Collapse actions" : "Expand actions", "aria-expanded": expanded, "data-testid": "activity-item-expand", children: expanded ? (_jsx(ChevronDown, { className: "h-3.5 w-3.5", strokeWidth: 1.5 })) : (_jsx(ChevronRight, { className: "h-3.5 w-3.5", strokeWidth: 1.5 })) }), _jsxs("div", { className: "flex min-w-0 flex-1 items-center gap-1.5", children: [_jsx("span", { className: cn("text-neutral-grey-100 truncate", summary.idOnly && "text-neutral-grey-50 font-mono"), title: summary.path ?? summary.item.id, children: summary.label }), summary.languages.length > 1 && (_jsxs("span", { className: "bg-neutral-grey-5 text-neutral-grey-50 shrink-0 rounded px-1 py-0.5 text-[10px]", children: ["+", summary.languages.length, " langs"] }))] }), _jsx("div", { className: "shrink-0", children: _jsx(ActivitySummaryCell, { summary: summary }) })] }), expanded && (_jsxs("div", { className: "bg-neutral-grey-5/40", children: [summary.operations.map((operation, index) => (_jsx(OperationItem, { operation: operation, index: index, hidePath: true, showLanguage: true }, operation.id))), summary.feedback.map((feedback) => (_jsx(ActivityFeedbackRow, { feedback: feedback }, feedback.id)))] }))] }));
}
export function AgentActivityOverviewPanel({ operations, messages, }) {
    const editContext = useEditContext();
    const overview = useMemo(() => buildActivityOverview(operations, extractAgentFeedback(messages)), [operations, messages]);
    const [resolvedItems, setResolvedItems] = useState({});
    const [isExpanded, setIsExpanded] = useState(false);
    const [expandedItemId, setExpandedItemId] = useState(null);
    useEffect(() => {
        if (!editContext?.itemsRepository)
            return;
        const currentItem = editContext.currentItemDescriptor;
        const rowsToResolve = overview.items.filter((summary) => {
            if (!summary.idOnly || resolvedItems[summary.itemId])
                return false;
            const language = summary.item.language || currentItem?.language;
            return Boolean(summary.item.id && language);
        });
        if (rowsToResolve.length === 0)
            return;
        let cancelled = false;
        void (async () => {
            try {
                const descriptors = rowsToResolve.map((summary) => ({
                    ...summary.item,
                    language: summary.item.language || currentItem?.language || "",
                    version: summary.item.version && summary.item.version > 0
                        ? summary.item.version
                        : currentItem?.version || summary.item.version || 0,
                }));
                const stubs = await editContext.itemsRepository.getItemsStubs(descriptors, currentItem);
                if (cancelled || stubs.length === 0)
                    return;
                setResolvedItems((current) => {
                    let changed = false;
                    const next = { ...current };
                    for (const stub of stubs) {
                        if (!stub?.id)
                            continue;
                        const label = stub.displayName || stub.name || leafOfPath(stub.path);
                        if (!label)
                            continue;
                        const key = stub.id.toLowerCase();
                        const resolved = {
                            item: {
                                id: stub.id,
                                language: stub.language,
                                version: stub.version,
                                name: stub.name,
                                displayName: stub.displayName,
                                path: stub.path,
                                database: stub.database,
                            },
                            label,
                            path: stub.path,
                        };
                        const existing = next[key];
                        if (existing?.label === resolved.label &&
                            existing?.path === resolved.path) {
                            continue;
                        }
                        next[key] = resolved;
                        changed = true;
                    }
                    return changed ? next : current;
                });
            }
            catch (error) {
                console.error("Failed to resolve agent activity item labels", error);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [
        editContext?.currentItemDescriptor,
        editContext?.itemsRepository,
        overview.items,
        resolvedItems,
    ]);
    const items = useMemo(() => overview.items.map((summary) => {
        const resolved = resolvedItems[summary.itemId];
        if (!resolved)
            return summary;
        return {
            ...summary,
            item: {
                ...summary.item,
                ...resolved.item,
                language: resolved.item.language || summary.item.language,
                version: resolved.item.version || summary.item.version,
            },
            path: resolved.path ?? summary.path,
            label: resolved.label,
            idOnly: false,
        };
    }), [overview.items, resolvedItems]);
    if (overview.items.length === 0) {
        return null;
    }
    return (_jsxs("div", { className: "border-border-default border-b", "data-testid": "agent-activity-overview", children: [_jsxs("button", { type: "button", onClick: () => setIsExpanded((value) => !value), className: "hover:bg-neutral-grey-5 flex w-full cursor-pointer items-center justify-between px-4 py-2 text-left transition-colors", "data-testid": "agent-activity-overview-trigger", "aria-expanded": isExpanded, children: [_jsxs("span", { className: "flex items-center gap-2", children: [_jsx(ListChecks, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1.5 }), _jsx("span", { className: "text-neutral-grey-100 text-xs font-normal", children: "Changes" }), _jsxs("span", { className: "text-neutral-grey-50 text-xs", children: ["(", overview.totalItems, ")"] })] }), isExpanded ? (_jsx(ChevronUp, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1.5 })) : (_jsx(ChevronDown, { className: "text-neutral-grey-50 h-4 w-4", strokeWidth: 1.5 }))] }), _jsx("div", { className: cn("grid transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none", isExpanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]"), children: _jsx("div", { className: "overflow-hidden", children: _jsx("div", { className: "border-border-default max-h-[40vh] overflow-y-auto border-t", children: items.map((summary) => (_jsx(ActivityItemRow, { summary: summary, expanded: expandedItemId === summary.itemId, onToggle: () => setExpandedItemId((current) => current === summary.itemId ? null : summary.itemId) }, summary.itemId))) }) }) })] }));
}
//# sourceMappingURL=AgentActivityOverviewPanel.js.map