"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useRef, useState } from "react";
import { cn } from "@stigmer/theme";
import { useRefineWorkflowFlow } from "./useRefineWorkflowFlow";
import { MessageThread } from "../execution/MessageThread";
import { computeUnifiedDiff } from "./workflow-yaml-diff";
import { WorkflowDiffGraph } from "./WorkflowDiffGraph";
const COMPOSER_ENABLED_PHASES = new Set([
    "idle",
    "ready",
    "complete",
    "error",
]);
/**
 * Side panel for agent-powered iterative workflow refinement.
 *
 * Renders inside the editor's right pane (replacing the topology graph
 * in code mode, or as a sidebar in visual mode). Layout:
 *
 * 1. **Header** — title + close button
 * 2. **MessageThread** — streaming agent conversation (all turns)
 * 3. **Result strip** — diff preview + accept/discard (when YAML extracted)
 * 4. **Composer** — textarea + send button (pinned to bottom)
 *
 * Powered by the Workflow Architect system agent via
 * {@link useRefineWorkflowFlow}. Styled via `--stgm-*` design tokens.
 * Zero console dependencies (DD-004).
 */
export function WorkflowRefinePanel({ org, currentYaml, onAccept, onClose, initialInstruction, className, }) {
    const [instruction, setInstruction] = useState("");
    const scrollRef = useRef(null);
    const didAutoSendRef = useRef(false);
    const flow = useRefineWorkflowFlow({
        org,
        currentYaml,
        onError: () => {
            /* Error is displayed inline via flow.error */
        },
    });
    // Auto-send initial instruction (e.g. from "Fix with AI")
    const { sendInstruction: flowSendInstruction, phase } = flow;
    if (initialInstruction && !didAutoSendRef.current && phase === "idle") {
        didAutoSendRef.current = true;
        // Schedule the send after the current render cycle
        Promise.resolve().then(() => flowSendInstruction(initialInstruction));
    }
    const composerEnabled = COMPOSER_ENABLED_PHASES.has(flow.phase);
    const hasConversation = flow.completedExecutions.length > 0 || flow.activeExecution !== null;
    // -------------------------------------------------------------------------
    // Handlers
    // -------------------------------------------------------------------------
    const handleSend = useCallback(async () => {
        const trimmed = instruction.trim();
        if (trimmed.length < 5)
            return;
        setInstruction("");
        await flow.sendInstruction(trimmed);
        requestAnimationFrame(() => {
            scrollRef.current?.scrollTo({
                top: scrollRef.current.scrollHeight,
                behavior: "smooth",
            });
        });
    }, [flow.sendInstruction, instruction]);
    const handleAccept = useCallback(() => {
        const yaml = flow.acceptResult();
        if (yaml) {
            onAccept(yaml);
        }
    }, [flow.acceptResult, onAccept]);
    const handleDiscard = useCallback(() => {
        flow.discardResult();
    }, [flow.discardResult]);
    const handleKeyDown = useCallback((e) => {
        if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
            e.preventDefault();
            handleSend();
        }
    }, [handleSend]);
    // -------------------------------------------------------------------------
    // Render
    // -------------------------------------------------------------------------
    return (_jsxs("div", { className: cn("flex h-full flex-col border-l border-border bg-background", className), role: "complementary", "aria-label": "Workflow refinement panel", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-border px-3 py-2", children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(SparklesIcon, {}), _jsx("h3", { className: "text-xs font-semibold text-foreground", children: "Refine with AI" }), flow.isStreaming && (_jsxs("span", { className: "inline-flex items-center gap-1 text-[0.65rem] text-muted-foreground", children: [_jsx(SpinnerIcon, { size: 10 }), "Working\u2026"] }))] }), _jsx("button", { type: "button", onClick: onClose, className: "rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground", "aria-label": "Close refinement panel", children: _jsx(CloseIcon, {}) })] }), _jsxs("div", { ref: scrollRef, className: "flex min-h-0 flex-1 flex-col overflow-y-auto", children: [!hasConversation && flow.phase === "idle" && (_jsxs("div", { className: "flex flex-1 flex-col items-center justify-center gap-2 px-4 py-8 text-center", children: [_jsx(SparklesIcon, {}), _jsx("p", { className: "text-xs text-muted-foreground", children: "Describe the changes you want and the Workflow Architect agent will refine your workflow definition." })] })), flow.phase === "starting" && (_jsxs("div", { className: "flex flex-col items-center justify-center gap-2 py-8", children: [_jsx(SpinnerIcon, {}), _jsx("p", { className: "text-xs text-muted-foreground", children: "Starting Workflow Architect\u2026" })] })), hasConversation && (_jsx(MessageThread, { executions: flow.completedExecutions, activeStreamExecution: flow.activeExecution, pendingUserMessage: flow.phase === "starting" ? instruction || undefined : undefined, className: "flex-1" })), flow.error && flow.phase === "error" && (_jsx("div", { className: "mx-3 mt-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive", role: "alert", children: flow.error }))] }), flow.phase === "complete" && flow.extractedYaml && (_jsx(ResultStrip, { extractedYaml: flow.extractedYaml, explanation: flow.explanation, beforeYaml: currentYaml, onAccept: handleAccept, onDiscard: handleDiscard })), _jsxs("div", { className: "border-t border-border p-3", children: [_jsx("textarea", { value: instruction, onChange: (e) => setInstruction(e.target.value), onKeyDown: handleKeyDown, placeholder: "What would you like to change?", disabled: !composerEnabled, rows: 3, className: cn("w-full resize-none rounded-md border border-input bg-background px-2.5 py-1.5 text-sm text-foreground", "placeholder:text-muted-foreground", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-50") }), _jsxs("div", { className: "mt-2 flex items-center justify-between", children: [_jsxs("p", { className: "text-[0.65rem] text-muted-foreground", children: ["\u2318", "+Enter to submit"] }), _jsx("button", { type: "button", onClick: handleSend, disabled: !composerEnabled || instruction.trim().length < 5, className: cn("inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors", "bg-primary text-primary-foreground hover:bg-primary/90", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "disabled:pointer-events-none disabled:opacity-40"), children: "Send" })] })] })] }));
}
// ---------------------------------------------------------------------------
// Result Strip — diff preview with accept/discard actions
// ---------------------------------------------------------------------------
function ResultStrip({ extractedYaml, explanation, beforeYaml, onAccept, onDiscard, }) {
    const [showYamlDiff, setShowYamlDiff] = useState(false);
    const diffLines = computeUnifiedDiff(beforeYaml, extractedYaml);
    const hasChanges = diffLines.some((l) => l.type !== "equal");
    return (_jsxs("div", { className: "border-t border-border px-3 py-3", "aria-live": "polite", children: [explanation && (_jsxs("div", { className: "mb-3", children: [_jsx("h4", { className: "mb-1 text-[0.65rem] font-medium uppercase tracking-wider text-muted-foreground", children: "Changes" }), _jsx("p", { className: "text-xs leading-relaxed text-foreground", children: explanation })] })), hasChanges && (_jsx("div", { className: "mb-3", children: _jsx("div", { className: "h-[200px] overflow-hidden rounded-md border border-border", children: _jsx(WorkflowDiffGraph, { beforeYaml: beforeYaml, afterYaml: extractedYaml }) }) })), hasChanges && (_jsxs("div", { className: "mb-3", children: [_jsx("button", { type: "button", onClick: () => setShowYamlDiff((v) => !v), className: "text-[0.65rem] font-medium text-muted-foreground hover:text-foreground", children: showYamlDiff ? "▾ Hide YAML diff" : "▸ View YAML diff" }), showYamlDiff && (_jsx("div", { className: "mt-1", children: _jsx(DiffPreview, { lines: diffLines }) }))] })), _jsxs("div", { className: "flex gap-2", children: [_jsx("button", { type: "button", onClick: onAccept, className: cn("flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors", "bg-primary text-primary-foreground hover:bg-primary/90", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Accept" }), _jsx("button", { type: "button", onClick: onDiscard, className: cn("flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors", "border border-input bg-background text-foreground", "hover:bg-accent hover:text-accent-foreground", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"), children: "Discard" })] })] }));
}
// ---------------------------------------------------------------------------
// Diff Preview
// ---------------------------------------------------------------------------
function DiffPreview({ lines }) {
    const filteredLines = lines.filter((l) => l.type !== "equal" || l.content.trim() !== "");
    if (filteredLines.length > 200) {
        return (_jsx("p", { className: "text-[0.7rem] text-muted-foreground", children: "Diff is too large to display. Accept to see the updated YAML." }));
    }
    return (_jsx("pre", { className: "max-h-60 overflow-auto rounded-md border border-border text-[0.7rem] leading-relaxed", children: lines.map((line, i) => (_jsxs("div", { className: cn("px-2", line.type === "added" && "bg-success/10 text-success", line.type === "removed" && "bg-destructive/10 text-destructive", line.type === "equal" && "text-muted-foreground"), children: [_jsx("span", { className: "mr-2 inline-block w-3 select-none text-right opacity-60", children: line.type === "added" ? "+" : line.type === "removed" ? "-" : " " }), line.content] }, i))) }));
}
// ---------------------------------------------------------------------------
// Icons
// ---------------------------------------------------------------------------
function SparklesIcon() {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M8 2l1.5 4.5L14 8l-4.5 1.5L8 14l-1.5-4.5L2 8l4.5-1.5z" }) }));
}
function CloseIcon() {
    return (_jsx("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M4 4l8 8M12 4l-8 8" }) }));
}
function SpinnerIcon({ size = 14 }) {
    return (_jsx("svg", { width: size, height: size, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", className: "animate-spin", "aria-hidden": "true", children: _jsx("path", { d: "M8 2a6 6 0 1 0 6 6" }) }));
}
//# sourceMappingURL=WorkflowRefinePanel.js.map