import test from "node:test";
import assert from "node:assert/strict";
import { mobComponents } from "../src/simulation/spawners.js";
import { MobId } from "../../shared/definitions/mobs.js";
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
import { WoodItemId } from "../../shared/definitions/woodItems.js";
import { GemItemId } from "../../shared/definitions/gemItems.js";
import { tierStatBonus, WoodTier } from "../../shared/definitions/materialTiers.js";
import { BlockType, blockBlocksRangedAttacks } from "../../shared/definitions/tiles.js";
import { Component } from "../src/ecs/components.js";
import { tileKey } from "../src/world/coordinates.js";
import { WorkerMessage } from "../src/simulation/protocol.js";
import { tileToRegion } from "../src/world/coordinates.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { SpellId } from "../../shared/definitions/spells.js";
import { totalXpForLevel } from "../../shared/skills/progression.js";
import { GAIT } from "../../shared/protocol/constants.js";
import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight, queueMeleeApproach, markSeekCover, engageTarget, applyDamageAndKill, markFleeOnHit, stepCombat, chebyshev, COMBAT_CHASE_RUN_TILES, combatLeashLimit, spawnOriginDistance } from "../src/combat/service.js";
import { combatDamageRollLevel } from "../../shared/combat/rolls.js";
import { SKULL_KILL_BONUS } from "../../shared/combat/skull.js";
import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
import { withDamagingCombatRng, installDamagingCombatRng, installMissDodgeRng, installBlockRng } from "./helpers/combatRng.js";

function workerOf (simulation, entityId)
{
	const record = simulation.entityRecord(entityId);
	assert.ok(record, "entity must be remembered");
	return simulation.workers[record.workerId];
}

function componentsOf (simulation, entityId)
{
	const worker = workerOf(simulation, entityId);
	const handle = worker.world.ecs.handleOf(entityId);
	assert.ok(handle != null);
	return worker.world.ecs.componentsOf(handle);
}

function teleportEntity (worker, entityId, tileX, tileY)
{
	const world = worker.world;
	const handle = world.ecs.handleOf(entityId);
	const pos = world.ecs.get(handle, Component.position);
	const fromKey = tileKey(pos.tileX, pos.tileY);
	const fromSet = world.occupancy.get(fromKey);
	if (fromSet)
	{
		fromSet.delete(entityId);
		if (fromSet.size === 0)
		{ world.occupancy.delete(fromKey); }
	}
	pos.tileX = tileX;
	pos.tileY = tileY;
	const toKey = tileKey(tileX, tileY);
	let toSet = world.occupancy.get(toKey);
	if (!toSet)
	{
		toSet = new Set();
		world.occupancy.set(toKey, toSet);
	}
	toSet.add(entityId);
}

function entityIsAlive (simulation, entityId)
{
	const record = simulation.entityRecord(entityId);
	if (!record)
	{ return false; }
	const worker = simulation.workers[record.workerId];
	const handle = worker.world.ecs.handleOf(entityId);
	if (handle == null)
	{ return false; }
	const health = worker.world.ecs.get(handle, Component.health);
	return (health?.current ?? 0) > 0;
}

function simulateAttackClick (harness, character, targetEntityId)
{
	harness.simulation.enqueue(1, {
		type: "attack",
		characterId: character.character_id,
		targetEntityId
	});
}

/** Run ticks until one combatant dies or the step budget is exhausted. */
function runCombatUntilOutcome (harness, playerId, deerId, maxSteps = 600)
{
	let swings = 0;
	for (let i = 0; i < maxSteps; i++)
	{
		harness.advance(50);
		const events = harness.simulation.step().events;
		swings += events.filter((event) => event.type === "combat-swing").length;
		const playerAlive = entityIsAlive(harness.simulation, playerId);
		const deerAlive = entityIsAlive(harness.simulation, deerId);
		if (!playerAlive || !deerAlive)
		{ return { playerAlive, deerAlive, swings, steps: i + 1 }; }
	}
	return {
		playerAlive: entityIsAlive(harness.simulation, playerId),
		deerAlive: entityIsAlive(harness.simulation, deerId),
		swings,
		steps: maxSteps
	};
}

function withDeterministicCombat (fn)
{
	withDamagingCombatRng(fn);
}

