export class WindowManager {
	private static _topmost: HTMLElement | null;

	static get topmost() {
		return this._topmost;
	}

	static set topmost(e) {
		if (this._topmost) {
			this._topmost.style.zIndex = "0";
		}
		this._topmost = e;
		this._topmost.style.display = "block";
		this._topmost.style.zIndex = "1";
	}

	static observe(element) {
		element.addEventListener("mousedown", () => {
			this.topmost = element;
		});

		const titleBar = element.querySelector(".title-bar");

		titleBar.addEventListener("mousedown", startDrag);
		titleBar.addEventListener("touchstart", startDrag, { passive: false });

		function startDrag(e) {
			if (e.target !== titleBar) return;

			let isTouch = e.type.startsWith("touch");
			let startX = isTouch ? e.touches[0].clientX : e.clientX;
			let startY = isTouch ? e.touches[0].clientY : e.clientY;

			let offsetX = startX - element.offsetLeft;
			let offsetY = startY - element.offsetTop;

			function onMove(e) {
				let clientX = isTouch ? e.touches[0].clientX : e.clientX;
				let clientY = isTouch ? e.touches[0].clientY : e.clientY;

				let newX = clientX - offsetX;
				let newY = clientY - offsetY;

				element.style.top = `${newY}px`;
				element.style.left = `${newX}px`;
			}

			function stopMove() {
				let maxX = window.innerWidth - element.offsetWidth;
				let maxY = window.innerHeight - element.offsetHeight;

				let finalX = Math.min(Math.max(element.offsetLeft, 0), maxX);
				let finalY = Math.min(Math.max(element.offsetTop, 0), maxY);

				element.style.top = `${finalY}px`;
				element.style.left = `${finalX}px`;

				document.removeEventListener("mousemove", onMove);
				document.removeEventListener("mouseup", stopMove);
				document.removeEventListener("touchmove", onMove);
				document.removeEventListener("touchend", stopMove);
			}

			document.addEventListener("mousemove", onMove);
			document.addEventListener("mouseup", stopMove);
			document.addEventListener("touchmove", onMove, { passive: false });
			document.addEventListener("touchend", stopMove);
		}
	}
}
