"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useMemo, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { getUserMessage } from "@stigmer/sdk";
import { ResizableSplit } from "../internal/ResizableSplit";
import { SelectionStore } from "../internal/store/selection-store";
import { ThreadSelectionContext } from "../execution/ThreadSelectionContext";
import { useSelectedThreadItem } from "../execution/useThreadSelection";
import { MessageThread } from "../execution/MessageThread";
import { ThreadSkeleton } from "../execution/ThreadSkeleton";
import { SessionComposer } from "../composer";
import { SecretFlowErrorGuide, isSecretFlowError } from "../error";
import { useSessionPageFlow } from "./useSessionPageFlow";
import { SessionInspector } from "./inspector/SessionInspector";
/**
 * Full-featured agent session viewer — the graph-less analog of
 * `WorkflowExecutionViewer`.
 *
 * Owns `useSessionPageFlow` internally and composes:
 * - **Conversation column** (primary): `MessageThread` + error
 *   banners + `SessionComposer`
 * - **SessionInspector** (secondary): tabbed panel with Plan,
 *   Changes, Artifacts, Usage, and Inspect facets
 *
 * Connected via `ResizableSplit` with persisted width.
 *
 * Thread selection is provided via `ThreadSelectionContext` (Phase 2
 * opt-in) for render-isolated per-item selection.
 *
 * Framework-agnostic — no Next.js, no Tauri, no routing deps. Host
 * apps inject platform-specific values via props (DD-004/DD-016).
 *
 * @example
 * ```tsx
 * // Web (cloud execution)
 * <SessionViewer
 *   sessionId={id}
 *   org={org}
 *   gitHubConnection={gitHubConnection}
 *   enableGitHub
 *   headerActions={<ShareButton sessionId={id} />}
 * />
 *
 * // Desktop (local execution with native picker)
 * <SessionViewer
 *   sessionId={id}
 *   org={org}
 *   enableLocal
 *   onBrowseLocalFolder={browseLocalFolder}
 *   headerActions={<ShareButton sessionId={id} />}
 * />
 * ```
 */