test("immortal deer auto-attacks until the player dies", () =>
{
	withDeterministicCombat(() =>
	{
		const harness = makeSimulation({ workerCount: 1 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const deerId = harness.simulation.spawnEntity(mobComponents({
				tileX: 9,
				tileY: 8,
				mobTypeId: MobId.deer,
				spawnerId: null
			}));
			const deer = componentsOf(harness.simulation, deerId);
			deer.health.current = 1_000_000;
			deer.health.max = 1_000_000;

			simulateAttackClick(harness, character, deerId);
			harness.simulation.step();

			const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
			assert.ok(outcome.swings >= 2, `expected sustained auto-attack swings, got ${outcome.swings}`);
			assert.equal(outcome.deerAlive, true, "immortal deer should survive");
			assert.equal(outcome.playerAlive, false, "deer should kill the player via auto-attack");
			assert.equal(
				componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null,
				null,
				"deer should clear engage after the player dies"
			);
		}
		finally
		{ harness.close(); }
	});
});

test("immortal deer keeps auto-attacking after the player walks away", () =>
{
	withDeterministicCombat(() =>
	{
		const harness = makeSimulation({ workerCount: 1 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const deerId = harness.simulation.spawnEntity(mobComponents({
				tileX: 9,
				tileY: 8,
				mobTypeId: MobId.deer,
				spawnerId: null
			}));
			const deer = componentsOf(harness.simulation, deerId);
			deer.health.current = 1_000_000;
			deer.health.max = 1_000_000;

			simulateAttackClick(harness, character, deerId);
			harness.simulation.step();

			// Let one exchange land, then cancel player engage by walking away (client moveTo).
			for (let i = 0; i < 30; i++)
			{
				harness.advance(50);
				const swings = harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
				if (swings > 0)
				{ break; }
			}
			harness.simulation.enqueue(1, {
				type: "move-to",
				characterId: character.character_id,
				tileX: 8,
				tileY: 14
			});
			harness.simulation.step();
			assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
			assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);

			const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
			assert.ok(outcome.swings >= 1, `expected deer pursuit swings, got ${outcome.swings}`);
			assert.equal(outcome.deerAlive, true);
			assert.equal(outcome.playerAlive, false, "deer should chase and kill the player after walk-away");
		}
		finally
		{ harness.close(); }
	});
});

test("cross-worker immortal deer auto-attacks until the player dies", () =>
{
	withDeterministicCombat(() =>
	{
		const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const deerId = harness.simulation.spawnEntity(mobComponents({
				tileX: 63,
				tileY: 8,
				mobTypeId: MobId.deer,
				spawnerId: null
			}));
			assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
			assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);

			const deerWorker = workerOf(harness.simulation, deerId);
			const deerHandle = deerWorker.world.ecs.handleOf(deerId);
			const deerHealth = deerWorker.world.ecs.get(deerHandle, Component.health);
			deerHealth.current = 1_000_000;
			deerHealth.max = 1_000_000;

			simulateAttackClick(harness, character, deerId);
			const first = harness.simulation.step();
			assert.equal(first.events.some((event) => event.type === "command-error"), false);

			const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
			assert.ok(outcome.swings >= 2, `expected sustained cross-worker swings, got ${outcome.swings}`);
			assert.equal(outcome.deerAlive, true);
			assert.equal(outcome.playerAlive, false, "cross-worker deer should kill the player via auto-attack");
		}
		finally
		{ harness.close(); }
	});
});

test("click attack from 5 tiles away ends with player or deer dead", () =>
{
	withDeterministicCombat(() =>
	{
		const harness = makeSimulation({ workerCount: 1 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const deerId = harness.simulation.spawnEntity(mobComponents({
				tileX: 13,
				tileY: 8,
				mobTypeId: MobId.deer,
				spawnerId: null
			}));

			simulateAttackClick(harness, character, deerId);
			harness.simulation.step();

			const outcome = runCombatUntilOutcome(harness, playerId, deerId);
			assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
			assert.ok(
				!outcome.playerAlive || !outcome.deerAlive,
				`expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
			);
		}
		finally
		{ harness.close(); }
	});
});

test("click attack while adjacent ends with player or deer dead", () =>
{
	withDeterministicCombat(() =>
	{
		const harness = makeSimulation({ workerCount: 1 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const deerId = harness.simulation.spawnEntity(mobComponents({
				tileX: 9,
				tileY: 8,
				mobTypeId: MobId.deer,
				spawnerId: null
			}));

			simulateAttackClick(harness, character, deerId);
			harness.simulation.step();

			const outcome = runCombatUntilOutcome(harness, playerId, deerId);
			assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
			assert.ok(
				!outcome.playerAlive || !outcome.deerAlive,
				`expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
			);
		}
		finally
		{ harness.close(); }
	});
});

test("cross-worker click attack from 5 tiles away ends with player or deer dead", () =>
{
	withDeterministicCombat(() =>
	{
		const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 59, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const deerId = harness.simulation.spawnEntity(mobComponents({
				tileX: 64,
				tileY: 8,
				mobTypeId: MobId.deer,
				spawnerId: null
			}));
			assert.equal(harness.simulation.entityRecord(playerId).workerId, 0);
			assert.equal(harness.simulation.entityRecord(deerId).workerId, 1);

			simulateAttackClick(harness, character, deerId);
			const first = harness.simulation.step();
			assert.equal(first.events.some((event) => event.type === "command-error"), false);

			const outcome = runCombatUntilOutcome(harness, playerId, deerId);
			assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
			assert.ok(
				!outcome.playerAlive || !outcome.deerAlive,
				`expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
			);
		}
		finally
		{ harness.close(); }
	});
});

test("cross-worker adjacent click attack ends with player or deer dead", () =>
{
	withDeterministicCombat(() =>
	{
		const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const deerId = harness.simulation.spawnEntity(mobComponents({
				tileX: 63,
				tileY: 8,
				mobTypeId: MobId.deer,
				spawnerId: null
			}));
			assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
			assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);

			simulateAttackClick(harness, character, deerId);
			const first = harness.simulation.step();
			assert.equal(first.events.some((event) => event.type === "command-error"), false);

			const outcome = runCombatUntilOutcome(harness, playerId, deerId);
			assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
			assert.ok(
				!outcome.playerAlive || !outcome.deerAlive,
				`expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
			);
		}
		finally
		{ harness.close(); }
	});
});

test("attack engages the attacker; target retaliates on first swing", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		// Deer are not aggressive — only retaliate after a real swing.
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: null
		}));

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: deerId
		});
		harness.simulation.step();

		assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, deerId);
		assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null, null);

		let swung = false;
		for (let i = 0; i < 80; i++)
		{
			harness.advance(50);
			const events = harness.simulation.step().events;
			if (events.some((event) => event.type === "combat-swing"))
			{
				swung = true;
				break;
			}
		}
		assert.ok(swung, "expected a melee swing once adjacent");
		assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
	}
	finally
	{ harness.close(); }
});

test("melee swing only resolves at Chebyshev distance 1", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const bag = harness.simulation.bagOf(playerId);
		const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
		assert.ok(stickSlot >= 0);
		harness.simulation.enqueue(1, {
			type: "equip-item",
			characterId: character.character_id,
			slotIndex: stickSlot
		});
		harness.simulation.step();
		assert.equal(
			harness.simulation.bagOf(playerId).equipment.slots[EQUIPMENT_SLOT.weapon]?.itemId,
			ItemId.stick
		);

		const farRat = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.rat
		}));
		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: farRat
		});
		const farEvents = harness.simulation.step().events;
		assert.equal(farEvents.some((event) => event.type === "combat-swing"), false);

		const nearRat = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat
		}));
		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: nearRat
		});
		const nearEvents = harness.simulation.step().events;
		assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
		assert.ok(nearEvents.some((event) =>
			event.type === "combat-hit"
			|| event.type === "combat-miss"
			|| event.type === "combat-block"));
	}
	finally
	{ harness.close(); }
});

