import {
	statusEffectDisplay,
	statusEffectIconPath,
	formatStatusRemaining
} from "/shared/statusEffects/display.js";

export function initStatusEffects ()
{
	let vitals = document.getElementById("vitals");
	if (!vitals)
	{
		vitals = document.createElement("div");
		vitals.id = "vitals";
		vitals.hidden = true;
		document.body.append(vitals);
	}

	let rail = document.getElementById("status-effects");
	if (!rail)
	{
		rail = document.createElement("div");
		rail.id = "status-effects";
		rail.setAttribute("aria-label", "Active effects");
		vitals.prepend(rail);
	}
	else if (rail.parentElement !== vitals)
	{ vitals.prepend(rail); }

	let tip = document.getElementById("status-effect-tooltip");
	if (!tip)
	{
		tip = document.createElement("div");
		tip.id = "status-effect-tooltip";
		tip.hidden = true;
		document.body.append(tip);
	}

	/** @type {Array<{ type: string, expiresAt: number, amount?: number, amountPerSecond?: number, scale?: number }>} */
	let effects = [];
	let hoverType = null;
	let tickId = 0;

	function remainingMs (entry, now = Date.now())
	{
		return Math.max(0, (entry.expiresAt | 0) - now);
	}

	function prune (now = Date.now())
	{
		effects = effects.filter((entry) => remainingMs(entry, now) > 0);
	}

	function hideTip ()
	{
		hoverType = null;
		tip.hidden = true;
	}

	function showTipFor (entry, anchor)
	{
		const display = statusEffectDisplay(entry.type);
		if (!display)
		{
			hideTip();
			return;
		}
		hoverType = entry.type;
		const left = remainingMs(entry);
		tip.innerHTML = "";
		const title = document.createElement("strong");
		title.textContent = display.title;
		const body = document.createElement("p");
		body.textContent = display.describe(entry);
		const time = document.createElement("p");
		time.className = "status-effect-tooltip-time";
		time.textContent = left > 0 ? `${formatStatusRemaining(left)} remaining` : "Expired";
		tip.append(title, body, time);
		tip.hidden = false;
		tip.dataset.polarity = display.polarity;
		const rect = anchor.getBoundingClientRect();
		const tipW = tip.offsetWidth || 180;
		const tipH = tip.offsetHeight || 60;
		let leftPx = rect.left - tipW - 8;
		if (leftPx < 8)
		{ leftPx = rect.right + 8; }
		let topPx = rect.bottom - tipH;
		if (topPx < 8)
		{ topPx = 8; }
		if (topPx + tipH > window.innerHeight - 8)
		{ topPx = window.innerHeight - tipH - 8; }
		tip.style.left = `${leftPx}px`;
		tip.style.top = `${topPx}px`;
	}

	function refreshTip ()
	{
		if (!hoverType)
		{ return; }
		const entry = effects.find((row) => row.type === hoverType);
		const btn = rail.querySelector(`[data-effect-type="${hoverType}"]`);
		if (!entry || !btn)
		{
			hideTip();
			return;
		}
		showTipFor(entry, btn);
	}

	function render ()
	{
		const now = Date.now();
		prune(now);
		rail.replaceChildren();
		for (const entry of effects)
		{
			const display = statusEffectDisplay(entry.type);
			if (!display)
			{ continue; }
			const btn = document.createElement("button");
			btn.type = "button";
			btn.className = `status-effect-icon status-effect-${display.polarity}`;
			btn.dataset.effectType = entry.type;
			btn.setAttribute("aria-label", display.title);
			const img = document.createElement("img");
			img.src = statusEffectIconPath(entry.type);
			img.alt = "";
			img.draggable = false;
			img.addEventListener("error", () =>
			{
				img.remove();
				btn.classList.add("status-effect-icon-fallback");
				btn.textContent = display.title.slice(0, 1);
			}, { once: true });
			btn.append(img);
			btn.addEventListener("mouseenter", () => showTipFor(entry, btn));
			btn.addEventListener("mouseleave", hideTip);
			btn.addEventListener("focus", () => showTipFor(entry, btn));
			btn.addEventListener("blur", hideTip);
			rail.append(btn);
		}
		rail.hidden = effects.length === 0;
		refreshTip();
	}

	function stopTick ()
	{
		if (tickId)
		{
			clearInterval(tickId);
			tickId = 0;
		}
	}

	function ensureTick ()
	{
		if (tickId || effects.length === 0)
		{ return; }
		tickId = setInterval(() =>
		{
			const before = effects.length;
			prune();
			if (effects.length !== before)
			{ render(); }
			else
			{ refreshTip(); }
			if (effects.length === 0)
			{ stopTick(); }
		}, 250);
	}

	return {
		apply (message)
		{
			const list = Array.isArray(message?.effects) ? message.effects : [];
			effects = list
				.filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())
				.map((entry) => ({
					type: entry.type,
					expiresAt: entry.expiresAt | 0,
					amount: entry.amount | 0,
					amountPerSecond: Number(entry.amountPerSecond) || 0,
					scale: entry.scale ?? null,
					lightRadiusTiles: entry.lightRadiusTiles ?? null
				}));
			render();
			if (effects.length)
			{ ensureTick(); }
			else
			{
				stopTick();
				hideTip();
			}
		},
		clear ()
		{
			effects = [];
			stopTick();
			hideTip();
			render();
		},
		show ()
		{
			vitals.hidden = false;
			render();
		},
		hide ()
		{
			this.clear();
		}
	};
}
