window.__ModuleLoader__.load({
	id: "@deepseek-ai/dsh-auto-chess",
	factory: (require) => {
		var module = { exports: {} };
		var exports = module.exports;
		Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
		let react = require("react");
		let react_jsx_runtime = require("react/jsx-runtime");
		/** Battle tick duration in seconds. */
		const TICK_SEC = .5;
		/** Horizontal cells a unit moves per battle tick. */
		const MOVE_PER_TICK = .5;
		/** Build a mulberry32 PRNG from a seed. */
		function mulberry32(seed) {
			let a = seed >>> 0;
			return () => {
				a = a + 1831565813 >>> 0;
				let t = a;
				t = Math.imul(t ^ t >>> 15, t | 1);
				t ^= t + Math.imul(t ^ t >>> 7, t | 61);
				return ((t ^ t >>> 14) >>> 0) / 4294967296;
			};
		}
		/** Human-readable trait name. */
		function traitName(id) {
			return TRAITS.find((trait) => trait.id === id)?.name ?? id;
		}
		/** The 24-unit public pool (ids 1..24, costs 1/2/3). */
		const UNIT_POOL = [
			{
				id: 1,
				name: "冰女",
				cost: 1,
				race: "frost",
				class: "mage",
				hp: 500,
				atk: 42,
				atkSpeed: .75,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.5
				}
			},
			{
				id: 2,
				name: "小鹿",
				cost: 1,
				race: "barbarian",
				class: "marksman",
				hp: 460,
				atk: 40,
				atkSpeed: .85,
				range: 4,
				skill: {
					kind: "damage",
					every: 5,
					power: 1.3
				}
			},
			{
				id: 3,
				name: "石像鬼",
				cost: 1,
				race: "stellar",
				class: "guardian",
				hp: 620,
				atk: 30,
				atkSpeed: .6,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.2,
					aoe: true
				}
			},
			{
				id: 4,
				name: "火鸡",
				cost: 1,
				race: "barbarian",
				class: "blade",
				hp: 480,
				atk: 44,
				atkSpeed: .8,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.5
				}
			},
			{
				id: 5,
				name: "幽魂",
				cost: 1,
				race: "shadow",
				class: "assassin",
				hp: 450,
				atk: 46,
				atkSpeed: .9,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.6
				}
			},
			{
				id: 6,
				name: "小精灵",
				cost: 1,
				race: "stellar",
				class: "mage",
				hp: 420,
				atk: 44,
				atkSpeed: .7,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.5
				}
			},
			{
				id: 7,
				name: "老铁匠",
				cost: 1,
				race: "barbarian",
				class: "guardian",
				hp: 640,
				atk: 32,
				atkSpeed: .6,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.4
				}
			},
			{
				id: 8,
				name: "白鸽",
				cost: 1,
				race: "frost",
				class: "priest",
				hp: 480,
				atk: 36,
				atkSpeed: .7,
				range: 1.5,
				skill: {
					kind: "heal-all",
					every: 4,
					power: 1.5
				}
			},
			{
				id: 9,
				name: "暗影鼠",
				cost: 1,
				race: "shadow",
				class: "assassin",
				hp: 440,
				atk: 45,
				atkSpeed: .85,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.5
				}
			},
			{
				id: 10,
				name: "见习剑士",
				cost: 1,
				race: "warmonger",
				class: "blade",
				hp: 500,
				atk: 42,
				atkSpeed: .75,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.5
				}
			},
			{
				id: 11,
				name: "剑圣",
				cost: 2,
				race: "warmonger",
				class: "blade",
				hp: 620,
				atk: 62,
				atkSpeed: .85,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2
				}
			},
			{
				id: 12,
				name: "冰霜守卫",
				cost: 2,
				race: "frost",
				class: "guardian",
				hp: 760,
				atk: 40,
				atkSpeed: .6,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.6
				}
			},
			{
				id: 13,
				name: "暗影法师",
				cost: 2,
				race: "shadow",
				class: "mage",
				hp: 560,
				atk: 58,
				atkSpeed: .7,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2
				}
			},
			{
				id: 14,
				name: "星灵射手",
				cost: 2,
				race: "stellar",
				class: "marksman",
				hp: 560,
				atk: 56,
				atkSpeed: .9,
				range: 4,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.8
				}
			},
			{
				id: 15,
				name: "蛮族勇士",
				cost: 2,
				race: "barbarian",
				class: "blade",
				hp: 700,
				atk: 55,
				atkSpeed: .7,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2
				}
			},
			{
				id: 16,
				name: "神官",
				cost: 2,
				race: "frost",
				class: "priest",
				hp: 580,
				atk: 44,
				atkSpeed: .65,
				range: 1.5,
				skill: {
					kind: "heal-all",
					every: 3,
					power: 1
				}
			},
			{
				id: 17,
				name: "猎手",
				cost: 2,
				race: "warmonger",
				class: "marksman",
				hp: 540,
				atk: 58,
				atkSpeed: .95,
				range: 4,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.9
				}
			},
			{
				id: 18,
				name: "影武者",
				cost: 2,
				race: "shadow",
				class: "assassin",
				hp: 560,
				atk: 60,
				atkSpeed: 1,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2.1
				}
			},
			{
				id: 19,
				name: "冰霜巨龙",
				cost: 3,
				race: "frost",
				class: "mage",
				hp: 800,
				atk: 70,
				atkSpeed: .7,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2.2,
					aoe: true
				}
			},
			{
				id: 20,
				name: "战神之王",
				cost: 3,
				race: "warmonger",
				class: "blade",
				hp: 900,
				atk: 80,
				atkSpeed: .75,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2.4
				}
			},
			{
				id: 21,
				name: "暗影领主",
				cost: 3,
				race: "shadow",
				class: "mage",
				hp: 760,
				atk: 78,
				atkSpeed: .7,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2.5
				}
			},
			{
				id: 22,
				name: "星灵女王",
				cost: 3,
				race: "stellar",
				class: "marksman",
				hp: 700,
				atk: 74,
				atkSpeed: 1,
				range: 4,
				skill: {
					kind: "damage",
					every: 4,
					power: 1.8
				}
			},
			{
				id: 23,
				name: "蛮族之王",
				cost: 3,
				race: "barbarian",
				class: "guardian",
				hp: 1100,
				atk: 60,
				atkSpeed: .55,
				range: 1.5,
				skill: {
					kind: "damage",
					every: 4,
					power: 2
				}
			},
			{
				id: 24,
				name: "大主教",
				cost: 3,
				race: "stellar",
				class: "priest",
				hp: 780,
				atk: 52,
				atkSpeed: .6,
				range: 1.5,
				skill: {
					kind: "heal-all",
					every: 3,
					power: 1.3
				}
			}
		];
		/** All trait definitions (races first, then classes, in display order). */
		const TRAITS = [
			{
				id: "frost",
				kind: "race",
				name: "冰裔",
				tiers: [{
					threshold: 2,
					desc: "冰裔生命上限+15%",
					effect: {
						hpPct: .15,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "冰裔生命上限+35%",
					effect: {
						hpPct: .35,
						scope: "self"
					}
				}]
			},
			{
				id: "shadow",
				kind: "race",
				name: "暗影",
				tiers: [{
					threshold: 2,
					desc: "暗影攻击力+20%",
					effect: {
						atkPct: .2,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "暗影攻击力+45%",
					effect: {
						atkPct: .45,
						scope: "self"
					}
				}]
			},
			{
				id: "warmonger",
				kind: "race",
				name: "战神",
				tiers: [{
					threshold: 2,
					desc: "战神攻速+15%",
					effect: {
						atkSpeedPct: .15,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "战神攻速+35%",
					effect: {
						atkSpeedPct: .35,
						scope: "self"
					}
				}]
			},
			{
				id: "stellar",
				kind: "race",
				name: "星灵",
				tiers: [{
					threshold: 2,
					desc: "星灵技能伤害+25%",
					effect: {
						skillPct: .25,
						scope: "self"
					}
				}, {
					threshold: 3,
					desc: "星灵技能伤害+50%",
					effect: {
						skillPct: .5,
						scope: "self"
					}
				}]
			},
			{
				id: "barbarian",
				kind: "race",
				name: "蛮族",
				tiers: [{
					threshold: 2,
					desc: "蛮族生命上限+20%、攻击力+10%",
					effect: {
						hpPct: .2,
						atkPct: .1,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "蛮族生命上限+40%、攻击力+25%",
					effect: {
						hpPct: .4,
						atkPct: .25,
						scope: "self"
					}
				}]
			},
			{
				id: "mage",
				kind: "class",
				name: "法师",
				tiers: [{
					threshold: 2,
					desc: "法师技能伤害+25%",
					effect: {
						skillPct: .25,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "法师技能伤害+60%",
					effect: {
						skillPct: .6,
						scope: "self"
					}
				}]
			},
			{
				id: "blade",
				kind: "class",
				name: "剑士",
				tiers: [{
					threshold: 2,
					desc: "剑士攻击力+25%",
					effect: {
						atkPct: .25,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "剑士攻击力+50%",
					effect: {
						atkPct: .5,
						scope: "self"
					}
				}]
			},
			{
				id: "marksman",
				kind: "class",
				name: "射手",
				tiers: [{
					threshold: 2,
					desc: "射手攻速+20%",
					effect: {
						atkSpeedPct: .2,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "射手攻速+45%",
					effect: {
						atkSpeedPct: .45,
						scope: "self"
					}
				}]
			},
			{
				id: "guardian",
				kind: "class",
				name: "守卫",
				tiers: [{
					threshold: 2,
					desc: "守卫生命上限+200",
					effect: {
						hpFlat: 200,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "守卫生命上限+500",
					effect: {
						hpFlat: 500,
						scope: "self"
					}
				}]
			},
			{
				id: "assassin",
				kind: "class",
				name: "刺客",
				tiers: [{
					threshold: 2,
					desc: "刺客暴击率+30%",
					effect: {
						critPct: .3,
						scope: "self"
					}
				}, {
					threshold: 4,
					desc: "刺客暴击率+60%",
					effect: {
						critPct: .6,
						scope: "self"
					}
				}]
			},
			{
				id: "priest",
				kind: "class",
				name: "牧师",
				tiers: [{
					threshold: 2,
					desc: "全体友方生命上限+10%",
					effect: {
						hpPct: .1,
						scope: "all"
					}
				}, {
					threshold: 3,
					desc: "全体友方生命上限+20%",
					effect: {
						hpPct: .2,
						scope: "all"
					}
				}]
			}
		];
		/** Shop cost odds per level: [1费, 2费, 3费]. */
		const SHOP_ODDS = [
			[
				1,
				0,
				0
			],
			[
				.7,
				.3,
				0
			],
			[
				.5,
				.4,
				.1
			],
			[
				.35,
				.45,
				.2
			],
			[
				.25,
				.45,
				.3
			],
			[
				.15,
				.45,
				.4
			],
			[
				.1,
				.4,
				.5
			],
			[
				.05,
				.35,
				.6
			]
		];
		/** Experience needed to advance from `level` to `level + 1`. */
		function expNeeded(level) {
			return level + 2;
		}
		/** Look a unit definition up by pool id. */
		function unitDef(defId) {
			return UNIT_POOL.find((def) => def.id === defId);
		}
		/** Star stat scale (2★ ≈ 1.8×, 3★ ≈ 3.24× of the 1★ base). */
		function starScale(star) {
			return star === 1 ? 1 : star === 2 ? 1.8 : 3.24;
		}
		/** Build a concrete unit instance from a pool definition. */
		function makeUnit(def, star, id) {
			const scale = starScale(star);
			const hp = Math.round(def.hp * scale);
			return {
				id,
				defId: def.id,
				name: def.name,
				cost: def.cost,
				star,
				race: def.race,
				class: def.class,
				hp,
				maxHp: hp,
				atk: Math.round(def.atk * scale),
				atkSpeed: def.atkSpeed,
				range: def.range,
				skill: { ...def.skill }
			};
		}
		/** Roll one shop of SHOP_SIZE distinct units for a level. */
		function rollShop(level, rng) {
			const odds = SHOP_ODDS[Math.max(1, Math.min(level, 8)) - 1];
			const pick = () => {
				const roll = rng();
				let acc = 0;
				let cost = 1;
				for (let i = 0; i < odds.length; i += 1) {
					acc += odds[i];
					if (roll < acc) {
						cost = i + 1;
						break;
					}
				}
				const candidates = UNIT_POOL.filter((def) => def.cost === cost);
				return candidates[Math.floor(rng() * candidates.length)];
			};
			const shop = [];
			let guard = 0;
			while (shop.length < 5 && guard < 200) {
				guard += 1;
				const entry = pick();
				if (shop.some((existing) => existing.defId === entry.id)) continue;
				shop.push({
					defId: entry.id,
					name: entry.name,
					cost: entry.cost,
					race: entry.race,
					class: entry.class
				});
			}
			return shop;
		}
		/** Fresh game state (round 1, both sides at 100 HP / 6 gold / level 1). */
		function freshGame(seed = 1) {
			const makeSide = (side) => ({
				side,
				hp: 100,
				gold: 6,
				level: 1,
				exp: 0,
				bench: [],
				board: new Array(28).fill(null),
				shop: [],
				winStreak: 0,
				lossStreak: 0,
				lastResult: null,
				lastSurvivors: 0
			});
			const state = {
				round: 1,
				sides: [makeSide(1), makeSide(2)],
				nextUnitId: 1,
				seed: seed >>> 0,
				history: [],
				over: false,
				winner: null
			};
			const rng = mulberry32(state.seed);
			state.sides[0].shop = rollShop(state.sides[0].level, rng);
			state.sides[1].shop = rollShop(state.sides[1].level, rng);
			return state;
		}
		/** Number of units currently deployed by a side. */
		function boardCount(side) {
			return side.board.filter((unit) => unit !== null).length;
		}
		/** Whether a cell index is inside the 4×7 board. */
		function inBoard(row, col) {
			return row >= 0 && row < 4 && col >= 0 && col < 7;
		}
		/** Cell index for a [row, col] pair. */
		function cellIndex(row, col) {
			return row * 7 + col;
		}
		/** Per-trait deployed counts of a side. */
		function traitCounts(side) {
			const counts = /* @__PURE__ */ new Map();
			for (const unit of side.board) {
				if (unit === null) continue;
				counts.set(unit.race, (counts.get(unit.race) ?? 0) + 1);
				counts.set(unit.class, (counts.get(unit.class) ?? 0) + 1);
			}
			return counts;
		}
		/** The traits of a side whose threshold is met, with the met tier. */
		function activeTraits(side) {
			const counts = traitCounts(side);
			const active = [];
			for (const trait of TRAITS) {
				const count = counts.get(trait.id) ?? 0;
				let met;
				for (const tier of trait.tiers) if (count >= tier.threshold) met = tier;
				if (met !== void 0) active.push({
					trait,
					tier: met
				});
			}
			return active;
		}
		/** Per-unit battle stat bonuses from the deployed traits of a side. */
		function traitEffectsForBoard(board) {
			const effects = /* @__PURE__ */ new Map();
			const active = activeTraits({ board: [...board] });
			for (const unit of board) {
				if (unit === null) continue;
				const merged = { scope: "self" };
				for (const { trait, tier } of active) {
					if (!(trait.kind === "race" ? tier.effect.scope === "all" || unit.race === trait.id : tier.effect.scope === "all" || unit.class === trait.id)) continue;
					merged.hpPct = (merged.hpPct ?? 0) + (tier.effect.hpPct ?? 0);
					merged.atkPct = (merged.atkPct ?? 0) + (tier.effect.atkPct ?? 0);
					merged.atkSpeedPct = (merged.atkSpeedPct ?? 0) + (tier.effect.atkSpeedPct ?? 0);
					merged.skillPct = (merged.skillPct ?? 0) + (tier.effect.skillPct ?? 0);
					merged.critPct = (merged.critPct ?? 0) + (tier.effect.critPct ?? 0);
					merged.hpFlat = (merged.hpFlat ?? 0) + (tier.effect.hpFlat ?? 0);
					merged.scope = "self";
				}
				if (merged.hpPct !== void 0 || merged.atkPct !== void 0 || merged.atkSpeedPct !== void 0 || merged.skillPct !== void 0 || merged.critPct !== void 0 || merged.hpFlat !== void 0) effects.set(unit.id, merged);
			}
			return effects;
		}
		/** Locate a unit by id; returns its location. */
		function findUnit(side, id) {
			const benchIndex = side.bench.findIndex((unit) => unit.id === id);
			if (benchIndex !== -1) return {
				where: "bench",
				index: benchIndex
			};
			const boardIndex = side.board.findIndex((unit) => unit?.id === id);
			if (boardIndex !== -1) return {
				where: "board",
				index: boardIndex
			};
			return null;
		}
		/** Merge triples of identical name+star units (bench first, then board in cell order). */
		function mergeStars(state, side) {
			for (;;) {
				const counts = /* @__PURE__ */ new Map();
				const collect = (unit) => {
					const key = `${unit.name}|${unit.star}`;
					counts.set(key, (counts.get(key) ?? 0) + 1);
				};
				for (const unit of side.bench) collect(unit);
				for (const unit of side.board) if (unit !== null) collect(unit);
				let targetKey;
				for (const [key, count] of counts) if (count >= 3) {
					targetKey = key;
					break;
				}
				if (targetKey === void 0) return;
				const [name, starText] = targetKey.split("|");
				const star = Number(starText);
				if (star >= 3) return;
				const def = UNIT_POOL.find((candidate) => candidate.name === name);
				if (def === void 0) return;
				let removed = 0;
				let keptId;
				const consume = (unit) => {
					if (unit.name !== name || unit.star !== star) return false;
					keptId = unit.id;
					return true;
				};
				side.bench = side.bench.filter((unit) => {
					if (removed < 3 && consume(unit)) {
						removed += 1;
						return false;
					}
					return true;
				});
				for (let index = 0; index < side.board.length && removed < 3; index += 1) {
					const unit = side.board[index];
					if (unit !== null && consume(unit)) {
						side.board[index] = null;
						removed += 1;
					}
				}
				side.bench.push(makeUnit(def, star + 1, keptId ?? state.nextUnitId));
				if (keptId === void 0) state.nextUnitId += 1;
			}
		}
		/**
		* Apply one prep action to a side, mutating the state. Returns an error
		* string when the action is illegal; `undefined` on success. The whole
		* action list of an AI decision is validated by applying every action to a
		* clone — any failure rejects the batch and triggers corrective feedback.
		*/
		function applyAction(state, side, action) {
			const player = state.sides[side - 1];
			switch (action.action) {
				case "buy": {
					const entry = player.shop.find((candidate) => candidate.name === action.name);
					if (entry === void 0) return `商店中没有名为「${action.name}」的棋子`;
					if (player.gold < entry.cost) return `金币不足（购买「${entry.name}」需要 ${entry.cost}，当前 ${player.gold}）`;
					if (player.bench.length >= 9) return `备战区已满（上限 9）`;
					const def = unitDef(entry.defId);
					if (def === void 0) return `未知棋子「${entry.name}」`;
					player.gold -= entry.cost;
					player.bench.push(makeUnit(def, 1, state.nextUnitId));
					state.nextUnitId += 1;
					mergeStars(state, player);
					return;
				}
				case "sell": {
					const found = findUnit(player, action.chess_id);
					if (found === null) return `未找到棋子（chess_id: ${action.chess_id}）`;
					const unit = found.where === "bench" ? player.bench[found.index] : player.board[found.index];
					const refund = unit.cost + (unit.star - 1) * 2;
					if (found.where === "bench") player.bench.splice(found.index, 1);
					else player.board[found.index] = null;
					player.gold += refund;
					return;
				}
				case "move": {
					const [row, col] = action.pos;
					if (!Number.isInteger(row) || !Number.isInteger(col) || !inBoard(row, col)) return `目标位置越界：[${row}, ${col}]（范围 0-3 行、0-6 列）`;
					const index = cellIndex(row, col);
					const found = findUnit(player, action.chess_id);
					if (found === null) return `未找到棋子（chess_id: ${action.chess_id}）`;
					const occupant = player.board[index];
					if (occupant !== null) return occupant.id === action.chess_id ? void 0 : `目标位置已被占用：[${row}, ${col}]`;
					const unit = found.where === "bench" ? player.bench[found.index] : player.board[found.index];
					if (found.where === "bench") {
						if (boardCount(player) >= player.level) return `上场棋子数已达上限（当前等级 ${player.level}）`;
						player.bench.splice(found.index, 1);
					} else player.board[found.index] = null;
					player.board[index] = unit;
					return;
				}
				case "upgrade":
					if (player.gold < 4) return `金币不足（购买经验需要 4，当前 ${player.gold}）`;
					player.gold -= 4;
					player.exp += 4;
					while (player.level < 8 && player.exp >= expNeeded(player.level)) {
						player.exp -= expNeeded(player.level);
						player.level += 1;
					}
					return;
				case "refresh":
					if (player.gold < 2) return `金币不足（刷新商店需要 2，当前 ${player.gold}）`;
					player.gold -= 2;
					player.shop = rollShop(player.level, mulberry32(state.seed ^ player.side));
					return;
				case "end_prep": return;
				/* v8 ignore next -- closed-union exhaustiveness guard */
				default: return "未知操作";
			}
		}
		/** The income a side would receive at the next settlement. */
		function incomePreview(side) {
			const interest = Math.min(Math.floor(side.gold / 10), 5);
			const longest = Math.max(side.winStreak, side.lossStreak);
			const streak = longest >= 6 ? 3 : longest >= 4 ? 2 : longest >= 2 ? 1 : 0;
			const win = side.lastResult === "win" ? 1 : 0;
			return {
				base: 5,
				interest,
				streak,
				win,
				total: 5 + interest + streak + win
			};
		}
		/** Build combat units for one side from its board (mirrored for side 2). */
		function combatUnitsOf(side, board, effects) {
			const units = [];
			for (let index = 0; index < board.length; index += 1) {
				const unit = board[index];
				if (unit === null) continue;
				const row = Math.floor(index / 7);
				const col = index % 7;
				const effect = effects.get(unit.id);
				const hpPct = effect?.hpPct ?? 0;
				const atkPct = effect?.atkPct ?? 0;
				const speedPct = effect?.atkSpeedPct ?? 0;
				const skillPct = effect?.skillPct ?? 0;
				const critPct = effect?.critPct ?? 0;
				const hpFlat = effect?.hpFlat ?? 0;
				const hp = Math.round(unit.hp * (1 + hpPct)) + hpFlat;
				units.push({
					uid: unit.id,
					side,
					name: unit.name,
					star: unit.star,
					row,
					col: side === 1 ? col : 13 - col,
					hp,
					maxHp: hp,
					atk: unit.atk * (1 + atkPct),
					atkSpeed: unit.atkSpeed * (1 + speedPct),
					range: unit.range,
					crit: critPct,
					skillPower: 1 + skillPct,
					skill: unit.skill,
					attacks: 0,
					timer: 0,
					alive: true
				});
			}
			return units;
		}
		/** Squared distance between two combat units (field coordinates). */
		function distanceSq(a, b) {
			const dr = a.row - b.row;
			const dc = a.col - b.col;
			return dr * dr + dc * dc;
		}
		/** The nearest living enemy of one combat unit, or null. */
		function nearestEnemy(unit, enemies) {
			let best = null;
			let bestD = Infinity;
			for (const enemy of enemies) {
				if (!enemy.alive) continue;
				const d = distanceSq(unit, enemy);
				if (d < bestD) {
					bestD = d;
					best = enemy;
				}
			}
			return best;
		}
		/** Star label for battle events. */
		function starLabel(star) {
			return `${star}星`;
		}
		/**
		* Simulate the battle between the two deployed boards. Pure: reads the
		* state, returns the replay; never mutates it. The RNG (crit rolls) comes
		* from the state's seed, so identical states produce identical battles.
		*/
		function simulateBattle(state) {
			const rng = mulberry32(state.seed);
			const effects1 = traitEffectsForBoard(state.sides[0].board);
			const effects2 = traitEffectsForBoard(state.sides[1].board);
			const units = [...combatUnitsOf(1, state.sides[0].board, effects1), ...combatUnitsOf(2, state.sides[1].board, effects2)];
			const snapshot = () => ({
				units: units.filter((unit) => unit.alive).map((unit) => ({
					uid: unit.uid,
					side: unit.side,
					name: unit.name,
					star: unit.star,
					row: unit.row,
					col: Math.round(unit.col * 2) / 2,
					hp: Math.max(0, Math.round(unit.hp)),
					maxHp: unit.maxHp
				})),
				events: []
			});
			const ticks = [snapshot()];
			const aliveOf = (side) => units.reduce((count, unit) => count + (unit.alive && unit.side === side ? 1 : 0), 0);
			for (let tickIndex = 0; tickIndex < 120; tickIndex += 1) {
				const events = [];
				const side1Alive = aliveOf(1);
				const side2Alive = aliveOf(2);
				if (side1Alive === 0 || side2Alive === 0) break;
				for (const unit of [...units].sort((a, b) => a.side - b.side || a.uid - b.uid)) {
					if (!unit.alive) continue;
					const enemies = units.filter((candidate) => candidate.side !== unit.side && candidate.alive);
					if (enemies.length === 0) continue;
					const target = nearestEnemy(unit, enemies);
					if (target === null) continue;
					if (distanceSq(unit, target) <= unit.range * unit.range) {
						unit.timer -= TICK_SEC;
						if (unit.timer > 0) continue;
						unit.timer = Math.max(1 / unit.atkSpeed, .25);
						unit.attacks += 1;
						if (unit.skill.every > 0 && unit.attacks % unit.skill.every === 0) if (unit.skill.kind === "heal-all") {
							const heal = unit.atk * unit.skill.power;
							for (const ally of units) if (ally.side === unit.side && ally.alive) ally.hp = Math.min(ally.maxHp, ally.hp + heal);
							events.push(`${unit.name}（${starLabel(unit.star)}）施放治疗，为全体友方恢复 ${Math.round(heal)} 生命`);
						} else {
							const damage = unit.atk * unit.skill.power * unit.skillPower;
							const targets = unit.skill.aoe === true ? enemies.filter((enemy) => distanceSq(unit, enemy) <= unit.range * unit.range || distanceSq(target, enemy) <= 2.25) : [target];
							const killed = [];
							for (const enemy of targets) {
								enemy.hp -= damage;
								if (enemy.hp <= 0 && enemy.alive) killed.push(enemy.name);
							}
							const hits = targets.map((enemy) => enemy.name).join("、");
							events.push(`${unit.name}（${starLabel(unit.star)}）发动技能，对${hits}造成 ${Math.round(damage)} 伤害${killed.length > 0 ? `，击败了${killed.join("、")}` : ""}`);
						}
						else {
							const damage = unit.atk * (rng() < unit.crit ? 1.5 : 1);
							target.hp -= damage;
							if (target.hp <= 0 && target.alive) events.push(`${unit.name}（${starLabel(unit.star)}）击败了${target.name}（${starLabel(target.star)}）`);
						}
					} else {
						const step = Math.sign(target.col - unit.col) * MOVE_PER_TICK;
						unit.col = Math.min(13, Math.max(0, unit.col + step));
					}
				}
				for (const unit of units) if (unit.alive && unit.hp <= 0) unit.alive = false;
				const tick = snapshot();
				tick.events = events;
				ticks.push(tick);
			}
			const survivors1 = aliveOf(1);
			const survivors2 = aliveOf(2);
			let winner = 0;
			let survivors = 0;
			if (survivors1 > 0 && survivors2 === 0) {
				winner = 1;
				survivors = survivors1;
			} else if (survivors2 > 0 && survivors1 === 0) {
				winner = 2;
				survivors = survivors2;
			} else if (survivors1 === 0 && survivors2 === 0) {
				winner = 0;
				survivors = 0;
			} else if (survivors1 > survivors2) {
				winner = 1;
				survivors = survivors1;
			} else if (survivors2 > survivors1) {
				winner = 2;
				survivors = survivors2;
			} else {
				winner = 0;
				survivors = 0;
			}
			return {
				winner,
				survivors,
				damage: winner === 0 ? 0 : survivors * 2,
				ticks
			};
		}
		/**
		* Apply a battle result: HP damage, streaks, income, round advance, shop
		* rerolls, and the game-over check. Mutates the state; advances the battle
		* seed so the next battle's crit rolls differ.
		*/
		function settleRound(state, result) {
			const winner = result.winner;
			if (winner === 1 || winner === 2) {
				const loser = state.sides[winner === 1 ? 1 : 0];
				const winnerSide = state.sides[winner - 1];
				loser.hp = Math.max(0, loser.hp - result.damage);
				loser.lastResult = "loss";
				loser.lastSurvivors = 0;
				winnerSide.lastResult = "win";
				winnerSide.lastSurvivors = result.survivors;
				winnerSide.winStreak += 1;
				loser.lossStreak += 1;
				state.history.push({
					round: state.round,
					winner,
					survivors: result.survivors,
					damage: result.damage
				});
			} else {
				state.sides[0].lastResult = "draw";
				state.sides[1].lastResult = "draw";
				state.sides[0].lastSurvivors = 0;
				state.sides[1].lastSurvivors = 0;
				state.history.push({
					round: state.round,
					winner: 0,
					survivors: 0,
					damage: 0
				});
			}
			for (const side of state.sides) {
				const preview = incomePreview(side);
				side.gold += preview.total;
				side.shop = rollShop(side.level, mulberry32(state.seed ^ side.side));
			}
			state.round += 1;
			state.seed = state.seed * 1103515245 + 12345 >>> 0;
			if (state.sides[0].hp <= 0) {
				state.over = true;
				state.winner = 2;
			} else if (state.sides[1].hp <= 0) {
				state.over = true;
				state.winner = 1;
			}
		}
		[
			"你是《简化自走棋》的一名玩家。请根据给定的局面，为你控制的阵营做出准备阶段的操作决策，并严格按照规定的 JSON 格式返回操作数组。",
			"",
			"# 游戏规则",
			`- 你与对手各控制一个阵营（蓝方/红方），初始生命值 100。每回合分为「准备阶段 → 自动战斗 → 结算」。`,
			`- 战斗自动进行：棋子自动索敌、移动、攻击，每累计一定次数攻击会触发技能。失败方按对方存活棋子数 ×2 扣除生命值，生命归零即输。`,
			`- 每个回合你最多可以执行 4 个操作（买棋、卖棋、布阵、购买经验、刷新商店、结束准备）。`,
			"",
			"# 棋盘",
			`- 你的布阵区域是 4 行 × 7 列，坐标写作 [row, col]（row 为 0-3，col 为 0-6）。`,
			`- 上场棋子数不能超过你的等级；备战区（未上场的棋子）上限 9 个。`,
			"",
			"# 棋子",
			"- 棋子分为 1 费、2 费、3 费。每颗棋子有生命（hp）、攻击力（atk）、攻速（每秒攻击次数）、攻击距离、种族、职业与技能。",
			"- 星阶：3 个同名同星棋子自动合成为 1 个更高星棋子（一星→二星→三星）。二星属性约为一星的 1.8 倍，三星约为 3.24 倍。",
			"- 合成会统计备战区与棋盘上所有的同名同星棋子，所以棋子上场不会影响后续合成。",
			"- 技能：每个棋子每累计 N 次攻击都会触发一次技能（造成技能伤害或治疗友方）。",
			"- 棋子 id：以局面文本中最新给出的 id 为准。购买触发合成后，被合成的旧棋子会消失，合成后的棋子保留「最后被消耗那颗」的 id（通常就是你刚买入的那颗）；因此批量操作中，先买后布阵时请使用刚买入棋子的 id，不要使用已被合成消耗的旧 id。",
			"",
			"# 种族与职业（羁绊）",
			"上场棋子的同种族/同职业数量达到阈值时触发加成，只计算已上场棋子，取满足的最高档：",
			...TRAITS.flatMap((trait) => [`- ${trait.name}（${trait.kind === "race" ? "种族" : "职业"}）${trait.tiers.map((tier) => `${tier.threshold}：${tier.desc}`).join("，")}`]),
			"",
			"# 商店与经济",
			`- 商店每回合免费刷新 5 颗棋子；主动刷新花费 2 金币。购买花费棋子费用（1/2/3 金币）。`,
			"- 卖出返还金币：费用 + (星阶-1) × 2（一星卖 1/2/3 金，二星多返 2 金，三星多返 4 金）。",
			`- 每回合结算收入 = 基础 5 + 利息 min(金币÷10, 5) + 连胜/连败奖励 + 胜利 +1。`,
			"- 连胜/连败奖励：2 连胜起 +1，4 连胜起 +2，6 连胜起 +3（连胜与连败都算）。",
			`- 升级：花费 4 金币购买 4 点经验。升级所需经验 = 等级 + 2（例如 4 级升 5 级需要 6 点）。等级提高上场人数上限与高费棋子的刷新概率，等级上限 8。`,
			"",
			"# 操作格式（必须严格遵守）",
			`只返回一个 JSON 数组（最多 4 个操作），按顺序执行；不要输出任何思考过程、解释、Markdown 代码块或前后缀（思考会占用输出预算，导致回复被截断）：`,
			"- 购买商店棋子：{\"action\":\"buy\", \"name\":\"棋子名\"}",
			"- 卖出：{\"action\":\"sell\", \"chess_id\":棋子id}",
			"- 布阵/移动：{\"action\":\"move\", \"chess_id\":棋子id, \"pos\":[row, col]}",
			"- 购买经验：{\"action\":\"upgrade\"}",
			"- 刷新商店：{\"action\":\"refresh\"}",
			"- 结束准备：{\"action\":\"end_prep\"}（建议放在最后一个操作）",
			"- 若不想执行任何操作，直接返回 [{\"action\":\"end_prep\"}]",
			"",
			"# 正确案例",
			"局面：你金币 12，等级 4，备战区已有 2 个「冰女」，商店里有「冰女」和「剑圣」，你想合成二星冰女并把它放到棋盘 (1,3)。",
			"返回：[{\"action\":\"buy\",\"name\":\"冰女\"},{\"action\":\"move\",\"chess_id\":6,\"pos\":[1,3]},{\"action\":\"end_prep\"}]",
			"（共 3 个操作，总花费 1 金币，符合数量与预算限制）",
			"",
			"# 错误示范（禁止返回）",
			"\"我觉得应该买剑圣。[{\"action\":\"buy\",\"name\":\"剑圣\"}]\" —— 带解释的文字不是合法输出；",
			"{\"action\":\"buy\",\"name\":\"剑圣\"} —— 必须是数组，不能是单个对象；",
			`操作数超过 4 个时，只执行前 4 个（多余的会被忽略）；总花费超过金币、买入商店里没有的棋子、把棋子移动到已占用的格子等，会导致整批操作被拒绝，你会收到纠正提示并重新决策。`,
			"",
			"# 基本策略",
			"1. 只要还有上场名额（已上场数 < 等级）且备战区有棋子，就必须用 move 把棋子上场：上场不会影响星阶合成（合成统计备战区与棋盘上的同名同星棋子），还能腾出备战区空位；空位优先放能触发羁绊或高星的棋子。",
			"2. 优先凑同种族/同职业羁绊（例如 2 冰裔、2 法师），并让触发羁绊的棋子上场。",
			"3. 购买同名同星棋子合成高星；2 费、3 费核心棋子值得重点培养。",
			"4. 守卫/坦克放前排（靠敌方一侧，col 4-6），射手/法师/刺客等输出放后排（col 0-2）。",
			"5. 金币低于 10 时慎重刷新商店（每 10 金币可多拿 1 利息，上限 5）。",
			"6. 有足够金币时优先购买经验升级，扩大上场人数。",
			"7. 凑不齐羁绊的废棋可以卖掉换经济（卖出会返还金币）。"
		].join("\n");
		/** Human-readable summary of one action (for the reasoning log). */
		function actionLabel(action) {
			switch (action.action) {
				case "buy": return `购买「${action.name}」`;
				case "sell": return `卖出#${action.chess_id}`;
				case "move": return `布阵#${action.chess_id}→[${action.pos[0]},${action.pos[1]}]`;
				case "upgrade": return "购买经验";
				case "refresh": return "刷新商店";
				case "end_prep": return "结束准备";
				/* v8 ignore next -- closed-union exhaustiveness guard */
				default: return String(action);
			}
		}
		//#endregion
		//#region src/client/store.ts
		/**
		* Auto-chess browser-half store: module-level game/settings state plus the
		* AI prep lifecycle and the battle replay clock. Living outside React means
		* the conversation view can unmount (tab switches, session switches)
		* without resetting the game or interrupting an in-flight AI decision — the
		* game and AI thinking continue in the background. The view subscribes via
		* useSyncExternalStore.
		*
		* The authoritative game state lives here (the node half only validates AI
		* actions against a clone), so the human's clicks and the AI's accepted
		* actions both commit through the same engine.
		*/
		/** The fresh game view state for a new game. */
		function freshGameView() {
			return {
				game: freshGame(),
				phase: "prep1",
				thinking: false,
				battle: null,
				log: [],
				pendingSide: null
			};
		}
		/** The default settings (models fill in from the catalog fetch). */
		function freshSettings() {
			return {
				mode: "pvp",
				blueModel: {
					provider: void 0,
					model: void 0
				},
				redModel: {
					provider: void 0,
					model: void 0
				},
				blueThinking: "off",
				redThinking: "off",
				actionTimeoutMs: 3e5,
				maxActionOutputTokens: 32e3,
				bluePrompt: void 0,
				redPrompt: void 0,
				groups: [],
				modelsError: void 0
			};
		}
		let snapshot = {
			game: freshGameView(),
			settings: freshSettings()
		};
		const listeners = /* @__PURE__ */ new Set();
		/** Game generation: bumped on every new game; stale async results are dropped. */
		let generation = 0;
		/** Per-request sequence: a settled reply only applies to the request it came from. */
		let requestSeq = 0;
		/** The in-flight decision request's abort handle (cancelled on new game / teardown). */
		let abort = null;
		/** The battle replay clock (store-owned so tab switches never pause it). */
		let battleTimer;
		/** The settle delay before the next prep phase starts. */
		let settleTimer;
		/** Subscribe to store changes (useSyncExternalStore's subscribe). */
		function subscribe(listener) {
			listeners.add(listener);
			return () => {
				listeners.delete(listener);
			};
		}
		/** The current stable snapshot (useSyncExternalStore's getSnapshot). */
		function getSnapshot() {
			return snapshot;
		}
		/** Publish one game state to all subscribers. */
		function commitGame(game) {
			snapshot = {
				...snapshot,
				game
			};
			for (const listener of [...listeners]) listener();
		}
		/** Publish one settings state to all subscribers. */
		function commitSettings(settings) {
			snapshot = {
				...snapshot,
				settings
			};
			for (const listener of [...listeners]) listener();
		}
		/** Whether the game has settled (a winner exists). */
		function gameOver(game) {
			return game.game.over || game.phase === "over";
		}
		/** Fetch the model catalog once; failures surface in settings.modelsError. */
		function loadModels() {
			if (snapshot.settings.groups.length > 0) return;
			fetch("/plugins/auto-chess/models").then((response) => response.json()).then((body) => {
				const groups = (body.groups ?? []).filter((group) => group.models.length > 0);
				const next = {
					...snapshot.settings,
					groups,
					modelsError: void 0
				};
				if (groups.length > 0) {
					const first = groups[0];
					const defaultModel = first.models[0]?.id;
					if (next.blueModel.provider === void 0) next.blueModel = {
						provider: first.provider,
						model: defaultModel
					};
					if (next.redModel.provider === void 0) next.redModel = {
						provider: first.provider,
						model: defaultModel
					};
				}
				commitSettings(next);
			}).catch((error) => {
				if (snapshot.settings.groups.length > 0) return;
				commitSettings({
					...snapshot.settings,
					modelsError: error instanceof Error ? error.message : String(error)
				});
			});
		}
		/** Clear store-owned timers of a previous generation. */
		function clearTimers() {
			if (battleTimer !== void 0) {
				window.clearInterval(battleTimer);
				battleTimer = void 0;
			}
			if (settleTimer !== void 0) {
				window.clearTimeout(settleTimer);
				settleTimer = void 0;
			}
		}
		/** Start a new game in the given mode (or the current one). */
		function newGame(mode) {
			generation += 1;
			abort?.abort();
			clearTimers();
			const nextMode = mode ?? snapshot.settings.mode;
			commitGame(freshGameView());
			if (nextMode === "ai") scheduleAi(1);
		}
		/** Switch the play mode and restart the game in it. */
		function changeMode(mode) {
			if (mode === snapshot.settings.mode) return;
			commitSettings({
				...snapshot.settings,
				mode
			});
			newGame(mode);
		}
		/** Apply one settings patch (model selection, thinking, overrides, prompt). */
		function patchSettings(patch) {
			commitSettings({
				...snapshot.settings,
				...patch
			});
		}
		/** Whether the human may act right now (pvp mode, blue's prep, idle). */
		function humanCanAct() {
			const { game, settings } = snapshot;
			return settings.mode === "pvp" && game.phase === "prep1" && !game.thinking && !gameOver(game);
		}
		/** The human's side in pvp mode (blue). */
		const HUMAN_SIDE = 1;
		/** Human: buy the shop offer at `index`. */
		function buy(index) {
			if (!humanCanAct()) return;
			const { game } = snapshot;
			const entry = game.game.sides[0].shop[index];
			if (entry === void 0) return;
			const error = applyAction(game.game, HUMAN_SIDE, {
				action: "buy",
				name: entry.name
			});
			if (error !== void 0) {
				commitGame({
					...game,
					log: [...game.log, {
						n: game.log.length + 1,
						round: game.game.round,
						side: HUMAN_SIDE,
						actions: `购买「${entry.name}」被拒绝：${error}`,
						reasoning: ""
					}]
				});
				return;
			}
			commitGame({ ...game });
		}
		/** Human: sell the unit with the given id. */
		function sell(id) {
			if (!humanCanAct()) return;
			const { game } = snapshot;
			applyAction(game.game, HUMAN_SIDE, {
				action: "sell",
				chess_id: id
			});
			commitGame({ ...game });
		}
		/** Human: move the unit with the given id to a board cell. */
		function moveUnit(id, row, col) {
			if (!humanCanAct()) return;
			const { game } = snapshot;
			applyAction(game.game, HUMAN_SIDE, {
				action: "move",
				chess_id: id,
				pos: [row, col]
			});
			commitGame({ ...game });
		}
		/** Human: buy 4 experience for 4 gold. */
		function upgradeExp() {
			if (!humanCanAct()) return;
			const { game } = snapshot;
			applyAction(game.game, HUMAN_SIDE, { action: "upgrade" });
			commitGame({ ...game });
		}
		/** Human: refresh the shop for 2 gold. */
		function refreshShop() {
			if (!humanCanAct()) return;
			const { game } = snapshot;
			applyAction(game.game, HUMAN_SIDE, { action: "refresh" });
			commitGame({ ...game });
		}
		/** Human: end the prep phase and hand over to red's AI. */
		function endPrep() {
			const { game, settings } = snapshot;
			if (!humanCanAct()) return;
			if (settings.mode === "pvp") {
				commitGame({
					...game,
					phase: "prep2"
				});
				scheduleAi(2);
			}
		}
		/** How long past the node half's own deadline a request may stay silent before the client declares the thinking interrupted. */
		const WATCHDOG_MARGIN_MS = 5e3;
		/** Post one AI action request to the node half's route. */
		async function requestAiActions(body, signal) {
			const response = await fetch("/plugins/auto-chess/action", {
				method: "POST",
				headers: { "content-type": "application/json" },
				body: JSON.stringify(body),
				signal
			});
			const parsed = await response.json();
			if (!response.ok) throw new Error(typeof parsed.error === "string" ? parsed.error : `auto-chess: HTTP ${response.status}`);
			return parsed;
		}
		/** Run one AI prep decision for a side. */
		function scheduleAi(side, feedback) {
			const { game, settings } = snapshot;
			if (gameOver(game) || game.thinking) return;
			const expectedPhase = side === 1 ? "prep1" : "prep2";
			if (game.phase !== expectedPhase) return;
			const model = side === 1 ? settings.blueModel : settings.redModel;
			const customPrompt = side === 1 ? settings.bluePrompt : settings.redPrompt;
			if (model.provider === void 0 || model.model === void 0) {
				commitGame({
					...game,
					thinking: false,
					log: [...game.log, {
						n: game.log.length + 1,
						round: game.game.round,
						side,
						actions: "",
						reasoning: "",
						error: settings.modelsError ?? "model catalog unavailable"
					}],
					pendingSide: side
				});
				return;
			}
			const gen = generation;
			commitGame({
				...game,
				thinking: true,
				pendingSide: null
			});
			const controller = new AbortController();
			abort = controller;
			const seq = ++requestSeq;
			const watchdog = window.setTimeout(() => {
				if (gen === generation && seq === requestSeq) controller.abort();
			}, settings.actionTimeoutMs + WATCHDOG_MARGIN_MS);
			requestAiActions({
				provider: model.provider,
				model: model.model,
				side,
				state: game.game,
				thinking: side === 1 ? settings.blueThinking : settings.redThinking,
				actionTimeoutMs: settings.actionTimeoutMs,
				maxActionOutputTokens: settings.maxActionOutputTokens,
				...customPrompt !== void 0 ? { system: customPrompt } : {},
				...feedback?.lastText !== void 0 ? { previous: feedback.lastText } : {},
				...feedback?.lastReason !== void 0 ? { reason: feedback.lastReason } : {}
			}, controller.signal).then((reply) => {
				window.clearTimeout(watchdog);
				if (gen !== generation || seq !== requestSeq) return;
				applyAiReply(reply, side, gen);
			}).catch((error) => {
				window.clearTimeout(watchdog);
				if (gen !== generation || seq !== requestSeq) return;
				const current = snapshot.game;
				if (current.phase !== (side === 1 ? "prep1" : "prep2")) return;
				if (error?.name === "AbortError") {
					commitGame({
						...current,
						thinking: false,
						log: [...current.log, {
							n: current.log.length + 1,
							round: current.game.round,
							side,
							actions: "",
							reasoning: "",
							interrupted: true
						}],
						pendingSide: side
					});
					return;
				}
				const message = error instanceof Error ? error.message : String(error);
				commitGame({
					...current,
					thinking: false,
					log: [...current.log, {
						n: current.log.length + 1,
						round: current.game.round,
						side,
						actions: "",
						reasoning: "",
						error: message
					}],
					pendingSide: side
				});
			});
		}
		/** Apply one settled AI reply for the side it was requested for. */
		function applyAiReply(reply, side, gen) {
			const { game, settings } = snapshot;
			if (gen !== generation) return;
			if (game.phase !== (side === 1 ? "prep1" : "prep2") || !game.thinking) return;
			if (reply.actions !== void 0) {
				let hasEndPrep = false;
				const labels = [];
				for (const verdict of reply.actions) {
					if (!verdict.ok) continue;
					labels.push(actionLabel(verdict.action));
					if (verdict.action.action === "end_prep") {
						hasEndPrep = true;
						continue;
					}
					applyAction(game.game, side, verdict.action);
				}
				const logEntry = {
					n: game.log.length + 1,
					round: game.game.round,
					side,
					actions: labels.length > 0 ? labels.join("、") : "（无操作，直接结束准备）",
					reasoning: reply.reasoning ?? ""
				};
				commitGame({
					...game,
					thinking: false,
					log: [...game.log, logEntry],
					pendingSide: null
				});
				if (hasEndPrep || labels.length === 0) if (side === 1) {
					commitGame({
						...snapshot.game,
						phase: "prep2"
					});
					scheduleAi(2);
				} else startBattle();
				else {
					const current = snapshot.game;
					const note = {
						n: current.log.length + 1,
						round: current.game.round,
						side,
						actions: "（AI 未返回 end_prep，自动进入战斗）",
						reasoning: ""
					};
					commitGame({
						...current,
						log: [...current.log, note]
					});
					if (side === 1) {
						commitGame({
							...snapshot.game,
							phase: "prep2"
						});
						scheduleAi(2);
					} else startBattle();
				}
				return;
			}
			const error = reply.error ?? "unknown error";
			const entry = {
				n: game.log.length + 1,
				round: game.game.round,
				side,
				actions: "",
				reasoning: reply.reasoning ?? "",
				error,
				...reply.lastText !== void 0 ? { lastText: reply.lastText } : {},
				...reply.lastReason !== void 0 ? { lastReason: reply.lastReason } : {}
			};
			commitGame({
				...game,
				thinking: false,
				log: [...game.log, entry],
				pendingSide: side
			});
		}
		/**
		* Retry the last failed AI decision for the pending side (the state is
		* unchanged, so the retry carries the corrective feedback from the previous
		* reply). A no-op while the game is settled or a request is in flight.
		*/
		function retryAction() {
			const { game } = snapshot;
			if (gameOver(game) || game.thinking) return;
			const side = game.pendingSide;
			if (side === null) return;
			const entry = game.log[game.log.length - 1];
			scheduleAi(side, entry?.lastText !== void 0 ? {
				lastText: entry.lastText,
				lastReason: entry.lastReason
			} : void 0);
		}
		/** Milliseconds between replay ticks. */
		const BATTLE_TICK_MS = 320;
		/** Milliseconds the final frame stays on screen before settlement. */
		const SETTLE_DELAY_MS = 700;
		/** Start the battle: simulate, show the replay, then settle. */
		function startBattle() {
			const { game } = snapshot;
			if (gameOver(game) || game.phase !== "prep2") return;
			const result = simulateBattle(game.game);
			const gen = generation;
			commitGame({
				...game,
				phase: "battle",
				battle: {
					result,
					tick: 0,
					done: false
				},
				thinking: false
			});
			let tick = 0;
			battleTimer = window.setInterval(() => {
				if (gen !== generation) return;
				const current = snapshot.game;
				if (current.battle === null) return;
				tick += 1;
				if (tick >= current.battle.result.ticks.length - 1) {
					window.clearInterval(battleTimer);
					battleTimer = void 0;
					commitGame({
						...current,
						battle: {
							...current.battle,
							tick: current.battle.result.ticks.length - 1,
							done: true
						}
					});
					settleTimer = window.setTimeout(() => {
						if (gen !== generation) return;
						settleAfterBattle();
					}, SETTLE_DELAY_MS);
					return;
				}
				commitGame({
					...current,
					battle: {
						...current.battle,
						tick
					}
				});
			}, BATTLE_TICK_MS);
		}
		/** Settle the finished battle and advance to the next round (or game over). */
		function settleAfterBattle() {
			const { game, settings } = snapshot;
			if (game.battle === null || game.battle.result === null) return;
			settleRound(game.game, game.battle.result);
			const over = game.game.over;
			const phase = over ? "over" : "prep1";
			commitGame({
				...game,
				phase,
				battle: null
			});
			if (!over && settings.mode === "ai") window.setTimeout(() => {
				scheduleAi(1);
			}, 250);
		}
		//#endregion
		//#region \0dsh-css:/Users/macmini_no1/WorkSpace/cyberfete-labs/2026-11-27-plugins/autochess-source/src/client/AutoChess.module.css.mjs
		const css = ".jyxQDW_view{box-sizing:border-box;--ac-bg:oklch(14.5% .014 258);--ac-surface:oklch(18.5% .016 258);--ac-surface2:oklch(21.5% .018 258);--ac-line:oklch(31% .02 258);--ac-line-soft:oklch(26% .018 258);--ac-text:oklch(93% .008 258);--ac-text-dim:oklch(70% .015 258);--ac-text-faint:oklch(55% .015 258);--ac-blue:oklch(66% .15 250);--ac-blue-bright:oklch(78% .12 250);--ac-red:oklch(62% .2 25);--ac-red-bright:oklch(75% .13 25);--ac-gold:oklch(80% .13 85);--ac-green:oklch(75% .15 145);height:100%;color:var(--ac-text);background:radial-gradient(1100px 520px at 50% -8%, oklch(24% .035 258/.55), transparent 62%), repeating-linear-gradient(0deg, transparent 0 31px, oklch(55% .02 258/.04) 31px 32px), repeating-linear-gradient(90deg, transparent 0 31px, oklch(55% .02 258/.04) 31px 32px), var(--ac-bg);padding:16px;overflow:auto;container-type:inline-size}.jyxQDW_inner{grid-template-columns:224px minmax(0,1fr) 224px;grid-template-areas:\"jyxQDW_blue jyxQDW_main jyxQDW_red\"\".jyxQDW_bottom.\";align-items:start;gap:14px;max-width:1560px;margin:0 auto;display:grid}@container (width<=1120px){.jyxQDW_inner{grid-template-columns:repeat(2,minmax(0,1fr));grid-template-areas:\"jyxQDW_blue jyxQDW_red\"\"jyxQDW_main jyxQDW_main\"\"jyxQDW_bottom jyxQDW_bottom\"}}.jyxQDW_sideBlockBlue{flex-direction:column;grid-area:jyxQDW_blue;gap:10px;min-width:0;display:flex}.jyxQDW_sideBlockRed{flex-direction:column;grid-area:jyxQDW_red;gap:10px;min-width:0;display:flex}.jyxQDW_main{flex-direction:column;grid-area:jyxQDW_main;gap:10px;min-width:0;display:flex}.jyxQDW_header{border-bottom:1px solid var(--ac-line-soft);flex-wrap:wrap;justify-content:space-between;align-items:center;gap:12px;padding-bottom:10px;display:flex}.jyxQDW_round{letter-spacing:.02em;color:var(--ac-text-dim);font-variant-numeric:tabular-nums;font-size:13px;font-weight:700}.jyxQDW_versus{font-variant-numeric:tabular-nums;align-items:baseline;gap:8px;display:inline-flex}.jyxQDW_vSideBlue{color:var(--ac-blue-bright);font-size:13px;font-weight:800}.jyxQDW_vSideRed{color:var(--ac-red-bright);font-size:13px;font-weight:800}.jyxQDW_vScore{font-size:22px;font-weight:800;line-height:1}.jyxQDW_vSep{color:var(--ac-text-faint);font-size:14px;font-weight:700}.jyxQDW_statusRow{align-items:center;gap:10px;min-height:18px;display:flex}.jyxQDW_status{font-size:13px;font-weight:600}.jyxQDW_statusError{color:oklch(70% .19 25)}.jyxQDW_statusThinking{color:var(--ac-gold);animation:1.1s ease-in-out infinite jyxQDW_thinking-pulse}@keyframes jyxQDW_thinking-pulse{0%,to{opacity:1}50%{opacity:.55}}.jyxQDW_retry{color:inherit;cursor:pointer;background:oklch(70% .19 25/.16);border:1px solid oklch(70% .19 25/.7);border-radius:6px;padding:2px 10px;font-size:12px;transition:background-color .12s}.jyxQDW_retry:hover{background:oklch(70% .19 25/.3)}.jyxQDW_boards{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start;gap:12px;display:grid}.jyxQDW_sidePanel{border:1px solid;border-radius:10px;flex-direction:column;gap:6px;min-width:0;padding:10px;display:flex}.jyxQDW_sideBlue{background:linear-gradient(oklch(50% .12 250/.1),oklch(16% .02 258/.35));border-color:oklch(52% .12 250/.55)}.jyxQDW_sideRed{background:linear-gradient(oklch(50% .17 25/.1),oklch(16% .02 258/.35));border-color:oklch(52% .17 25/.55)}.jyxQDW_sideHeader{grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:8px;display:grid}.jyxQDW_sideName{white-space:nowrap;border-radius:5px;padding:2px 8px;font-size:12px;font-weight:800}.jyxQDW_sideBlue .jyxQDW_sideName{color:var(--ac-blue-bright);background:oklch(55% .13 250/.22)}.jyxQDW_sideRed .jyxQDW_sideName{color:var(--ac-red-bright);background:oklch(55% .17 25/.22)}.jyxQDW_hpBar{background:oklch(16% .015 258);border-radius:4px;width:100%;max-width:96px;height:8px;display:block;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(50% .02 258/.4)}.jyxQDW_hpFill{background:linear-gradient(90deg,oklch(66% .16 145),oklch(80% .18 145));height:100%;display:block}.jyxQDW_hpText{color:var(--ac-text-dim);white-space:nowrap;font-variant-numeric:tabular-nums;font-size:11px}.jyxQDW_sideStats{color:var(--ac-text-dim);font-variant-numeric:tabular-nums;grid-column:1/-1;gap:12px;font-size:11px;display:flex}.jyxQDW_sectionLabel{letter-spacing:.08em;color:var(--ac-text-faint);margin-top:2px;font-size:10px;font-weight:700}.jyxQDW_board{aspect-ratio:7/4;box-sizing:border-box;border:1px solid var(--ac-line);background:var(--ac-surface2);user-select:none;border-radius:8px;grid-template-columns:repeat(7,1fr);gap:2px;width:100%;max-width:400px;margin:0 auto;padding:5px;display:grid}.jyxQDW_sideBlue .jyxQDW_board{border-color:oklch(50% .12 250/.6)}.jyxQDW_sideRed .jyxQDW_board{border-color:oklch(50% .17 25/.6)}.jyxQDW_cell{background:oklch(30% .02 258/.55);border:none;border-radius:4px;justify-content:center;align-items:center;padding:0;display:flex;position:relative}.jyxQDW_cell:nth-child(2n){background:oklch(34.5% .024 258/.55)}.jyxQDW_cellInteractive{cursor:pointer}.jyxQDW_cellInteractive:hover{background:oklch(50% .02 258/.6)}.jyxQDW_cell:disabled{cursor:default}.jyxQDW_chip{box-sizing:border-box;width:100%;height:100%;min-height:26px;color:inherit;cursor:default;background:oklch(50% .12 250/.55);border:none;border-radius:4px;flex-direction:column;justify-content:center;align-items:center;gap:1px;padding:2px;display:flex;position:relative}.jyxQDW_sideRed .jyxQDW_chip{background:oklch(50% .16 25/.55)}.jyxQDW_chipDim{opacity:.7}button.jyxQDW_chip{cursor:pointer;font-family:inherit}button.jyxQDW_chip:hover{outline:1px solid oklch(93% .01 258/.45)}.jyxQDW_chipSelected{outline:2px solid var(--ac-gold);outline-offset:1px}.jyxQDW_chipName{text-overflow:ellipsis;white-space:nowrap;max-width:100%;font-size:10px;font-weight:600;line-height:1.1;overflow:hidden}.jyxQDW_chipStar{color:var(--ac-gold);font-size:8px;line-height:1}.jyxQDW_chipHpBar{background:oklch(16% .015 258);border-radius:2px;width:80%;height:4px;display:block;overflow:hidden}.jyxQDW_chipHpFill{background:var(--ac-green);height:100%;display:block}.jyxQDW_bench{flex-flow:wrap;justify-content:center;gap:5px;min-height:32px;display:flex}.jyxQDW_bench>div{width:54px}.jyxQDW_shopRow{flex-flow:wrap;justify-content:center;gap:5px;display:flex}.jyxQDW_shopCard{border:1px solid var(--ac-line);background:var(--ac-surface2);border-radius:7px;flex-direction:column;align-items:stretch;gap:3px;width:76px;padding:4px;transition:border-color .12s;display:flex}.jyxQDW_shopCard:hover{border-color:oklch(80% .13 85/.7)}.jyxQDW_shopCardDim{opacity:.65}.jyxQDW_shopName{text-align:center;text-overflow:ellipsis;white-space:nowrap;font-size:11px;font-weight:700;overflow:hidden}.jyxQDW_shopMeta{color:var(--ac-text-dim);text-align:center;justify-content:center;align-items:center;gap:3px;min-width:0;font-size:9px;display:flex;overflow:hidden}.jyxQDW_shopMeta>span:last-child{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.jyxQDW_costBadge{color:var(--ac-gold);background:oklch(80% .13 85/.16);border-radius:4px;flex-shrink:0;padding:0 3px;font-weight:700}.jyxQDW_buyButton{color:oklch(16% .02 258);cursor:pointer;background:oklch(62% .15 250/.85);border:1px solid oklch(66% .15 250/.85);border-radius:5px;padding:2px 6px;font-size:11px;font-weight:700;transition:background-color .12s}.jyxQDW_buyButton:hover:not(:disabled){background:oklch(72% .14 250)}.jyxQDW_buyButton:disabled{opacity:.4;cursor:default}.jyxQDW_battleArea{flex-direction:column;gap:8px;width:100%;display:flex}.jyxQDW_field{aspect-ratio:14/4;border:1px solid var(--ac-line);background:linear-gradient(90deg, oklch(55% .13 250/.18), oklch(16% .02 258/.3) 46%, oklch(16% .02 258/.3) 54%, oklch(55% .17 25/.18)), var(--ac-surface2);border-radius:8px;width:100%;position:relative}.jyxQDW_field:after{content:\"\";background:oklch(70% .02 258/.4);width:1px;position:absolute;top:5%;bottom:5%;left:50%}.jyxQDW_fieldUnit{z-index:1;box-sizing:border-box;white-space:nowrap;border:1px solid oklch(50% .02 258/.6);border-radius:6px;flex-direction:column;align-items:center;gap:1px;width:64px;padding:2px 4px;font-size:10px;line-height:1.2;display:flex;position:absolute;transform:translate(-50%,-50%)}.jyxQDW_fieldBlue{background:oklch(55% .13 250/.65)}.jyxQDW_fieldRed{background:oklch(55% .17 25/.65)}.jyxQDW_fieldName{font-weight:600}.jyxQDW_fieldHp{background:oklch(16% .015 258);border-radius:2px;width:100%;height:4px;display:block;overflow:hidden}.jyxQDW_fieldHpFill{background:var(--ac-green);height:100%;display:block}.jyxQDW_fieldEvents{min-height:14px;color:var(--ac-text-dim);flex-direction:column;gap:1px;font-size:11px;display:flex}.jyxQDW_fieldEvent{line-height:1.4}.jyxQDW_battleResult{color:var(--ac-gold);font-size:13px;font-weight:700}.jyxQDW_sideSettings{flex-direction:column;gap:8px;padding:2px 0 4px;display:flex}.jyxQDW_sideSettingsBlue .jyxQDW_panelTitle{color:var(--ac-blue-bright)}.jyxQDW_sideSettingsRed .jyxQDW_panelTitle{color:var(--ac-red-bright)}.jyxQDW_panelTitle{letter-spacing:.02em;align-items:center;gap:6px;font-size:13px;font-weight:800;display:flex}.jyxQDW_panelTitle:before{content:\"\";background:currentColor;border-radius:2px;flex-shrink:0;width:8px;height:8px}.jyxQDW_bottom{border-top:1px solid var(--ac-line-soft);flex-direction:column;grid-area:jyxQDW_bottom;gap:8px;margin-top:4px;padding-top:10px;display:flex}.jyxQDW_bottomRow{flex-wrap:wrap;justify-content:center;align-items:center;gap:14px;display:flex}.jyxQDW_toolbar{flex-wrap:wrap;align-items:center;gap:8px;display:flex}.jyxQDW_label{color:var(--ac-text-dim);font-size:11px}.jyxQDW_segmented{border:1px solid var(--ac-line);background:var(--ac-surface);border-radius:6px;display:inline-flex;overflow:hidden}.jyxQDW_segButton{cursor:pointer;color:inherit;background:0 0;border:none;padding:3px 9px;font-size:11px;transition:background-color .12s}.jyxQDW_segButton+.jyxQDW_segButton{border-left:1px solid var(--ac-line)}.jyxQDW_segButton:hover{background:oklch(50% .02 258/.35)}.jyxQDW_segActive{color:oklch(95% .01 258);background:oklch(62% .15 250/.55)}.jyxQDW_sideSettingsRed .jyxQDW_segActive{background:oklch(60% .18 25/.55)}.jyxQDW_select{border:1px solid var(--ac-line);background:var(--ac-surface);color:inherit;box-sizing:border-box;cursor:pointer;border-radius:6px;width:100%;padding:5px 8px;font-size:12px}.jyxQDW_field{flex-direction:column;gap:4px;min-width:0;display:flex}.jyxQDW_ghost{border:1px solid var(--ac-line);color:inherit;cursor:pointer;background:0 0;border-radius:6px;padding:4px 10px;font-size:12px;transition:background-color .12s,border-color .12s}.jyxQDW_ghost:hover{background:oklch(50% .02 258/.3);border-color:oklch(60% .02 258/.7)}.jyxQDW_primary{color:oklch(16% .02 258);cursor:pointer;background:oklch(62% .15 250/.85);border:1px solid oklch(66% .15 250/.85);border-radius:6px;padding:4px 12px;font-size:12px;font-weight:700;transition:background-color .12s}.jyxQDW_primary:hover{background:oklch(72% .14 250)}.jyxQDW_sellButton{color:inherit;cursor:pointer;background:oklch(70% .19 25/.16);border:1px solid oklch(70% .19 25/.7);border-radius:6px;padding:4px 10px;font-size:12px;transition:background-color .12s}.jyxQDW_sellButton:hover{background:oklch(70% .19 25/.3)}.jyxQDW_hint{color:var(--ac-text-faint);white-space:nowrap;text-overflow:ellipsis;min-height:16px;font-size:11px;line-height:1.45;overflow:hidden}.jyxQDW_promptArea{border:1px solid var(--ac-line-soft);background:oklch(14% .012 258/.55);border-radius:8px;flex-direction:column;gap:5px;padding:8px;display:flex}.jyxQDW_promptTitle{color:var(--ac-text-dim);font-size:11px;font-weight:700}.jyxQDW_promptTextarea{box-sizing:border-box;border:1px solid var(--ac-line);width:100%;color:var(--ac-text);resize:vertical;background:oklch(12% .01 258/.6);border-radius:5px;min-height:0;padding:5px 6px;font-family:inherit;font-size:11.5px;line-height:1.5}.jyxQDW_promptActions{flex-wrap:wrap;align-items:center;gap:8px;display:flex}.jyxQDW_promptActions .jyxQDW_ghost,.jyxQDW_promptActions .jyxQDW_primary{padding:2px 8px;font-size:11px}.jyxQDW_flash{color:oklch(80% .18 145);font-size:11px;font-weight:600}.jyxQDW_reasoningList{border:1px solid var(--ac-line-soft);background:oklch(14% .012 258/.5);border-radius:8px;flex-direction:column;gap:6px;max-height:420px;padding:8px;display:flex;overflow-y:auto}.jyxQDW_reasoningTitle{color:var(--ac-text-dim);align-items:center;gap:6px;font-size:11px;font-weight:700;display:flex}.jyxQDW_reasoningTitle:before{content:\"\";background:currentColor;border-radius:50%;flex-shrink:0;width:6px;height:6px}.jyxQDW_sideReasoningBlue .jyxQDW_reasoningTitle{color:var(--ac-blue-bright)}.jyxQDW_sideReasoningRed .jyxQDW_reasoningTitle{color:var(--ac-red-bright)}.jyxQDW_reasoningItem{border:1px solid var(--ac-line-soft);background:var(--ac-surface2);border-radius:6px;padding:3px 6px}.jyxQDW_sideReasoningBlue .jyxQDW_reasoningItem{background:oklch(50% .12 250/.1)}.jyxQDW_sideReasoningRed .jyxQDW_reasoningItem{background:oklch(50% .17 25/.1)}.jyxQDW_reasoningHeader{box-sizing:border-box;width:100%;color:inherit;text-align:left;cursor:pointer;background:0 0;border:none;align-items:baseline;gap:8px;padding:3px 2px;font-size:11px;font-weight:600;display:flex}.jyxQDW_reasoningHeader:hover{opacity:.85}.jyxQDW_chevron{font-size:10px;transition:transform .15s;display:inline-block}.jyxQDW_chevronOpen{transform:rotate(90deg)}.jyxQDW_reasoningMove{text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;overflow:hidden}.jyxQDW_errorText{color:oklch(70% .19 25);font-weight:400}.jyxQDW_reasoningText{white-space:pre-wrap;word-break:break-word;color:var(--ac-text-dim);margin:5px 0 0;font-family:inherit;font-size:10.5px;line-height:1.5}.jyxQDW_select:focus-visible,.jyxQDW_segButton:focus-visible,.jyxQDW_ghost:focus-visible,.jyxQDW_primary:focus-visible,.jyxQDW_sellButton:focus-visible,.jyxQDW_retry:focus-visible,.jyxQDW_buyButton:focus-visible,.jyxQDW_reasoningHeader:focus-visible,.jyxQDW_chip:focus-visible,.jyxQDW_cell:focus-visible,.jyxQDW_promptTextarea:focus-visible{outline-offset:1px;outline:2px solid oklch(66% .15 250/.7)}html.jyxQDW_viewActive [data-composer-seat]{display:none}";
		const tagId = "@deepseek-ai/dsh-auto-chess/AutoChess.module.css";
		if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
			const tag = document.createElement("style");
			tag.dataset.plugin = "@deepseek-ai/dsh-auto-chess";
			tag.dataset.pluginCss = tagId;
			tag.textContent = css;
			document.head.appendChild(tag);
		}
		var AutoChess_module_css_default = {
			"versus": "jyxQDW_versus",
			"promptArea": "jyxQDW_promptArea",
			"chipStar": "jyxQDW_chipStar",
			"reasoningList": "jyxQDW_reasoningList",
			"chevronOpen": "jyxQDW_chevronOpen",
			"boards": "jyxQDW_boards",
			"chip": "jyxQDW_chip",
			"label": "jyxQDW_label",
			"vSideRed": "jyxQDW_vSideRed",
			"sideBlockRed": "jyxQDW_sideBlockRed",
			"fieldName": "jyxQDW_fieldName",
			"header": "jyxQDW_header",
			"thinking-pulse": "jyxQDW_thinking-pulse",
			"blue": "jyxQDW_blue",
			"fieldHp": "jyxQDW_fieldHp",
			"sideSettingsBlue": "jyxQDW_sideSettingsBlue",
			"segButton": "jyxQDW_segButton",
			"promptTextarea": "jyxQDW_promptTextarea",
			"reasoningMove": "jyxQDW_reasoningMove",
			"inner": "jyxQDW_inner",
			"battleArea": "jyxQDW_battleArea",
			"reasoningItem": "jyxQDW_reasoningItem",
			"statusThinking": "jyxQDW_statusThinking",
			"bottom": "jyxQDW_bottom",
			"status": "jyxQDW_status",
			"sideName": "jyxQDW_sideName",
			"bench": "jyxQDW_bench",
			"field": "jyxQDW_field",
			"fieldUnit": "jyxQDW_fieldUnit",
			"battleResult": "jyxQDW_battleResult",
			"cellInteractive": "jyxQDW_cellInteractive",
			"panelTitle": "jyxQDW_panelTitle",
			"sideSettingsRed": "jyxQDW_sideSettingsRed",
			"segActive": "jyxQDW_segActive",
			"select": "jyxQDW_select",
			"ghost": "jyxQDW_ghost",
			"reasoningHeader": "jyxQDW_reasoningHeader",
			"flash": "jyxQDW_flash",
			"reasoningText": "jyxQDW_reasoningText",
			"round": "jyxQDW_round",
			"sideReasoningRed": "jyxQDW_sideReasoningRed",
			"promptTitle": "jyxQDW_promptTitle",
			"sideHeader": "jyxQDW_sideHeader",
			"sideStats": "jyxQDW_sideStats",
			"fieldEvent": "jyxQDW_fieldEvent",
			"chipDim": "jyxQDW_chipDim",
			"vScore": "jyxQDW_vScore",
			"primary": "jyxQDW_primary",
			"viewActive": "jyxQDW_viewActive",
			"retry": "jyxQDW_retry",
			"cell": "jyxQDW_cell",
			"shopCard": "jyxQDW_shopCard",
			"reasoningTitle": "jyxQDW_reasoningTitle",
			"sideRed": "jyxQDW_sideRed",
			"view": "jyxQDW_view",
			"board": "jyxQDW_board",
			"main": "jyxQDW_main",
			"chipSelected": "jyxQDW_chipSelected",
			"vSideBlue": "jyxQDW_vSideBlue",
			"shopMeta": "jyxQDW_shopMeta",
			"fieldRed": "jyxQDW_fieldRed",
			"sideReasoningBlue": "jyxQDW_sideReasoningBlue",
			"chipHpFill": "jyxQDW_chipHpFill",
			"shopRow": "jyxQDW_shopRow",
			"shopCardDim": "jyxQDW_shopCardDim",
			"hpFill": "jyxQDW_hpFill",
			"hpText": "jyxQDW_hpText",
			"sideSettings": "jyxQDW_sideSettings",
			"sellButton": "jyxQDW_sellButton",
			"toolbar": "jyxQDW_toolbar",
			"hint": "jyxQDW_hint",
			"statusRow": "jyxQDW_statusRow",
			"promptActions": "jyxQDW_promptActions",
			"red": "jyxQDW_red",
			"buyButton": "jyxQDW_buyButton",
			"sideBlockBlue": "jyxQDW_sideBlockBlue",
			"statusError": "jyxQDW_statusError",
			"fieldHpFill": "jyxQDW_fieldHpFill",
			"fieldEvents": "jyxQDW_fieldEvents",
			"errorText": "jyxQDW_errorText",
			"sidePanel": "jyxQDW_sidePanel",
			"sideBlue": "jyxQDW_sideBlue",
			"costBadge": "jyxQDW_costBadge",
			"chevron": "jyxQDW_chevron",
			"segmented": "jyxQDW_segmented",
			"sectionLabel": "jyxQDW_sectionLabel",
			"chipHpBar": "jyxQDW_chipHpBar",
			"shopName": "jyxQDW_shopName",
			"fieldBlue": "jyxQDW_fieldBlue",
			"vSep": "jyxQDW_vSep",
			"chipName": "jyxQDW_chipName",
			"bottomRow": "jyxQDW_bottomRow",
			"hpBar": "jyxQDW_hpBar"
		};
		//#endregion
		//#region src/client/AutoChessView.tsx
		/**
		* The auto-chess conversation view: the 自走棋 tab content. A responsive
		* three-column grid: blue's stack (AI settings, always-visible prompt
		* editor, reasoning log) on the left, the board area (header, status, the
		* two sides' panels / battle field, human toolbar) in the middle, red's
		* stack on the right; on narrower columns the two stacks move to a top row
		* and the board area takes the full width below them, the two board panels
		* always staying side by side on one row. A bottom bar under the board
		* area holds the play-mode selector and the new-game button. Each side's
		* AI (model, thinking level and custom prompt) is configured independently
		* in its own stack, the prompt textarea is always editable directly, and
		* each side's reasoning log shows only that side's decisions. Rendered
		* inside the conversation view ring (the same slot Trajectory occupies),
		* one-at-a-time by the session body, so the component unmounts on tab
		* switches and the game state lives in the module-level store (see
		* store.ts), never here.
		*
		* While this view is active the composer seat is hidden: the view marks the
		* document root with a class on mount and the stylesheet hides the
		* platform's composer seat (`[data-composer-seat]`) under it.
		*/
		const MODES = [{
			value: "pvp",
			key: "mode.pvp"
		}, {
			value: "ai",
			key: "mode.ai"
		}];
		const THINKINGS = [
			{
				value: "off",
				key: "thinking.off"
			},
			{
				value: "high",
				key: "thinking.high"
			},
			{
				value: "max",
				key: "thinking.max"
			}
		];
		/** The star glyphs of a unit. */
		function starText(star) {
			return "★".repeat(star);
		}
		/** The status line copy for the current game. */
		function statusCopy(game, mode, t) {
			if (game.game.over) return game.game.winner === 1 ? {
				text: t("status.win.blue"),
				error: false
			} : {
				text: t("status.win.red"),
				error: false
			};
			if (game.phase === "battle") return {
				text: t("status.battle"),
				error: false
			};
			if (game.phase === "settle") return {
				text: t("status.settle"),
				error: false
			};
			if (game.thinking) return {
				text: t("status.thinking"),
				error: false
			};
			const last = game.log[game.log.length - 1];
			if (last?.interrupted === true) return {
				text: t("status.interrupted"),
				error: true
			};
			if (last?.error !== void 0) return {
				text: t("status.error", { message: last.error }),
				error: true
			};
			if (game.phase === "prep1") return {
				text: mode === "pvp" ? t("status.prep.blue.human") : t("status.prep.blue.ai"),
				error: false
			};
			if (game.phase === "prep2") return {
				text: t("status.prep.red"),
				error: false
			};
			return {
				text: t("game.phase.over"),
				error: false
			};
		}
		/** A unit chip: used on the board, the bench and the battle field. */
		function UnitChip({ unit, selected, dim, onClick }) {
			const ratio = unit.maxHp > 0 ? Math.max(0, Math.min(1, unit.hp / unit.maxHp)) : 0;
			const content = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
					className: AutoChess_module_css_default.chipName,
					children: unit.name
				}),
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
					className: AutoChess_module_css_default.chipStar,
					children: starText(unit.star)
				}),
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
					className: AutoChess_module_css_default.chipHpBar,
					children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
						className: AutoChess_module_css_default.chipHpFill,
						style: { width: `${ratio * 100}%` }
					})
				})
			] });
			if (onClick === void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
				className: `${AutoChess_module_css_default.chip}${dim ? ` ${AutoChess_module_css_default.chipDim}` : ""}`,
				children: content
			});
			return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
				type: "button",
				className: `${AutoChess_module_css_default.chip}${selected === true ? ` ${AutoChess_module_css_default.chipSelected}` : ""}`,
				onClick,
				"aria-label": unit.name,
				title: `${unit.name}（${unit.cost}费 ${starText(unit.star)}）hp ${unit.hp} atk ${unit.atk}`,
				children: content
			});
		}
		/** One side's board (4×7). */
		function BoardGrid({ side, state, interactive, selectedId, onCell }) {
			return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
				className: AutoChess_module_css_default.board,
				role: "grid",
				"aria-label": `side ${side.side}`,
				children: side.board.map((unit, index) => {
					const row = Math.floor(index / 7);
					const col = index % 7;
					return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
						type: "button",
						className: `${AutoChess_module_css_default.cell}${interactive ? ` ${AutoChess_module_css_default.cellInteractive}` : ""}`,
						disabled: !interactive,
						"aria-label": `${row},${col}`,
						title: unit !== null ? unit.name : `${row},${col}`,
						onClick: () => onCell(row, col),
						children: unit !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UnitChip, {
							unit,
							selected: unit.id === selectedId,
							onClick: interactive ? () => onCell(row, col) : void 0
						})
					}, index);
				})
			});
		}
		/** One side's bench row. */
		function BenchRow({ side, interactive, selectedId, onSelect }) {
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: AutoChess_module_css_default.bench,
				role: "list",
				"aria-label": "bench",
				children: [side.bench.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
					className: AutoChess_module_css_default.hint,
					children: "—"
				}), side.bench.map((unit) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
					role: "listitem",
					children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UnitChip, {
						unit,
						selected: unit.id === selectedId,
						dim: !interactive,
						onClick: interactive ? () => onSelect(unit.id) : void 0
					})
				}, unit.id))]
			});
		}
		/** One shop offer card. */
		function ShopCard({ entry, affordable, benchFull, interactive, onBuy }) {
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: `${AutoChess_module_css_default.shopCard}${!interactive ? ` ${AutoChess_module_css_default.shopCardDim}` : ""}`,
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.shopName,
						children: entry.name
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						className: AutoChess_module_css_default.shopMeta,
						children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
							className: AutoChess_module_css_default.costBadge,
							children: [entry.cost, "费"]
						}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
							traitName(entry.race),
							"·",
							traitName(entry.class)
						] })]
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
						type: "button",
						className: AutoChess_module_css_default.buyButton,
						disabled: !interactive || !affordable || benchFull,
						title: benchFull ? "bench full" : void 0,
						onClick: onBuy,
						children: "购买"
					})
				]
			});
		}
		/** One side's panel: header, board, bench, shop (own side, or both while spectating) and toolbar. */
		function SidePanel({ side, state, mode, interactive, selectedId, onCell, onSelect, onBuy }) {
			const preview = incomePreview(side);
			const hpRatio = Math.max(0, Math.min(1, side.hp / 100));
			const isBlue = side.side === 1;
			const showShop = isBlue || mode === "ai";
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: `${AutoChess_module_css_default.sidePanel}${isBlue ? ` ${AutoChess_module_css_default.sideBlue}` : ` ${AutoChess_module_css_default.sideRed}`}`,
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						className: AutoChess_module_css_default.sideHeader,
						children: [
							/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
								className: AutoChess_module_css_default.sideName,
								children: [isBlue ? "蓝方" : "红方", interactive ? "（你）" : ""]
							}),
							/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
								className: AutoChess_module_css_default.hpBar,
								children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
									className: AutoChess_module_css_default.hpFill,
									style: { width: `${hpRatio * 100}%` }
								})
							}),
							/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
								className: AutoChess_module_css_default.hpText,
								children: [side.hp, "/100"]
							}),
							/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
								className: AutoChess_module_css_default.sideStats,
								children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["金币 ", side.gold] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
									"等级 ",
									side.level,
									"（",
									side.exp,
									"/",
									expNeeded(side.level),
									"）"
								] })]
							})
						]
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.hint,
						children: interactive ? `下回合收入 ${preview.base}+${preview.interest}+${preview.streak}${preview.win > 0 ? `+${preview.win}` : ""} = ${preview.total}` + (side.winStreak >= 2 ? ` · 连胜×${side.winStreak}` : "") + (side.lossStreak >= 2 ? ` · 连败×${side.lossStreak}` : "") : ""
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)(BoardGrid, {
						side,
						state,
						interactive,
						selectedId,
						onCell
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.sectionLabel,
						children: "备战区"
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)(BenchRow, {
						side,
						interactive,
						selectedId,
						onSelect
					}),
					showShop && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.sectionLabel,
						children: "商店"
					}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.shopRow,
						children: side.shop.map((entry, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ShopCard, {
							entry,
							affordable: side.gold >= entry.cost,
							benchFull: side.bench.length >= 9,
							interactive,
							onBuy: () => onBuy(index)
						}, entry.defId))
					})] })
				]
			});
		}
		/** The battle field (4×14): units positioned by the current replay tick. */
		function BattleField({ battle }) {
			const tick = battle.result.ticks[Math.min(battle.tick, battle.result.ticks.length - 1)];
			const events = tick?.events ?? [];
			const result = battle.result;
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: AutoChess_module_css_default.battleArea,
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.field,
						children: tick?.units.map((unit) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							className: `${AutoChess_module_css_default.fieldUnit}${unit.side === 1 ? ` ${AutoChess_module_css_default.fieldBlue}` : ` ${AutoChess_module_css_default.fieldRed}`}`,
							style: {
								left: `${unit.col / 13 * 100}%`,
								top: `${unit.row / 3 * 100}%`
							},
							title: `${unit.name}（${starText(unit.star)}）`,
							children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
								className: AutoChess_module_css_default.fieldName,
								children: [unit.name, starText(unit.star)]
							}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
								className: AutoChess_module_css_default.fieldHp,
								children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
									className: AutoChess_module_css_default.fieldHpFill,
									style: { width: `${Math.max(0, Math.min(100, unit.hp / unit.maxHp * 100))}%` }
								})
							})]
						}, `${unit.side}-${unit.uid}`))
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						className: AutoChess_module_css_default.fieldEvents,
						children: [events.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
							className: AutoChess_module_css_default.hint,
							children: "—"
						}), events.slice(-4).map((event, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
							className: AutoChess_module_css_default.fieldEvent,
							children: event
						}, index))]
					}),
					battle.done && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						className: AutoChess_module_css_default.battleResult,
						children: [
							result.winner === 1 && "蓝方获胜，红方",
							result.winner === 2 && "红方获胜，蓝方",
							result.winner === 0 && "平局",
							result.winner !== 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
								" -",
								result.damage,
								" 生命（剩余 ",
								result.survivors,
								" 个棋子）"
							] })
						]
					})
				]
			});
		}
		/** One per-side model selector. */
		function ModelSelect({ label, value, groups, onChange }) {
			const selected = value.provider !== void 0 && value.model !== void 0 ? `${value.provider}/${value.model}` : "";
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
				className: AutoChess_module_css_default.field,
				children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
					className: AutoChess_module_css_default.label,
					children: label
				}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
					className: AutoChess_module_css_default.select,
					value: selected,
					onChange: (event) => {
						const [provider, ...rest] = event.target.value.split("/");
						onChange({
							provider,
							model: rest.join("/")
						});
					},
					disabled: groups.length === 0,
					children: [groups.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
						value: "",
						children: "—"
					}), groups.map((group) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("optgroup", {
						label: group.displayName,
						children: group.models.map((model) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
							value: `${group.provider}/${model.id}`,
							children: model.name
						}, model.id))
					}, group.provider))]
				})]
			});
		}
		/** One side's AI settings: the model selector and the thinking level. The
		*  prompt editor below is always visible, so no toggle button is needed. */
		function SideAISettings({ t, title, modelLabel, thinkingLabel, model, groups, thinking, variant, onModel, onThinking }) {
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: `${AutoChess_module_css_default.sideSettings}${variant === "blue" ? ` ${AutoChess_module_css_default.sideSettingsBlue}` : ` ${AutoChess_module_css_default.sideSettingsRed}`}`,
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.panelTitle,
						children: title
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelSelect, {
						label: modelLabel,
						value: model,
						groups,
						onChange: onModel
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						className: AutoChess_module_css_default.toolbar,
						children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
							className: AutoChess_module_css_default.label,
							children: thinkingLabel
						}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
							className: AutoChess_module_css_default.segmented,
							role: "group",
							"aria-label": thinkingLabel,
							children: THINKINGS.map((level) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
								type: "button",
								className: `${AutoChess_module_css_default.segButton}${thinking === level.value ? ` ${AutoChess_module_css_default.segActive}` : ""}`,
								onClick: () => onThinking(level.value),
								children: t(level.key)
							}, level.value))
						})]
					})
				]
			});
		}
		/** One side's prompt editor: default-loading textarea with restore/save actions. */
		function SidePromptEditor({ t, title, loading, value, saved, onChange, onSave, onRestore }) {
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: AutoChess_module_css_default.promptArea,
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.promptTitle,
						children: title
					}),
					loading && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.hint,
						children: t("panel.prompt.loading")
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
						className: AutoChess_module_css_default.promptTextarea,
						value,
						rows: 5,
						spellCheck: false,
						onChange: (event) => onChange(event.target.value)
					}),
					/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
						className: AutoChess_module_css_default.promptActions,
						children: [
							/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
								type: "button",
								className: AutoChess_module_css_default.ghost,
								onClick: onRestore,
								children: t("panel.prompt.restore")
							}),
							/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
								type: "button",
								className: AutoChess_module_css_default.primary,
								onClick: onSave,
								children: t("panel.prompt.save")
							}),
							saved && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
								className: AutoChess_module_css_default.flash,
								children: t("panel.prompt.saved")
							})
						]
					})
				]
			});
		}
		/** One side's reasoning log: only that side's decisions, newest last. */
		function SideReasoningList({ t, title, variant, entries, expandedEntries, onToggle }) {
			return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
				className: `${AutoChess_module_css_default.reasoningList}${variant === "blue" ? ` ${AutoChess_module_css_default.sideReasoningBlue}` : ` ${AutoChess_module_css_default.sideReasoningRed}`}`,
				children: [
					/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.reasoningTitle,
						children: title
					}),
					entries.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
						className: AutoChess_module_css_default.hint,
						children: t("reasoning.empty")
					}),
					entries.map(({ entry, index }) => {
						const isExpanded = expandedEntries.has(index);
						return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							className: AutoChess_module_css_default.reasoningItem,
							children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
								type: "button",
								className: AutoChess_module_css_default.reasoningHeader,
								"aria-expanded": isExpanded,
								"aria-label": isExpanded ? t("reasoning.collapse") : t("reasoning.expand"),
								onClick: () => onToggle(index),
								children: [
									/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
										className: `${AutoChess_module_css_default.chevron}${isExpanded ? ` ${AutoChess_module_css_default.chevronOpen}` : ""}`,
										children: "▸"
									}),
									/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
										className: AutoChess_module_css_default.reasoningMove,
										children: [
											t("reasoning.entry", {
												round: entry.round,
												side: entry.side === 1 ? t("reasoning.side.blue") : t("reasoning.side.red")
											}),
											" · ",
											entry.actions
										]
									}),
									entry.interrupted === true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
										className: AutoChess_module_css_default.errorText,
										children: t("status.interrupted")
									}),
									entry.error !== void 0 && entry.interrupted !== true && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
										className: AutoChess_module_css_default.errorText,
										children: entry.error
									})
								]
							}), isExpanded && entry.reasoning !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
								className: AutoChess_module_css_default.reasoningText,
								children: entry.reasoning
							})]
						}, index);
					})
				]
			});
		}
		/** The auto-chess view tab body. */
		function AutoChessView({ t }) {
			const { game, settings } = (0, react.useSyncExternalStore)(subscribe, getSnapshot);
			const [bluePromptText, setBluePromptText] = (0, react.useState)("");
			const [redPromptText, setRedPromptText] = (0, react.useState)("");
			const [defaultPrompt, setDefaultPrompt] = (0, react.useState)(void 0);
			const [promptLoading, setPromptLoading] = (0, react.useState)(false);
			const [savedFlash, setSavedFlash] = (0, react.useState)(null);
			const savedTimer = (0, react.useRef)(void 0);
			const [expandedEntries, setExpandedEntries] = (0, react.useState)(/* @__PURE__ */ new Set());
			const [selectedId, setSelectedId] = (0, react.useState)(null);
			(0, react.useEffect)(() => {
				loadModels();
			}, []);
			(0, react.useEffect)(() => {
				document.documentElement.classList.add(AutoChess_module_css_default.viewActive);
				return () => {
					document.documentElement.classList.remove(AutoChess_module_css_default.viewActive);
				};
			}, []);
			(0, react.useEffect)(() => {
				if (defaultPrompt !== void 0) return;
				let cancelled = false;
				setPromptLoading(true);
				fetch("/plugins/auto-chess/prompt").then((response) => response.json()).then((body) => {
					if (cancelled) return;
					const prompt = body.prompt;
					if (prompt !== void 0) {
						setDefaultPrompt(prompt);
						setBluePromptText((current) => current !== "" ? current : settings.bluePrompt ?? prompt);
						setRedPromptText((current) => current !== "" ? current : settings.redPrompt ?? prompt);
					}
				}).catch(() => {}).finally(() => {
					if (!cancelled) setPromptLoading(false);
				});
				return () => {
					cancelled = true;
				};
			}, [
				defaultPrompt,
				settings.bluePrompt,
				settings.redPrompt
			]);
			(0, react.useEffect)(() => () => {
				window.clearTimeout(savedTimer.current);
			}, []);
			const flashSaved = (side) => {
				setSavedFlash(side);
				window.clearTimeout(savedTimer.current);
				savedTimer.current = window.setTimeout(() => setSavedFlash(null), 1500);
			};
			/** Save one side's draft as that side's custom prompt. */
			const savePrompt = (side) => {
				const text = side === "blue" ? bluePromptText : redPromptText;
				const trimmed = text.trim();
				patchSettings(side === "blue" ? { bluePrompt: trimmed.length > 0 ? text : void 0 } : { redPrompt: trimmed.length > 0 ? text : void 0 });
				flashSaved(side);
			};
			/** Restore one side's editor to the package default prompt. */
			const restorePrompt = (side) => {
				const prompt = defaultPrompt ?? "";
				if (side === "blue") {
					setBluePromptText(prompt);
					patchSettings({ bluePrompt: void 0 });
				} else {
					setRedPromptText(prompt);
					patchSettings({ redPrompt: void 0 });
				}
			};
			const status = statusCopy(game, settings.mode, t);
			const settled = game.game.over;
			const humanTurn = settings.mode === "pvp" && game.phase === "prep1" && !game.thinking && !settled;
			const retryableError = status.error && !settled && !game.thinking && game.pendingSide !== null;
			const inBattle = game.phase === "battle" || game.phase === "settle";
			const toggleEntry = (index) => {
				setExpandedEntries((prev) => {
					const next = new Set(prev);
					if (next.has(index)) next.delete(index);
					else next.add(index);
					return next;
				});
			};
			/** Human cell click on blue's board. */
			const handleCell = (row, col) => {
				if (!humanTurn) return;
				const unit = game.game.sides[0].board[cellIndex(row, col)];
				if (unit !== null) {
					setSelectedId((current) => current === unit.id ? null : unit.id);
					return;
				}
				if (selectedId !== null) {
					moveUnit(selectedId, row, col);
					setSelectedId(null);
				}
			};
			/** Human click on blue's bench. */
			const handleSelect = (id) => {
				if (!humanTurn) return;
				setSelectedId((current) => current === id ? null : id);
			};
			/** Human click on a shop offer. */
			const handleBuy = (index) => {
				if (!humanTurn) return;
				buy(index);
				setSelectedId(null);
			};
			const blue = game.game.sides[0];
			const red = game.game.sides[1];
			const logEntries = game.log.map((entry, index) => ({
				entry,
				index
			}));
			const blueLog = logEntries.filter((item) => item.entry.side === 1);
			const redLog = logEntries.filter((item) => item.entry.side === 2);
			return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
				className: AutoChess_module_css_default.view,
				children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
					className: AutoChess_module_css_default.inner,
					children: [
						/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							className: AutoChess_module_css_default.sideBlockBlue,
							children: [
								/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SideAISettings, {
									t,
									title: t("panel.settings.blue"),
									modelLabel: t("panel.model.blue"),
									thinkingLabel: t("panel.thinking.blue"),
									model: settings.blueModel,
									groups: settings.groups,
									thinking: settings.blueThinking,
									variant: "blue",
									onModel: (blueModel) => patchSettings({ blueModel }),
									onThinking: (thinking) => patchSettings({ blueThinking: thinking })
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SidePromptEditor, {
									t,
									title: t("panel.prompt.title.blue"),
									loading: promptLoading,
									value: bluePromptText,
									saved: savedFlash === "blue",
									onChange: setBluePromptText,
									onSave: () => savePrompt("blue"),
									onRestore: () => restorePrompt("blue")
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SideReasoningList, {
									t,
									variant: "blue",
									title: t("reasoning.title.blue"),
									entries: blueLog,
									expandedEntries,
									onToggle: toggleEntry
								})
							]
						}),
						/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							className: AutoChess_module_css_default.sideBlockRed,
							children: [
								/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SideAISettings, {
									t,
									title: t("panel.settings.red"),
									modelLabel: t("panel.model.red"),
									thinkingLabel: t("panel.thinking.red"),
									model: settings.redModel,
									groups: settings.groups,
									thinking: settings.redThinking,
									variant: "red",
									onModel: (redModel) => patchSettings({ redModel }),
									onThinking: (thinking) => patchSettings({ redThinking: thinking })
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SidePromptEditor, {
									t,
									title: t("panel.prompt.title.red"),
									loading: promptLoading,
									value: redPromptText,
									saved: savedFlash === "red",
									onChange: setRedPromptText,
									onSave: () => savePrompt("red"),
									onRestore: () => restorePrompt("red")
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SideReasoningList, {
									t,
									variant: "red",
									title: t("reasoning.title.red"),
									entries: redLog,
									expandedEntries,
									onToggle: toggleEntry
								})
							]
						}),
						/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
							className: AutoChess_module_css_default.main,
							children: [
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
									className: AutoChess_module_css_default.header,
									children: [
										/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
											className: AutoChess_module_css_default.round,
											children: [
												t("game.round", { n: game.game.round }),
												" · ",
												game.phase === "prep1" && t("game.phase.prep"),
												game.phase === "prep2" && t("game.phase.prep"),
												game.phase === "battle" && t("game.phase.battle"),
												game.phase === "settle" && t("game.phase.settle"),
												game.phase === "over" && t("game.phase.over")
											]
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
											className: AutoChess_module_css_default.versus,
											"aria-label": `蓝方 ${blue.hp} 比 ${red.hp} 红方`,
											children: [
												/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
													className: AutoChess_module_css_default.vSideBlue,
													children: "蓝方"
												}),
												/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
													className: AutoChess_module_css_default.vScore,
													children: blue.hp
												}),
												/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
													className: AutoChess_module_css_default.vSep,
													children: ":"
												}),
												/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
													className: AutoChess_module_css_default.vScore,
													children: red.hp
												}),
												/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
													className: AutoChess_module_css_default.vSideRed,
													children: "红方"
												})
											]
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
											className: AutoChess_module_css_default.hint,
											children: settings.mode === "pvp" ? t("status.side.hint.pvp") : t("status.side.hint.ai")
										})
									]
								}),
								/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
									className: AutoChess_module_css_default.statusRow,
									children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
										className: `${AutoChess_module_css_default.status}${status.error ? ` ${AutoChess_module_css_default.statusError}` : ""}${game.thinking ? ` ${AutoChess_module_css_default.statusThinking}` : ""}`,
										children: status.text
									}), retryableError && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
										type: "button",
										className: AutoChess_module_css_default.retry,
										onClick: retryAction,
										children: t("status.retry")
									})]
								}),
								inBattle && game.battle !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BattleField, { battle: game.battle }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
									className: AutoChess_module_css_default.boards,
									children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(SidePanel, {
										side: blue,
										state: game.game,
										mode: settings.mode,
										interactive: humanTurn,
										selectedId,
										onCell: handleCell,
										onSelect: handleSelect,
										onBuy: handleBuy
									}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SidePanel, {
										side: red,
										state: game.game,
										mode: settings.mode,
										interactive: false,
										selectedId: null,
										onCell: () => {},
										onSelect: () => {},
										onBuy: () => {}
									})]
								}),
								humanTurn && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
									className: AutoChess_module_css_default.toolbar,
									children: [
										selectedId !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
											type: "button",
											className: AutoChess_module_css_default.sellButton,
											onClick: () => {
												sell(selectedId);
												setSelectedId(null);
											},
											children: t("game.sell")
										}),
										selectedId !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
											className: AutoChess_module_css_default.hint,
											children: t("game.place")
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
											type: "button",
											className: AutoChess_module_css_default.ghost,
											onClick: upgradeExp,
											children: t("game.upgrade")
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
											type: "button",
											className: AutoChess_module_css_default.ghost,
											onClick: refreshShop,
											children: t("game.refresh")
										}),
										/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
											type: "button",
											className: AutoChess_module_css_default.primary,
											onClick: endPrep,
											children: t("game.endPrep")
										})
									]
								})
							]
						}),
						/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
							className: AutoChess_module_css_default.bottom,
							children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
								className: AutoChess_module_css_default.bottomRow,
								children: [
									/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
										className: AutoChess_module_css_default.label,
										children: t("panel.mode")
									}),
									/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
										className: AutoChess_module_css_default.segmented,
										role: "group",
										"aria-label": t("panel.mode"),
										children: MODES.map((mode) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
											type: "button",
											className: `${AutoChess_module_css_default.segButton}${settings.mode === mode.value ? ` ${AutoChess_module_css_default.segActive}` : ""}`,
											onClick: () => changeMode(mode.value),
											children: t(mode.key)
										}, mode.value))
									}),
									/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
										type: "button",
										className: AutoChess_module_css_default.ghost,
										onClick: () => newGame(),
										children: t("panel.newGame")
									})
								]
							})
						})
					]
				})
			});
		}
		//#endregion
		//#region src/client/locales.ts
		/** `auto-chess` namespace dictionaries for the board tab. */
		/** Dictionary namespace owned by this plugin. */
		const NS = "auto-chess";
		/** Simplified Chinese dictionary (the key-set source of truth). */
		const zh = {
			"tab.label": "自走棋",
			"panel.mode": "对局模式",
			"mode.pvp": "人机对战",
			"mode.ai": "双 AI 对战",
			"panel.settings.blue": "蓝方 AI 设置",
			"panel.settings.red": "红方 AI 设置",
			"panel.thinking.blue": "蓝方思考档位",
			"panel.thinking.red": "红方思考档位",
			"thinking.off": "Off",
			"thinking.high": "High",
			"thinking.max": "Max",
			"panel.model.blue": "蓝方模型",
			"panel.model.red": "红方模型",
			"panel.newGame": "新开局",
			"panel.prompt.title.blue": "蓝方提示词",
			"panel.prompt.title.red": "红方提示词",
			"panel.prompt.save": "保存",
			"panel.prompt.restore": "恢复默认",
			"panel.prompt.loading": "正在加载默认提示词…",
			"panel.prompt.saved": "已保存",
			"status.prep.blue.human": "你的准备阶段（蓝方）",
			"status.prep.blue.ai": "蓝方准备中",
			"status.prep.red": "红方准备中",
			"status.thinking": "AI 思考中…",
			"status.battle": "战斗进行中…",
			"status.settle": "结算中…",
			"status.win.blue": "蓝方胜利！",
			"status.win.red": "红方胜利！",
			"status.error": "出错了：{message}",
			"status.interrupted": "AI 思考已中断",
			"status.retry": "重试",
			"status.side.hint.pvp": "你执蓝方 · AI 执红方",
			"status.side.hint.ai": "双 AI 对弈，旁观中",
			"game.round": "第 {n} 回合",
			"game.phase.prep": "准备阶段",
			"game.phase.battle": "战斗阶段",
			"game.phase.settle": "结算阶段",
			"game.phase.over": "游戏结束",
			"game.hp": "生命",
			"game.gold": "金币",
			"game.level": "等级",
			"game.exp": "经验",
			"game.bench": "备战区",
			"game.shop": "商店",
			"game.upgrade": "升级（4金）",
			"game.refresh": "刷新（2金）",
			"game.endPrep": "结束准备",
			"game.sell": "卖出",
			"game.place": "点击布阵区放置",
			"game.buy": "购买",
			"game.income": "下回合收入",
			"game.streak.win": "连胜×{n}",
			"game.streak.loss": "连败×{n}",
			"game.boardFull": "上场已满（等级 {level}）",
			"game.benchFull": "备战区已满",
			"game.battleResult.win": "蓝方获胜，红方 -{damage} 生命",
			"game.battleResult.loss": "红方获胜，蓝方 -{damage} 生命",
			"game.battleResult.draw": "平局",
			"game.over": "本局结束",
			"reasoning.title.blue": "蓝方 AI 思考记录",
			"reasoning.title.red": "红方 AI 思考记录",
			"reasoning.empty": "暂无思考记录",
			"reasoning.entry": "第 {round} 回合 · {side}",
			"reasoning.side.blue": "蓝方",
			"reasoning.side.red": "红方",
			"reasoning.expand": "展开详情",
			"reasoning.collapse": "收起",
			"reasoning.noActions": "（无操作，直接结束准备）"
		};
		/** English dictionary, checked complete against the zh key set. */
		const en = {
			"tab.label": "Auto Chess",
			"panel.mode": "Mode",
			"mode.pvp": "vs AI",
			"mode.ai": "AI vs AI",
			"panel.settings.blue": "Blue AI setup",
			"panel.settings.red": "Red AI setup",
			"panel.thinking.blue": "Blue thinking",
			"panel.thinking.red": "Red thinking",
			"thinking.off": "Off",
			"thinking.high": "High",
			"thinking.max": "Max",
			"panel.model.blue": "Blue model",
			"panel.model.red": "Red model",
			"panel.newGame": "New game",
			"panel.prompt.title.blue": "Blue prompt",
			"panel.prompt.title.red": "Red prompt",
			"panel.prompt.save": "Save",
			"panel.prompt.restore": "Restore default",
			"panel.prompt.loading": "Loading default prompt…",
			"panel.prompt.saved": "Saved",
			"status.prep.blue.human": "Your prep phase (blue)",
			"status.prep.blue.ai": "Blue is preparing",
			"status.prep.red": "Red is preparing",
			"status.thinking": "AI is thinking…",
			"status.battle": "Battle in progress…",
			"status.settle": "Settling…",
			"status.win.blue": "Blue wins!",
			"status.win.red": "Red wins!",
			"status.error": "Error: {message}",
			"status.interrupted": "AI thinking interrupted",
			"status.retry": "Retry",
			"status.side.hint.pvp": "You play blue · AI plays red",
			"status.side.hint.ai": "AI vs AI — spectating",
			"game.round": "Round {n}",
			"game.phase.prep": "Prep",
			"game.phase.battle": "Battle",
			"game.phase.settle": "Settlement",
			"game.phase.over": "Game over",
			"game.hp": "HP",
			"game.gold": "Gold",
			"game.level": "Level",
			"game.exp": "Exp",
			"game.bench": "Bench",
			"game.shop": "Shop",
			"game.upgrade": "Level up (4g)",
			"game.refresh": "Refresh (2g)",
			"game.endPrep": "End prep",
			"game.sell": "Sell",
			"game.place": "Click the board to deploy",
			"game.buy": "Buy",
			"game.income": "Next income",
			"game.streak.win": "{n}-win streak",
			"game.streak.loss": "{n}-loss streak",
			"game.boardFull": "Board full (level {level})",
			"game.benchFull": "Bench full",
			"game.battleResult.win": "Blue wins, red -{damage} HP",
			"game.battleResult.loss": "Red wins, blue -{damage} HP",
			"game.battleResult.draw": "Draw",
			"game.over": "Game over",
			"reasoning.title.blue": "Blue AI reasoning log",
			"reasoning.title.red": "Red AI reasoning log",
			"reasoning.empty": "No reasoning recorded yet",
			"reasoning.entry": "Round {round} · {side}",
			"reasoning.side.blue": "Blue",
			"reasoning.side.red": "Red",
			"reasoning.expand": "Expand",
			"reasoning.collapse": "Collapse",
			"reasoning.noActions": "（no actions, prep ended）"
		};
		//#endregion
		//#region src/client/index.ts
		/** Required services: the locale service and the slot registry. */
		const inject = ["locale", "slots"];
		/**
		* Client plugin body: register the auto-chess dictionaries and the
		* conversation-view tab. The registration rides the slot service's effect
		* wrapper, so plugin unload removes the tab.
		* @param ctx - client root context.
		*/
		function apply(ctx) {
			ctx.effect(() => ctx.locale.register(NS, {
				zh,
				en
			}), "auto-chess: dictionaries");
			const t = ctx.locale.bind(NS);
			ctx.slots.inject("conversation.view", () => ctx.slots.register({
				name: "conversation.view",
				id: "auto-chess",
				order: 30,
				label: () => t("tab.label"),
				locale: NS
			}, AutoChessView));
		}
		//#endregion
		exports.apply = apply;
		exports.inject = inject;
		return module.exports;
	}
});

//# sourceMappingURL=client.js.map