test("pigeons are untargetable free-flight and never get path tiles", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		harness.simulation.spawnCharacter(1, character);
		const pigeonId = harness.simulation.spawnEntity(mobComponents({
			tileX: 10,
			tileY: 8,
			mobTypeId: MobId.pigeon
		}));

		const before = componentsOf(harness.simulation, pigeonId);
		assert.equal(before.flight != null, true);
		assert.equal(before.combat == null, true);
		assert.deepEqual(before.path?.tiles ?? [], []);

		harness.setNow(harness.now() + 500);
		stepTimes(harness.simulation, 10);
		const after = componentsOf(harness.simulation, pigeonId);
		assert.deepEqual(after.path?.tiles ?? [], []);
		assert.equal(after.flight != null, true);

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: pigeonId
		});
		const result = harness.simulation.step();
		assert.ok(result.events.some((event) => event.type === "command-error"));
		assert.equal(componentsOf(harness.simulation, pigeonId).path?.tiles?.length ?? 0, 0);
	}
	finally
	{ harness.close(); }
});

test("deer retaliate when attacked", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: null
		}));

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: deerId
		});
		const events = harness.simulation.step().events;
		assert.ok(events.some((event) => event.type === "combat-swing"));

		const deer = componentsOf(harness.simulation, deerId);
		assert.equal(deer.combat?.targetEntityId, playerId);
		assert.ok(deer.skills?.levels?.unarmed >= 1);
	}
	finally
	{ harness.close(); }
});

test("aggressive rats engage players within aggro range and LOS", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));

		harness.simulation.step();
		assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);
	}
	finally
	{ harness.close(); }
});

test("aggressive creatures run when chasing farther than two tiles", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));

		harness.simulation.step();
		assert.equal(componentsOf(harness.simulation, ratId).combat?.targetEntityId, playerId);
		assert.equal(componentsOf(harness.simulation, ratId).movement.gait, GAIT.run);
		assert.equal(chebyshev(12, 8, 8, 8) > COMBAT_CHASE_RUN_TILES, true);
		assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.walk);

		const worker = workerOf(harness.simulation, ratId);
		teleportEntity(worker, ratId, 10, 8);
		harness.simulation.step();
		assert.equal(chebyshev(10, 8, 8, 8), COMBAT_CHASE_RUN_TILES);
		assert.equal(componentsOf(harness.simulation, ratId).movement.gait, GAIT.walk);
	}
	finally
	{ harness.close(); }
});

test("aggressive mobs and town guards aggro each other", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 2 });
		harness.simulation.spawnCharacter(1, character);
		const guardId = harness.simulation.spawnEntity(mobComponents({
			tileX: 10,
			tileY: 8,
			mobTypeId: MobId.townGuard,
			spawnerId: "0:0:guard",
			originTileX: 10,
			originTileY: 8,
			wanderRangeTiles: 4,
			level: 10
		}));
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: "0:0:rat",
			originTileX: 12,
			originTileY: 8,
			wanderRangeTiles: 4,
			aggressive: true
		}));

		harness.simulation.step();
		const ratCombat = componentsOf(harness.simulation, ratId).combat?.targetEntityId;
		const guardCombat = componentsOf(harness.simulation, guardId).combat?.targetEntityId;
		assert.ok(
			ratCombat === guardId || guardCombat === ratId,
			`expected mutual aggro; rat→${ratCombat} guard→${guardCombat}`
		);
	}
	finally
	{ harness.close(); }
});

test("town guards aggro players whose skull tint lerps toward red", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		harness.stateDb.addKillCounter(character.character_id, SKULL_KILL_BONUS + 1, harness.now());
		const playerId = harness.simulation.spawnCharacter(1, character);
		assert.equal(componentsOf(harness.simulation, playerId).character?.skullValue, SKULL_KILL_BONUS + 1);

		const guardId = harness.simulation.spawnEntity(mobComponents({
			tileX: 10,
			tileY: 8,
			mobTypeId: MobId.townGuard,
			spawnerId: "0:0:guard",
			originTileX: 10,
			originTileY: 8,
			wanderRangeTiles: 8,
			level: 10
		}));

		harness.simulation.step();
		assert.equal(
			componentsOf(harness.simulation, guardId).combat?.targetEntityId,
			playerId
		);
	}
	finally
	{ harness.close(); }
});

test("town guards ignore players at black-max skull (not yet red)", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		harness.stateDb.setKillCounter(character.character_id, SKULL_KILL_BONUS, harness.now());
		const playerId = harness.simulation.spawnCharacter(1, character);
		assert.equal(componentsOf(harness.simulation, playerId).character?.skullValue, SKULL_KILL_BONUS);

		const guardId = harness.simulation.spawnEntity(mobComponents({
			tileX: 10,
			tileY: 8,
			mobTypeId: MobId.townGuard,
			spawnerId: "0:0:guard",
			originTileX: 10,
			originTileY: 8,
			wanderRangeTiles: 8,
			level: 10
		}));

		harness.simulation.step();
		assert.equal(componentsOf(harness.simulation, guardId).combat?.targetEntityId, null);
		assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, null);
	}
	finally
	{ harness.close(); }
});

