import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useMemo, useEffect, useRef, } from "react";
import { Button } from "../../../components/ui/button";
import { Checkbox } from "../../../components/ui/checkbox";
import { Textarea } from "../../../components/ui/textarea";
import { ClipboardList, FileUp, Loader2, Paperclip } from "lucide-react";
import { DeleteIcon } from "../../../components/ui/delete-icon";
import { ItemCollectionEditor, } from "../../ui/ItemCollectionEditor";
import { TreeListSelector } from "../../ui/TreeListSelector";
import { useEditContext } from "../../client/editContext";
import { cn } from "../../../lib/utils";
import { uploadDocument } from "../../services/agentService";
import { uploadAttachmentFile } from "../../../task-board/services/taskService";
const questionnaireDrafts = new Map();
const questionnairePendingFileDrafts = new Map();
const QUESTIONNAIRE_MAX_FILE_SIZE_MB = 10;
const QUESTIONNAIRE_MAX_FILE_SIZE_BYTES = QUESTIONNAIRE_MAX_FILE_SIZE_MB * 1024 * 1024;
const QUESTIONNAIRE_FILE_ACCEPT = ".txt,.md,.pdf,.docx,.xlsx,.pptx,.csv,.json,.xml,.cs,.js,.ts,.tsx,.jsx,.py,.java,.cpp,.c,.h,.hpp,.cshtml,.razor,.vb,.php,.rb,.go,.rs,.swift,.kt,.scala,.sql,.sh,.ps1,.bat,.yaml,.yml,.png,.jpg,.jpeg,.gif,.webp";
function isItemSelectionType(type) {
    return type === "item-picker" || type === "item-collection";
}
function isFileUploadType(type) {
    return type === "file-upload";
}
function createEmptyAnswer(questionId) {
    return {
        questionId,
        selectedOptions: [],
        selectedItems: [],
        uploadedDocuments: [],
        freetext: undefined,
    };
}
function shouldStoreInAgentDocumentStore(question) {
    return question.storeInAgentDocumentStore !== false;
}
function toUploadedDocumentReference(document) {
    if (!document) {
        return null;
    }
    return {
        id: document.id,
        agentId: document.agentId,
        fileName: document.fileName,
        fileSize: document.fileSize,
        contentType: document.contentType,
        uploadedBy: document.uploadedBy,
        uploadedDate: document.uploadedDate,
    };
}
function toUploadedDocumentReferenceFromTaskAttachment(attachment) {
    return {
        fileName: attachment.fileName,
        fileSize: attachment.fileSize,
        contentType: attachment.fileType ?? undefined,
        uploadedBy: attachment.uploadedBy,
        uploadedDate: attachment.uploadedAt,
    };
}
function toItemCollectionItems(selectedItems, language) {
    return (selectedItems ?? []).map((item) => ({
        descriptor: {
            id: item.id,
            language,
            version: 1,
            name: item.name || "",
            displayName: item.name || "",
            path: item.path || "",
        },
        includeSubitems: Boolean(item.includeSubitems),
    }));
}
function toSelectedItems(items) {
    return items.map((item) => ({
        id: item.descriptor.id,
        name: item.descriptor.displayName ||
            item.descriptor.name ||
            item.descriptor.path ||
            item.descriptor.id,
        path: item.descriptor.path,
        includeSubitems: item.includeSubitems,
    }));
}
function createInitialAnswers(parameters, savedAnswers) {
    const initial = new Map();
    parameters.questions.forEach((q) => {
        const preselectedItems = isItemSelectionType(q.type)
            ? (q.preselectedItemIds ?? [])
                .slice(q.type === "item-picker" && !q.allowMultiple ? -1 : 0)
                .filter((id) => Boolean(id && id.trim()))
                .map((id) => ({
                id,
                includeSubitems: false,
            }))
            : [];
        const savedAnswer = savedAnswers?.get(q.id);
        const isTextQuestion = !isItemSelectionType(q.type) &&
            !isFileUploadType(q.type) &&
            (q.options?.length ?? 0) === 0;
        initial.set(q.id, {
            questionId: q.id,
            selectedOptions: savedAnswer?.selectedOptions ?? [],
            selectedItems: savedAnswer?.selectedItems ?? preselectedItems,
            uploadedDocuments: savedAnswer?.uploadedDocuments ?? [],
            freetext: savedAnswer?.freetext ?? (isTextQuestion ? q.default : undefined),
        });
    });
    return initial;
}
function createInitialPendingFiles(parameters, savedFiles) {
    const initial = new Map();
    parameters.questions.forEach((question) => {
        if (!isFileUploadType(question.type)) {
            return;
        }
        initial.set(question.id, [...(savedFiles?.get(question.id) ?? [])]);
    });
    return initial;
}
function QuestionnaireFileUploadField({ questionId, agentId, allowMultiple, selectedFiles, submissionError, disabled, storeInAgentDocumentStore, attachToTaskIfAvailable, taskId, onChange, }) {
    const [isDragOver, setIsDragOver] = useState(false);
    const [selectionError, setSelectionError] = useState(null);
    const fileInputRef = useRef(null);
    const canStoreInAgentDocumentStore = storeInAgentDocumentStore !== false;
    const canAttachToTask = Boolean(attachToTaskIfAvailable && taskId);
    const hasUploadDestination = canAttachToTask || Boolean(agentId && canStoreInAgentDocumentStore);
    const handleFiles = useCallback((files) => {
        if (!files || files.length === 0) {
            return;
        }
        if (!hasUploadDestination) {
            setSelectionError("File upload is unavailable because this questionnaire has no valid upload destination.");
            return;
        }
        const nextValidFiles = [];
        let nextError = null;
        for (const file of Array.from(files)) {
            if (file.size > QUESTIONNAIRE_MAX_FILE_SIZE_BYTES) {
                nextError = `File "${file.name}" exceeds the maximum size of ${QUESTIONNAIRE_MAX_FILE_SIZE_MB} MB.`;
                continue;
            }
            nextValidFiles.push(file);
        }
        if (nextValidFiles.length === 0) {
            setSelectionError(nextError);
            return;
        }
        setSelectionError(nextError);
        onChange(allowMultiple
            ? [...selectedFiles, ...nextValidFiles]
            : nextValidFiles.slice(0, 1));
    }, [allowMultiple, hasUploadDestination, onChange, selectedFiles]);
    const removeSelectedFile = useCallback((fileIndex) => {
        onChange(selectedFiles.filter((_, index) => index !== fileIndex));
    }, [onChange, selectedFiles]);
    return (_jsxs("div", { className: "space-y-2", children: [_jsx("div", { "data-testid": "questionnaire-file-upload", "data-question-id": questionId, className: cn("rounded-lg border-2 border-dashed p-3 transition-colors", isDragOver
                    ? "border-feedback-blue bg-feedback-blue-light"
                    : "border-border-default bg-neutral-grey-5/70"), onDragOver: (event) => {
                    event.preventDefault();
                    event.stopPropagation();
                    setIsDragOver(true);
                }, onDragEnter: (event) => {
                    event.preventDefault();
                    event.stopPropagation();
                    setIsDragOver(true);
                }, onDragLeave: (event) => {
                    event.preventDefault();
                    event.stopPropagation();
                    setIsDragOver(false);
                }, onDrop: (event) => {
                    event.preventDefault();
                    event.stopPropagation();
                    setIsDragOver(false);
                    handleFiles(event.dataTransfer.files);
                }, children: _jsxs("div", { className: "flex items-start gap-2", children: [_jsx(FileUp, { strokeWidth: 1, className: "text-feedback-blue mt-0.5 h-4 w-4 shrink-0" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("p", { className: "text-neutral-grey-100 text-xs font-medium", children: allowMultiple
                                        ? "Drop files here or browse to attach"
                                        : "Drop a file here or browse to attach" }), _jsxs("p", { className: "text-neutral-grey-50 mt-0.5 text-[11px]", children: ["Files stay local until you submit the questionnaire. Max", " ", QUESTIONNAIRE_MAX_FILE_SIZE_MB, " MB per file.", canStoreInAgentDocumentStore
                                            ? " Submitted files will be stored with this agent."
                                            : "", canAttachToTask
                                            ? canStoreInAgentDocumentStore
                                                ? " They will also be attached to the current task."
                                                : " Submitted files will be attached to the current task."
                                            : ""] }), _jsxs("div", { className: "mt-2", children: [_jsx("input", { ref: fileInputRef, "data-testid": "questionnaire-file-input", "data-question-id": questionId, type: "file", className: "hidden", multiple: allowMultiple, accept: QUESTIONNAIRE_FILE_ACCEPT, onChange: (event) => {
                                                handleFiles(event.target.files);
                                                event.target.value = "";
                                            } }), _jsx(Button, { type: "button", variant: "outline", size: "sm", disabled: disabled || !hasUploadDestination, onClick: () => fileInputRef.current?.click(), className: "h-8 text-xs", children: allowMultiple ? "Browse Files" : "Browse File" })] })] })] }) }), (selectionError || submissionError) && (_jsx("div", { "data-testid": "questionnaire-file-upload-error", "data-question-id": questionId, className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded border px-2 py-1.5 text-[11px]", children: selectionError || submissionError })), selectedFiles.length > 0 && (_jsx("div", { className: "flex flex-wrap gap-2", children: selectedFiles.map((file, index) => (_jsxs("span", { "data-testid": "questionnaire-selected-file", "data-question-id": questionId, className: "rounded-badge border-border-default badge-pad text-2xs text-neutral-grey-100 inline-flex items-center gap-1.5 border bg-white", title: file.name, children: [_jsx(Paperclip, { strokeWidth: 1, className: "text-neutral-grey-50 h-3 w-3" }), _jsx("span", { className: "max-w-[220px] truncate", children: file.name }), _jsx("button", { type: "button", "data-testid": "questionnaire-remove-selected-file", "data-file-index": index, onClick: () => removeSelectedFile(index), className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-50 rounded p-0.5 transition-colors", "aria-label": `Remove ${file.name}`, children: _jsx(DeleteIcon, { size: "sm" }) })] }, `${file.name}-${file.size}-${index}`))) }))] }));
}
function QuestionnaireItemCollectionField({ questionId, rootItemId, answer, language, onChange, }) {
    const editContext = useEditContext();
    const items = useMemo(() => toItemCollectionItems(answer?.selectedItems, language), [answer?.selectedItems, language]);
    const [selectedInTree, setSelectedInTree] = useState([]);
    const [selectedFromList, setSelectedFromList] = useState([]);
    useEffect(() => {
        setSelectedInTree([]);
        setSelectedFromList([]);
    }, [answer?.selectedItems]);
    const commitItems = useCallback((nextItems) => {
        onChange(toSelectedItems(nextItems));
    }, [onChange]);
    const addToList = useCallback(async (itemsToAdd) => {
        const nextItems = [...items];
        const sourceItems = itemsToAdd ?? selectedInTree;
        const nodesToAdd = sourceItems.filter((node) => !nextItems.some((item) => item.descriptor.id === node.id));
        const nodesNeedingFetch = nodesToAdd.filter((node) => !node.path || !node.name || !node.displayName);
        if (nodesNeedingFetch.length > 0 && editContext?.itemsRepository) {
            try {
                const stubs = await editContext.itemsRepository.getItemsStubs(nodesNeedingFetch.map((node) => ({
                    id: node.id,
                    language: node.language || language,
                    version: node.version || 1,
                })));
                const stubMap = new Map(stubs.map((stub) => [stub.id, stub]));
                nodesToAdd.forEach((node) => {
                    const stub = stubMap.get(node.id);
                    nextItems.push({
                        descriptor: {
                            id: node.id,
                            language: node.language || language,
                            version: node.version || 1,
                            name: stub?.name || node.name || "",
                            displayName: stub?.displayName || node.displayName || "",
                            path: stub?.path || node.path || node.idPath || "",
                        },
                        includeSubitems: false,
                    });
                });
            }
            catch (error) {
                console.error("Failed to fetch item stubs:", error);
                nodesToAdd.forEach((node) => {
                    nextItems.push({
                        descriptor: {
                            id: node.id,
                            language: node.language || language,
                            version: node.version || 1,
                            name: node.name || "",
                            displayName: node.displayName || "",
                            path: node.path || node.idPath || "",
                        },
                        includeSubitems: false,
                    });
                });
            }
        }
        else {
            nodesToAdd.forEach((node) => {
                nextItems.push({
                    descriptor: {
                        id: node.id,
                        language: node.language || language,
                        version: node.version || 1,
                        name: node.name || "",
                        displayName: node.displayName || "",
                        path: node.path || node.idPath || "",
                    },
                    includeSubitems: false,
                });
            });
        }
        commitItems(nextItems);
        setSelectedInTree([]);
        setSelectedFromList([]);
    }, [
        items,
        selectedInTree,
        editContext?.itemsRepository,
        language,
        commitItems,
    ]);
    const handleAddItem = useCallback(async (item) => {
        const itemId = item.id;
        if (items.some((existing) => existing.descriptor.id === itemId)) {
            return;
        }
        let itemDescriptor = {
            id: itemId,
            language: item.language || language,
            version: item.version ?? 1,
            name: item.name || "",
            displayName: item.displayName || "",
            path: item.path || "",
        };
        if ((!itemDescriptor.path ||
            !itemDescriptor.name ||
            !itemDescriptor.displayName) &&
            editContext?.itemsRepository) {
            try {
                const stubs = await editContext.itemsRepository.getItemsStubs([
                    {
                        id: itemId,
                        language: itemDescriptor.language,
                        version: itemDescriptor.version,
                    },
                ]);
                if (stubs[0]) {
                    itemDescriptor = {
                        ...itemDescriptor,
                        name: stubs[0].name || itemDescriptor.name,
                        displayName: stubs[0].displayName || itemDescriptor.displayName,
                        path: stubs[0].path || itemDescriptor.path,
                    };
                }
            }
            catch (error) {
                console.error("Failed to fetch item stub:", error);
            }
        }
        commitItems([
            ...items,
            {
                descriptor: itemDescriptor,
                includeSubitems: false,
            },
        ]);
        setSelectedFromList([]);
    }, [items, editContext?.itemsRepository, language, commitItems]);
    const removeFromList = useCallback(() => {
        const idsToRemove = new Set(selectedFromList.map((item) => item.descriptor.id));
        commitItems(items.filter((item) => !idsToRemove.has(item.descriptor.id)));
        setSelectedFromList([]);
    }, [items, selectedFromList, commitItems]);
    const removeItem = useCallback((index) => {
        commitItems(items.filter((_, itemIndex) => itemIndex !== index));
        setSelectedFromList([]);
    }, [items, commitItems]);
    const toggleSubitems = useCallback((index) => {
        commitItems(items.map((item, itemIndex) => itemIndex === index
            ? { ...item, includeSubitems: !item.includeSubitems }
            : item));
        setSelectedFromList([]);
    }, [items, commitItems]);
    return (_jsx(ItemCollectionEditor, { items: items, selectedInTree: selectedInTree, onSelectedInTreeChange: setSelectedInTree, selectedFromList: selectedFromList, onSelectedFromListChange: setSelectedFromList, onAddToList: addToList, onRemoveFromList: removeFromList, onAddItem: handleAddItem, onRemoveItem: removeItem, onToggleSubitems: toggleSubitems, language: language, rootItemIds: rootItemId ? [rootItemId] : undefined, selectedItemsLabel: "Selected Items", emptyMessage: "No items selected", emptyHint: "Browse or search to add items", height: 320, localStorageKey: `questionnaire-item-collection-${questionId}` }));
}
/**
 * QuestionnaireInline - Inline component for displaying a questionnaire
 *
 * This is rendered directly inside the AgentTerminal rather than as a modal dialog.
 * Displays questions with multiple-choice options and optional freetext input.
 */
