"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useMemo, useState } from "react";
import { cn } from "@stigmer/theme";
import { SessionComposer } from "../composer/index.js";
import { ResizableSplit } from "../internal/ResizableSplit.js";
import { useWorkspaceEditors } from "../internal/store/index.js";
import { WorkspaceSurface } from "../workspace/WorkspaceSurface.js";
import { useNewSessionFlow } from "./useNewSessionFlow.js";
import { useSessionPanel } from "./useSessionPanel.js";
import { useSessionRailViews } from "./useSessionRailViews.js";
import { SessionPanelChip } from "./SessionPanelChip.js";
/**
 * Full-featured new-session launcher organism — the pre-session analog
 * of `SessionViewer`.
 *
 * Owns `useNewSessionFlow` internally and composes:
 * - **Centered composer** (primary pane): `SessionComposer` with all
 *   context pickers (agent, workspace, MCP servers, skills)
 * - **Session panel** (secondary pane): the unified `WorkspaceSurface` with a
 *   Config rail view — collapsed by default behind a persistent top-right chip
 *   and homing on the Config facet when opened. Same layout model as
 *   `SessionViewer` (DD-016).
 *
 * Framework-agnostic — no Next.js, no Tauri, no routing deps. Host
 * apps inject platform-specific values via props (DD-004/DD-016).
 *
 * @example
 * ```tsx
 * // Desktop
 * <NewSessionViewer
 *   org={org}
 *   onSessionCreated={(id) => navigate(`/sessions/${id}`)}
 *   onError={(msg) => toast.error(msg)}
 *   enableLocal
 *   onBrowseLocalFolder={browseLocalFolder}
 * />
 *
 * // Web
 * <NewSessionViewer
 *   org={org}
 *   onSessionCreated={navigateToSession}
 *   onError={(msg) => toast.error(msg)}
 *   enableGitHub
 *   gitHubConnection={gitHubConnection}
 * />
 * ```
 */