test("town guards ignore players with white-only skull", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		harness.stateDb.setKillCounter(character.character_id, 1, harness.now());
		const playerId = harness.simulation.spawnCharacter(1, character);
		assert.equal(componentsOf(harness.simulation, playerId).character?.skullValue, 1);

		const guardId = harness.simulation.spawnEntity(mobComponents({
			tileX: 10,
			tileY: 8,
			mobTypeId: MobId.townGuard,
			spawnerId: "0:0:guard",
			originTileX: 10,
			originTileY: 8,
			wanderRangeTiles: 8,
			level: 10
		}));

		harness.simulation.step();
		assert.equal(componentsOf(harness.simulation, guardId).combat?.targetEntityId, null);
		assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, null);
	}
	finally
	{ harness.close(); }
});

test("spawner mobs far from home path chunk-step toward the origin", () =>
{
	const harness = makeSimulation({ workerCount: 1, maxChunkX: 5 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 10,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: "0:0:deer",
			originTileX: 8,
			originTileY: 8,
			wanderRangeTiles: 2
		}));
		const worker = workerOf(harness.simulation, playerId);
		teleportEntity(worker, deerId, 40, 8);
		const handle = worker.world.ecs.handleOf(deerId);
		worker.world.ecs.get(handle, Component.path).tiles = [];

		let movedCloser = false;
		for (let i = 0; i < 40; i++)
		{
			harness.advance(50);
			harness.simulation.step();
			const pos = worker.world.ecs.get(handle, Component.position);
			const path = worker.world.ecs.get(handle, Component.path)?.tiles ?? [];
			const fromX = pos.tileX;
			const fromY = pos.tileY;
			const fromDist = Math.max(Math.abs(fromX - 8), Math.abs(fromY - 8));
			if (path.length)
			{
				const dest = path[path.length - 1];
				const destDist = Math.max(Math.abs(dest.x - 8), Math.abs(dest.y - 8));
				if (destDist < fromDist)
				{
					movedCloser = true;
					break;
				}
			}
			if (fromDist < 32)
			{
				movedCloser = true;
				break;
			}
		}
		assert.ok(movedCloser, "expected a return path closer to the spawner");
	}
	finally
	{ harness.close(); }
});

test("players retaliate when a mob swings at them", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));

		assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);

		let swung = false;
		for (let i = 0; i < 80; i++)
		{
			harness.advance(50);
			const events = harness.simulation.step().events;
			if (events.some((event) =>
				event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
			))
			{
				swung = true;
				break;
			}
		}
		assert.ok(swung, "expected the rat to swing at the player");
		assert.equal(
			componentsOf(harness.simulation, playerId).combat?.targetEntityId,
			ratId,
			"player should auto-retaliate after the mob swing"
		);
	}
	finally
	{ harness.close(); }
});

test("staff with favorite attack spell retaliates by auto-casting it", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const equipment = worker.world.ecs.get(handle, Component.equipment);
		equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
		const spells = worker.world.ecs.get(handle, Component.spells);
		spells.known.push(SpellId.manaBullet);
		spells.favorites = [SpellId.light, SpellId.manaBullet];
		spells.autoCast = false;

		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
		resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());

		const casting = worker.world.ecs.get(handle, Component.spellcasting);
		assert.equal(casting.repeatSpellId, SpellId.manaBullet);
		assert.equal(casting.repeatTargetEntityId, ratId);
		assert.equal(
			componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
			null,
			"staff spell retaliate should not melee-engage"
		);
	}
	finally
	{ harness.close(); }
});

test("staff without favorite attack spell retaliates with melee", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const equipment = worker.world.ecs.get(handle, Component.equipment);
		equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
		const spells = worker.world.ecs.get(handle, Component.spells);
		spells.favorites = [SpellId.light];

		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
		resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());

		assert.equal(
			componentsOf(harness.simulation, playerId).combat?.targetEntityId,
			ratId,
			"staff without attack favorites should melee-retaliate"
		);
		assert.equal(
			worker.world.ecs.get(handle, Component.spellcasting)?.repeatSpellId ?? null,
			null
		);
	}
	finally
	{ harness.close(); }
});

test("staff click-attack arms favorite spell instead of melee approach", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		// Beyond spell range so auto-cast queues a stand-in-range path (not melee adjacency).
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 28,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const equipment = worker.world.ecs.get(handle, Component.equipment);
		equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
		const spells = worker.world.ecs.get(handle, Component.spells);
		spells.known.push(SpellId.manaBullet);
		spells.favorites = [SpellId.manaBullet];
		spells.autoCast = false;

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: ratId
		});
		harness.simulation.step();

		const casting = worker.world.ecs.get(handle, Component.spellcasting);
		assert.equal(casting.repeatSpellId, SpellId.manaBullet);
		assert.equal(casting.repeatTargetEntityId, ratId);
		assert.equal(
			componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
			null,
			"staff click-attack should not melee-engage"
		);

		const path = componentsOf(harness.simulation, playerId).path;
		const tiles = path?.tiles ?? [];
		assert.ok(tiles.length > 0, "should approach into spell range");
		const last = tiles[tiles.length - 1];
		const standDist = chebyshev(last.x, last.y, 28, 8);
		assert.ok(
			standDist > 1,
			`spell approach should stop outside melee adjacency, got dist=${standDist}`
		);
	}
	finally
	{ harness.close(); }
});

test("staff cast-spell-entity approaches spell range and keeps auto-repeat without autoCast", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 28,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const equipment = worker.world.ecs.get(handle, Component.equipment);
		equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
		const spells = worker.world.ecs.get(handle, Component.spells);
		spells.known.push(SpellId.manaBullet);
		spells.favorites = [SpellId.manaBullet];
		spells.autoCast = false;
		const skills = worker.world.ecs.get(handle, Component.skills);
		skills.xp[SkillId.magic] = totalXpForLevel(20);

		harness.simulation.enqueue(1, {
			type: "cast-spell-entity",
			characterId: character.character_id,
			spellId: SpellId.manaBullet,
			targetEntityId: ratId
		});
		harness.simulation.step();

		const casting = worker.world.ecs.get(handle, Component.spellcasting);
		assert.equal(casting.repeatSpellId, SpellId.manaBullet);
		assert.equal(casting.repeatTargetEntityId, ratId);
		assert.equal(casting.pendingCast?.spellId, SpellId.manaBullet);
		assert.equal(
			componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
			null
		);
		const path = componentsOf(harness.simulation, playerId).path;
		const tiles = path?.tiles ?? [];
		assert.ok(tiles.length > 0, "should approach into spell range");
		const last = tiles[tiles.length - 1];
		assert.ok(chebyshev(last.x, last.y, 28, 8) > 1);
	}
	finally
	{ harness.close(); }
});

