import { spriteImageName } from "./tileSprites.js";
import { centralExchangeStaffCount } from "../market/exchange.js";
import { LeatherItemId } from "./leatherItems.js";
import { RangedItemId } from "./rangedItems.js";
import { ItemId } from "./items.js";

export const MobId = Object.freeze({
	deer: "deer",
	pigeon: "pigeon",
	rat: "rat",
	chicken: "chicken",
	humanoid: "humanoid",
	/** Humanoid guards that respond to bounty kills within wander range. */
	townGuard: "town-guard",
	/** Editor/spawner identity for Central Exchange staff (always humanoid bodies). */
	centralExchange: "central-exchange"
});

/** @typedef {{ itemId: number, chance: number, quantity?: number, quantityMin?: number, quantityMax?: number }} MobDrop */
/** @typedef {{ isPlayer: boolean, text: string }} DialogueLine */
/** @typedef {{ trigger: string, text: string, available?: (ctx: object) => boolean }} DialogueResponse */

/**
 * Target mob content schema (rendering fields stay alongside gameplay fields for now).
 * - displayName: shown name
 * - health / maxHealth: hit points
 * - attackSkill: one skill level for hit chance and damage
 * - drops: { itemId, chance } roll on death
 * - sells: default item IDs for shop stock (overridable per spawner)
 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
 * - usePlayerBody: draw male/female character body instead of a mob sprite
 */
export const MOB_DEFINITIONS = Object.freeze({
	[MobId.deer]: Object.freeze({
		mobTypeId: MobId.deer,
		key: "deer",
		assetFolder: "mobs",
		displayName: "Deer",
		health: 8,
		maxHealth: 8,
		attackSkill: 2,
		attackCooldownMs: 1000,
		drops: Object.freeze([
			{ itemId: LeatherItemId.softLeather, chance: 1 }
		]),
		sells: Object.freeze([]),
		dialogue: Object.freeze([]),
		persistent: false,
		flying: false,
		freeFlight: false,
		ambient: false,
		talkable: false,
		untargetable: false,
		aggressive: false,
		gait: "walk",
		sex: "male",
		frames: 1,
		framesPerRow: 1,
		animationSpeed: 0
	}),
	[MobId.pigeon]: Object.freeze({
		mobTypeId: MobId.pigeon,
		key: "pigeon",
		assetFolder: "pigeons",
		displayName: "Pigeon",
		health: 1,
		maxHealth: 1,
		canFight: false,
		drops: Object.freeze([]),
		sells: Object.freeze([]),
		dialogue: Object.freeze([]),
		persistent: false,
		flying: true,
		freeFlight: true,
		ambient: false,
		talkable: false,
		untargetable: true,
		aggressive: false,
		gait: "walk",
		sex: "male",
		frames: 2,
		framesPerRow: 2,
		animationSpeed: 0.18,
		defaultState: "pigeon-flying",
		flightSpeedTilesPerSec: 2.5
	}),
	[MobId.rat]: Object.freeze({
		mobTypeId: MobId.rat,
		key: "rat",
		assetFolder: "mobs",
		displayName: "Rat",
		health: 12,
		maxHealth: 12,
		attackSkill: 3,
		attackCooldownMs: 900,
		drops: Object.freeze([]),
		sells: Object.freeze([]),
		dialogue: Object.freeze([]),
		persistent: false,
		flying: false,
		freeFlight: false,
		ambient: false,
		talkable: false,
		untargetable: false,
		/** Auto-engage nearby players when in range with line of sight. */
		aggressive: true,
		aggroRangeTiles: 5,
		elementAffinities: Object.freeze({ fire: "weak" }),
		gait: "walk",
		sex: "male",
		frames: 1,
		framesPerRow: 1,
		animationSpeed: 0
	}),
	[MobId.chicken]: Object.freeze({
		mobTypeId: MobId.chicken,
		key: "chicken",
		assetFolder: "mobs",
		displayName: "Chicken",
		health: 5,
		maxHealth: 5,
		attackSkill: 1,
		attackCooldownMs: 1200,
		drops: Object.freeze([
			{ itemId: RangedItemId.feather, chance: 1, quantityMin: 1, quantityMax: 3 },
			{ itemId: ItemId.egg, chance: 0.2 }
		]),
		sells: Object.freeze([]),
		dialogue: Object.freeze([]),
		persistent: false,
		flying: false,
		freeFlight: false,
		ambient: false,
		talkable: false,
		untargetable: false,
		aggressive: false,
		gait: "walk",
		sex: "female",
		frames: 1,
		framesPerRow: 1,
		animationSpeed: 0
	}),
	[MobId.humanoid]: Object.freeze({
		mobTypeId: MobId.humanoid,
		key: "humanoid",
		assetFolder: "characters",
		displayName: "Humanoid",
		health: 10,
		maxHealth: 10,
		/** HP = spawner level + 10 (same floor as a starting player's Health). */
		maxHealthFromLevel: "levelPlus10",
		drops: Object.freeze([]),
		sells: Object.freeze([]),
		dialogue: Object.freeze([]),
		persistent: false,
		flying: false,
		freeFlight: false,
		ambient: false,
		talkable: true,
		untargetable: false,
		aggressive: false,
		usePlayerBody: true,
		gait: "walk",
		sex: "male",
		frames: 1,
		framesPerRow: 1,
		animationSpeed: 0
	}),
	[MobId.townGuard]: Object.freeze({
		mobTypeId: MobId.townGuard,
		key: "town-guard",
		assetFolder: "characters",
		displayName: "Town Guard",
		health: 10,
		maxHealth: 10,
		maxHealthFromLevel: "levelPlus10",
		drops: Object.freeze([]),
		sells: Object.freeze([]),
		dialogue: Object.freeze([]),
		persistent: false,
		flying: false,
		freeFlight: false,
		ambient: false,
		talkable: false,
		untargetable: false,
		aggressive: false,
		usePlayerBody: true,
		townGuard: true,
		gait: "walk",
		sex: "male",
		frames: 1,
		framesPerRow: 1,
		animationSpeed: 0
	}),
	[MobId.centralExchange]: Object.freeze({
		mobTypeId: MobId.centralExchange,
		key: "central-exchange",
		assetFolder: "characters",
		displayName: "Central Exchange staff",
		health: 10,
		maxHealth: 10,
		maxHealthFromLevel: "levelPlus10",
		drops: Object.freeze([]),
		sells: Object.freeze([]),
		dialogue: Object.freeze([]),
		persistent: false,
		flying: false,
		freeFlight: false,
		ambient: false,
		talkable: false,
		untargetable: false,
		aggressive: false,
		usePlayerBody: true,
		centralExchange: true,
		gait: "walk",
		sex: "male",
		frames: 1,
		framesPerRow: 1,
		animationSpeed: 0
	})
});

