import { Component } from "../ecs/components.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { CraftingItemId } from "../../../shared/definitions/craftingItems.js";
import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { cookedFishItemId } from "../../../shared/definitions/fishItems.js";
import { SkillId } from "../../../shared/definitions/skills.js";
import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
import { rollSkill } from "../../../shared/combat/rolls.js";
import { firestartingDifficulty, campfireDurationMs } from "../../../shared/definitions/craftingStations.js";
import { MATERIAL_DISPLAY_NAME } from "../../../shared/definitions/materialTiers.js";
import { stackQuantity } from "../../../shared/items/inventory.js";
import { attachOrigins, craftOrigin, CraftOriginVerb, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
import
{
	addGroundItem,
	publicGroundItem,
	removeGroundItem
} from "../items/bags.js";
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";

const TINDERS_COOK_BURN_CHANCE = 0.4;
const COOK_DIFFICULTY = 1;

function woodTierFromLogItemId (itemId)
{
	const def = itemDefinition(itemId);
	if (!def || def.familyId !== ItemFamilyId.log)
	{ return null; }
	return def.tier ?? null;
}

function groundItemsAt (world, tileX, tileY)
{
	const out = [];
	for (const item of world.groundItems?.values?.() ?? [])
	{
		if (item.tileX === tileX && item.tileY === tileY)
		{ out.push(item); }
	}
	return out;
}

function blockAt (world, tileX, tileY)
{
	const chunkX = tileToChunk(tileX);
	const chunkY = tileToChunk(tileY);
	const data = world.chunkData?.(chunkX, chunkY);
	if (!data)
	{ return null; }
	const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
	return data.blocks?.[index] ?? null;
}

function placeCampfire (world, tileX, tileY, woodTier, litByName, now)
{
	const chunkX = tileToChunk(tileX);
	const chunkY = tileToChunk(tileY);
	const localX = tileToLocal(tileX);
	const localY = tileToLocal(tileY);
	const data = world.chunkData(chunkX, chunkY);
	const index = localY * CHUNK_SIZE + localX;
	const expiresAt = now + campfireDurationMs(woodTier);
	const block = {
		typeId: BlockType.campfire,
		state: woodTier,
		config: { woodTier, litAt: now, expiresAt, litByName }
	};
	data.blocks[index] = block;
	if (!world.campfireExpires)
	{ world.campfireExpires = new Map(); }
	world.campfireExpires.set(`${tileX},${tileY}`, {
		tileX,
		tileY,
		woodTier,
		expiresAt,
		litByName
	});
	return {
		type: "chunk-delta",
		chunkX,
		chunkY,
		tileX,
		tileY,
		localX,
		localY,
		block
	};
}

function consumeOneGroundStack (world, item, events)
{
	const qty = stackQuantity(item.stack?.quantity);
	if (qty <= 1)
	{
		removeGroundItem(world, item.groundItemId);
		events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
		return;
	}
	const split = splitOrigins(normalizeOrigins(item.stack), 1);
	item.stack.quantity = qty - 1;
	item.stack.origins = split.remain;
	delete item.stack.origin;
	events.push({
		type: "ground-item-appear",
		...publicGroundItem(item),
		stack: item.stack,
		droppedAt: item.droppedAt,
		source: item.source,
		expiresAt: item.expiresAt
	});
}

function cookableRawDef (itemId)
{
	const def = itemDefinition(itemId);
	if (!def?.cookable || def.cookState !== "raw")
	{ return null; }
	return def;
}

function cookedItemIdForRaw (rawDef)
{
	if (rawDef.fishSpeciesId)
	{ return cookedFishItemId(rawDef.fishSpeciesId); }
	if (rawDef.cookedItemId)
	{ return rawDef.cookedItemId; }
	if (rawDef.itemId === CraftingItemId.rawMeat)
	{ return CraftingItemId.cookedMeat; }
	return CraftingItemId.cookedMeat;
}

function spawnGroundStack (world, tileX, tileY, stack, now, events)
{
	const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
	const item = {
		groundItemId,
		tileX,
		tileY,
		stack,
		droppedAt: now,
		source: "tinders",
		expiresAt: now + 1000 * 60 * 30
	};
	addGroundItem(world, item);
	events.push({
		type: "ground-item-appear",
		...publicGroundItem(item),
		stack: item.stack,
		droppedAt: item.droppedAt,
		source: item.source,
		expiresAt: item.expiresAt
	});
}

/**
 * True while Tinders still has work on this tile (unlit logs or raw food).
 * Used to stop auto-cast once a campfire is lit or nothing remains.
 */
export function tindersTileStillNeedsCast (world, tileX, tileY)
{
	if (blockAt(world, tileX, tileY)?.typeId === BlockType.campfire)
	{ return false; }
	const items = groundItemsAt(world, tileX, tileY);
	if (items.some((item) => woodTierFromLogItemId(item.stack?.itemId)))
	{ return true; }
	if (items.some((item) => cookableRawDef(item.stack?.itemId)))
	{ return true; }
	return false;
}

/**
 * Tinders: Mind roll lights ground logs (as firestarting) or cooks raw meat/fish (40% burn).
 */
export function applyTindersAtTile (world, impact, now)
{
	const events = [];
	const tileX = impact.targetTileX | 0;
	const tileY = impact.targetTileY | 0;
	const mind = impact.levels?.mind | 0 || 0;
	const rng = world.rng ?? Math.random;
	const items = groundItemsAt(world, tileX, tileY);

	const logItem = items.find((item) => woodTierFromLogItemId(item.stack?.itemId));
	if (logItem)
	{
		const woodTier = woodTierFromLogItemId(logItem.stack.itemId);
		const difficulty = firestartingDifficulty(woodTier);
		if (mind < difficulty)
		{
			const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
			events.push({
				type: "command-error",
				sessionId: null,
				message: `Your mind is too weak to light ${label} logs.`
			});
			return events;
		}
		if (blockAt(world, tileX, tileY))
		{
			events.push({
				type: "command-error",
				sessionId: null,
				message: "There is no room for a fire there."
			});
			return events;
		}
		const roll = rollSkill(mind, rng);
		if (roll < difficulty)
		{
			events.push({
				type: "command-error",
				sessionId: null,
				message: "The sparks fail to catch."
			});
			return events;
		}
		consumeOneGroundStack(world, logItem, events);
		const casterHandle = world.ecs.handleOf(impact.casterEntityId);
		const appearance = casterHandle != null
			? world.ecs.get(casterHandle, Component.appearance)
			: null;
		const litByName = [appearance?.firstName, appearance?.lastName]
			.filter(Boolean)
			.join(" ")
			.trim() || "someone";
		events.push(placeCampfire(world, tileX, tileY, woodTier, litByName, now));
		return events;
	}

	const meatItem = items.find((item) => cookableRawDef(item.stack?.itemId));
	if (meatItem)
	{
		const rawDef = cookableRawDef(meatItem.stack.itemId);
		const roll = rollSkill(mind, rng);
		if (roll < COOK_DIFFICULTY)
		{
			events.push({
				type: "command-error",
				sessionId: null,
				message: "The meat fails to cook."
			});
			return events;
		}
		const burned = rng() < TINDERS_COOK_BURN_CHANCE;
		const outId = burned
			? (rawDef.burntItemId ?? CraftingItemId.burntMeat)
			: cookedItemIdForRaw(rawDef);
		consumeOneGroundStack(world, meatItem, events);
		const casterHandle = world.ecs.handleOf(impact.casterEntityId);
		const appearance = casterHandle != null
			? world.ecs.get(casterHandle, Component.appearance)
			: null;
		const cookName = [appearance?.firstName, appearance?.lastName]
			.filter(Boolean)
			.join(" ")
			.trim() || "someone";
		const origin = craftOrigin(
			burned ? CraftOriginVerb.ruined : CraftOriginVerb.made,
			cookName
		);
		const stack = attachOrigins({
			itemId: outId,
			quantity: 1,
			origins: [{ origin, quantity: 1 }]
		});
		spawnGroundStack(world, tileX, tileY, stack, now, events);

		const skills = casterHandle != null ? world.ecs.get(casterHandle, Component.skills) : null;
		if (skills?.xp && impact.casterCharacterId)
		{
			const result = applySkillXp(skills, SkillId.cooking, COOK_DIFFICULTY);
			if (result.changed)
			{
				events.push({
					type: "skills-updated",
					entityId: impact.casterEntityId,
					characterId: impact.casterCharacterId,
					...publicSkillsPayload(skills),
					stored: storedSkillXp(skills),
					levelUps: result.levelUp ? [result.levelUp] : []
				});
			}
		}
		return events;
	}

	events.push({
		type: "command-error",
		sessionId: null,
		message: "There is nothing here to light or cook."
	});
	return events;
}