test("players do not auto-retaliate while walking from a click order", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));

		harness.simulation.enqueue(1, {
			type: "move-to",
			characterId: character.character_id,
			tileX: 8,
			tileY: 14
		});
		harness.simulation.step();
		const path = componentsOf(harness.simulation, playerId).path;
		assert.ok((path?.tiles?.length ?? 0) > 0, "player should be pathing");

		let swung = false;
		for (let i = 0; i < 80; i++)
		{
			harness.advance(50);
			const events = harness.simulation.step().events;
			if (events.some((event) =>
				event.type === "combat-swing" && event.attackerId === ratId && event.targetId === playerId
			))
			{
				swung = true;
				break;
			}
		}
		assert.ok(swung, "expected the rat to swing at the walking player");
		assert.equal(
			componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
			null,
			"walking player should not auto-retaliate"
		);
		assert.ok(
			(componentsOf(harness.simulation, playerId).path?.tiles?.length ?? 0) > 0
				|| componentsOf(harness.simulation, playerId).position.tileY !== 8,
			"walk order should continue after the hit"
		);
	}
	finally
	{ harness.close(); }
});

test("players do not auto-retaliate while gathering", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	const restore = installDamagingCombatRng();
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		worker.world.ecs.add(handle, Component.gather, {
			kind: "mining",
			tileX: 7,
			tileY: 8,
			materialId: "copper",
			durationMs: 60_000,
			startedAt: Date.now(),
			finishesAt: Date.now() + 60_000,
			nextSwingAt: Date.now() + 60_000
		});
		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
		const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
		assert.ok(events.some((event) => event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block"));
		assert.equal(
			componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null,
			null,
			"gathering player should not auto-retaliate"
		);
		assert.ok(
			worker.world.ecs.has(handle, Component.gather),
			"gather session should survive the hit"
		);
	}
	finally
	{
		restore();
		harness.close();
	}
});

test("aggressive rats do not aggro through walls or beyond range", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const blockedRat = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const world = worker.world;
		const data = world.chunkData(0, 0);
		const wall = { typeId: BlockType.stoneWall, state: null, config: null };
		for (let y = 6; y <= 10; y++)
		{ data.blocks[y * 16 + 10] = wall; }

		harness.simulation.step();
		assert.equal(
			componentsOf(harness.simulation, blockedRat).combat?.targetEntityId ?? null,
			null,
			"wall blocks LOS aggro"
		);

		const farRat = harness.simulation.spawnEntity(mobComponents({
			tileX: 20,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		harness.simulation.step();
		assert.equal(
			componentsOf(harness.simulation, farRat).combat?.targetEntityId ?? null,
			null,
			"out of range does not aggro"
		);
	}
	finally
	{ harness.close(); }
});

test("crafting stations and tables do not block ranged or spell line of sight", () =>
{
	assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
	assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
	assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
	assert.equal(blockBlocksRangedAttacks(null), false);

	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const worker = workerOf(harness.simulation, playerId);
		const data = worker.world.chunkData(0, 0);
		const blockIndex = (localY, localX) => localY * 16 + localX;

		data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
		assert.equal(
			hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
			true,
			"furnace between caster and target should not block"
		);

		data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
		assert.equal(
			hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
			true,
			"table between caster and target should not block"
		);

		data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
		assert.equal(
			hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
			false,
			"stone wall should still block"
		);
	}
	finally
	{ harness.close(); }
});

test("attacker keeps pursuing and can swing after the target moves", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: ratId
		});
		harness.simulation.step();

		const worker = workerOf(harness.simulation, playerId);
		stepTimes(harness.simulation, 4);
		teleportEntity(worker, ratId, 12, 10);

		let swings = 0;
		for (let i = 0; i < 120; i++)
		{
			const events = harness.simulation.step().events;
			swings += events.filter((event) => event.type === "combat-swing").length;
			if (swings > 0)
			{ break; }
		}

		assert.ok(swings >= 1);
		assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, ratId);
	}
	finally
	{ harness.close(); }
});

test("combatants keep auto-attacking while adjacent", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: null
		}));

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: deerId
		});
		harness.simulation.step();

		let swings = 0;
		for (let i = 0; i < 50; i++)
		{
			harness.advance(50);
			const events = harness.simulation.step().events;
			swings += events.filter((event) => event.type === "combat-swing").length;
			const player = componentsOf(harness.simulation, playerId);
			const deer = componentsOf(harness.simulation, deerId);
			if (swings >= 4
				&& player.combat?.targetEntityId === deerId
				&& deer.combat?.targetEntityId === playerId
				&& (player.health?.current ?? 0) > 0)
			{ break; }
		}

		assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
		const player = componentsOf(harness.simulation, playerId);
		const deer = componentsOf(harness.simulation, deerId);
		assert.ok((player.health?.current ?? 0) > 0, "player should still be alive during sustained combat");
		assert.equal(player.combat?.targetEntityId, deerId);
		assert.equal(deer.combat?.targetEntityId, playerId);
	}
	finally
	{ harness.close(); }
});

