import { equipImageName, spriteImageName } from "./tileSprites.js";
import { SkillId } from "./skills.js";
import { MaterialTier } from "./materialTiers.js";
import { AttackType } from "./attackTypes.js";
import { EquipmentKind } from "./equipmentKinds.js";
import { formatQuantity } from "../items/formatQuantity.js";
import { formatOriginBreakdown } from "../items/origin.js";
import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
import { ArmourItemId, ARMOUR_ITEM_DEFINITIONS } from "./armourItems.js";
import { ClothItemId, CLOTH_ITEM_DEFINITIONS } from "./clothItems.js";
import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
import { POTION_MAX_STACK } from "./alchemy.js";

export const ItemId = Object.freeze({
	paper: 1,
	apple: 2,
	stick: 3,
	blankCheque: 4,
	clothShirt: 5,
	letter: 6,
	filledCheque: 7,
	coins: 8,
	...CraftingItemId,
	lantern: 26,
	bones: 27,
	skull: 28,
	glassBottle: 29,
	potion: 32,
	recipePaper: 33,
	...MetalItemId,
	...WoodItemId,
	...ArmourItemId,
	...ClothItemId,
	...DyeItemId,
	...HerbItemId
});

export const EQUIPMENT_SLOT = Object.freeze({
	head: "head",
	chest: "chest",
	legs: "legs",
	boots: "boots",
	weapon: "weapon",
	offhand: "offhand"
});

export const EQUIPMENT_DRAW_ORDER = Object.freeze([
	EQUIPMENT_SLOT.boots,
	EQUIPMENT_SLOT.legs,
	EQUIPMENT_SLOT.chest,
	EQUIPMENT_SLOT.head,
	EQUIPMENT_SLOT.offhand,
	EQUIPMENT_SLOT.weapon
]);

export const DEFAULT_MAX_STACK = 99;
export const BLANK_CHEQUE_CARRY_CAP = 99;
export const COIN_MAX_STACK = 999_000_000_000;

/** Coin sprite tiers (coins-<n>.png); pick the largest n where stack quantity >= n. */
export const COIN_SPRITE_TIERS = Object.freeze([
	1, 5, 15, 50, 150, 500, 1000, 1500, 2000, 5000, 10000, 20000, 50000,
	1_000_000, 10_000_000, 50_000_000, 100_000_000, 500_000_000,
	1_000_000_000, 10_000_000_000, 100_000_000_000, 1_000_000_000_000,
	10_000_000_000_000, 100_000_000_000_000, 500_000_000_000_000,
	999_999_999_999_999
]);