export function SessionViewer({ sessionId, org, gitHubConnection, enableGitHub = true, enableLocal = false, onBrowseLocalFolder, workspaceFileLister, headerActions, onApplied, className, }) {
    const flow = useSessionPageFlow({ sessionId, org });
    const { conv } = flow;
    const [modelId, setModelId] = flow.model;
    const [interactionMode, setInteractionMode] = useState("agent");
    const composerRef = useRef(null);
    const selectionStoreRef = useRef(null);
    if (!selectionStoreRef.current) {
        selectionStoreRef.current = new SelectionStore();
    }
    const selectionStore = selectionStoreRef.current;
    const handleBuildFromPlan = useCallback(() => {
        setInteractionMode("agent");
        // Reference the plan explicitly (it is also published as plan.md) and direct
        // the agent to act on it, rather than a bare "implement" that relies on the
        // model re-reading its own prior message.
        composerRef.current?.setMessage("Implement the plan above (saved as plan.md). Follow it step by step and make the changes it describes.");
        composerRef.current?.focus();
    }, []);
    if (conv.isLoading) {
        return (_jsx("div", { className: cn("flex h-full w-full flex-col", className), children: _jsx(ThreadSkeleton, { className: "flex-1 px-0" }) }));
    }
    if (conv.loadError) {
        return _jsx(SessionLoadError, { error: conv.loadError });
    }
    if (!conv.session && !conv.isLoading) {
        return _jsx(SessionStarting, {});
    }
    return (_jsxs("div", { className: cn("relative flex h-full w-full flex-col", className), children: [headerActions && (_jsx("div", { className: "absolute top-2 right-6 z-10", children: headerActions })), _jsx(ThreadSelectionContext.Provider, { value: selectionStore, children: _jsx(ResizableSplit, { defaultSize: 384, minSize: 280, maxSize: 600, storageKey: "stgm-session-inspector-width", className: cn("min-h-0 flex-1", "[&>*:nth-child(2)]:max-lg:hidden [&>*:nth-child(3)]:max-lg:hidden"), primary: _jsx(ConversationColumn, { flow: flow, modelId: modelId, setModelId: setModelId, interactionMode: interactionMode, setInteractionMode: setInteractionMode, composerRef: composerRef, org: org, gitHubConnection: gitHubConnection, enableGitHub: enableGitHub, enableLocal: enableLocal, onBrowseLocalFolder: onBrowseLocalFolder, onBuildFromPlan: handleBuildFromPlan }), secondary: _jsx(InspectorPanel, { flow: flow, org: org, selectionStore: selectionStore, onApplied: onApplied, enableGitHub: enableGitHub, enableLocal: enableLocal, gitHubConnection: gitHubConnection, onBrowseLocalFolder: onBrowseLocalFolder, workspaceFileLister: workspaceFileLister }) }) })] }));
}
function ConversationColumn({ flow, modelId, setModelId, interactionMode, setInteractionMode, composerRef, org, gitHubConnection, enableGitHub, enableLocal, onBrowseLocalFolder, onBuildFromPlan, }) {
    const { conv } = flow;
    return (_jsxs("div", { className: "flex h-full min-w-0 flex-col", children: [_jsx(MessageThread, { executions: conv.completedExecutions, activeStreamExecution: conv.activeStreamExecution, pendingUserMessage: conv.pendingUserMessage, onApprovalSubmit: flow.submitApproval, submittingApprovalIds: conv.submittingApprovalIds, workspaceEntries: conv.workspaceEntries, sandboxWorkspaceRoot: flow.sandboxWorkspaceRoot, onBuildFromPlan: onBuildFromPlan, centerContent: true, className: "flex-1" }), _jsxs("div", { className: "mx-auto w-full max-w-3xl", children: [conv.streamError && (_jsx(StreamErrorBanner, { error: conv.streamError, onReconnect: conv.reconnectStream })), (conv.sendError || conv.approvalError) && (_jsx(SendErrorBanner, { error: (conv.sendError ?? conv.approvalError) })), flow.autoApproveAll && (_jsx(AutoApproveIndicator, { onTurnOff: () => flow.setAutoApproveAll(false) })), _jsx(SessionComposer, { ref: composerRef, onSubmit: flow.handleSubmit, isSubmitting: conv.isSending, disabled: !conv.canSendFollowUp, org: org, harness: flow.harness, defaultModelId: modelId, onModelChange: setModelId, interactionMode: interactionMode, onInteractionModeChange: setInteractionMode, showInteractionModePicker: true, workspace: flow.workspace, gitHubConnection: gitHubConnection, enableGitHub: enableGitHub, enableLocal: enableLocal, onBrowseLocalFolder: onBrowseLocalFolder, agentRef: flow.agentRef, onAgentRefChange: flow.setAgentRef, onAgentResolutionChange: flow.setResolution, isDefaultAgent: flow.isDefaultAgent, mcpServerUsages: flow.mcpServerUsages, onMcpServerUsagesChange: flow.setMcpServerUsages, skillRefs: flow.skillRefs, onSkillRefsChange: flow.setSkillRefs, sessionVariables: flow.sessionVariables, className: "px-4 py-3" })] })] }));
}
function InspectorPanel({ flow, org, selectionStore, onApplied, enableGitHub, enableLocal, gitHubConnection, onBrowseLocalFolder, workspaceFileLister, }) {
    const selectedItem = useSelectedThreadItem();
    const handleRemoveAgent = useCallback(() => {
        flow.setAgentRef(null);
        flow.setResolution(null);
    }, [flow.setAgentRef, flow.setResolution]);
    const handleRemoveMcp = useCallback((ref) => {
        flow.setMcpServerUsages(flow.mcpServerUsages.filter((u) => !(u.mcpServerRef.org === ref.org && u.mcpServerRef.slug === ref.slug)));
    }, [flow.mcpServerUsages, flow.setMcpServerUsages]);
    const handleRemoveSkill = useCallback((ref) => {
        flow.setSkillRefs(flow.skillRefs.filter((r) => !(r.org === ref.org && r.slug === ref.slug)));
    }, [flow.skillRefs, flow.setSkillRefs]);
    const sessionConfig = useMemo(() => ({
        agentRef: flow.agentRef,
        isDefaultAgent: flow.isDefaultAgent,
        mcpServerUsages: flow.mcpServerUsages,
        skillRefs: flow.skillRefs,
        sessionVariables: flow.sessionVariables,
        harness: flow.harness,
        executionTarget: flow.executionTarget,
        modelId: flow.model[0],
        mutations: {
            onRemoveAgent: flow.isDefaultAgent ? undefined : handleRemoveAgent,
            onRemoveMcp: handleRemoveMcp,
            onRemoveSkill: handleRemoveSkill,
        },
    }), [
        flow.agentRef, flow.isDefaultAgent, flow.mcpServerUsages, flow.skillRefs,
        flow.sessionVariables, flow.harness, flow.executionTarget, flow.model,
        handleRemoveAgent, handleRemoveMcp, handleRemoveSkill,
    ]);
    const workspaceConfig = useMemo(() => ({
        actions: {
            workspace: flow.workspace,
            enableGitHub,
            enableLocal,
            gitHubConnection,
            onBrowseLocalFolder,
            workspaceFileLister,
        },
    }), [flow.workspace, enableGitHub, enableLocal, gitHubConnection, onBrowseLocalFolder, workspaceFileLister]);
    return (_jsx("aside", { className: "flex h-full flex-col overflow-hidden", children: _jsx(SessionInspector, { displayExecution: flow.displayExecution, allExecutions: flow.allExecutions, org: org, selectedItem: selectedItem, onApplied: onApplied, sessionConfig: sessionConfig, workspaceConfig: workspaceConfig, className: "min-h-0 flex-1" }) }));
}
// ---------------------------------------------------------------------------
// Local sub-components (error states)
// ---------------------------------------------------------------------------
function SessionLoadError({ error }) {
    return (_jsx("div", { className: "flex min-h-[60vh] flex-col items-center justify-center px-4", children: _jsxs("div", { className: "w-full max-w-sm space-y-6 text-center", children: [_jsx("div", { className: "mx-auto flex size-12 items-center justify-center rounded-full bg-destructive-subtle", children: _jsx(ErrorTriangleIcon, {}) }), _jsxs("div", { className: "space-y-2", children: [_jsx("h1", { className: "text-lg font-semibold", children: "Failed to load session" }), _jsx("p", { className: "text-sm text-muted-foreground", children: getUserMessage(error) })] }), _jsx("button", { type: "button", onClick: () => window.location.reload(), className: "inline-flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-1.5 text-sm font-medium hover:bg-muted", children: "Try again" })] }) }));
}
function SessionStarting() {
    return (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsxs("div", { className: "space-y-2 text-center", children: [_jsx(LoaderIcon, {}), _jsx("p", { className: "text-sm text-muted-foreground", children: "Starting session\u2026" })] }) }));
}
/**
 * Low-weight, always-visible indicator shown while the session-scoped
 * auto-approve preference is active. The "Turn off" control reverts the
 * preference in one click — the safety affordance for "Approve & don't ask
 * again". Nothing about approvals appears until the user opts in at a gate.
 */