test("cross-worker adjacent combat keeps engaging and swinging", () =>
{
	const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 63,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: null
		}));
		assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
		assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: deerId
		});
		const first = harness.simulation.step();
		assert.equal(first.events.some((event) => event.type === "command-error"), false);

		const random = Math.random;
		Math.random = () => 0;
		try
		{
			let swings = 0;
			for (let i = 0; i < 40; i++)
			{
				harness.advance(50);
				swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
				if (swings >= 4)
				{ break; }
			}

			assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
			const deerWorker = harness.simulation.workers[0];
			const playerWorker = harness.simulation.workers[1];
			const deerHandle = deerWorker.world.ecs.handleOf(deerId);
			const playerHandle = playerWorker.world.ecs.handleOf(playerId);
			const deerCombat = deerWorker.world.ecs.get(deerHandle, Component.combat);
			const playerCombat = playerWorker.world.ecs.get(playerHandle, Component.combat);
			const playerHealth = playerWorker.world.ecs.get(playerHandle, Component.health);
			assert.ok((playerHealth?.current ?? 0) > 0, "player should survive sustained cross-worker combat");
			assert.equal(deerCombat?.targetEntityId, playerId);
			assert.equal(playerCombat?.targetEntityId, deerId);
		}
		finally
		{ Math.random = random; }
	}
	finally
	{ harness.close(); }
});

test("cancel attack stops the player but the mob keeps pursuing", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));

		harness.simulation.enqueue(1, {
			type: "attack",
			characterId: character.character_id,
			targetEntityId: ratId
		});
		harness.simulation.step();

		harness.simulation.enqueue(1, {
			type: "cancel-attack",
			characterId: character.character_id
		});
		harness.simulation.step();

		const player = componentsOf(harness.simulation, playerId);
		const rat = componentsOf(harness.simulation, ratId);
		assert.equal(player.combat?.targetEntityId, null);
		assert.equal(rat.combat?.targetEntityId, playerId);
	}
	finally
	{ harness.close(); }
});

test("player combat and skills components are present on spawn", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb);
		const playerId = harness.simulation.spawnCharacter(1, character);
		const comps = componentsOf(harness.simulation, playerId);
		assert.ok(comps.combat);
		assert.equal(comps.skills?.xp?.clubfighting, 0);
		assert.ok(comps.health);
	}
	finally
	{ harness.close(); }
});

test("mobs heal to full when their region unloads", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const ratId = harness.simulation.spawnEntity(mobComponents({
			tileX: 8,
			tileY: 8,
			mobTypeId: MobId.rat
		}));
		const worker = workerOf(harness.simulation, ratId);
		const handle = worker.world.ecs.handleOf(ratId);
		worker.world.ecs.get(handle, Component.health).current = 2;
		const result = worker.call({
			type: WorkerMessage.dropRegion,
			regionX: tileToRegion(8),
			regionY: tileToRegion(8)
		});
		const record = result.dropped.find((entry) => entry.entityId === ratId);
		assert.ok(record);
		assert.equal(
			record.payload.components.health.current,
			record.payload.components.health.max
		);
	}
	finally
	{ harness.close(); }
});

test("taking damage awards Health XP equal to damage dealt", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	const restore = installDamagingCombatRng();
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			mobTypeId: MobId.rat,
			tileX: 9,
			tileY: 8
		}));
		const worker = harness.simulation.workers[0];
		const playerHandle = worker.world.ecs.handleOf(playerId);
		const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
		const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
		const hit = events.find((event) => event.type === "combat-hit");
		assert.ok(hit);
		const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
		assert.ok(updated);
		assert.equal(updated.stored[SkillId.health] - before, hit.damage);
	}
	finally
	{
		restore();
		harness.close();
	}
});

test("lethal damage awards no Health XP", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	const restore = installDamagingCombatRng();
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			mobTypeId: MobId.rat,
			tileX: 9,
			tileY: 8
		}));
		const worker = harness.simulation.workers[0];
		const playerHandle = worker.world.ecs.handleOf(playerId);
		const health = worker.world.ecs.get(playerHandle, Component.health);
		health.current = 1;
		const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
		const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
		const hit = events.find((event) => event.type === "combat-hit");
		assert.ok(hit);
		assert.ok(hit.damage >= 1);
		assert.equal(hit.health, 0);
		const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
		assert.equal(updated, undefined);
		assert.equal(worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health], before);
	}
	finally
	{
		restore();
		harness.close();
	}
});

test("dodging a hit awards Agility XP equal to avoided damage", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	const restore = installMissDodgeRng(1);
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			mobTypeId: MobId.rat,
			tileX: 9,
			tileY: 8
		}));
		const worker = harness.simulation.workers[0];
		const playerHandle = worker.world.ecs.handleOf(playerId);
		const skills = worker.world.ecs.get(playerHandle, Component.skills);
		skills.xp[SkillId.agility] = totalXpForLevel(10);
		const before = skills.xp[SkillId.agility] | 0;
		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
		const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
		assert.ok(events.find((event) => event.type === "combat-miss"));
		const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
		assert.ok(updated);
		assert.equal(updated.stored[SkillId.agility] - before, 1);
	}
	finally
	{
		restore();
		harness.close();
	}
});

test("blocking a hit awards Defence XP equal to avoided damage", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	const restore = installBlockRng(1);
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const ratId = harness.simulation.spawnEntity(mobComponents({
			mobTypeId: MobId.rat,
			tileX: 9,
			tileY: 8
		}));
		const worker = harness.simulation.workers[0];
		const playerHandle = worker.world.ecs.handleOf(playerId);
		const skills = worker.world.ecs.get(playerHandle, Component.skills);
		skills.xp[SkillId.defence] = totalXpForLevel(10);
		const before = skills.xp[SkillId.defence] | 0;
		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
		const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
		assert.ok(events.find((event) => event.type === "combat-block"));
		const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
		assert.ok(updated);
		assert.equal(updated.stored[SkillId.defence] - before, 1);
	}
	finally
	{
		restore();
		harness.close();
	}
});

