import { useStudio as e } from "../providers/StudioProvider.js";
import { useFilterWorkflows as t, useWorkflow as n, useWorkflowConfigByName as r } from "../hooks/useWorkflows.js";
import { Button as i } from "../components/ui/button.js";
import a from "../components/feedback/LoadingCentered.js";
import o from "../components/feedback/ErrorSnackbar.js";
import { require_enums as s } from "../packages/contracts/dist/enums/index.js";
import c from "../features/workbench/WorkflowItem.js";
import { ReactFlowProvider as l } from "../node_modules/@xyflow/react/dist/esm/index.js";
import u from "../features/debug/components/WorkflowFlowViewer.js";
import "../features/debug/index.js";
import d from "../features/workbench/components/WorkflowHistoryList.js";
import { NewRunDialog as f } from "../features/workbench/components/NewRunDialog.js";
import "../features/workbench/index.js";
import { useCallback as p, useEffect as m, useMemo as h, useRef as g, useState as _ } from "react";
import { jsx as v, jsxs as y } from "react/jsx-runtime";
import { useQuery as b } from "@tanstack/react-query";
import { useNavigate as x, useParams as S } from "react-router-dom";
import { ChevronDown as C, ListOrdered as w, Loader2 as T, Play as E, RefreshCw as D, ScrollText as O, Workflow as k } from "lucide-react";
import { formatDistanceToNow as A } from "date-fns";
//#region src/pages/PreviewWorkbenchPage.tsx
var j = s(), M = "loopstack:embed:workflow-completed", N = "loopstack:embed:resize", P = "loopstack:embed:new-run";
function F() {
	let { workflowId: e } = S(), [t, n] = _(!1), r = p((e) => {
		n(!1), window.parent !== window && window.parent.postMessage({
			type: P,
			workflowId: e
		}, window.location.origin);
	}, []);
	return e ? /* @__PURE__ */ v(I, {
		workflowId: e,
		onNewRunSuccess: r
	}) : /* @__PURE__ */ v(R, {
		newRunDialogOpen: t,
		onNewRunDialogOpenChange: n,
		onNewRunSuccess: r
	});
}
function I({ workflowId: e, onNewRunSuccess: t }) {
	let s = g(null), [h, b] = _("output"), [x, S] = _(!1), C = n(e), T = g(!1), D = r(C.data?.className ?? void 0);
	m(() => {
		!C.data || T.current || C.data.status === j.WorkflowState.Completed && window.parent !== window && (T.current = !0, window.parent.postMessage({
			type: M,
			workflowId: e
		}, window.location.origin));
	}, [C.data, e]), m(() => {
		if (window.parent === window || !s.current) return;
		let t = new ResizeObserver(() => {
			if (!s.current) return;
			let t = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);
			window.parent.postMessage({
				type: N,
				workflowId: e,
				height: t
			}, window.location.origin);
		});
		return t.observe(s.current), () => t.disconnect();
	}, [e]);
	let A = p((e) => {
		S(!1), t(e);
	}, [t]);
	return /* @__PURE__ */ y("div", {
		ref: s,
		className: "flex h-screen flex-col overflow-hidden",
		children: [
			/* @__PURE__ */ y("div", {
				className: "bg-muted/50 flex h-11 shrink-0 items-center justify-between border-b px-3",
				children: [/* @__PURE__ */ v("div", {
					className: "bg-background flex items-center rounded-md border p-0.5",
					children: [
						{
							value: "output",
							label: "Output",
							icon: /* @__PURE__ */ v(O, { className: "h-3.5 w-3.5" })
						},
						{
							value: "graph",
							label: "Graph",
							icon: /* @__PURE__ */ v(k, { className: "h-3.5 w-3.5" })
						},
						{
							value: "run-log",
							label: "Run Log",
							icon: /* @__PURE__ */ v(w, { className: "h-3.5 w-3.5" })
						},
						{
							value: "logs",
							label: "Logs",
							icon: /* @__PURE__ */ v(O, { className: "h-3.5 w-3.5" })
						}
					].map((e) => /* @__PURE__ */ y("button", {
						onClick: () => b(e.value),
						className: `flex items-center gap-1.5 rounded-sm px-2.5 py-1 text-xs font-medium transition-colors ${h === e.value ? "bg-foreground text-background shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
						children: [e.icon, e.label]
					}, e.value))
				}), /* @__PURE__ */ y(i, {
					variant: "outline",
					size: "sm",
					className: "h-7 gap-1.5",
					onClick: () => S(!0),
					children: [/* @__PURE__ */ v(E, { className: "h-3 w-3" }), "New Run"]
				})]
			}),
			/* @__PURE__ */ y("div", {
				className: "flex-1 overflow-auto",
				children: [
					/* @__PURE__ */ v(o, { error: C.error }),
					h === "output" && /* @__PURE__ */ v("div", {
						className: "px-4 py-3",
						children: /* @__PURE__ */ v(a, {
							loading: C.isLoading,
							children: C.data ? /* @__PURE__ */ v(c, {
								workflow: C.data,
								workflowId: C.data.id,
								scrollTo: () => {},
								settings: {
									enableDebugMode: !1,
									showFullMessageHistory: !1
								}
							}) : null
						})
					}),
					h === "graph" && /* @__PURE__ */ v("div", {
						className: "h-full",
						children: /* @__PURE__ */ v(a, {
							loading: C.isLoading,
							children: C.data ? /* @__PURE__ */ v(l, { children: /* @__PURE__ */ v(u, {
								workflowId: e,
								workflows: [C.data],
								workflowConfig: D.data,
								direction: "TB"
							}) }) : /* @__PURE__ */ v("div", {
								className: "text-muted-foreground flex h-full items-center justify-center",
								children: /* @__PURE__ */ v("p", {
									className: "text-sm",
									children: "No workflows found"
								})
							})
						})
					}),
					h === "run-log" && /* @__PURE__ */ v("div", {
						className: "px-4",
						children: /* @__PURE__ */ v(d, { workflow: C.data })
					}),
					h === "logs" && /* @__PURE__ */ v(H, {})
				]
			}),
			/* @__PURE__ */ v(f, {
				open: x,
				onOpenChange: S,
				onSuccess: A
			})
		]
	});
}
var L = {
	completed: "bg-green-500",
	running: "bg-blue-500",
	failed: "bg-red-500",
	paused: "bg-yellow-500",
	canceled: "bg-orange-500",
	pending: "bg-muted-foreground"
};
function R({ newRunDialogOpen: n, onNewRunDialogOpenChange: r, onNewRunSuccess: a }) {
	let o = x(), { router: s } = e(), [c, l] = _(3), u = t(void 0, { parentId: null }, "createdAt", "DESC", 0, c), d = u.data?.data ?? [], p = u.data?.total ?? 0, m = d.length < p;
	return /* @__PURE__ */ y("div", {
		className: "flex h-screen flex-col items-center justify-center",
		children: [/* @__PURE__ */ y("div", {
			className: "w-full max-w-sm space-y-6 px-4",
			children: [/* @__PURE__ */ v("div", {
				className: "flex justify-center",
				children: /* @__PURE__ */ y(i, {
					variant: "secondary",
					size: "sm",
					className: "gap-1.5",
					onClick: () => r(!0),
					children: [/* @__PURE__ */ v(E, { className: "h-3.5 w-3.5" }), "New Run"]
				})
			}), u.isLoading && d.length === 0 ? /* @__PURE__ */ v("div", {
				className: "flex justify-center py-4",
				children: /* @__PURE__ */ v(T, { className: "text-muted-foreground h-4 w-4 animate-spin" })
			}) : d.length > 0 ? /* @__PURE__ */ y("div", { children: [
				/* @__PURE__ */ v("p", {
					className: "text-muted-foreground mb-2 text-xs font-medium",
					children: "Recent"
				}),
				/* @__PURE__ */ v("div", {
					className: "max-h-[280px] overflow-auto",
					children: /* @__PURE__ */ v("div", {
						className: "divide-border divide-y",
						children: d.map((e) => /* @__PURE__ */ v(z, {
							workflow: e,
							onClick: () => void o(s.getPreviewWorkflow(e.id))
						}, e.id))
					})
				}),
				m && /* @__PURE__ */ y("button", {
					className: "text-muted-foreground hover:text-foreground mt-2 flex w-full items-center justify-center gap-1 py-1 text-xs transition-colors",
					onClick: () => l((e) => e + 5),
					children: [/* @__PURE__ */ v(C, { className: "h-3 w-3" }), "Load more"]
				})
			] }) : null]
		}), /* @__PURE__ */ v(f, {
			open: n,
			onOpenChange: r,
			onSuccess: a
		})]
	});
}
function z({ workflow: e, onClick: t }) {
	return /* @__PURE__ */ y("button", {
		className: "hover:bg-accent w-full rounded-md px-2 py-2.5 text-left transition-colors",
		onClick: t,
		children: [/* @__PURE__ */ y("div", {
			className: "flex items-center gap-2",
			children: [/* @__PURE__ */ v("span", { className: `h-1.5 w-1.5 shrink-0 rounded-full ${L[e.status] ?? "bg-muted-foreground"}` }), /* @__PURE__ */ y("span", {
				className: "truncate text-sm font-medium",
				children: [
					"Run #",
					e.run,
					" · ",
					e.alias
				]
			})]
		}), /* @__PURE__ */ y("p", {
			className: "text-muted-foreground mt-0.5 pl-3.5 text-xs",
			children: [
				e.status,
				" · ",
				A(new Date(e.createdAt), { addSuffix: !0 })
			]
		})]
	});
}
function B(e) {
	return e.replace(/\x1b\[[0-9;]*m/g, "");
}
function V({ line: e, index: t }) {
	let n = B(e), r = /\bERROR\b/.test(n), i = /\bWARN\b/.test(n) || /\b(Warning|WARNING|DeprecationWarning)\b/.test(n);
	return /* @__PURE__ */ y("div", {
		className: `group flex border-b border-border/30 hover:bg-accent/30 ${r ? "bg-destructive/5" : i ? "bg-yellow-500/5" : ""}`,
		children: [/* @__PURE__ */ v("span", {
			className: "w-10 shrink-0 select-none border-r border-border/30 px-2 py-0.5 text-right text-[10px] text-muted-foreground/50",
			children: t + 1
		}), /* @__PURE__ */ v("span", {
			className: `flex-1 px-3 py-0.5 text-[11px] leading-5 font-mono ${r ? "text-destructive" : i ? "text-yellow-600 dark:text-yellow-400" : ""}`,
			children: n
		})]
	});
}
function H() {
	let e = g(null), t = b({
		queryKey: ["remote-agent-app-logs"],
		queryFn: async () => {
			let e = await fetch("http://localhost:8000/api/v1/app/logs?lines=200", { credentials: "include" });
			if (!e.ok) {
				let t = await e.text();
				throw Error(`Failed to fetch logs (${e.status}): ${t}`);
			}
			return await e.json();
		},
		refetchInterval: 5e3
	});
	m(() => {
		e.current?.scrollIntoView({ behavior: "smooth" });
	}, [t.data]);
	let n = h(() => {
		let e = [];
		return t.data?.stdout && e.push(t.data.stdout), t.data?.stderr && e.push(t.data.stderr), e.join("\n").split("\n").filter((e) => e.length > 0);
	}, [t.data]);
	return /* @__PURE__ */ y("div", {
		className: "flex h-full flex-col",
		children: [/* @__PURE__ */ y("div", {
			className: "flex h-9 shrink-0 items-center justify-between border-b bg-muted/30 px-3",
			children: [/* @__PURE__ */ v("span", {
				className: "text-xs font-medium text-muted-foreground",
				children: "Application Logs"
			}), /* @__PURE__ */ v("button", {
				onClick: () => void t.refetch(),
				className: `text-muted-foreground hover:text-foreground rounded-md p-1 transition-colors hover:cursor-pointer ${t.isFetching ? "animate-spin" : ""}`,
				children: /* @__PURE__ */ v(D, { className: "h-3 w-3" })
			})]
		}), /* @__PURE__ */ v("div", {
			className: "flex-1 overflow-auto bg-background",
			children: t.isLoading && !t.data ? /* @__PURE__ */ v("div", {
				className: "flex justify-center py-8",
				children: /* @__PURE__ */ v(T, { className: "text-muted-foreground h-4 w-4 animate-spin" })
			}) : t.error ? /* @__PURE__ */ v("div", {
				className: "px-4 py-3",
				children: /* @__PURE__ */ y("p", {
					className: "text-sm text-destructive",
					children: ["Error: ", t.error.message]
				})
			}) : n.length > 0 ? /* @__PURE__ */ y("div", {
				className: "font-mono",
				children: [n.map((e, t) => /* @__PURE__ */ v(V, {
					line: e,
					index: t
				}, t)), /* @__PURE__ */ v("div", { ref: e })]
			}) : /* @__PURE__ */ y("div", {
				className: "flex flex-col items-center justify-center gap-2 py-8 text-muted-foreground",
				children: [/* @__PURE__ */ v(O, { className: "h-5 w-5" }), /* @__PURE__ */ v("span", {
					className: "text-xs",
					children: "No logs available"
				})]
			})
		})]
	});
}
//#endregion
export { F as default };