export function mobDefinition (mobTypeId)
{
	return MOB_DEFINITIONS[mobTypeId] ?? null;
}

export function mobSpriteName (mobTypeId)
{
	const def = mobDefinition(mobTypeId);
	const key = def?.key ?? def?.mobTypeId ?? "deer";
	if (def?.usePlayerBody)
	{
		// Editor palette preview; live entities use appearance.sex → bodySprite().
		return spriteImageName("character", "player-body-male", "player-body-male");
	}
	if (def?.sprite)
	{ return def.sprite; }
	const state = def?.defaultState ?? key;
	return spriteImageName("mob", key, state);
}

export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
{
	const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
	const townGuard = mobTypeId === MobId.townGuard;
	const centralExchange = mobTypeId === MobId.centralExchange;
	const bodyNpc = humanoid || townGuard || centralExchange;
	return {
		spawnerId,
		mobTypeId,
		maxAlive: centralExchange
			? centralExchangeStaffCount()
			: (bodyNpc ? 1 : 3),
		spawnRangeTiles: bodyNpc ? 1 : 4,
		maxWanderRangeTiles: bodyNpc ? 1 : 8,
		level: 1,
		bounty: 0,
		/** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
		aggressive: false,
		sex: "male",
		displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
		equipment: emptySpawnerEquipment(),
		sells: [],
		spells: [],
		buysItems: false,
		hiddenDiscount: 0.9,
		centralExchange,
		townGuard,
		dialogueId: null
	};
}

function emptySpawnerEquipment ()
{
	return {
		head: null,
		chest: null,
		legs: null,
		boots: null,
		weapon: null,
		offhand: null
	};
}

/**
 * Spawner equipment entry: legacy itemId number, or `{ itemId, dyeColor? }` for dyed clothing.
 * Normalized form keeps a plain number when undyed (world-save compatible).
 */
function normalizeEquipmentEntry (value)
{
	if (value == null || value === "" || value === "0")
	{ return null; }
	let itemId = 0;
	let dyeColor = null;
	if (typeof value === "object")
	{
		itemId = Number(value.itemId) | 0;
		dyeColor = normalizeDyeColor(value.dyeColor);
	}
	else
	{ itemId = Number(value) | 0; }
	if (!Number.isFinite(itemId) || itemId <= 0)
	{ return null; }
	if (!dyeColor)
	{ return itemId; }
	return Object.freeze({ itemId, dyeColor });
}

function normalizeDyeColor (raw)
{
	if (!raw || typeof raw !== "object")
	{ return null; }
	const r = Number(raw.r);
	const g = Number(raw.g);
	const b = Number(raw.b);
	if (![r, g, b].every(Number.isFinite))
	{ return null; }
	const asByte = r > 1 || g > 1 || b > 1;
	return Object.freeze({
		r: Math.min(1, Math.max(0, asByte ? r / 255 : r)),
		g: Math.min(1, Math.max(0, asByte ? g / 255 : g)),
		b: Math.min(1, Math.max(0, asByte ? b / 255 : b))
	});
}

function normalizeEquipment (raw)
{
	const next = emptySpawnerEquipment();
	if (!raw || typeof raw !== "object")
	{ return next; }
	for (const slot of Object.keys(next))
	{ next[slot] = normalizeEquipmentEntry(raw[slot]); }
	return next;
}

/** Resolve authored spawner equipment into itemId (+ optional dye). */
export function spawnerEquipmentSlot (entry)
{
	if (entry == null)
	{ return { itemId: 0, dyeColor: null }; }
	if (typeof entry === "object")
	{
		return {
			itemId: Number(entry.itemId) | 0,
			dyeColor: entry.dyeColor ?? null
		};
	}
	return { itemId: Number(entry) | 0, dyeColor: null };
}

function normalizeSells (raw)
{
	if (!Array.isArray(raw))
	{ return []; }
	const lines = [];
	const seen = new Set();
	for (const entry of raw)
	{
		let itemId;
		let quantity = 0;
		if (entry && typeof entry === "object")
		{
			itemId = Number(entry.itemId);
			quantity = Math.max(0, Number(entry.quantity) || 0) | 0;
		}
		else
		{ itemId = Number(entry); }
		if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
		{ continue; }
		seen.add(itemId | 0);
		lines.push({ itemId: itemId | 0, quantity });
	}
	return lines;
}

function normalizeSpells (raw)
{
	if (!Array.isArray(raw))
	{ return []; }
	const lines = [];
	const seen = new Set();
	for (const entry of raw)
	{
		if (!entry || typeof entry !== "object")
		{ continue; }
		const spellId = String(entry.spellId ?? "").trim();
		if (!spellId || seen.has(spellId))
		{ continue; }
		seen.add(spellId);
		// Cast chance is derived from mob level at spawn time — not stored.
		lines.push({ spellId });
	}
	return lines;
}

/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
export function normalizeSpawnerConfig (config, spawnerId = "spawner")
{
	const mobTypeId = config?.mobTypeId ?? MobId.deer;
	const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
	const townGuard = !centralExchange && (mobTypeId === MobId.townGuard || !!config?.townGuard);
	const effectiveMob = centralExchange
		? MobId.centralExchange
		: (townGuard ? MobId.townGuard : mobTypeId);
	const base = defaultSpawnerConfig(spawnerId, effectiveMob);
	const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId: effectiveMob };
	const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
	const maxWanderRangeTiles = Math.max(
		spawnRangeTiles,
		Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
	);
	const sex = merged.sex === "female" ? "female" : "male";
	const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
	const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
	const staffCap = centralExchangeStaffCount();
	const level = Math.max(1, Math.min(99, Number(merged.level) || base.level || 1)) | 0;
	const bodyNpc = isHumanoidMob(effectiveMob) || centralExchange || townGuard;
	const aggressive = bodyNpc ? !!merged.aggressive : false;
	const bounty = aggressive ? 0 : (Math.max(0, Number(merged.bounty) || 0) | 0);
	return {
		spawnerId: String(merged.spawnerId),
		mobTypeId: effectiveMob,
		maxAlive: centralExchange
			? staffCap
			: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
		spawnRangeTiles,
		maxWanderRangeTiles,
		level,
		bounty,
		aggressive,
		sex,
		displayName,
		equipment: normalizeEquipment(merged.equipment),
		sells: centralExchange ? [] : normalizeSells(merged.sells),
		spells: normalizeSpells(merged.spells),
		buysItems: centralExchange ? false : !!merged.buysItems,
		hiddenDiscount,
		centralExchange,
		townGuard,
		dialogueId: bodyNpc
			? (String(merged.dialogueId ?? "").trim().slice(0, 64) || null)
			: null
	};
}

export function listAmbientMobTypes ()
{
	return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
}

/** Every mob type that can be authored as a world-editor spawner. */
export function listSpawnableMobTypes ()
{
	return Object.values(MOB_DEFINITIONS);
}

export function isHumanoidMob (mobTypeId)
{
	return mobDefinition(mobTypeId)?.usePlayerBody === true;
}

export function isTownGuardMob (mobTypeId)
{
	return mobTypeId === MobId.townGuard || !!mobDefinition(mobTypeId)?.townGuard;
}

export function isCentralExchangeSpawner (configOrMobTypeId)
{
	if (configOrMobTypeId && typeof configOrMobTypeId === "object")
	{ return !!configOrMobTypeId.centralExchange || configOrMobTypeId.mobTypeId === MobId.centralExchange; }
	return configOrMobTypeId === MobId.centralExchange;
}

/** Max HP for a mob at the given spawner level. */
export function mobMaxHealthForLevel (def, level)
{
	const lv = Math.max(1, Math.floor(Number(level) || 1));
	const formula = def?.maxHealthFromLevel;
	if (formula === "levelPlus10" || (!formula && def?.usePlayerBody))
	{ return lv + 10; }
	const base = Math.max(1, Number(def?.health ?? def?.maxHealth ?? 8) || 8);
	return Math.max(1, base + (lv - 1));
}

/** Display label for hover / UI: `Lv.5 Deer`. */
export function mobLevelDisplayName (level, displayName)
{
	const lv = Math.max(1, Math.floor(Number(level) || 1));
	const name = String(displayName ?? "").trim() || "Creature";
	return `Lv.${lv} ${name}`;
}