test("stacked combatants against the same target spread to different tiles", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const rat1 = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const rat2 = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 7,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const playerHealth = worker.world.ecs.get(handle, Component.health);
		playerHealth.max = 500;
		playerHealth.current = 500;
		engageTarget(worker.world.ecs, rat1, playerId);
		engageTarget(worker.world.ecs, rat2, playerId);
		assert.equal(componentsOf(harness.simulation, rat1).combat?.targetEntityId, playerId);
		assert.equal(componentsOf(harness.simulation, rat2).combat?.targetEntityId, playerId);
		teleportEntity(worker, rat2, 9, 8);

		for (let i = 0; i < 200; i++)
		{
			harness.advance(50);
			harness.simulation.step();
		}

		const pos1 = componentsOf(harness.simulation, rat1).position;
		const pos2 = componentsOf(harness.simulation, rat2).position;
		assert.notEqual(
			`${pos1.tileX},${pos1.tileY}`,
			`${pos2.tileX},${pos2.tileY}`,
			"expected stacked rats to spread apart"
		);
	}
	finally
	{ harness.close(); }
});

test("approaching combatants pick different adjacent goals", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const rat1 = harness.simulation.spawnEntity(mobComponents({
			tileX: 6,
			tileY: 8,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const rat2 = harness.simulation.spawnEntity(mobComponents({
			tileX: 6,
			tileY: 7,
			mobTypeId: MobId.rat,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		teleportEntity(worker, rat2, 6, 8);

		for (let i = 0; i < 120; i++)
		{
			harness.advance(50);
			harness.simulation.step();
		}

		const path1 = componentsOf(harness.simulation, rat1).path?.tiles ?? [];
		const path2 = componentsOf(harness.simulation, rat2).path?.tiles ?? [];
		const goal1 = path1[path1.length - 1];
		const goal2 = path2[path2.length - 1];
		if (goal1 && goal2)
		{
			assert.notEqual(
				`${goal1.x},${goal1.y}`,
				`${goal2.x},${goal2.y}`,
				"expected different approach goals"
			);
		}

		const pos1 = componentsOf(harness.simulation, rat1).position;
		const pos2 = componentsOf(harness.simulation, rat2).position;
		assert.notEqual(`${pos1.tileX},${pos1.tileY}`, `${pos2.tileX},${pos2.tileY}`);
	}
	finally
	{ harness.close(); }
});

test("humanoid attackers add equipment bonuses on top of spawner level", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	const random = Math.random;
	/** Max every skill roll so damage equals effective damage skill. */
	Math.random = () => 0.999999;
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const player = componentsOf(harness.simulation, playerId);
		player.skills.xp[SkillId.agility] = 0;
		player.skills.xp[SkillId.defence] = 0;

		const level = 5;
		const npcId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.humanoid,
			level,
			displayName: "Guard",
			sex: "male",
			equipment: {
				weapon: WoodItemId.oakQuarterstaff
			}
		}));
		const worker = workerOf(harness.simulation, npcId);
		const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(npcId));
		assert.equal(profile.mobAttackSkill, level);
		assert.equal(profile.damageSkillId, SkillId.strength);

		const events = resolveMeleeSwing(worker.world, npcId, playerId, profile, Date.now());
		const hit = events.find((event) => event.type === "combat-hit");
		assert.ok(hit, "expected a hit");
		assert.equal(hit.damage, combatDamageRollLevel(level + tierStatBonus(WoodTier.oak)));
	}
	finally
	{
		Math.random = random;
		harness.close();
	}
});

test("staff melees like a quarterstaff and awards clubs XP", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	const random = Math.random;
	Math.random = () => 0.999999;
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.deer
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const equipment = worker.world.ecs.get(handle, Component.equipment);
		equipment.slots.weapon = { itemId: GemItemId.pineStaff, quantity: 1 };
		const skills = worker.world.ecs.get(handle, Component.skills);
		skills.xp[SkillId.clubfighting] = totalXpForLevel(10);
		skills.xp[SkillId.magic] = totalXpForLevel(10);
		const clubsBefore = skills.xp[SkillId.clubfighting];
		const magicBefore = skills.xp[SkillId.magic];

		const profile = attackProfileOf(worker.world.ecs, handle);
		assert.equal(profile.mode, "melee");
		assert.equal(profile.hitSkillId, SkillId.clubfighting);
		assert.equal(profile.damageSkillId, SkillId.strength);

		const events = resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
		const hit = events.find((event) => event.type === "combat-hit");
		assert.ok(hit, "staff should land a melee hit");
		const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
		assert.ok(updated);
		assert.ok(updated.stored[SkillId.clubfighting] > clubsBefore, "melee staff awards clubs XP");
		assert.equal(updated.stored[SkillId.magic], magicBefore, "melee staff does not award magic XP");
	}
	finally
	{
		Math.random = random;
		harness.close();
	}
});

test("spell damage marks seekCover on a melee mob", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 12,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		applyDamageAndKill(worker.world, playerId, deerId, 1, Date.now());
		assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
		assert.equal(componentsOf(harness.simulation, deerId).combat?.seekCover, true);
	}
	finally
	{ harness.close(); }
});

test("melee hit does not mark seekCover on a retaliating mob", () =>
{
	const random = Math.random;
	Math.random = () => 0;
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const handle = worker.world.ecs.handleOf(playerId);
		const bag = harness.simulation.bagOf(playerId);
		const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
		if (stickSlot >= 0)
		{
			harness.simulation.enqueue(1, {
				type: "equip-item",
				characterId: character.character_id,
				slotIndex: stickSlot
			});
			harness.simulation.step();
		}
		const profile = attackProfileOf(worker.world.ecs, handle);
		assert.equal(profile.mode, "melee");
		resolveMeleeSwing(worker.world, playerId, deerId, profile, Date.now());
		assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
		assert.equal(!!componentsOf(harness.simulation, deerId).combat?.seekCover, false);
	}
	finally
	{
		Math.random = random;
		harness.close();
	}
});