export function QuestionnaireInline({ requestId, agentId, onClose, onCancel, title = "Questionnaire", description, parameters, footerActions, }) {
    const editContext = useEditContext();
    const language = editContext?.currentItemDescriptor?.language || "en";
    const questionsScrollAreaRef = useRef(null);
    const taskId = parameters.taskId?.trim() || undefined;
    const [isHighlighted, setIsHighlighted] = useState(false);
    useEffect(() => {
        // Flash highlight on mount to grab user's attention
        setIsHighlighted(true);
        const highlightTimer = setTimeout(() => {
            setIsHighlighted(false);
        }, 4000);
        return () => {
            clearTimeout(highlightTimer);
        };
    }, [parameters.questions.length, requestId, title]);
    // State for each question's answers: Map<questionId, { selectedOptions, freetext }>
    const [answers, setAnswers] = useState(() => createInitialAnswers(parameters, requestId ? questionnaireDrafts.get(requestId) : undefined));
    const [pendingFiles, setPendingFiles] = useState(() => createInitialPendingFiles(parameters, requestId ? questionnairePendingFileDrafts.get(requestId) : undefined));
    const [fileUploadErrors, setFileUploadErrors] = useState(() => new Map());
    const [isSubmitting, setIsSubmitting] = useState(false);
    useEffect(() => {
        setAnswers(createInitialAnswers(parameters, requestId ? questionnaireDrafts.get(requestId) : undefined));
        setPendingFiles(createInitialPendingFiles(parameters, requestId ? questionnairePendingFileDrafts.get(requestId) : undefined));
        setFileUploadErrors(new Map());
        setIsSubmitting(false);
    }, [parameters, requestId]);
    useEffect(() => {
        const scrollArea = questionsScrollAreaRef.current;
        if (!scrollArea) {
            return;
        }
        scrollArea.scrollTop = 0;
    }, [requestId, title, description, parameters.questions]);
    useEffect(() => {
        if (!requestId) {
            return;
        }
        questionnaireDrafts.set(requestId, new Map(answers));
    }, [answers, requestId]);
    useEffect(() => {
        if (!requestId) {
            return;
        }
        questionnairePendingFileDrafts.set(requestId, new Map(pendingFiles));
    }, [pendingFiles, requestId]);
    const updateSelectedItems = useCallback((questionId, items) => {
        setAnswers((prev) => {
            const newMap = new Map(prev);
            const currentAnswer = newMap.get(questionId) || createEmptyAnswer(questionId);
            newMap.set(questionId, {
                ...currentAnswer,
                selectedItems: items,
            });
            return newMap;
        });
    }, []);
    const upsertSelectedItem = useCallback((questionId, item, allowMultiple) => {
        setAnswers((prev) => {
            const newMap = new Map(prev);
            const currentAnswer = newMap.get(questionId) || createEmptyAnswer(questionId);
            const existing = currentAnswer.selectedItems ?? [];
            const next = allowMultiple
                ? existing.some((i) => i.id === item.id)
                    ? existing
                    : [...existing, item]
                : [item];
            newMap.set(questionId, {
                ...currentAnswer,
                selectedItems: next,
            });
            return newMap;
        });
    }, []);
    const updatePendingFiles = useCallback((questionId, files) => {
        setPendingFiles((prev) => {
            const newMap = new Map(prev);
            newMap.set(questionId, files);
            return newMap;
        });
        setFileUploadErrors((prev) => {
            if (!prev.has(questionId)) {
                return prev;
            }
            const newMap = new Map(prev);
            newMap.delete(questionId);
            return newMap;
        });
    }, []);
    // Toggle option selection for a question
    const toggleOption = useCallback((questionId, optionId, allowMultiple) => {
        setAnswers((prev) => {
            const newMap = new Map(prev);
            const currentAnswer = newMap.get(questionId) || createEmptyAnswer(questionId);
            let newSelectedOptions;
            if (allowMultiple) {
                // Multi-select: toggle the option
                if (currentAnswer.selectedOptions.includes(optionId)) {
                    newSelectedOptions = currentAnswer.selectedOptions.filter((id) => id !== optionId);
                }
                else {
                    newSelectedOptions = [...currentAnswer.selectedOptions, optionId];
                }
            }
            else {
                // Single-select: replace selection
                if (currentAnswer.selectedOptions.includes(optionId)) {
                    newSelectedOptions = []; // Deselect if already selected
                }
                else {
                    newSelectedOptions = [optionId];
                }
            }
            newMap.set(questionId, {
                ...currentAnswer,
                selectedOptions: newSelectedOptions,
            });
            return newMap;
        });
    }, []);
    // Update freetext for a question
    const updateFreetext = useCallback((questionId, text) => {
        setAnswers((prev) => {
            const newMap = new Map(prev);
            const currentAnswer = newMap.get(questionId) || createEmptyAnswer(questionId);
            newMap.set(questionId, {
                ...currentAnswer,
                freetext: text || undefined,
            });
            return newMap;
        });
    }, []);
    // Check if a question has been answered (at least one option selected or freetext provided)
    const isQuestionAnswered = useCallback((question) => {
        if (question.optional)
            return true;
        const answer = answers.get(question.id);
        if (!answer)
            return false;
        if (isItemSelectionType(question.type)) {
            return (answer.selectedItems?.length ?? 0) > 0;
        }
        if (isFileUploadType(question.type)) {
            return ((pendingFiles.get(question.id)?.length ?? 0) > 0 ||
                (answer.uploadedDocuments?.length ?? 0) > 0);
        }
        return (answer.selectedOptions.length > 0 ||
            (answer.freetext !== undefined && answer.freetext.trim() !== ""));
    }, [answers, pendingFiles]);
    // Check if all required questions have been answered
    const allRequiredQuestionsAnswered = useMemo(() => {
        return parameters.questions.every((q) => q.optional || isQuestionAnswered(q));
    }, [parameters.questions, isQuestionAnswered]);
    const requiredQuestionCount = useMemo(() => {
        return parameters.questions.filter((q) => !q.optional).length;
    }, [parameters.questions]);
    const answeredRequiredCount = useMemo(() => {
        return parameters.questions.filter((q) => !q.optional && isQuestionAnswered(q)).length;
    }, [parameters.questions, isQuestionAnswered]);
    // Handle submit
    const handleSubmit = useCallback(async () => {
        if (isSubmitting) {
            return;
        }
        setIsSubmitting(true);
        setFileUploadErrors(new Map());
        const nextAnswers = [];
        const nextErrors = new Map();
        try {
            for (const question of parameters.questions) {
                const currentAnswer = answers.get(question.id) || createEmptyAnswer(question.id);
                if (!isFileUploadType(question.type)) {
                    nextAnswers.push(currentAnswer);
                    continue;
                }
                const files = pendingFiles.get(question.id) ?? [];
                if (files.length === 0) {
                    nextAnswers.push({
                        ...currentAnswer,
                        uploadedDocuments: currentAnswer.uploadedDocuments ?? [],
                    });
                    continue;
                }
                const storeInAgentDocumentStore = shouldStoreInAgentDocumentStore(question);
                const attachToTask = Boolean(question.attachToTaskIfAvailable && taskId);
                if (storeInAgentDocumentStore && !agentId) {
                    nextErrors.set(question.id, "File upload to the agent document store is unavailable because no agent is associated with this questionnaire.");
                    continue;
                }
                if (!storeInAgentDocumentStore && !attachToTask) {
                    nextErrors.set(question.id, "This file upload question is configured without a valid upload destination.");
                    continue;
                }
                const uploadedDocuments = [];
                for (const file of files) {
                    let uploadedDocument = null;
                    if (storeInAgentDocumentStore) {
                        const result = await uploadDocument(agentId, file);
                        if (!result.success || !result.document) {
                            nextErrors.set(question.id, result.error || `Failed to upload "${file.name}".`);
                            break;
                        }
                        uploadedDocument = toUploadedDocumentReference(result.document);
                        if (!uploadedDocument) {
                            nextErrors.set(question.id, `Failed to capture upload metadata for "${file.name}".`);
                            break;
                        }
                    }
                    if (attachToTask) {
                        const attachmentResult = await uploadAttachmentFile(taskId, file);
                        if (attachmentResult.type !== "success") {
                            nextErrors.set(question.id, attachmentResult.details ||
                                attachmentResult.summary ||
                                `Failed to attach "${file.name}" to the current task.`);
                            break;
                        }
                        if (!uploadedDocument && attachmentResult.data) {
                            uploadedDocument = toUploadedDocumentReferenceFromTaskAttachment(attachmentResult.data);
                        }
                    }
                    if (!uploadedDocument) {
                        nextErrors.set(question.id, `Failed to capture upload metadata for "${file.name}".`);
                        break;
                    }
                    uploadedDocuments.push(uploadedDocument);
                }
                if (nextErrors.has(question.id)) {
                    continue;
                }
                nextAnswers.push({
                    ...currentAnswer,
                    uploadedDocuments,
                });
            }
            if (nextErrors.size > 0) {
                setFileUploadErrors(nextErrors);
                return;
            }
            if (requestId) {
                questionnaireDrafts.delete(requestId);
                questionnairePendingFileDrafts.delete(requestId);
            }
            const result = {
                answers: nextAnswers.filter((answer) => answer.selectedOptions.length > 0 ||
                    (answer.selectedItems?.length ?? 0) > 0 ||
                    (answer.uploadedDocuments?.length ?? 0) > 0 ||
                    (answer.freetext !== undefined && answer.freetext.trim() !== "")),
            };
            onClose(result);
        }
        finally {
            setIsSubmitting(false);
        }
    }, [
        agentId,
        answers,
        isSubmitting,
        onClose,
        parameters.questions,
        pendingFiles,
        requestId,
        taskId,
    ]);
    const handleCancel = useCallback(() => {
        if (requestId) {
            questionnaireDrafts.delete(requestId);
            questionnairePendingFileDrafts.delete(requestId);
        }
        onCancel();
    }, [onCancel, requestId]);
    return (_jsxs("div", { "data-testid": "questionnaire-container", className: "flex flex-col gap-3", children: [_jsxs("div", { className: "flex items-start justify-between gap-2 pt-1", children: [_jsxs("div", { className: "min-w-0", children: [_jsx("h3", { "data-testid": "questionnaire-title", className: "text-neutral-grey-100 text-lg leading-6 font-medium", children: title }), description && (_jsx("p", { "data-testid": "questionnaire-description", className: "text-neutral-grey-50 mt-0.5 text-xs", children: description }))] }), isHighlighted && (_jsx("span", { className: "rounded-badge bg-feedback-orange badge-pad-sm text-2xs shrink-0 font-bold text-white shadow-sm", children: "Waiting for you" }))] }), _jsxs("div", { className: cn("rounded-xl border bg-white transition-all duration-1000", isHighlighted
                    ? "border-feedback-orange ring-feedback-orange/50 shadow-[0_0_25px_color-mix(in_srgb,var(--color-feedback-orange)_15%,transparent)] ring-2"
                    : "border-border-default shadow-none ring-0"), children: [_jsx("div", { ref: questionsScrollAreaRef, "data-testid": "questionnaire-scroll-area", children: parameters.questions.length === 0 ? (_jsxs("div", { "data-testid": "questionnaire-empty", className: "text-neutral-grey-50 flex h-full min-h-[220px] flex-col items-center justify-center py-8", children: [_jsx(ClipboardList, { size: 32, strokeWidth: 1, className: "mb-2 opacity-50" }), _jsx("p", { className: "text-xs", children: "No questions to display." })] })) : (_jsx("div", { className: "divide-border-default divide-y", children: parameters.questions.map((question, index) => {
                                const answer = answers.get(question.id);
                                const isItemPicker = question.type === "item-picker";
                                const isItemCollection = question.type === "item-collection";
                                const isFileUpload = isFileUploadType(question.type);
                                const isItemSelection = isItemPicker || isItemCollection;
                                const isStructuredQuestion = isItemSelection || isFileUpload;
                                // Auto-enable freetext if options array is empty, but not for structured question types.
                                const hasOptions = question.options && question.options.length > 0;
                                const effectiveAllowFreetext = isStructuredQuestion
                                    ? (question.allowFreetext ?? false)
                                    : question.allowFreetext || !hasOptions;
                                const effectiveRootItemId = question.rootItemId || question.root;
                                return (_jsxs("div", { "data-testid": "questionnaire-question", "data-question-id": question.id, className: "flex flex-col gap-3 p-4", children: [_jsxs("div", { children: [_jsxs("p", { className: "text-neutral-grey-100 text-sm leading-5 font-medium", children: [index + 1, ". ", question.prompt] }), _jsxs("p", { className: "text-neutral-grey-50 mt-0.5 text-xs", children: [isItemCollection
                                                            ? "Select items and choose whether to include subitems"
                                                            : isItemPicker
                                                                ? question.allowMultiple
                                                                    ? "Select one or more items"
                                                                    : "Select one item"
                                                                : isFileUpload
                                                                    ? question.allowMultiple
                                                                        ? "Upload one or more files"
                                                                        : "Upload a file"
                                                                    : !hasOptions
                                                                        ? "Open-ended question"
                                                                        : question.allowMultiple
                                                                            ? "Select one or more options"
                                                                            : "Select one option", isFileUpload &&
                                                            question.attachToTaskIfAvailable &&
                                                            taskId &&
                                                            " • Also attaches to task", question.optional && " (optional)", effectiveAllowFreetext &&
                                                            (isItemSelection || hasOptions) &&
                                                            " • Freetext allowed"] })] }), isItemCollection && (_jsx("div", { children: _jsx(QuestionnaireItemCollectionField, { questionId: question.id, rootItemId: effectiveRootItemId, answer: answer, language: language, onChange: (items) => updateSelectedItems(question.id, items) }) })), isItemPicker && (_jsxs("div", { children: [_jsx("div", { className: "border-border-default h-[250px] overflow-hidden rounded-lg border", children: _jsx(TreeListSelector, { language: language, rootItemIds: effectiveRootItemId
                                                            ? [effectiveRootItemId]
                                                            : undefined, selectedItemIds: (answer?.selectedItems ?? []).map((i) => i.id), selectionMode: question.allowMultiple ? "multiple" : "single", multiSelectRequiresModifier: !question.allowMultiple, onSelectionChange: (items) => {
                                                            const effectiveItems = question.allowMultiple
                                                                ? items
                                                                : items.slice(-1);
                                                            updateSelectedItems(question.id, effectiveItems.map((i) => ({
                                                                id: i.id,
                                                                name: i.displayName || i.name,
                                                                path: i.path,
                                                            })));
                                                        }, onItemSelected: (item) => {
                                                            const id = item.id;
                                                            const name = item.name || item.path || item.id;
                                                            upsertSelectedItem(question.id, { id, name, path: item.path }, question.allowMultiple ?? false);
                                                        }, className: "h-full" }) }), (answer?.selectedItems?.length ?? 0) > 0 && (_jsxs("div", { className: "mt-2 flex flex-wrap gap-1", children: [(answer?.selectedItems ?? [])
                                                            .slice(0, 8)
                                                            .map((i) => (_jsx("span", { className: "border-border-default bg-neutral-grey-5 badge-pad-sm text-neutral-grey-50 rounded border text-[10px]", title: i.path || i.id, children: i.name || i.path || i.id }, i.id))), (answer?.selectedItems?.length ?? 0) > 8 && (_jsxs("span", { className: "badge-pad-sm text-neutral-grey-50 text-[10px]", children: ["+", (answer?.selectedItems?.length ?? 0) - 8, " more"] }))] }))] })), isFileUpload && (_jsx("div", { children: _jsx(QuestionnaireFileUploadField, { questionId: question.id, agentId: agentId, allowMultiple: question.allowMultiple ?? false, selectedFiles: pendingFiles.get(question.id) ?? [], submissionError: fileUploadErrors.get(question.id), disabled: isSubmitting, storeInAgentDocumentStore: question.storeInAgentDocumentStore, attachToTaskIfAvailable: question.attachToTaskIfAvailable, taskId: taskId, onChange: (files) => updatePendingFiles(question.id, files) }) })), !isStructuredQuestion && hasOptions && (_jsx("div", { className: "space-y-0.5", children: question.options.map((option) => {
                                                const isSelected = answer?.selectedOptions.includes(option.id) ??
                                                    false;
                                                return (_jsxs("div", { "data-testid": "questionnaire-option", "data-option-id": option.id, "data-selected": isSelected, className: `flex cursor-pointer items-center gap-2.5 rounded-lg px-3 py-2 transition-colors ${isSelected
                                                        ? "bg-highlight-30/40"
                                                        : "hover:bg-neutral-grey-5"}`, onClick: () => toggleOption(question.id, option.id, question.allowMultiple ?? false), children: [question.allowMultiple ? (_jsx(Checkbox, { checked: isSelected, onCheckedChange: () => toggleOption(question.id, option.id, question.allowMultiple ?? false), className: "pointer-events-none h-3.5 w-3.5" })) : (_jsx("div", { className: `flex h-3.5 w-3.5 items-center justify-center rounded-full border-2 ${isSelected
                                                                ? "border-highlight-100 bg-highlight-100"
                                                                : "border-border-default"}`, children: isSelected && (_jsx("div", { className: "h-1.5 w-1.5 rounded-full bg-white" })) })), _jsx("span", { className: "text-neutral-grey-100 flex-1 text-sm", children: option.label })] }, option.id));
                                            }) })), effectiveAllowFreetext && (_jsxs("div", { children: [hasOptions && (_jsx("div", { className: "text-neutral-grey-50 mb-1 text-xs", children: "Additional comments (optional)" })), _jsx(Textarea, { "data-testid": "questionnaire-freetext", value: answer?.freetext ?? "", onChange: (e) => updateFreetext(question.id, e.target.value), placeholder: "Enter your response...", className: "bg-neutral-grey-5/50 min-h-[44px] rounded-lg text-sm" })] }))] }, question.id));
                            }) })) }), _jsxs("div", { className: "border-border-default flex items-center gap-3 border-t px-4 py-3", children: [_jsxs("span", { "data-testid": "questionnaire-progress", className: "text-neutral-grey-50 min-w-0 flex-1 truncate text-[11px]", children: [answeredRequiredCount, " of ", requiredQuestionCount, " required answered", " · ", _jsx("span", { className: allRequiredQuestionsAnswered
                                            ? "text-feedback-green"
                                            : "text-feedback-orange", children: allRequiredQuestionsAnswered
                                            ? "Ready to submit"
                                            : "Please answer all required questions" })] }), footerActions, _jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
                                    handleCancel();
                                }, "data-testid": "questionnaire-cancel", className: "h-8 shrink-0 text-xs", children: "Cancel" }), _jsx(Button, { size: "sm", onClick: () => {
                                    void handleSubmit();
                                }, disabled: !allRequiredQuestionsAnswered || isSubmitting, "data-testid": "questionnaire-submit", className: "h-8 shrink-0 text-xs", children: isSubmitting ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { strokeWidth: 1, className: "mr-1 h-3 w-3 animate-spin" }), "Submitting..."] })) : ("Submit answers") })] })] })] }));
}
export default QuestionnaireInline;
//# sourceMappingURL=QuestionnaireInline.js.map