function AutoApproveIndicator({ onTurnOff }) {
    return (_jsxs("div", { role: "status", className: "flex items-center gap-2 border-t border-border-muted px-4 py-1.5 text-xs text-muted-foreground", children: [_jsx(ShieldCheckIcon, {}), _jsx("span", { className: "min-w-0 flex-1 truncate", children: "Auto-approving tool calls for this session" }), _jsx("button", { type: "button", onClick: onTurnOff, className: "shrink-0 rounded font-medium text-foreground underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", children: "Turn off" })] }));
}
function SendErrorBanner({ error }) {
    if (isSecretFlowError(error)) {
        return _jsx(SecretFlowErrorGuide, { error: error, className: "mx-4 my-2" });
    }
    return (_jsx("div", { role: "alert", className: "border-t border-border px-4 py-2 text-xs text-destructive", children: getUserMessage(error) }));
}
function StreamErrorBanner({ error, onReconnect, }) {
    return (_jsxs("div", { role: "alert", className: "flex items-center gap-3 border-t border-border bg-muted px-4 py-2.5", children: [_jsx("p", { className: "min-w-0 flex-1 truncate text-sm text-muted-foreground", children: getUserMessage(error) }), _jsx("button", { type: "button", onClick: onReconnect, className: "inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs font-medium hover:bg-card", children: "Reconnect" })] }));
}
// ---------------------------------------------------------------------------
// Inline SVG icons (SDK independence — no lucide dependency)
// ---------------------------------------------------------------------------
function ErrorTriangleIcon() {
    return (_jsxs("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", className: "text-destructive", children: [_jsx("path", { d: "M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" }), _jsx("line", { x1: "12", y1: "9", x2: "12", y2: "13" }), _jsx("line", { x1: "12", y1: "17", x2: "12.01", y2: "17" })] }));
}
function LoaderIcon() {
    return (_jsx("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: "2", className: "mx-auto animate-spin text-muted-foreground", children: _jsx("path", { d: "M10 2a8 8 0 0 1 0 16", strokeLinecap: "round" }) }));
}
function ShieldCheckIcon() {
    return (_jsxs("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", className: "shrink-0 text-success", "aria-hidden": "true", children: [_jsx("path", { d: "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" }), _jsx("path", { d: "m9 12 2 2 4-4" })] }));
}
//# sourceMappingURL=SessionViewer.js.map