export const ITEM_DEFINITIONS = Object.freeze({
	[ItemId.paper]: Object.freeze({
		itemId: ItemId.paper,
		key: "paper",
		displayName: "Paper",
		description: "Blank sheet of paper.",
		seedValue: 2,
		stackable: true,
		maxStackSize: DEFAULT_MAX_STACK,
		uniqueInstance: false,
		category: "document"
	}),
	[ItemId.letter]: Object.freeze({
		itemId: ItemId.letter,
		key: "letter",
		displayName: "Letter",
		description: "A written letter.",
		seedValue: 2,
		stackable: false,
		maxStackSize: 1,
		uniqueInstance: true,
		category: "document",
		defaultState: "letter-opened"
	}),
	[ItemId.apple]: Object.freeze({
		itemId: ItemId.apple,
		key: "apple",
		displayName: "Apple",
		description: "Round and juicy!",
		seedValue: 1,
		stackable: true,
		maxStackSize: DEFAULT_MAX_STACK,
		uniqueInstance: false,
		category: "food",
		healing: 4
	}),
	[ItemId.stick]: Object.freeze({
		itemId: ItemId.stick,
		key: "stick",
		displayName: "Stick",
		description: "A wooden stick. Simple and sturdy.",
		seedValue: 3,
		stackable: false,
		maxStackSize: 1,
		uniqueInstance: false,
		category: "finished",
		equipment: Object.freeze({
			slot: EQUIPMENT_SLOT.weapon,
			tier: MaterialTier.bronze,
			kind: EquipmentKind.clubWeapon,
			attack: Object.freeze({
				mode: "melee",
				rangeTiles: 1,
				hitSkillId: SkillId.clubfighting,
				damageSkillId: SkillId.strength,
				attackType: AttackType.blunt,
				cooldownMs: 700,
				baseDamage: 2
			})
		})
	}),
	[ItemId.blankCheque]: Object.freeze({
		itemId: ItemId.blankCheque,
		key: "blank-cheque",
		displayName: "Blank cheque",
		description: "Bank stationery for writing cheques against deposited goods.",
		seedValue: 5,
		stackable: true,
		maxStackSize: DEFAULT_MAX_STACK,
		uniqueInstance: false,
		category: "document",
		marketplaceSellable: false,
		marketplaceSellBlockedReason: "Blank cheques cannot be sold on the marketplace."
	}),
	[ItemId.filledCheque]: Object.freeze({
		itemId: ItemId.filledCheque,
		key: "filled-cheque",
		displayName: "Cheque",
		description: "A bearer cheque linked to reserved goods in the issuer's bank.",
		seedValue: 5,
		stackable: false,
		maxStackSize: 1,
		uniqueInstance: true,
		category: "document",
		defaultState: "filled-cheque",
		marketplaceSellable: true
	}),
	[ItemId.clothShirt]: Object.freeze({
		itemId: ItemId.clothShirt,
		key: "cloth-shirt",
		displayName: "Cloth shirt",
		description: "A simple cloth shirt, plain and practical.",
		seedValue: 8,
		stackable: false,
		maxStackSize: 1,
		uniqueInstance: false,
		category: "finished",
		iconKey: "clothing",
		defaultState: "shirt",
		dyeable: true,
		clothing: Object.freeze({ warm: false, style: true }),
		equipment: Object.freeze({
			slot: EQUIPMENT_SLOT.chest,
			tier: MaterialTier.bronze,
			kind: EquipmentKind.clothArmour,
			equipSprite: equipImageName("item", "clothing", "shirt")
		})
	}),
	[ItemId.coins]: Object.freeze({
		itemId: ItemId.coins,
		key: "coins",
		displayName: "Coin",
		displayNamePlural: "Coins",
		description: "Hard currency of the realm.",
		seedValue: 1,
		stackable: true,
		maxStackSize: COIN_MAX_STACK,
		uniqueInstance: false,
		category: "currency"
	}),
	[ItemId.lantern]: Object.freeze({
		itemId: ItemId.lantern,
		key: "lantern",
		displayName: "Lantern",
		description: "A handheld lamp that pushes back the night.",
		seedValue: 12,
		stackable: false,
		maxStackSize: 1,
		uniqueInstance: false,
		category: "tool",
		equipment: Object.freeze({
			slot: EQUIPMENT_SLOT.offhand,
			lightRadiusTiles: 6
		})
	}),
	[ItemId.bones]: Object.freeze({
		itemId: ItemId.bones,
		key: "bones",
		displayName: "Bones",
		description: "Bones of a dead creature.",
		seedValue: 1,
		stackable: true,
		maxStackSize: DEFAULT_MAX_STACK,
		uniqueInstance: false,
		category: "ingredient"
	}),
	[ItemId.skull]: Object.freeze({
		itemId: ItemId.skull,
		key: "skull",
		displayName: "Skull",
		description: "Unlucky.",
		seedValue: 1,
		stackable: true,
		maxStackSize: DEFAULT_MAX_STACK,
		uniqueInstance: false,
		category: "misc"
	}),
	[ItemId.glassBottle]: Object.freeze({
		itemId: ItemId.glassBottle,
		key: "glass-bottle",
		displayName: "Glass bottle",
		description: "A clear bottle, ready to hold a brew or dye.",
		seedValue: 2,
		stackable: true,
		maxStackSize: DEFAULT_MAX_STACK,
		uniqueInstance: false,
		category: "tool",
		iconKey: "potion",
		defaultState: "potion-0",
		npcShopAllowed: true
	}),
	[ItemId.potion]: Object.freeze({
		itemId: ItemId.potion,
		key: "potion",
		displayName: "Potion",
		description: "A bottled brew. Sip with care.",
		seedValue: 8,
		stackable: true,
		maxStackSize: POTION_MAX_STACK,
		uniqueInstance: false,
		category: "potion",
		potion: true,
		iconKey: "potion"
	}),
	[ItemId.recipePaper]: Object.freeze({
		itemId: ItemId.recipePaper,
		key: "recipe-paper",
		displayName: "Recipe paper",
		description: "An alchemy recipe written for a cauldron.",
		seedValue: 2,
		stackable: false,
		maxStackSize: 1,
		uniqueInstance: true,
		category: "document",
		defaultState: "recipe-paper",
		iconKey: "paper"
	}),
	...CRAFTING_ITEM_STUBS,
	...METAL_ITEM_DEFINITIONS,
	...WOOD_ITEM_DEFINITIONS,
	...ARMOUR_ITEM_DEFINITIONS,
	...CLOTH_ITEM_DEFINITIONS,
	...HERB_ITEM_DEFINITIONS,
	[DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
	[DyeItemId.dye]: DYE_ITEM_DEFINITION
});

export function itemDefinition (itemId)
{
	return ITEM_DEFINITIONS[itemId] ?? null;
}

/** Garments that accept optional `instance.dyeColor` (tailor / cloth clothing). */
export function isDyeableClothing (itemIdOrDef)
{
	const def = typeof itemIdOrDef === "number"
		? itemDefinition(itemIdOrDef)
		: itemIdOrDef;
	return !!def?.dyeable;
}

export { formatQuantity };

export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
{
	if (!def)
	{ return "Item"; }
	const qty = stack?.quantity ?? 1;
	if (stack?.itemId === ItemId.coins)
	{ return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
	if (stack?.itemId === ItemId.potion && stack.instance?.displayName)
	{ return stack.instance.displayName; }
	if (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye")
	{ return "Dye"; }
	if (stack?.itemId === ItemId.flower && stack.instance?.colorId)
	{
		return `${FLOWER_COLOR_DISPLAY[stack.instance.colorId] ?? "Flower"} flower`;
	}
	if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
	{ return stack.instance.displayName; }
	return def.displayName ?? "Item";
}

export function stackDisplayLabel (stack)
{
	const name = itemDisplayName(stack);
	const qty = stack?.quantity ?? 1;
	if (qty <= 1)
	{ return name; }
	return `${name} (${formatQuantity(qty)})`;
}

export function coinSpriteTierForQuantity (quantity)
{
	const qty = Math.max(0, Math.floor(Number(quantity) || 0));
	let tier = COIN_SPRITE_TIERS[0];
	for (const candidate of COIN_SPRITE_TIERS)
	{
		if (qty >= candidate)
		{ tier = candidate; }
		else
		{ break; }
	}
	return tier;
}

/** Stack-aware description (letters include open state and author). */
export function itemDescription (stack, { localCharacterId } = {})
{
	const def = itemDefinition(stack?.itemId);
	if (!def)
	{ return ""; }
	if (stack.itemId === ItemId.letter && stack.instance?.kind === "letter")
	{
		const state = stack.instance.opened === false ? "unopened" : "opened";
		const authorId = stack.instance.authorCharacterId;
		const byYou = authorId != null && Number(authorId) === Number(localCharacterId);
		const author = byYou
			? "you"
			: (stack.instance.authorDisplayName?.trim() || "someone");
		return `An ${state} letter, written by ${author}.`;
	}
	if (stack.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
	{
		const reserved = itemDefinition(stack.instance.itemId);
		const qty = stack.instance.quantity | 0;
		const name = reserved?.displayName ?? "goods";
		return `Bearer cheque for ${qty}× ${name}.`;
	}
	if (stack.itemId === ItemId.potion && stack.instance?.kind === "potion")
	{
		const name = stack.instance.displayName ?? "Potion";
		return stack.instance.unstable
			? `${name}. The brew smells wrong — best sipped with caution.`
			: `${name}. A carefully bottled draught.`;
	}
	if (stack.itemId === ItemId.recipePaper && stack.instance?.kind === "recipe-paper")
	{ return "Notes on how to brew a particular draught."; }
	return def.description ?? "";
}

export function itemOriginSummary (stack)
{
	return formatOriginBreakdown(stack);
}

export function itemDefaultState (def)
{
	return def?.defaultState ?? def?.key ?? "paper";
}

export function itemSpriteName (itemId, instance = null)
{
	const def = itemDefinition(itemId);
	if (!def)
	{ return spriteImageName("item", "paper", "paper"); }
	if (itemId === ItemId.letter)
	{ return spriteImageName("item", "letter", letterVisualState(instance)); }
	const folderKey = def.iconKey ?? def.key;
	return def.sprite ?? spriteImageName("item", folderKey, itemDefaultState(def));
}

export function itemEquipSprite (itemId)
{
	const def = itemDefinition(itemId);
	const equipment = def?.equipment;
	if (!equipment)
	{ return null; }
	const folderKey = def.iconKey ?? def.key;
	return equipment.equipSprite
		?? equipment.overlaySpriteId
		?? equipImageName("item", folderKey, itemDefaultState(def));
}

/** Largest equipped light radius (e.g. lantern in offhand). */
export function equippedLightRadiusTiles (equipment)
{
	let best = 0;
	for (const stack of Object.values(equipment?.slots ?? {}))
	{
		if (!stack)
		{ continue; }
		const radius = itemDefinition(stack.itemId)?.equipment?.lightRadiusTiles ?? 0;
		if (radius > best)
		{ best = radius; }
	}
	return best;
}

export function letterVisualState (instance)
{
	return instance?.opened === false ? "letter-closed" : "letter-opened";
}

export function itemAssetPath (itemId, companion = null, instance = null)
{
	const def = itemDefinition(itemId);
	if (def?.herb)
	{
		const suffix = companion ? `-${companion}` : "";
		return `/assets/herbs/${def.key}${suffix}.png`;
	}
	const key = def?.iconKey ?? def?.key ?? "paper";
	const state = itemId === ItemId.letter
		? letterVisualState(instance)
		: itemDefaultState(def ?? { key });
	const suffix = companion ? `-${companion}` : "";
	return `/assets/items/${key}/${state}${suffix}.png`;
}

export function itemAssetPathForStack (stack)
{
	if (!stack)
	{ return itemAssetPath(null); }
	if (stack.itemId === ItemId.coins)
	{
		const tier = coinSpriteTierForQuantity(stack.quantity);
		return `/assets/items/coins/coins-${tier}.png`;
	}
	if (stack.itemId === ItemId.potion)
	{
		const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
		return `/assets/items/potion/potion-${fill}.png`;
	}
	if (stack.itemId === ItemId.dye)
	{
		const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
		return `/assets/items/potion/potion-${fill}.png`;
	}
	if (stack.itemId === ItemId.glassBottle)
	{ return `/assets/items/potion/potion-0.png`; }
	if (stack.itemId === ItemId.flower)
	{ return `/assets/items/flower/flower.png`; }
	return itemAssetPath(stack.itemId, null, stack.instance);
}

export const LETTER_MAX_BODY_CHARS = 2000;

export const STARTER_ITEMS = Object.freeze([
	Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
	Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
	Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
	Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 }),
	Object.freeze({ itemId: ItemId.coins, quantity: 25 })
]);
