import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { ChevronDown, ChevronUp, ListTodo, Loader2 } from "lucide-react";
import { extractTodosFromMessages, } from "./agentTodoExtraction";
export const TodoListPanel = ({ messages, agentMetadata, }) => {
    const [isExpanded, setIsExpanded] = useState(true);
    // Server sends additionalData.todoList directly via contextChanged status
    const metadataTodos = (() => {
        try {
            const todoList = agentMetadata?.additionalData?.todoList;
            if (todoList?.items && Array.isArray(todoList.items)) {
                const rawItems = todoList.items
                    .map((item, idx) => ({
                    id: item.id || `metadata-${idx}`,
                    title: item.title || item.text || item.label || String(item.task || ""),
                    status: item.status || "pending",
                    instructions: item.instructions || item.note || item.description,
                    agentProfileId: item.agentProfileId,
                    messageId: undefined,
                    sourceTitle: todoList.title,
                }))
                    .filter((item) => item.title);
                const todoMap = new Map();
                for (const todo of rawItems) {
                    const key = todo.id || todo.title;
                    todoMap.set(key, todo);
                }
                return Array.from(todoMap.values());
            }
        }
        catch (e) {
            console.error("📋 Error extracting todos from metadata:", e);
        }
        return null;
    })();
    const usingMetadata = metadataTodos && metadataTodos.length > 0;
    const todos = usingMetadata
        ? metadataTodos
        : extractTodosFromMessages(messages);
    const isUpdating = messages.some((msg) => {
        if (msg.role !== "assistant" || msg.isCompleted)
            return false;
        const content = msg.content || "";
        const fencedStart = content.indexOf("```todo_list");
        if (fencedStart !== -1) {
            const afterStart = fencedStart + "```todo_list".length;
            const closePos = content.indexOf("```", afterStart);
            if (closePos === -1) {
                return true;
            }
        }
        const plainStart = content.indexOf("todo_list");
        if (plainStart !== -1 && plainStart !== fencedStart) {
            const before = plainStart > 0 ? content[plainStart - 1] : "\n";
            if (before === "\n" || before === "\r" || plainStart === 0) {
                const braceStart = content.indexOf("{", plainStart);
                if (braceStart !== -1) {
                    let depth = 0;
                    let braceEnd = -1;
                    for (let i = braceStart; i < content.length; i++) {
                        if (content[i] === "{")
                            depth++;
                        if (content[i] === "}") {
                            depth--;
                            if (depth === 0) {
                                braceEnd = i;
                                break;
                            }
                        }
                    }
                    if (braceEnd === -1) {
                        return true;
                    }
                }
            }
        }
        return false;
    });
    if (todos.length === 0 && !isUpdating)
        return null;
    const completedCount = todos.filter((t) => t.status === "completed").length;
    const totalCount = todos.length;
    const getStatusIcon = (status) => {
        switch (status) {
            case "completed":
                return (_jsx("div", { className: "flex h-4 w-4 items-center justify-center rounded border-2 border-green-500 bg-green-500", children: _jsx("svg", { className: "h-3 w-3 text-white", fill: "none", strokeWidth: 2, stroke: "currentColor", viewBox: "0 0 24 24", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M5 13l4 4L19 7" }) }) }));
            case "in_progress":
                return (_jsx("div", { className: "flex h-4 w-4 items-center justify-center rounded border-2 border-blue-500 bg-blue-500", children: _jsx(Loader2, { className: "h-3 w-3 animate-spin text-white", strokeWidth: 2 }) }));
            case "cancelled":
                return (_jsx("div", { className: "flex h-4 w-4 items-center justify-center rounded border-2 border-gray-400 bg-gray-400", children: _jsx("svg", { className: "h-3 w-3 text-white", fill: "none", strokeWidth: 2, stroke: "currentColor", viewBox: "0 0 24 24", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18L18 6M6 6l12 12" }) }) }));
            default:
                return _jsx("div", { className: "h-4 w-4 rounded border-2 border-gray-300" });
        }
    };
    const getTextClass = (status) => {
        switch (status) {
            case "completed":
                return "text-gray-500 line-through";
            case "cancelled":
                return "text-gray-400 line-through";
            case "in_progress":
                return "text-blue-700 font-medium";
            default:
                return "text-gray-900";
        }
    };
    return (_jsxs("div", { className: "border-t border-gray-200 bg-gray-50", children: [_jsxs("button", { onClick: () => setIsExpanded(!isExpanded), className: "flex w-full cursor-pointer items-center justify-between px-4 py-2 text-left transition-colors hover:bg-gray-100", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(ListTodo, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 }), _jsx("span", { className: "text-[11px] font-medium text-gray-700", children: "Todo List" }), isUpdating ? (_jsxs("span", { className: "text-theme-secondary flex items-center gap-1 text-[11px]", children: [_jsx(Loader2, { className: "h-3 w-3 animate-spin", strokeWidth: 1 }), "Updating..."] })) : (_jsxs("span", { className: "text-[11px] text-gray-500", children: [completedCount, "/", totalCount, " completed"] }))] }), isExpanded ? (_jsx(ChevronUp, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 })) : (_jsx(ChevronDown, { className: "h-4 w-4 text-gray-500", strokeWidth: 1 }))] }), isExpanded && (_jsxs("div", { className: "max-h-64 overflow-y-auto px-4 pb-3", children: [todos.length > 0 && (_jsx("div", { className: "space-y-1.5", children: todos.map((todo, idx) => (_jsxs("div", { className: "flex items-start gap-2 rounded bg-white p-2 text-[11px]", children: [_jsx("div", { className: "shrink-0 pt-0.5", children: getStatusIcon(todo.status) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: getTextClass(todo.status), children: todo.title }), todo.instructions && (_jsx("div", { className: "mt-0.5 text-[11px] text-gray-500", children: todo.instructions }))] })] }, todo.id || `${todo.messageId}-${idx}`))) })), isUpdating && (_jsxs("div", { className: `flex items-center gap-2 rounded px-3 py-2 text-[11px] ${todos.length > 0
                            ? "bg-theme-secondary-light text-theme-secondary mt-2"
                            : "justify-center bg-white text-gray-500"}`, children: [_jsx(Loader2, { className: "h-3 w-3 animate-spin", strokeWidth: 1 }), _jsx("span", { children: todos.length > 0
                                    ? "Updating todo list..."
                                    : "Loading todo list..." })] }))] }))] }));
};
//# sourceMappingURL=TodoListPanel.js.map