export function NewSessionViewer({ org, onSessionCreated, onError, gitHubConnection, enableGitHub = true, enableLocal = false, onBrowseLocalFolder, workspaceFileLister, workspaceFileReader, workspaceContentSearcher, getRuntimeEnv, audience = "integrator", defaultHarness, initialAgentRef, initialInstanceId, initialAttachments, heading = "What would you like to work on?", placeholder = "Describe what you need help with\u2026", initialRows = 3, autoFocus = true, footerContent, className, }) {
    const flow = useNewSessionFlow({
        org,
        onSessionCreated,
        onError,
        getRuntimeEnv,
        defaultHarness,
    });
    const [interactionMode, setInteractionMode] = useState("agent");
    const isEndUser = audience === "endUser";
    // The unified-panel controller (shared with SessionViewer, DD-016). The
    // launcher has no execution yet, so the FSM inputs are static. It has no
    // streaming column to isolate either, so subscribing to the editor group in
    // the body is harmless — unlike `SessionViewer`, which subscribes one level
    // down. Homes on Config: pre-session the Explorer is empty, while Config
    // carries the run defaults (harness/model) worth seeing before starting.
    const panel = useSessionPanel({
        phase: null,
        hasChanges: false,
        defaultView: "configure",
    });
    const { editors, activeKey, activeFile, reveal } = useWorkspaceEditors(panel.editorsStore);
    // Honor a jump-to-line reveal only while it targets the active editor
    // (DD-016 parity with SessionViewer).
    const activeReveal = reveal && reveal.key === activeKey ? reveal : undefined;
    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: false,
        mcpServerUsages: flow.mcpServerUsages,
        skillRefs: flow.skillRefs,
        sessionVariables: flow.sessionVariables,
        harness: flow.harness,
        executionTarget: undefined,
        modelId: flow.modelId,
        // End users see the configuration but cannot strip it — the Setup
        // tab renders read-only without mutation callbacks (DD-011).
        mutations: isEndUser
            ? undefined
            : {
                onRemoveAgent: flow.agentRef ? handleRemoveAgent : undefined,
                onRemoveMcp: handleRemoveMcp,
                onRemoveSkill: handleRemoveSkill,
            },
    }), [
        flow.agentRef, flow.mcpServerUsages, flow.skillRefs,
        flow.sessionVariables, flow.harness, flow.modelId,
        isEndUser, handleRemoveAgent, handleRemoveMcp, handleRemoveSkill,
    ]);
    // Launcher facets: Config only — no executions exist yet, so the
    // execution-derived facets (Changes/Artifacts/Usage) don't apply.
    const railViews = useSessionRailViews({
        allExecutions: [],
        org,
        sessionConfig,
        selectedItem: null,
        includeExecutionFacets: false,
    });
    // Explorer-footer folder attach (desktop only — needs the native picker).
    const canAddLocalFolder = enableLocal && !!onBrowseLocalFolder;
    const handleAddLocalFolder = useCallback(async () => {
        const path = await onBrowseLocalFolder?.();
        if (path)
            flow.workspace.addLocalPath(path);
    }, [onBrowseLocalFolder, flow.workspace.addLocalPath]);
    const composerNode = (
    // `my-auto` centers the composer vertically whether or not context is
    // attached — safe-centering, not a special case: auto margins absorb free
    // space when the composer is shorter than the pane and collapse to zero
    // when it outgrows it, degrading to a normal top-aligned scroll. The
    // scroll container's `py-6` keeps breathing room in that overflow case.
    // Do NOT reintroduce a context-driven position flip: the composer must not
    // move as context is attached (DD-16's layout-stability rationale — chrome
    // that shifts with attached context reads as instability).
    _jsx("div", { className: "flex h-full flex-col items-center overflow-y-auto px-4 py-6", children: _jsxs("div", { className: "my-auto w-full max-w-2xl space-y-6", children: [_jsx("h1", { className: "text-center text-lg font-medium text-foreground", children: heading }), _jsx(SessionComposer, { onSubmit: flow.submit, isSubmitting: flow.isSubmitting, org: org, workspace: flow.workspace, gitHubConnection: enableGitHub ? gitHubConnection : undefined, enableGitHub: enableGitHub, enableLocal: enableLocal, onBrowseLocalFolder: onBrowseLocalFolder, agentRef: flow.agentRef, onAgentRefChange: flow.setAgentRef, onAgentResolutionChange: flow.setResolution, initialAgentRef: initialAgentRef, initialInstanceId: initialInstanceId, initialAttachments: initialAttachments, lockAgent: isEndUser && initialAgentRef != null, mcpServerUsages: isEndUser ? undefined : flow.mcpServerUsages, onMcpServerUsagesChange: isEndUser ? undefined : flow.setMcpServerUsages, skillRefs: isEndUser ? undefined : flow.skillRefs, onSkillRefsChange: isEndUser ? undefined : flow.setSkillRefs, sessionVariables: isEndUser ? undefined : flow.sessionVariables, showHarnessSelector: true, harness: flow.harness, onHarnessChange: flow.setHarness, interactionMode: interactionMode, onInteractionModeChange: setInteractionMode, showInteractionModePicker: true, defaultModelId: flow.modelId, onModelChange: flow.setModelId, placeholder: placeholder, initialRows: initialRows, autoFocus: autoFocus, ariaLabel: "Start a new session" }), footerContent, _jsx("p", { className: "text-center text-[0.65rem] text-muted-foreground", children: "Press Enter to send, Shift+Enter for a new line" })] }) }));
    return (_jsxs("div", { className: cn("relative flex h-full w-full flex-col", className), children: [_jsx("div", { className: "absolute top-2 right-6 z-10", children: _jsx(SessionPanelChip, { isOpen: panel.isOpen, onToggle: panel.isOpen ? panel.closePanel : panel.openPanel }) }), _jsx(ResizableSplit, { resizablePane: "primary", collapsedPane: panel.isOpen ? "none" : "secondary", defaultSize: 420, minSize: 320, maxSize: 640, storageKey: "stgm-new-session-chat-width", responsiveCollapse: panel.isOpen ? "primary" : "none", ariaLabel: "Resize composer panel", className: "min-h-0 flex-1", primary: composerNode, secondary: panel.isOpen ? (_jsx(WorkspaceSurface, { entries: flow.workspace.entries, lister: workspaceFileLister, reader: workspaceFileReader, searcher: workspaceContentSearcher, view: panel.view, onViewChange: panel.setView, extraViews: railViews, onRemoveEntry: flow.workspace.remove, onAddLocalFolder: canAddLocalFolder ? handleAddLocalFolder : undefined, editors: editors, selectedFile: activeFile, onOpenFile: panel.openFile, onActivateEditor: panel.activateEditor, onPinEditor: panel.pinEditor, onCloseEditor: panel.closeEditor, onCollapse: panel.closePanel, reveal: activeReveal, className: "h-full" })) : null })] }));
}
//# sourceMappingURL=NewSessionViewer.js.map