test("seekCover mob flees to a no-LOS tile when melee approach is impossible", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const deerId = harness.simulation.spawnEntity(mobComponents({
			tileX: 14,
			tileY: 8,
			mobTypeId: MobId.deer,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, playerId);
		const world = worker.world;
		const data = world.chunkData(0, 0);
		const wall = { typeId: BlockType.stoneWall, state: null, config: null };
		const furnace = { typeId: BlockType.furnace, state: null, config: null };
		// Impassable stations around the player (do not block LOS) so no melee stand tile exists.
		for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]])
		{ data.blocks[(8 + dy) * 16 + (8 + dx)] = furnace; }
		// Cover wall east of the approach.
		for (let y = 6; y <= 10; y++)
		{ data.blocks[y * 16 + 12] = wall; }

		assert.equal(hasCombatLineOfSight(world, 8, 8, 14, 8), false, "wall should block LOS east of the wall");

		const deerHandle = world.ecs.handleOf(deerId);
		engageTarget(world.ecs, deerId, playerId);
		markSeekCover(world.ecs, deerId);
		const playerPos = world.ecs.get(world.ecs.handleOf(playerId), Component.position);
		teleportEntity(worker, deerId, 11, 8);
		assert.equal(hasCombatLineOfSight(world, 8, 8, 11, 8), true);
		queueMeleeApproach(world, deerId, deerHandle, world.ecs.get(deerHandle, Component.position), playerPos);
		const path = world.ecs.get(deerHandle, Component.path)?.tiles ?? [];
		assert.ok(path.length > 0, "expected a flee path into cover");
		const dest = path[path.length - 1];
		assert.equal(
			hasCombatLineOfSight(world, playerPos.tileX, playerPos.tileY, dest.x, dest.y),
			false,
			"flee destination must be out of player LOS"
		);
	}
	finally
	{ harness.close(); }
});

test("fairy flees to 2 tiles from hit source, then stops until hit again", () =>
{
	const harness = makeSimulation({ workerCount: 1 });
	try
	{
		const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
		const playerId = harness.simulation.spawnCharacter(1, character);
		const fairyId = harness.simulation.spawnEntity(mobComponents({
			tileX: 9,
			tileY: 8,
			mobTypeId: MobId.fairy,
			spawnerId: null
		}));
		const worker = workerOf(harness.simulation, fairyId);
		const world = worker.world;
		const fairyHandle = world.ecs.handleOf(fairyId);

		applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
		const combat = world.ecs.get(fairyHandle, Component.combat);
		assert.equal(combat?.fleeFrom?.tileX, 8);
		assert.equal(combat?.fleeFrom?.tileY, 8);
		assert.equal(combat?.fleeFrom?.minDist, 2);
		assert.equal(combat?.targetEntityId, playerId);

		stepCombat(world, Date.now());
		const path = world.ecs.get(fairyHandle, Component.path)?.tiles ?? [];
		assert.ok(path.length > 0, "fairy should path away while fleeing");
		const dest = path[path.length - 1];
		assert.ok(
			chebyshev(dest.x, dest.y, 8, 8) >= 2,
			`flee dest should be ≥2 from hit source, got ${dest.x},${dest.y}`
		);

		teleportEntity(worker, fairyId, dest.x, dest.y);
		world.ecs.get(fairyHandle, Component.path).tiles = [];
		stepCombat(world, Date.now());
		assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom, null);

		stepCombat(world, Date.now() + 5000);
		assert.equal(
			world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
			null,
			"no flee until hit again"
		);

		teleportEntity(worker, fairyId, 9, 8);
		applyDamageAndKill(world, playerId, fairyId, 1, Date.now());
		assert.equal(world.ecs.get(fairyHandle, Component.combat)?.fleeFrom?.minDist, 2);

		teleportEntity(worker, fairyId, 12, 8);
		markFleeOnHit(world, fairyId, playerId);
		assert.equal(
			world.ecs.get(fairyHandle, Component.combat)?.fleeFrom,
			null,
			"already ≥2 tiles away does not start a flee"
		);
	}
	finally
	{ harness.close(); }
});

test("combat leash limit is three times wander range", () =>
{
	assert.equal(combatLeashLimit(4), 12);
	assert.equal(combatLeashLimit(0), 0);
	assert.equal(spawnOriginDistance({ tileX: 8, tileY: 8 }, { originTileX: 8, originTileY: 12 }), 4);
});

test("spawner mobs break combat beyond 3× wander range and leash home", () =>
{
	withDamagingCombatRng(() =>
	{
		const harness = makeSimulation({ workerCount: 1 });
		try
		{
			const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
			const playerId = harness.simulation.spawnCharacter(1, character);
			const ratId = harness.simulation.spawnEntity(mobComponents({
				tileX: 10,
				tileY: 8,
				mobTypeId: MobId.rat,
				spawnerId: "leash-rat",
				originTileX: 10,
				originTileY: 8,
				wanderRangeTiles: 2,
				aggressive: true
			}));
			harness.simulation.step();

			const worker = workerOf(harness.simulation, ratId);
			const world = worker.world;
			const handle = world.ecs.handleOf(ratId);
			engageTarget(world.ecs, ratId, playerId, Date.now());
			assert.equal(world.ecs.get(handle, Component.combat)?.targetEntityId, playerId);

			// Euclidean distance 7 > 3×2=6 → break leash.
			teleportEntity(worker, ratId, 17, 8);
			stepCombat(world, Date.now());
			const combat = world.ecs.get(handle, Component.combat);
			assert.equal(combat?.targetEntityId, null);
			assert.equal(combat?.leashing, true);

			stepTimes(harness.simulation, 5);
			const path = world.ecs.get(handle, Component.path);
			assert.ok(
				(path?.tiles?.length ?? 0) > 0 || (() =>
				{
					const pos = world.ecs.get(handle, Component.position);
					return Math.max(Math.abs(pos.tileX - 10), Math.abs(pos.tileY - 8)) <= 2;
				})(),
				"leashing mob should path toward wander home"
			);
		}
		finally
		{ harness.close(); }
	});
});
