const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
let react = require("react");
react = require_runtime.__toESM(react);
//#region src/plus/salesSdk/demo/components/DemoStepRunner.tsx
const INITIAL_STATE = { status: "idle" };
function formatResult(result) {
	if (result === void 0) return "";
	try {
		return JSON.stringify(result, null, 2);
	} catch (_unused) {
		return String(result);
	}
}
function durationLabel(state) {
	if (!state.startedAt || !state.finishedAt) return "";
	const ms = state.finishedAt - state.startedAt;
	if (ms < 1e3) return `${ms}ms`;
	return `${(ms / 1e3).toFixed(2)}s`;
}
/**
* 步骤序列执行器：
*  - 顶部「一键执行」按钮：从第一步开始串行 `await`，中断条件 = 抛错。
*  - 每一步右侧提供「单步执行」按钮，便于反复点击调试。
*  - 状态、结果、错误信息聚合渲染在每一步下方；同时维护 `running` 互斥锁，避免并行写。
*/
const DemoStepRunner = ({ title, steps, oneClickLabel = "一键测试用例", onAllDone, onReset, className }) => {
	const [stateMap, setStateMap] = (0, react.useState)({});
	const [running, setRunning] = (0, react.useState)(false);
	const [resetting, setResetting] = (0, react.useState)(false);
	const [resetError, setResetError] = (0, react.useState)(null);
	const getState = (0, react.useCallback)((id) => stateMap[id] || INITIAL_STATE, [stateMap]);
	const updateState = (0, react.useCallback)((id, patch) => {
		setStateMap((prev) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev), {}, { [id]: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, prev[id] || INITIAL_STATE), patch) }));
	}, []);
	const runOne = (0, react.useCallback)(function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (step) {
			const startedAt = Date.now();
			updateState(step.id, {
				status: "running",
				startedAt,
				finishedAt: void 0,
				result: void 0,
				error: void 0
			});
			try {
				const next = {
					status: "success",
					result: yield step.run(),
					startedAt,
					finishedAt: Date.now()
				};
				updateState(step.id, next);
				return next;
			} catch (e) {
				var _e$message;
				const finishedAt = Date.now();
				const next = {
					status: "error",
					error: String((_e$message = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message !== void 0 ? _e$message : e),
					startedAt,
					finishedAt
				};
				updateState(step.id, next);
				return next;
			}
		});
		return function(_x) {
			return _ref.apply(this, arguments);
		};
	}(), [updateState]);
	const runSingle = (0, react.useCallback)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (step) {
			if (running || resetting) return;
			if (step.skip) {
				updateState(step.id, { status: "skipped" });
				return;
			}
			setRunning(true);
			try {
				yield runOne(step);
			} finally {
				setRunning(false);
			}
		});
		return function(_x2) {
			return _ref2.apply(this, arguments);
		};
	}(), [
		running,
		resetting,
		runOne,
		updateState
	]);
	const runAll = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (running || resetting) return;
		setRunning(true);
		const next = {};
		steps.forEach((step) => {
			next[step.id] = step.skip ? { status: "skipped" } : INITIAL_STATE;
		});
		setStateMap(next);
		try {
			for (const step of steps) {
				if (step.skip) continue;
				if ((yield runOne(step)).status === "error") break;
			}
		} finally {
			setRunning(false);
			if (onAllDone) setStateMap((current) => {
				onAllDone(current);
				return current;
			});
		}
	}), [
		running,
		resetting,
		runOne,
		steps,
		onAllDone
	]);
	const summary = (0, react.useMemo)(() => {
		const counts = {
			success: 0,
			error: 0,
			skipped: 0,
			idle: 0,
			running: 0
		};
		steps.forEach((step) => {
			var _stateMap$step$id$sta, _stateMap$step$id;
			const s = (_stateMap$step$id$sta = (_stateMap$step$id = stateMap[step.id]) === null || _stateMap$step$id === void 0 ? void 0 : _stateMap$step$id.status) !== null && _stateMap$step$id$sta !== void 0 ? _stateMap$step$id$sta : "idle";
			counts[s] += 1;
		});
		return counts;
	}, [stateMap, steps]);
	const handleReset = (0, react.useCallback)(require_asyncToGenerator._asyncToGenerator(function* () {
		if (running || resetting) return;
		setResetError(null);
		if (onReset) {
			setResetting(true);
			try {
				yield onReset();
			} catch (e) {
				var _e$message2;
				setResetError(String((_e$message2 = e === null || e === void 0 ? void 0 : e.message) !== null && _e$message2 !== void 0 ? _e$message2 : e));
				return;
			} finally {
				setResetting(false);
			}
		}
		setStateMap({});
	}), [
		running,
		resetting,
		onReset
	]);
	const busy = running || resetting;
	return /* @__PURE__ */ react.default.createElement("section", { className: [
		"sales-sdk-demo__panel",
		"sales-sdk-demo__steps",
		className
	].filter(Boolean).join(" ") }, /* @__PURE__ */ react.default.createElement("div", { className: "sales-sdk-demo__section-title" }, /* @__PURE__ */ react.default.createElement("h3", null, title), /* @__PURE__ */ react.default.createElement("span", null, summary.success, " ok / ", summary.error, " fail / ", summary.skipped, " skipped /", " ", summary.idle + summary.running, " pending")), /* @__PURE__ */ react.default.createElement("div", { className: "sales-sdk-demo__steps-toolbar" }, /* @__PURE__ */ react.default.createElement("button", {
		type: "button",
		className: "sales-sdk-demo__primary",
		disabled: busy || steps.length === 0,
		onClick: runAll
	}, oneClickLabel), /* @__PURE__ */ react.default.createElement("button", {
		type: "button",
		disabled: busy,
		onClick: handleReset
	}, resetting ? "resetting…" : "reset")), resetError ? /* @__PURE__ */ react.default.createElement("pre", { className: "sales-sdk-demo__step-error" }, "reset 失败: ", resetError) : null, /* @__PURE__ */ react.default.createElement("ol", { className: "sales-sdk-demo__step-list" }, steps.map((step, index) => {
		const state = getState(step.id);
		const status = step.skip ? "skipped" : state.status;
		return /* @__PURE__ */ react.default.createElement("li", {
			key: step.id,
			className: `sales-sdk-demo__step sales-sdk-demo__step--${status}`
		}, /* @__PURE__ */ react.default.createElement("div", { className: "sales-sdk-demo__step-head" }, /* @__PURE__ */ react.default.createElement("span", { className: "sales-sdk-demo__step-index" }, index + 1), /* @__PURE__ */ react.default.createElement("div", { className: "sales-sdk-demo__step-meta" }, /* @__PURE__ */ react.default.createElement("strong", null, step.label), step.description ? /* @__PURE__ */ react.default.createElement("em", { className: "sales-sdk-demo__step-desc" }, step.description) : null), /* @__PURE__ */ react.default.createElement("div", { className: "sales-sdk-demo__step-status" }, /* @__PURE__ */ react.default.createElement("span", null, status), durationLabel(state) ? /* @__PURE__ */ react.default.createElement("em", null, durationLabel(state)) : null), /* @__PURE__ */ react.default.createElement("button", {
			type: "button",
			disabled: busy || Boolean(step.skip),
			onClick: () => runSingle(step)
		}, "单步执行")), state.error ? /* @__PURE__ */ react.default.createElement("pre", { className: "sales-sdk-demo__step-error" }, state.error) : null, state.status === "success" && state.result !== void 0 ? /* @__PURE__ */ react.default.createElement("pre", { className: "sales-sdk-demo__step-result" }, formatResult(state.result)) : null);
	})));
};
//#endregion
exports.DemoStepRunner = DemoStepRunner;
