import { Component } from "../ecs/components.js";
import { mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
import { resolveShears } from "../../../shared/definitions/gathering.js";
import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
import {
	clothExhaustDurationMs
} from "../../../shared/definitions/materialTiers.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { SkillId } from "../../../shared/definitions/skills.js";
import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
import { insertStack } from "../../../shared/items/inventory.js";
import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
import { bagView } from "../items/bags.js";
import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
import { publicEntityView, replicationAppearance } from "../ecs/serialize.js";
import { scaleRegrowDurationMs } from "../../../shared/world/season.js";
import { tileShoveEvent } from "../simulation/tileInteract.js";
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";

const SHEAR_DURATION_MS = 3000;
const SHEAR_SHOVE_MS = 1000;

function userError (message)
{
	const error = new Error(message);
	error.userFacing = true;
	return error;
}

function characterDisplayName (world, handle)
{
	const appearance = world.ecs.get(handle, Component.appearance);
	const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
	return name || "someone";
}

function ensureShearSessions (world)
{
	if (!world.shearSessions)
	{ world.shearSessions = new Map(); }
	return world.shearSessions;
}

function clearShearSession (world, characterId)
{
	const sessions = world.shearSessions;
	if (!sessions)
	{ return; }
	const session = sessions.get(characterId);
	if (session)
	{
		unpinShearTarget(world, session.targetEntityId, characterId);
		sessions.delete(characterId);
	}
}

function pinShearTarget (world, entityId, characterId)
{
	const handle = world.ecs.handleOf(entityId | 0);
	if (handle == null)
	{ return; }
	const origin = world.ecs.get(handle, Component.spawnOrigin);
	if (!origin)
	{ return; }
	if (!origin.shearBrowsers || typeof origin.shearBrowsers !== "object")
	{ origin.shearBrowsers = Object.create(null); }
	origin.shearBrowsers[characterId | 0] = true;
	const path = world.ecs.get(handle, Component.path);
	if (path)
	{ path.tiles = []; }
}

function unpinShearTarget (world, entityId, characterId)
{
	const handle = world.ecs.handleOf(entityId | 0);
	if (handle == null)
	{ return; }
	const origin = world.ecs.get(handle, Component.spawnOrigin);
	if (!origin?.shearBrowsers)
	{ return; }
	delete origin.shearBrowsers[characterId | 0];
}

function hasShearBrowsers (origin)
{
	const browsers = origin?.shearBrowsers;
	if (!browsers || typeof browsers !== "object")
	{ return false; }
	return Object.keys(browsers).length > 0;
}

export function originIsBusyPinned (origin)
{
	const dialogue = origin?.dialogueBrowsers;
	const hasDialogue = dialogue && typeof dialogue === "object" && Object.keys(dialogue).length > 0;
	return hasDialogue || hasShearBrowsers(origin);
}

/**
 * Start shearing a fleece-bearing mob (3s channel, shears overlay, freeze target).
 */
export function startShear (world, sessionId, characterId, targetEntityId, now)
{
	const entityId = world.characterEntities.get(characterId);
	if (entityId == null)
	{ throw userError("Character is not in the world."); }
	const handle = world.ecs.handleOf(entityId);
	const identity = world.ecs.get(handle, Component.networkIdentity);
	if (!identity || identity.sessionId !== sessionId)
	{ throw userError("Character is not in the world."); }
	if (world.ecs.has(handle, Component.dead))
	{ throw userError("You are dead."); }

	const targetHandle = world.ecs.handleOf(targetEntityId | 0);
	if (targetHandle == null)
	{ throw userError("That creature is gone."); }
	if (world.ecs.has(targetHandle, Component.dead))
	{ throw userError("That creature is dead."); }

	const creature = world.ecs.get(targetHandle, Component.creature);
	const mob = mobDefinition(creature?.mobTypeId);
	const shearable = mob?.shearable;
	if (!shearable)
	{ throw userError("You cannot shear that."); }

	const fleeceState = creature.fleeceState ?? shearable.fleeceState;
	if (fleeceState === shearable.shornState)
	{ throw userError("That fleece has not grown back yet."); }

	const playerPos = world.ecs.get(handle, Component.position);
	const targetPos = world.ecs.get(targetHandle, Component.position);
	if (!isAdjacentTile(playerPos.tileX, playerPos.tileY, targetPos.tileX, targetPos.tileY))
	{ throw userError("You need to stand next to it."); }

	const inventory = world.ecs.get(handle, Component.inventory);
	const equipment = world.ecs.get(handle, Component.equipment);
	const skills = world.ecs.get(handle, Component.skills);
	const resolved = resolveShears({
		inventorySlots: inventory?.slots,
		equipmentSlots: equipment?.slots,
		skills,
		clothTier: shearable.clothTier
	});
	if (!resolved.ok)
	{ throw userError(resolved.reason); }

	clearShearSession(world, characterId);
	if (world.ecs.has(handle, Component.gather))
	{ world.ecs.remove(handle, Component.gather); }
	const path = world.ecs.get(handle, Component.path);
	if (path)
	{ path.tiles = []; }

	pinShearTarget(world, targetEntityId | 0, characterId);

	ensureShearSessions(world).set(characterId, {
		sessionId,
		targetEntityId: targetEntityId | 0,
		clothTier: shearable.clothTier,
		fleeceState: shearable.fleeceState,
		shornState: shearable.shornState,
		mobTypeId: creature.mobTypeId,
		toolItemId: resolved.tool.stack.itemId,
		startedAt: now,
		endsAt: now + SHEAR_DURATION_MS,
		nextShoveAt: now
	});

	return { events: [], private: bagView(world.ecs, handle) };
}

export function cancelShearing (world, characterId)
{
	clearShearSession(world, characterId);
}

export function handleShearingCommand (world, sessionId, command, now = Date.now())
{
	if (command.type === "shear")
	{
		return startShear(world, sessionId, command.characterId, command.targetEntityId, now);
	}
	if (command.type === "cancel-shear")
	{
		cancelShearing(world, command.characterId);
		return { events: [] };
	}
	return null;
}

function completeShear (world, handle, entityId, characterId, session, events, privates, now)
{
	const character = world.ecs.get(handle, Component.character);
	const inventory = world.ecs.get(handle, Component.inventory);
	const targetHandle = world.ecs.handleOf(session.targetEntityId);
	if (targetHandle == null || !inventory || !character)
	{
		clearShearSession(world, characterId);
		return;
	}

	const itemId = rawClothItemId(session.clothTier);
	const def = itemDefinition(itemId);
	if (!def)
	{
		clearShearSession(world, characterId);
		return;
	}

	const origin = gatherOrigin(GatherOriginVerb.sheared, characterDisplayName(world, handle));
	const stack = attachOrigins({
		itemId,
		quantity: 1,
		origins: [{ origin, quantity: 1 }]
	});
	const inserted = insertStack(inventory.slots, stack, def);
	if (!inserted.ok || inserted.remainder > 0)
	{
		events.push({
			type: "command-error",
			sessionId: session.sessionId,
			message: "Your inventory is full."
		});
		clearShearSession(world, characterId);
		return;
	}
	inventory.slots = inserted.slots;

	const creature = world.ecs.get(targetHandle, Component.creature);
	const appearance = world.ecs.get(targetHandle, Component.appearance);
	if (creature)
	{
		creature.fleeceState = session.shornState;
		creature.woolReadyAt = now + scaleRegrowDurationMs(
			clothExhaustDurationMs(session.clothTier),
			now
		);
	}
	if (appearance)
	{
		appearance.sprite = mobSpriteName(session.mobTypeId, session.shornState);
		const view = publicEntityView(world.ecs, session.targetEntityId);
		const appearanceEvent = replicationAppearance(view);
		if (appearanceEvent)
		{ events.push(appearanceEvent); }
	}

	const skills = world.ecs.get(handle, Component.skills);
	let skillsChanged = false;
	const levelUps = [];
	if (skills?.xp)
	{
		const result = applySkillXp(skills, SkillId.herbalism, 4 + Math.max(1, Math.floor(
			(clothExhaustDurationMs(session.clothTier) / 10_000)
		)), world.ecs.get(handle, Component.equipment));
		if (result.changed)
		{ skillsChanged = true; }
		if (result.levelUp)
		{ levelUps.push(result.levelUp); }
	}
	if (skillsChanged)
	{
		events.push({
			type: "skills-updated",
			entityId,
			characterId,
			...publicSkillsPayload(skills),
			stored: storedSkillXp(skills),
			levelUps
		});
	}

	privates.push({ characterId, bag: bagView(world.ecs, handle) });
	clearShearSession(world, characterId);
}

/**
 * Advance shear channels and fleece regrowth.
 */
export function stepShearing (world, now)
{
	const events = [];
	const privates = [];

	for (const entity of world.ecs.query(Component.creature, Component.appearance))
	{
		const creature = entity.creature;
		if (creature?.woolReadyAt == null || now < creature.woolReadyAt)
		{ continue; }
		const mob = mobDefinition(creature.mobTypeId);
		const shearable = mob?.shearable;
		if (!shearable)
		{
			creature.woolReadyAt = null;
			continue;
		}
		creature.fleeceState = shearable.fleeceState;
		creature.woolReadyAt = null;
		entity.appearance.sprite = mobSpriteName(creature.mobTypeId, shearable.fleeceState);
		const view = publicEntityView(world.ecs, entity.entityId);
		const appearanceEvent = replicationAppearance(view);
		if (appearanceEvent)
		{ events.push(appearanceEvent); }
	}

	const sessions = ensureShearSessions(world);
	for (const [characterId, session] of [...sessions.entries()])
	{
		const entityId = world.characterEntities.get(characterId);
		if (entityId == null)
		{
			clearShearSession(world, characterId);
			continue;
		}
		const handle = world.ecs.handleOf(entityId);
		if (world.ecs.has(handle, Component.dead))
		{
			clearShearSession(world, characterId);
			continue;
		}

		const targetHandle = world.ecs.handleOf(session.targetEntityId);
		if (targetHandle == null || world.ecs.has(targetHandle, Component.dead))
		{
			events.push({
				type: "command-error",
				sessionId: session.sessionId,
				message: "The creature got away."
			});
			clearShearSession(world, characterId);
			continue;
		}

		const position = world.ecs.get(handle, Component.position);
		const targetPos = world.ecs.get(targetHandle, Component.position);
		if (!isAdjacentTile(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY))
		{
			clearShearSession(world, characterId);
			continue;
		}

		if (now >= session.nextShoveAt && now < session.endsAt)
		{
			session.nextShoveAt = now + SHEAR_SHOVE_MS;
			events.push(tileShoveEvent(
				entityId,
				position.tileX,
				position.tileY,
				targetPos.tileX,
				targetPos.tileY,
				normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID)
			));
			events.push({
				type: "gather-swing",
				attackerId: entityId,
				tileX: targetPos.tileX,
				tileY: targetPos.tileY,
				fromTileX: position.tileX,
				fromTileY: position.tileY,
				dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID),
				toolItemId: session.toolItemId,
				swipe: false
			});
		}

		if (now < session.endsAt)
		{ continue; }

		completeShear(world, handle, entityId, characterId, session, events, privates, now);
	}

	return { events, privates };
}
