import { Component } from "../ecs/components.js";
import {
	activeStatusEffects,
	pruneStatusEffects,
	StatusEffectType,
	publicStatusEffectsView,
	hasStatusEffect
} from "../../../shared/statusEffects/rules.js";
import { publicEntityView } from "../ecs/serialize.js";
import { syncPlayerHealth } from "../skills/service.js";

/**
 * Tick timed potion effects: health/stamina regen & drain.
 * Returns replication events (health/stamina/appearance/status-effects).
 */
export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
{
	const events = [];
	for (const entity of world.ecs.query(Component.character, Component.statusEffects))
	{
		const { handle, entityId, character, statusEffects } = entity;
		if (world.ecs.has(handle, Component.dead))
		{ continue; }

		const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
		const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
		const beforeBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);
		pruneStatusEffects(statusEffects, now);
		const afterScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
		const afterGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
		const afterBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);

		let healthChanged = false;
		let staminaChanged = false;
		const health = world.ecs.get(handle, Component.health);
		const stamina = world.ecs.get(handle, Component.stamina);

		for (const entry of activeStatusEffects(statusEffects, now))
		{
			const rate = Number(entry.amountPerSecond) || 0;
			if (!rate)
			{ continue; }
			if (entry.type === StatusEffectType.healthRegen && health)
			{
				const before = health.current | 0;
				health.current = Math.min(health.max | 0, (health.current | 0) + rate * dt);
				if ((health.current | 0) !== before)
				{ healthChanged = true; }
			}
			if (entry.type === StatusEffectType.staminaRegen && stamina)
			{
				const before = Number(stamina.current) || 0;
				stamina.current = Math.min(stamina.max, before + rate * dt);
				if (Math.ceil(before) !== Math.ceil(stamina.current))
				{ staminaChanged = true; }
			}
			if (entry.type === StatusEffectType.staminaDrain && stamina)
			{
				const before = Number(stamina.current) || 0;
				stamina.current = Math.max(0, before - rate * dt);
				if (Math.ceil(before) !== Math.ceil(stamina.current))
				{ staminaChanged = true; }
			}
		}

		if (healthChanged)
		{
			syncPlayerHealth(world.ecs, handle);
			const view = publicEntityView(world.ecs, entityId);
			if (view)
			{
				events.push({
					type: "entity-health",
					entityId,
					characterId: character.characterId,
					health: view.health,
					maxHealth: view.maxHealth,
					tileX: view.tileX,
					tileY: view.tileY
				});
			}
		}

		if (staminaChanged)
		{
			events.push({
				type: "stamina",
				characterId: character.characterId,
				current: Number(stamina.current) || 0,
				max: Math.max(1, stamina.max | 0)
			});
		}

		const appearanceChanged = beforeScale !== afterScale || beforeGlow !== afterGlow;
		const statusChanged = appearanceChanged || beforeBlind !== afterBlind;
		if (appearanceChanged)
		{
			const view = publicEntityView(world.ecs, entityId);
			if (view)
			{
				events.push({
					type: "entity-appearance",
					entityId: view.entityId,
					tileX: view.tileX,
					tileY: view.tileY,
					sprite: view.sprite ?? null,
					layers: view.layers ?? [],
					lightRadiusTiles: view.lightRadiusTiles ?? 0,
					visualScale: view.visualScale ?? 1
				});
			}
		}
		if (statusChanged || healthChanged)
		{
			events.push({
				type: "status-effects",
				characterId: character.characterId,
				effects: publicStatusEffectsView(statusEffects, now),
				blind: hasStatusEffect(statusEffects, StatusEffectType.blind, now)
			});
		}
	}
	return events;
}
