import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { TerminalSquare } from "lucide-react";
import { toast } from "sonner";
import { Button } from "../../components/ui/button";
import { getAiProfilesErrorMessage, loadAiProfiles, } from "../../editor/services/aiService";
import { getLinkedAgentId } from "../taskAgentLink";
import { normalizeTaskStatus } from "../taskStatus";
import { updateTask } from "../services/taskService";
import { FinishedProjectCard } from "./FinishedProjectCard";
import { WizardProjectSummaryCard } from "./WizardCommunicationCards";
import { getSummaryPresentation, } from "./WizardCommunicationShared";
import { WizardTask } from "./WizardTask";
import { LicenseFeatures, useFeature } from "../../licensing";
export function WizardCommunicationCenter(props) {
    const { task, agentId, agentStatus, executionDisplay, summaryState, stats, allTasks = [], dependencies = [], canEdit = false, onTaskChanged, onContentChanged, onTaskApproved, showApprovedState, hasNextReviewTask, onReviewNext, onInteractionSubmitted, onCloseTask, onSelectTask, canArchiveProject = false, isArchivingProject = false, onArchiveProject, onOpenAgentTab, } = props;
    const canUseAi = useFeature(LicenseFeatures.AI);
    const effectiveAgentId = agentId ?? getLinkedAgentId(task);
    const [profiles, setProfiles] = useState([]);
    const [profilesError, setProfilesError] = useState(null);
    const [showFullTerminal, setShowFullTerminal] = useState(false);
    const [hasOpenQuestionnaire, setHasOpenQuestionnaire] = useState(false);
    const [isEditingDescription, setIsEditingDescription] = useState(false);
    const [localDescriptionMarkdown, setLocalDescriptionMarkdown] = useState(task?.description ?? "");
    const [isSavingDescription, setIsSavingDescription] = useState(false);
    const [isEditingPlan, setIsEditingPlan] = useState(false);
    const [localPlanMarkdown, setLocalPlanMarkdown] = useState(task?.resultData ?? "");
    const [isSavingPlan, setIsSavingPlan] = useState(false);
    const autoOpenedTaskKeyRef = useRef(null);
    const isPlanTask = String(task?.taskType ?? "").toLowerCase() === "plan" ||
        (task?.title ?? "").trim() === "Project Plan";
    const shouldAutoOpenTerminal = task?.executionState === "WaitingForInput" ||
        task?.executionState === "WaitingForToolApproval";
    useEffect(() => {
        if (!canUseAi) {
            setProfiles([]);
            setProfilesError(null);
            return;
        }
        let cancelled = false;
        setProfilesError(null);
        loadAiProfiles()
            .then((loadedProfiles) => {
            if (!cancelled)
                setProfiles(loadedProfiles);
        })
            .catch((error) => {
            if (!cancelled) {
                const message = getAiProfilesErrorMessage(error);
                setProfiles([]);
                setProfilesError(message);
                toast.error(message);
            }
        });
        return () => {
            cancelled = true;
        };
    }, [canUseAi]);
    useEffect(() => {
        if (shouldAutoOpenTerminal) {
            return;
        }
        setShowFullTerminal(false);
    }, [
        effectiveAgentId,
        shouldAutoOpenTerminal,
        summaryState,
        task?.executionState,
        task?.taskId,
    ]);
    // Reset questionnaire state only when switching to a different task/agent.
    // Do NOT reset on summaryState/executionDisplay/etc—those can change while viewing
    // the same task and would overwrite hasOpenQuestionnaire set by onQuestionnaireOpenChange
    // (timing: questionnaire accepted → set true → effect runs → set false).
    useEffect(() => {
        setHasOpenQuestionnaire(false);
    }, [effectiveAgentId, task?.taskId]);
    useEffect(() => {
        if (!isEditingDescription) {
            setLocalDescriptionMarkdown(task?.description ?? "");
        }
    }, [isEditingDescription, task?.description, task?.taskId]);
    useEffect(() => {
        if (!isEditingPlan) {
            setLocalPlanMarkdown(task?.resultData ?? "");
        }
    }, [isEditingPlan, task?.resultData, task?.taskId]);
    useEffect(() => {
        setIsEditingDescription(false);
        setIsSavingDescription(false);
        setIsEditingPlan(false);
        setIsSavingPlan(false);
    }, [task?.taskId]);
    const agentStub = useMemo(() => {
        if (!effectiveAgentId)
            return null;
        return {
            id: effectiveAgentId,
            name: "",
            userId: "",
            updatedDate: task?.updatedAt || new Date().toISOString(),
            status: agentStatus ?? "running",
        };
    }, [effectiveAgentId, agentStatus, task?.updatedAt]);
    const summaryPresentation = getSummaryPresentation(summaryState, stats);
    const hasAttentionTarget = !!task && !!agentStub;
    const isApprovalTask = !!task &&
        normalizeTaskStatus(task.status, task.executionState) === "Review";
    const isTaskDone = !!task && normalizeTaskStatus(task.status, task.executionState) === "Done";
    const summaryPlaceholderMessage = !canUseAi
        ? "AI features are unavailable with the current license."
        : isTaskDone
            ? "This task is complete. Open chat to view the conversation history."
            : undefined;
    const shouldHideSummaryWaitingPlaceholder = !!agentStub && isApprovalTask;
    const shouldCollapseApprovalCommunication = canUseAi && !!agentStub && isApprovalTask && !showFullTerminal;
    const shouldRenderAgentTerminalPanel = canUseAi && !!agentStub && !shouldCollapseApprovalCommunication;
    const shouldShowWorkingTaskSummary = canUseAi &&
        !!task &&
        task.executionState === "Working" &&
        !showFullTerminal;
    const communicationTransitionKey = task
        ? `task-${task.taskId}-${effectiveAgentId ?? "no-agent"}`
        : `summary-${summaryState}`;
    const shouldShowAgentTerminal = canUseAi && hasAttentionTarget;
    const isAgentChatTabActive = !!task && showFullTerminal && shouldShowAgentTerminal;
    const rootClassName = isAgentChatTabActive
        ? "flex h-full min-h-0 flex-col bg-white"
        : "flex h-full min-h-0 flex-col bg-white";
    useEffect(() => {
        const autoOpenKey = task?.taskId
            ? `${task.taskId}:${task.executionState}`
            : null;
        if (!autoOpenKey) {
            autoOpenedTaskKeyRef.current = null;
            return;
        }
        if (!shouldAutoOpenTerminal) {
            autoOpenedTaskKeyRef.current = autoOpenKey;
            return;
        }
        if (autoOpenedTaskKeyRef.current === autoOpenKey) {
            return;
        }
        setShowFullTerminal(true);
        autoOpenedTaskKeyRef.current = autoOpenKey;
    }, [shouldAutoOpenTerminal, task?.executionState, task?.taskId]);
    const unresolvedBlockingDetails = useMemo(() => {
        if (!task) {
            return {
                tasks: [],
                hiddenCount: 0,
            };
        }
        const unresolvedTasks = [];
        const seenTaskIds = new Set();
        let hiddenCount = 0;
        for (const dependency of dependencies) {
            if (dependency.taskId !== task.taskId ||
                dependency.dependencyType !== "BlockedBy") {
                continue;
            }
            const blocker = allTasks.find((candidate) => candidate.taskId === dependency.dependsOnTaskId);
            if (!blocker) {
                hiddenCount += 1;
                continue;
            }
            if (normalizeTaskStatus(blocker.status, blocker.executionState) === "Done") {
                continue;
            }
            if (!seenTaskIds.has(blocker.taskId)) {
                seenTaskIds.add(blocker.taskId);
                unresolvedTasks.push(blocker);
            }
        }
        return {
            tasks: unresolvedTasks,
            hiddenCount,
        };
    }, [allTasks, dependencies, task]);
    const shouldShowBlockingSummary = !!task &&
        !agentStub &&
        (unresolvedBlockingDetails.tasks.length > 0 ||
            unresolvedBlockingDetails.hiddenCount > 0);
    const shouldShowProjectSummary = !task;
    const handleQuestionnaireOpenChange = (isOpen) => {
        setHasOpenQuestionnaire(isOpen);
    };
    const handleSaveDescription = useCallback(async () => {
        if (!task)
            return;
        const trimmed = localDescriptionMarkdown.trim();
        if (trimmed === (task.description ?? "").trim()) {
            setIsEditingDescription(false);
            return;
        }
        setIsSavingDescription(true);
        try {
            const result = await updateTask({
                taskId: task.taskId,
                description: trimmed || undefined,
            });
            if (result.type !== "success") {
                toast.error(result.summary || "Failed to update description");
                return;
            }
            setIsEditingDescription(false);
            await (onContentChanged ?? onTaskChanged)?.();
        }
        finally {
            setIsSavingDescription(false);
        }
    }, [localDescriptionMarkdown, onContentChanged, onTaskChanged, task]);
    const handleCancelDescriptionEdit = useCallback(() => {
        setLocalDescriptionMarkdown(task?.description ?? "");
        setIsEditingDescription(false);
    }, [task?.description]);
    const handleSavePlan = useCallback(async () => {
        if (!task || !isPlanTask)
            return;
        const trimmed = localPlanMarkdown.trim();
        if (trimmed === (task.resultData ?? "").trim()) {
            setIsEditingPlan(false);
            return;
        }
        setIsSavingPlan(true);
        try {
            const result = await updateTask({
                taskId: task.taskId,
                resultData: trimmed || null,
            });
            if (result.type !== "success") {
                toast.error(result.summary || "Failed to update plan");
                return;
            }
            setIsEditingPlan(false);
            await (onContentChanged ?? onTaskChanged)?.();
        }
        finally {
            setIsSavingPlan(false);
        }
    }, [isPlanTask, localPlanMarkdown, onContentChanged, onTaskChanged, task]);
    const handleCancelPlanEdit = useCallback(() => {
        setLocalPlanMarkdown(task?.resultData ?? "");
        setIsEditingPlan(false);
    }, [task?.resultData]);
    const openChatButton = canUseAi && agentStub && !showFullTerminal ? (_jsxs(Button, { type: "button", variant: "outline", size: "sm", className: "h-8 shrink-0 px-2 text-xs", "data-testid": "taskboard-wizard-open-terminal", onClick: () => {
            if (onOpenAgentTab) {
                onOpenAgentTab();
                return;
            }
            setShowFullTerminal(true);
        }, children: [_jsx(TerminalSquare, { className: "mr-1.5 h-3.5 w-3.5" }), "Open chat"] })) : undefined;
    return (_jsx("div", { className: rootClassName, children: _jsxs("div", { className: "animate-view-slide-in flex h-full min-h-0 flex-col bg-white", children: [profilesError ? (_jsx("div", { className: "border-destructive/20 bg-destructive/5 text-destructive border-b px-4 py-2 text-xs", children: profilesError })) : null, task ? (_jsx(WizardTask, { task: task, agentId: agentId, agentStub: agentStub, profiles: profiles, executionDisplay: executionDisplay, canEdit: canEdit, isPlanTask: isPlanTask, isTaskDone: isTaskDone, isEditingDescription: isEditingDescription, localDescriptionMarkdown: localDescriptionMarkdown, isSavingDescription: isSavingDescription, isEditingPlan: isEditingPlan, localPlanMarkdown: localPlanMarkdown, isSavingPlan: isSavingPlan, showFullTerminal: showFullTerminal, hasOpenQuestionnaire: hasOpenQuestionnaire, shouldCollapseApprovalCommunication: shouldCollapseApprovalCommunication, shouldRenderAgentTerminalPanel: shouldRenderAgentTerminalPanel, shouldShowWorkingTaskSummary: shouldShowWorkingTaskSummary, shouldShowAgentTerminal: shouldShowAgentTerminal, shouldShowBlockingSummary: shouldShowBlockingSummary, unresolvedBlockingDetails: unresolvedBlockingDetails, openChatButton: openChatButton, summaryPlaceholderMessage: summaryPlaceholderMessage, hideSummaryWaitingPlaceholder: shouldHideSummaryWaitingPlaceholder, onDescriptionChange: setLocalDescriptionMarkdown, onDescriptionSave: () => void handleSaveDescription(), onDescriptionCancel: handleCancelDescriptionEdit, onPlanEdit: () => setIsEditingPlan(true), onPlanChange: setLocalPlanMarkdown, onPlanSave: () => void handleSavePlan(), onPlanCancel: handleCancelPlanEdit, onShowTerminal: () => setShowFullTerminal(true), onHideTerminal: () => setShowFullTerminal(false), onQuestionnaireOpenChange: handleQuestionnaireOpenChange, onTaskChanged: onTaskChanged, onAttachmentsChanged: onContentChanged, onTaskApproved: onTaskApproved, showApprovedState: showApprovedState, hasNextReviewTask: hasNextReviewTask, onReviewNext: onReviewNext, onInteractionSubmitted: onInteractionSubmitted, onCloseTask: onCloseTask, onSelectTask: onSelectTask })) : (_jsx(_Fragment, { children: shouldShowProjectSummary ? (_jsx("div", { className: "flex min-h-0 flex-1 flex-col", children: summaryState === "complete" ? (_jsx(FinishedProjectCard, { canArchive: canArchiveProject, isArchiving: isArchivingProject, onArchive: onArchiveProject })) : (_jsx("div", { className: "min-h-0 flex-1", children: _jsx(WizardProjectSummaryCard, { summaryState: summaryState, summaryPresentation: summaryPresentation, stats: stats }) })) })) : null }))] }, communicationTransitionKey) }));
}
//# sourceMappingURL=WizardCommunicationCenter.js.map