import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
import
{
	GROUND_DEFINITIONS,
	BLOCK_DEFINITIONS,
	GroundType,
	BlockType,
	normalizeGround,
	normalizeBlock,
	listPlaceableBlockPaletteEntries
} from "/shared/definitions/tiles.js";
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
import
{
	SeasonId,
	seasonIdAt,
	seasonalCycleStates,
	seasonIdFromVisualState,
	placeableStatesForType
} from "/shared/world/season.js";
import { loadGraphicsSettings } from "/shared/graphics/settings.js";
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
import
	{
		isItemSpawnerConfig,
		defaultItemSpawnerConfig,
		normalizeItemSpawnerConfig,
		itemSpawnerPreviewSpriteName,
		itemSpawnerContainerSpriteName
	} from "/shared/definitions/itemSpawners.js";
import
{
	computeNeighborConnectMask,
	composeNeighborConnectState,
	definitionUsesNeighborConnect,
	neighborConnectBlocksMatch,
	neighborConnectRefreshTiles,
	worldTileToChunkLocal
} from "/shared/world/neighborConnect.js";
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
import { WorldView } from "../render/worldView.js";
import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
import { initPaletteModal } from "./paletteModal.js";
import { initPalettePanel } from "./palettePanel.js";
import { initTileConfigModal } from "./tileConfigModal.js";
import { initQuestsModal } from "./questsModal.js";
import { initDialoguesModal } from "./dialoguesModal.js";
import { initGiftsModal } from "./giftsModal.js";
import { initDimensionPickerModal } from "./dimensionPickerModal.js";
import { initEditorMinimap } from "./minimap.js";
import
{
	OVERWORLD_ID,
	normalizeDimensionId,
	isOverworld
} from "/shared/world/dimensions.js";
import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";
import
{
	editorChunkSaveKey,
	editorDirtyChunk,
	editorDraftOwner,
	sameEditorChunk,
	shouldApplySelectedEditorChunk
} from "./saveAck.js";

const game = new Game();
let socket;
let scene;
let editorMinimap = null;
let minimapRequestTimer = 0;
let view;
let draft = null;
/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
let draftBaseline = null;
/**
 * Chunk the current `draft` belongs to. Navigation may update `chunkX`/`chunkY`
 * (viewed chunk) before save/discard; save must still write to this owner.
 * @type {{ dimensionId: string, chunkX: number, chunkY: number }|null}
 */
let draftOwner = null;
/** @type {ReturnType<typeof cloneDraftContents>|null} In-memory chunk clipboard for copy/paste. */
let chunkClipboard = null;
/**
 * Neighbor chunks whose connect masks were updated while editing the selected chunk.
 * Key `"chunkX,chunkY"` → `{ open, grounds, blocks, spawners }`.
 * @type {Map<string, { open: boolean, grounds: object[], blocks: object[], spawners: object[] }>}
 */
let dirtyNeighborChunks = new Map();
/** Spawners for loaded non-selected chunks (needed when saving edge-mask fixes). */
let neighborSpawnersByChunk = new Map();
/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
let pendingNavigate = null;
/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
let navigateAfterSave = false;
/** Keys (`dimensionId:chunkX,chunkY`) for in-flight `EDITOR_SAVE_CHUNK` acks. */
const pendingSaveAcks = new Set();
let chunkX = 0;
let chunkY = 0;
let selectedDimensionId = OVERWORLD_ID;
/** @type {string|null} */
let pendingCreatedDimensionId = null;
/** @type {Map<string, object>} */
let dimensionsById = new Map();
let dimensionPicker = null;
let dimensionSettings = null;
let tool = { kind: "ground", typeId: GroundType.grass, state: null };
let settingsModal;
let paletteModal;
let palettePanel;
let tileConfigModal;
let questsModal;
let dialoguesModal;
let giftsModal;
let catalog = { grounds: {}, blocks: {}, images: [] };
let imageUrlByName = new Map();
let hoverLocal = null;
let editorZoom = null;
let activeRevisionId = null;
let pendingRevisionId = null;
let applyInFlight = false;
/** @type {string|null} */
let sessionAuthSubject = null;
/** True after the first successful SESSION message for this page load. */
let sessionReady = false;
/** Display label for #who while reconnecting. */
let accountWhoLabel = "Editor";
const EDITOR_DRAFT_STORAGE_PREFIX = "questward-editor-draft:";
const EDITOR_ZOOM_MIN = 0.25;
const EDITOR_ZOOM_MAX = 8;
const EDITOR_ZOOM_STEP = 1.12;
const CONSOLE_MAX_LINES = 2000;

function $ (id)
{
	return document.getElementById(id);
}

function formatConsoleTime (t)
{
	try
	{ return new Date(t).toLocaleTimeString(); }
	catch
	{ return ""; }
}

function appendConsoleLine (entry, { scroll = true } = {})
{
	const pre = $("editor-console");
	if (!pre || !entry)
	{ return; }
	const line = document.createElement("div");
	const level = entry.level || "info";
	line.className = `console-${level}`;
	line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
	pre.append(line);
	while (pre.childElementCount > CONSOLE_MAX_LINES)
	{ pre.firstChild?.remove(); }
	if (scroll)
	{ pre.scrollTop = pre.scrollHeight; }
}

function applyConsoleSnapshot (lines)
{
	const pre = $("editor-console");
	if (!pre)
	{ return; }
	pre.replaceChildren();
	for (const entry of lines ?? [])
	{ appendConsoleLine(entry, { scroll: false }); }
	pre.scrollTop = pre.scrollHeight;
}

function initSidePanelTabs ()
{
	const tabs = document.querySelectorAll(".side-panel-tab");
	const bodies = document.querySelectorAll("[data-side-panel-body]");
	function activate (name)
	{
		for (const tab of tabs)
		{
			const on = tab.dataset.sidePanel === name;
			tab.classList.toggle("active", on);
			tab.setAttribute("aria-selected", on ? "true" : "false");
		}
		for (const body of bodies)
		{ body.hidden = body.dataset.sidePanelBody !== name; }
		if (name === "console")
		{
			const pre = $("editor-console");
			if (pre)
			{ pre.scrollTop = pre.scrollHeight; }
		}
	}
	for (const tab of tabs)
	{
		tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
	}
	$("console-clear")?.addEventListener("click", () =>
	{
		const pre = $("editor-console");
		if (pre)
		{ pre.replaceChildren(); }
	});
	activate("changelog");
}

function selectedToolLabel ()
{
	if (tool.kind === "erase")
	{ return "Erase block"; }
	if (tool.kind === "spawner")
	{
		if (tool.spawnerKind === "item" || isItemSpawnerConfig(tool))
		{ return "Spawner · Item Spawner"; }
		const def = mobDefinition(tool.mobTypeId);
		return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
	}
	const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
	const layer = tool.kind === "ground" ? "ground" : "block";
	const states = statesForType(catalog, layer, def.key);
	const state = resolveState(states, tool.state);
	if (tool.kind === "block" && def.id === BlockType.flower)
	{ return "Flower"; }
	if (tool.kind === "block" && def.id === BlockType.boulder)
	{
		const entry = listPlaceableBlockPaletteEntries(catalog)
			.find((row) => row.typeId === def.id && row.state === state);
		if (entry)
		{ return entry.displayName; }
	}
	if (states.length > 1)
	{ return `${def.displayName} (${state})`; }
	return def.displayName;
}

function notifyToolChanged ()
{
	const label = $("tool");
	if (label)
	{ label.textContent = selectedToolLabel(); }
	palettePanel?.sync();
}

function selectTool (next)
{
	if (next.kind === "erase")
	{ tool = { kind: "erase" }; }
	else if (next.kind === "spawner")
	{
		if (next.spawnerKind === "item")
		{ tool = { kind: "spawner", spawnerKind: "item" }; }
		else
		{ tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
	}
	else
	{
		const layer = next.kind === "ground" ? "ground" : "block";
		const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
		tool = {
			kind: next.kind,
			typeId: next.typeId,
			state: next.state ?? defaultStateForType(catalog, layer, def.key)
		};
	}
	notifyToolChanged();
}

function placeableToolState ()
{
	if (tool.kind === "erase" || tool.kind === "spawner")
	{ return null; }
	const layer = tool.kind === "ground" ? "ground" : "block";
	const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
	return resolveState(statesForType(catalog, layer, def.key), tool.state);
}

function previewFromTool ()
{
	if (tool.kind === "erase")
	{ return { block: null }; }
	if (tool.kind === "spawner")
	{ return {}; }
	const state = placeableToolState();
	if (tool.kind === "ground")
	{ return { ground: { typeId: tool.typeId, state } }; }
	return { block: { typeId: tool.typeId, state, config: null } };
}

/** Editor map neighborhood (Chebyshev); 2 → 5×5 chunks around the selection. */
const EDITOR_VIEW_CHUNK_RADIUS = STATIC_CHUNK_RADIUS;

function inEditorView (x, y)
{
	return Math.abs(x - chunkX) <= EDITOR_VIEW_CHUNK_RADIUS && Math.abs(y - chunkY) <= EDITOR_VIEW_CHUNK_RADIUS;
}

function neighborhoodCoords (centerX, centerY)
{
	const coords = [];
	for (let dy = -EDITOR_VIEW_CHUNK_RADIUS; dy <= EDITOR_VIEW_CHUNK_RADIUS; dy++)
	{
		for (let dx = -EDITOR_VIEW_CHUNK_RADIUS; dx <= EDITOR_VIEW_CHUNK_RADIUS; dx++)
		{ coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
	}
	return coords;
}

function snapshotFromPayload (payload)
{
	return {
		chunkX: payload.chunkX,
		chunkY: payload.chunkY,
		open: payload.data.open,
		closedEdges: payload.closedEdges,
		grounds: payload.data.grounds,
		blocks: payload.data.blocks,
		light: payload.data.light,
		enclosed: payload.data.enclosed,
		entities: []
	};
}

function syncSpawnersOverlay (cx, cy, spawners)
{
	view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
}

function spawnerAt (localX, localY)
{
	return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
}

function draftPersistable ()
{
	if (!draft)
	{ return null; }
	return {
		open: !!draft.open,
		grounds: draft.grounds,
		blocks: draft.blocks,
		spawners: draft.spawners ?? []
	};
}

function isSelectedChunkDirty ()
{
	if (!draft || draftBaseline == null)
	{ return false; }
	return JSON.stringify(draftPersistable()) !== draftBaseline;
}

function draftStorageKey (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId, subject = sessionAuthSubject)
{
	const who = subject ?? "anon";
	return `${EDITOR_DRAFT_STORAGE_PREFIX}${who}:${normalizeDimensionId(dimensionId)}:${cx},${cy}`;
}

function viewedChunkOwner ()
{
	return editorDraftOwner(selectedDimensionId, chunkX, chunkY);
}

function persistDirtyDraftBackup ()
{
	if (!draft || !isSelectedChunkDirty())
	{ return; }
	const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
	try
	{
		const payload = {
			savedAt: Date.now(),
			dimensionId: owner.dimensionId,
			chunkX: owner.chunkX,
			chunkY: owner.chunkY,
			authSubject: sessionAuthSubject,
			open: !!draft.open,
			grounds: draft.grounds,
			blocks: draft.blocks,
			spawners: draft.spawners ?? [],
			light: draft.light,
			enclosed: draft.enclosed,
			baseline: draftBaseline
		};
		sessionStorage.setItem(
			draftStorageKey(owner.chunkX, owner.chunkY, owner.dimensionId),
			JSON.stringify(payload)
		);
	}
	catch
	{ /* quota / private mode */ }
}

function clearDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
{
	try
	{ sessionStorage.removeItem(draftStorageKey(cx, cy, dimensionId)); }
	catch
	{ /* ignore */ }
}

function readDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
{
	try
	{
		const raw = sessionStorage.getItem(draftStorageKey(cx, cy, dimensionId));
		if (!raw)
		{ return null; }
		const parsed = JSON.parse(raw);
		if (!parsed || !Array.isArray(parsed.grounds) || !Array.isArray(parsed.blocks))
		{ return null; }
		return parsed;
	}
	catch
	{ return null; }
}

function applyRestoredDraftBackup (backup)
{
	if (!backup || !draft)
	{ return false; }
	draft.open = !!backup.open;
	draft.grounds = backup.grounds.map((ground) => normalizeGround(ground));
	draft.blocks = backup.blocks.map((block) => (block
		? { ...block, config: block.config ?? null }
		: null));
	const tileCount = CHUNK_SIZE * CHUNK_SIZE;
	draft.light = Array.isArray(backup.light) && backup.light.length === tileCount
		? backup.light.slice()
		: (draft.light ?? new Array(tileCount).fill(0));
	draft.enclosed = Array.isArray(backup.enclosed) && backup.enclosed.length === tileCount
		? backup.enclosed.slice().map((v) => (v ? 1 : 0))
		: (draft.enclosed ?? new Array(tileCount).fill(0));
	draft.spawners = (backup.spawners ?? []).map((entry) => ({
		localX: entry.localX | 0,
		localY: entry.localY | 0,
		config: { ...(entry.config ?? {}) }
	}));
	if (typeof backup.baseline === "string")
	{ draftBaseline = backup.baseline; }
	$("open").checked = draft.open;
	const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
	view.applySnapshot({
		chunkX,
		chunkY,
		open: draft.open,
		closedEdges: existing?.closedEdges,
		grounds: draft.grounds,
		blocks: draft.blocks,
		light: draft.light,
		enclosed: draft.enclosed,
		entities: []
	});
	syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
	syncSaveButton();
	return true;
}

function tryRestoreDraftBackupAfterServerLoad (payload)
{
	const dim = normalizeDimensionId(payload.dimensionId ?? selectedDimensionId);
	const backup = readDraftBackup(payload.chunkX, payload.chunkY, dim);
	if (!backup)
	{ return false; }
	const serverPersistable = {
		open: !!payload.data.open,
		grounds: payload.data.grounds,
		blocks: payload.data.blocks,
		spawners: payload.data.spawners ?? []
	};
	const backupPersistable = {
		open: !!backup.open,
		grounds: backup.grounds,
		blocks: backup.blocks,
		spawners: backup.spawners ?? []
	};
	if (JSON.stringify(serverPersistable) === JSON.stringify(backupPersistable))
	{
		clearDraftBackup(payload.chunkX, payload.chunkY, dim);
		return false;
	}
	// Treat server payload as the clean baseline so the restored paint stays dirty.
	draftBaseline = JSON.stringify(serverPersistable);
	return applyRestoredDraftBackup(backup);
}

function cloneDraftContents (source)
{
	if (!source)
	{ return null; }
	const tileCount = CHUNK_SIZE * CHUNK_SIZE;
	return {
		open: !!source.open,
		grounds: (source.grounds ?? []).map((ground) => normalizeGround(ground)),
		blocks: (source.blocks ?? []).map((block) => (block
			? {
				...block,
				config: block.config != null ? structuredClone(block.config) : null
			}
			: null)),
		light: Array.isArray(source.light) && source.light.length === tileCount
			? source.light.slice()
			: new Array(tileCount).fill(0),
		spawners: (source.spawners ?? []).map((entry) => ({
			localX: entry.localX | 0,
			localY: entry.localY | 0,
			config: structuredClone(entry.config ?? {})
		}))
	};
}

function blankChunkContents ()
{
	const groundTypeId = dimensionsById.get(selectedDimensionId)?.defaultGroundTypeId
		?? GroundType.grass;
	const tileCount = CHUNK_SIZE * CHUNK_SIZE;
	return {
		open: false,
		grounds: new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId)),
		blocks: new Array(tileCount).fill(null),
		light: new Array(tileCount).fill(0),
		spawners: []
	};
}

function applyDraftContents (next)
{
	if (!draft || !next || isSelectedDimensionSoftDeleted())
	{ return; }
	clearNeighborEditState();
	draft.open = !!next.open;
	draft.grounds = next.grounds.map((ground) => normalizeGround(ground));
	draft.blocks = next.blocks.map((block) => (block
		? { ...block, config: block.config ?? null }
		: null));
	draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
	draft.enclosed = Array.isArray(next.enclosed)
		? next.enclosed.slice().map((v) => (v ? 1 : 0))
		: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
	draft.spawners = (next.spawners ?? []).map((entry) => ({
		localX: entry.localX | 0,
		localY: entry.localY | 0,
		config: { ...(entry.config ?? {}) }
	}));
	$("open").checked = draft.open;
	const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
	view.applySnapshot({
		chunkX,
		chunkY,
		open: draft.open,
		closedEdges: existing?.closedEdges,
		grounds: draft.grounds,
		blocks: draft.blocks,
		light: draft.light,
		enclosed: draft.enclosed,
		entities: []
	});
	syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
	afterDraftMutation();
}

function syncChunkClipboardButtons ()
{
	const softDeleted = isSelectedDimensionSoftDeleted();
	const copyBtn = $("copy-chunk");
	const pasteBtn = $("paste-chunk");
	const clearBtn = $("clear-chunk");
	if (copyBtn)
	{
		copyBtn.disabled = !draft || softDeleted;
		copyBtn.title = softDeleted
			? "Cannot copy while this dimension is soft-deleted"
			: "Copy this chunk into the editor clipboard";
	}
	if (pasteBtn)
	{
		const canPaste = !!draft && !!chunkClipboard && !softDeleted;
		pasteBtn.disabled = !canPaste;
		pasteBtn.title = softDeleted
			? "Cannot paste while this dimension is soft-deleted"
			: chunkClipboard
				? "Paste the copied chunk over the current draft (does not save)"
				: "Copy a chunk first";
	}
	if (clearBtn)
	{
		clearBtn.disabled = !draft || softDeleted;
		clearBtn.title = softDeleted
			? "Cannot clear while this dimension is soft-deleted"
			: "Erase this chunk to a blank slate (does not save)";
	}
}

function copySelectedChunk ()
{
	if (!draft || isSelectedDimensionSoftDeleted())
	{ return; }
	chunkClipboard = cloneDraftContents(draft);
	syncChunkClipboardButtons();
}

function pasteSelectedChunk ()
{
	if (!draft || !chunkClipboard || isSelectedDimensionSoftDeleted())
	{ return; }
	const ok = window.confirm(
		"This will replace your current chunk entirely with your copied chunk. Are you sure?"
	);
	if (!ok)
	{ return; }
	applyDraftContents(cloneDraftContents(chunkClipboard));
}

function clearSelectedChunk ()
{
	if (!draft || isSelectedDimensionSoftDeleted())
	{ return; }
	const ok = window.confirm(
		"this will erase the chunk and reset it to a default blank slate. Are you certain?"
	);
	if (!ok)
	{ return; }
	applyDraftContents(blankChunkContents());
}

function captureDraftBaseline ()
{
	const payload = draftPersistable();
	draftBaseline = payload ? JSON.stringify(payload) : null;
	const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
	clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId);
	syncSaveButton();
}

function discardUnsavedDraft ()
{
	const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
	clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId);
	clearNeighborEditState();
	draft = null;
	draftBaseline = null;
	draftOwner = null;
	syncSaveButton();
}

function chunkKey (cx, cy)
{
	return `${cx},${cy}`;
}

function isDraftDirty ()
{
	if (dirtyNeighborChunks.size > 0)
	{ return true; }
	return isSelectedChunkDirty();
}

function syncSaveButton ()
{
	const btn = $("save");
	if (!btn)
	{ return; }
	const softDeleted = isSelectedDimensionSoftDeleted();
	const dirty = isDraftDirty();
	btn.disabled = !dirty || softDeleted;
	btn.classList.toggle("save-dirty", dirty && !softDeleted);
	btn.title = softDeleted
		? "Cannot save while this dimension is soft-deleted"
		: dirty
			? "Save unsaved chunk changes"
			: "No unsaved changes";
	syncChunkClipboardButtons();
}

function afterDraftMutation ()
{
	syncSaveButton();
	const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
	if (isSelectedChunkDirty())
	{ persistDirtyDraftBackup(); }
	else
	{ clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId); }
}

function clearNeighborEditState ()
{
	dirtyNeighborChunks.clear();
}

function groundAtWorld (tileX, tileY)
{
	const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
	const index = localY * CHUNK_SIZE + localX;
	if (cx === chunkX && cy === chunkY && draft)
	{ return draft.grounds[index] ?? null; }
	const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
	if (dirty)
	{ return dirty.grounds[index] ?? null; }
	const snapshot = view?.chunks.get(chunkKey(cx, cy));
	return snapshot?.grounds?.[index] ?? null;
}

function spawnerAtWorld (tileX, tileY)
{
	const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
	if (cx === chunkX && cy === chunkY && draft)
	{ return spawnerAt(localX, localY); }
	const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
	if (dirty)
	{ return dirty.spawners?.find((entry) => entry.localX === localX && entry.localY === localY) ?? null; }
	return (neighborSpawnersByChunk.get(chunkKey(cx, cy)) ?? [])
		.find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
}

/** Human-readable summary of authored ground/block/spawner on a world tile. */
function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)
{
	const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
	if (dim !== selectedDimensionId)
	{
		return `Currently editing “${selectedDimensionId}”; switch to “${dim}” to inspect this tile.`;
	}
	const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
	const key = chunkKey(cx, cy);
	const loaded = (cx === chunkX && cy === chunkY && draft)
		|| dirtyNeighborChunks.has(key)
		|| view?.chunks?.has(key);
	if (!loaded)
	{ return `Chunk (${cx}, ${cy}) not loaded — center on this tile to load it.`; }

	const lines = [];
	const ground = normalizeGround(groundAtWorld(tileX, tileY));
	const groundDef = GROUND_DEFINITIONS[ground?.typeId];
	lines.push(`Ground: ${groundDef?.displayName ?? `type ${ground?.typeId ?? "?"}`}`);
	const block = normalizeBlock(blockAtWorld(tileX, tileY));
	if (block)
	{
		const blockDef = BLOCK_DEFINITIONS[block.typeId];
		lines.push(`Block: ${blockDef?.displayName ?? `type ${block.typeId}`}${block.state ? ` (${block.state})` : ""}`);
		if (block.config && Object.keys(block.config).length)
		{
			for (const [keyName, value] of Object.entries(block.config))
			{ lines.push(`  ${keyName}: ${value}`); }
		}
	}
	else
	{ lines.push("Block: (none)"); }
	const spawner = spawnerAtWorld(tileX, tileY);
	if (spawner)
	{
		const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
		if (isItemSpawnerConfig(config))
		{ lines.push(`Spawner: Item Spawner (${config.spawnerId})`); }
		else
		{
			const mob = mobDefinition(config.mobTypeId);
			lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
		}
	}
	else
	{ lines.push("Spawner: (none)"); }
	return lines.join("\n");
}

/** Pan the editor to a world tile without closing other UI; loads its chunk neighborhood. */
function centerEditorOnTile (tileX, tileY, dimensionId = selectedDimensionId)
{
	const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
	const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX | 0, tileY | 0, CHUNK_SIZE);
	if (dim !== selectedDimensionId)
	{
		if (isDraftDirty())
		{
			showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: dim });
			return false;
		}
		selectedDimensionId = dim;
		syncDimensionUi();
		clearNeighborhoodView();
		doLoadNeighborhood(cx, cy);
	}
	else if (cx !== chunkX || cy !== chunkY)
	{
		if (isDraftDirty())
		{
			showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: selectedDimensionId });
			return false;
		}
		doLoadNeighborhood(cx, cy);
	}
	if (!view?.scene)
	{ return true; }
	const size = view.tileSize();
	view.followPlayer = false;
	view.scene.cameraPosition.x = view.scene.real_size.x / 2 - ((tileX | 0) + 0.5) * size;
	view.scene.cameraPosition.y = view.scene.real_size.y / 2 - ((tileY | 0) + 0.5) * size;
	view.refreshViewport();
	updateSelectionBorder();
	return true;
}

function blockAtWorld (tileX, tileY)
{
	const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
	if (cx === chunkX && cy === chunkY && draft)
	{ return draft.blocks[localY * CHUNK_SIZE + localX] ?? null; }
	const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
	if (dirty)
	{ return dirty.blocks[localY * CHUNK_SIZE + localX] ?? null; }
	const snapshot = view?.chunks.get(chunkKey(cx, cy));
	return snapshot?.blocks?.[localY * CHUNK_SIZE + localX] ?? null;
}

function ensureDirtyNeighborChunk (cx, cy)
{
	const key = chunkKey(cx, cy);
	let data = dirtyNeighborChunks.get(key);
	if (data)
	{ return data; }
	const snapshot = view?.chunks.get(key);
	if (!snapshot)
	{ return null; }
	data = {
		open: !!snapshot.open,
		grounds: (snapshot.grounds ?? []).map((ground) => normalizeGround(ground)),
		blocks: (snapshot.blocks ?? []).map((block) => (block ? { ...block, config: block.config ?? null } : null)),
		spawners: structuredClone(neighborSpawnersByChunk.get(key) ?? [])
	};
	dirtyNeighborChunks.set(key, data);
	return data;
}

function writeBlockAtWorld (tileX, tileY, block)
{
	const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
	const index = localY * CHUNK_SIZE + localX;
	if (cx === chunkX && cy === chunkY && draft)
	{
		draft.blocks[index] = block;
		view.updateAuthoredTile(cx, cy, localX, localY, {
			ground: draft.grounds[index],
			block: draft.blocks[index],
			light: draft.light[index]
		});
		return true;
	}
	const data = ensureDirtyNeighborChunk(cx, cy);
	if (!data)
	{ return false; }
	data.blocks[index] = block;
	const snapshot = view?.chunks.get(chunkKey(cx, cy));
	const light = snapshot?.light?.[index];
	view.updateAuthoredTile(cx, cy, localX, localY, {
		ground: data.grounds[index],
		block: data.blocks[index],
		light
	});
	return true;
}

function showUnsavedModal (target)
{
	pendingNavigate = target;
	$("unsaved-chunk-backdrop").hidden = false;
	$("unsaved-chunk-modal").hidden = false;
}

function hideUnsavedModal ()
{
	$("unsaved-chunk-backdrop").hidden = true;
	$("unsaved-chunk-modal").hidden = true;
}

function saveSelectedChunk ()
{
	if (!draft || !isDraftDirty())
	{ return false; }
	if (isSelectedDimensionSoftDeleted())
	{
		$("error").textContent = "Cannot save while this dimension is soft-deleted.";
		return false;
	}
	$("error").textContent = "";
	$("apply-status").textContent = "";
	$("apply-status").className = "hint";
	const target = editorDirtyChunk(draftOwner, viewedChunkOwner());
	const neighborSaves = [...dirtyNeighborChunks.entries()];
	clearNeighborEditState();
	const savedChunks = [{ chunkX: target.chunkX, chunkY: target.chunkY }];
	pendingSaveAcks.add(editorChunkSaveKey(target.dimensionId, target.chunkX, target.chunkY));
	socket.send({
		type: MessageType.editorSaveChunk,
		chunkX: target.chunkX,
		chunkY: target.chunkY,
		dimensionId: target.dimensionId,
		draft: {
			open: $("open").checked,
			grounds: draft.grounds,
			blocks: draft.blocks,
			spawners: draft.spawners ?? []
		}
	});
	for (const [key, data] of neighborSaves)
	{
		const [cx, cy] = key.split(",").map(Number);
		savedChunks.push({ chunkX: cx, chunkY: cy });
		pendingSaveAcks.add(editorChunkSaveKey(target.dimensionId, cx, cy));
		socket.send({
			type: MessageType.editorSaveChunk,
			chunkX: cx,
			chunkY: cy,
			dimensionId: target.dimensionId,
			draft: {
				open: data.open,
				grounds: data.grounds,
				blocks: data.blocks,
				spawners: data.spawners ?? []
			}
		});
	}
	view?.bakeNatureTintForChunks?.(savedChunks);
	requestNeighbors();
	return true;
}

function isSelectedDimensionSoftDeleted ()
{
	const record = dimensionsById.get(selectedDimensionId);
	return record?.deletedAt != null;
}

function formatPurgeHint (record)
{
	if (!record?.purgeAfter)
	{ return "Soft-deleted — painting disabled."; }
	const when = new Date(record.purgeAfter);
	return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
}

function syncDimensionUi ()
{
	const record = dimensionsById.get(selectedDimensionId);
	const softDeleted = record?.deletedAt != null;
	const hint = $("dimension-purge-hint");
	if (hint)
	{
		hint.hidden = !softDeleted;
		hint.textContent = softDeleted ? formatPurgeHint(record) : "";
	}
	const openToggle = $("open");
	if (openToggle)
	{ openToggle.disabled = softDeleted; }
	dimensionPicker?.setValue(selectedDimensionId);
	dimensionSettings?.refresh();
	palettePanel?.sync();
	syncSaveButton();
}

function applyDimensionsList (payload)
{
	const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
	dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
	if (!dimensionsById.has(OVERWORLD_ID))
	{
		dimensionsById.set(OVERWORLD_ID, {
			dimensionId: OVERWORLD_ID,
			displayName: "Overworld",
			lightingMode: "dayNight",
			seasonMode: "auto",
			defaultGroundTypeId: 1,
			deletedAt: null,
			purgeAfter: null
		});
	}
	const options = [...dimensionsById.values()].map((dim) => ({
		id: dim.dimensionId,
		label: dim.displayName || dim.dimensionId,
		disabled: dim.deletedAt != null,
		hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
	}));
	dimensionPicker?.setOptions(options);
	const createdId = pendingCreatedDimensionId;
	pendingCreatedDimensionId = null;
	if (createdId && dimensionsById.has(createdId))
	{
		setRevisionState({
			activeRevisionId: payload.activeRevisionId,
			pendingRevisionId: payload.pendingRevisionId
		});
		selectDimension(createdId, { force: true });
		return;
	}
	if (!dimensionsById.has(selectedDimensionId))
	{ selectedDimensionId = OVERWORLD_ID; }
	setRevisionState({
		activeRevisionId: payload.activeRevisionId,
		pendingRevisionId: payload.pendingRevisionId
	});
	syncDimensionUi();
	if (!isDraftDirty())
	{ requestChunks(neighborhoodCoords(chunkX, chunkY)); }
}

function requestDimensions ()
{
	socket.send({ type: MessageType.editorListDimensions });
}

function selectDimension (dimensionId, { force = false } = {})
{
	const nextId = normalizeDimensionId(dimensionId);
	if (!force && nextId === selectedDimensionId)
	{ return; }
	if (!force && isDraftDirty())
	{
		showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
		dimensionPicker?.setValue(selectedDimensionId);
		return;
	}
	selectedDimensionId = nextId;
	syncDimensionUi();
	clearNeighborhoodView();
	doLoadNeighborhood(chunkX, chunkY);
}

function clearNeighborhoodView ()
{
	draft = null;
	draftBaseline = null;
	draftOwner = null;
	clearNeighborEditState();
	neighborSpawnersByChunk.clear();
	if (!view)
	{ return; }
	for (const key of [...view.chunks.keys()])
	{
		const [x, y] = key.split(",").map(Number);
		view.removeChunk(x, y);
	}
	view.clearEditorSpawners?.();
	syncSaveButton();
}

function paintAt (localX, localY)
{
	if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
	{ return; }
	if (isSelectedDimensionSoftDeleted())
	{ return; }
	const index = localY * CHUNK_SIZE + localX;
	const state = placeableToolState();
	if (tool.kind === "ground")
	{ draft.grounds[index] = { typeId: tool.typeId, state }; }
	else if (tool.kind === "erase")
	{
		const removed = draft.blocks[index];
		draft.blocks[index] = null;
		view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
			ground: draft.grounds[index],
			block: draft.blocks[index],
			light: draft.light[index]
		});
		if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
		{ refreshNeighborConnect(localX, localY, removed.typeId); }
		afterDraftMutation();
		return;
	}
	else if (tool.kind === "spawner")
	{
		const existing = spawnerAt(localX, localY);
		const spawnerId = existing?.config?.spawnerId
			?? `${normalizeDimensionId(selectedDimensionId)}:${chunkX}:${chunkY}:${index}`;
		const config = tool.spawnerKind === "item"
			? normalizeItemSpawnerConfig({
				...defaultItemSpawnerConfig(spawnerId),
				...(isItemSpawnerConfig(existing?.config) ? existing.config : {}),
				spawnerId
			}, spawnerId)
			: normalizeSpawnerConfig({
				...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
				...(existing?.config && !isItemSpawnerConfig(existing.config) ? existing.config : {}),
				spawnerId,
				mobTypeId: tool.mobTypeId
			}, spawnerId);
		const entry = { localX, localY, config };
		draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
		draft.spawners.push(entry);
		syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
		afterDraftMutation();
		return;
	}
	else
	{
		const def = BLOCK_DEFINITIONS[tool.typeId];
		if (def?.id === BlockType.fishingSpot)
		{
			const groundType = draft.grounds[index]?.typeId;
			if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
			{ return; }
		}
		let nextState = definitionUsesNeighborConnect(def)
			? composeNeighborConnectState(def, state, 0)
			: state;
		if (def?.id === BlockType.flower)
		{ nextState = flowerBlockState(randomFlowerColorId()); }
		if (def?.id === BlockType.fishingSpot && !nextState)
		{ nextState = "fishing-spot"; }
		const config = def?.id === BlockType.doorway
			? {
				targetDimensionId: selectedDimensionId,
				tileX: chunkX * CHUNK_SIZE + localX,
				tileY: chunkY * CHUNK_SIZE + localY
			}
			: (def?.id === BlockType.fishingSpot
				? { fishes: [] }
				: null);
		if (def?.id === BlockType.doorway && !nextState)
		{ nextState = "door"; }
		draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
		view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
			ground: draft.grounds[index],
			block: draft.blocks[index],
			light: draft.light[index]
		});
		if (definitionUsesNeighborConnect(def))
		{ refreshNeighborConnect(localX, localY, tool.typeId); }
		afterDraftMutation();
		return;
	}
	view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
		ground: draft.grounds[index],
		block: draft.blocks[index],
		light: draft.light[index]
	});
	afterDraftMutation();
}

/** Recompute neighbor-connect masks around a local tile, including across chunk edges. */
function refreshNeighborConnect (localX, localY, typeId)
{
	const def = BLOCK_DEFINITIONS[typeId];
	if (!draft || !definitionUsesNeighborConnect(def))
	{ return; }
	const originTileX = chunkX * CHUNK_SIZE + localX;
	const originTileY = chunkY * CHUNK_SIZE + localY;
	for (const [tileX, tileY] of neighborConnectRefreshTiles(originTileX, originTileY))
	{
		const block = blockAtWorld(tileX, tileY);
		if (!block || block.typeId !== typeId)
		{ continue; }
		const mask = computeNeighborConnectMask((dx, dy) =>
		{
			const neighbor = blockAtWorld(tileX + dx, tileY + dy);
			return neighborConnectBlocksMatch(block, neighbor, def);
		});
		const nextState = composeNeighborConnectState(def, block.state, mask);
		if (block.state === nextState)
		{ continue; }
		writeBlockAtWorld(tileX, tileY, { ...block, state: nextState });
	}
}

function updateRevisionUI ()
{
	const applyBtn = $("apply");
	$("revision").textContent = `active ${activeRevisionId ?? "?"}` +
		(pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
	if (applyBtn)
	{
		applyBtn.disabled = !pendingRevisionId || applyInFlight;
		applyBtn.title = pendingRevisionId
			? "Reload the live world with the pending map revision"
			: "Save a chunk first to create a pending revision";
	}
}

function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
{
	if (active != null)
	{ activeRevisionId = active; }
	pendingRevisionId = pending ?? null;
	updateRevisionUI();
}

function showSelectedChunk (payload, { isSaveAck = false } = {})
{
	const incoming = editorDraftOwner(
		payload.dimensionId ?? selectedDimensionId,
		payload.chunkX,
		payload.chunkY
	);
	const keepDirtyDraft = !shouldApplySelectedEditorChunk({
		isSaveAck,
		isDirty: !!draft && isSelectedChunkDirty(),
		incoming,
		draftOwner
	});
	if (!keepDirtyDraft)
	{
		if (draftOwner && !sameEditorChunk(incoming, draftOwner))
		{ clearDraftBackup(draftOwner.chunkX, draftOwner.chunkY, draftOwner.dimensionId); }
		clearNeighborEditState();
	}
	if (keepDirtyDraft)
	{
		setRevisionState({
			activeRevisionId: payload.activeRevisionId,
			pendingRevisionId: payload.pendingRevisionId
		});
		$("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
		syncSaveButton();
		return;
	}
	draft = {
		open: payload.data.open,
		grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
		blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
		light: payload.data.light.slice(),
		enclosed: Array.isArray(payload.data.enclosed)
			? payload.data.enclosed.slice().map((v) => (v ? 1 : 0))
			: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0),
		spawners: (payload.data.spawners ?? []).map((entry) => ({
			localX: entry.localX,
			localY: entry.localY,
			config: { ...entry.config }
		}))
	};
	draftOwner = incoming;
	$("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
	$("open").checked = draft.open;
	setRevisionState({
		activeRevisionId: payload.activeRevisionId,
		pendingRevisionId: payload.pendingRevisionId
	});
	$("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
	const log = $("changelog");
	log.innerHTML = "";
	for (const entry of payload.changelog ?? [])
	{
		const item = document.createElement("article");
		item.innerHTML = `<header>${entry.editorDisplayName || entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
		const list = document.createElement("ul");
		for (const bullet of entry.diffEntries)
		{
			const li = document.createElement("li");
			li.textContent = bullet;
			list.append(li);
		}
		item.append(list);
		log.append(item);
	}
	view.applySnapshot(snapshotFromPayload(payload));
	syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
	const restored = isSaveAck ? false : tryRestoreDraftBackupAfterServerLoad(payload);
	if (!restored)
	{ captureDraftBaseline(); }
	else
	{ syncSaveButton(); }
	if (navigateAfterSave && pendingNavigate)
	{
		const next = pendingNavigate;
		navigateAfterSave = false;
		pendingNavigate = null;
		const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
		if (nextDim !== selectedDimensionId)
		{
			selectedDimensionId = nextDim;
			syncDimensionUi();
			clearNeighborhoodView();
		}
		doLoadNeighborhood(next.chunkX, next.chunkY);
	}
}

function pruneView ()
{
	for (const key of [...view.chunks.keys()])
	{
		const [x, y] = key.split(",").map(Number);
		if (!inEditorView(x, y))
		{
			view.removeChunk(x, y);
			neighborSpawnersByChunk.delete(key);
			dirtyNeighborChunks.delete(key);
		}
	}
}

function frameNeighborhood ()
{
	const size = view.tileSize();
	view.followPlayer = false;
	const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
	const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
	view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
	view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
	view.refreshViewport();
	updateSelectionBorder();
}

function updateSelectionBorder ()
{
	const border = $("selection-border");
	const canvas = scene?.canvas;
	if (!border || !canvas)
	{ return; }

	const rect = canvas.getBoundingClientRect();
	const size = view.tileSize();
	const chunkPx = CHUNK_SIZE * size;
	const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
	const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
	border.style.left = `${rect.left + screenLeft}px`;
	border.style.top = `${rect.top + screenTop}px`;
	border.style.width = `${chunkPx}px`;
	border.style.height = `${chunkPx}px`;
}

function layoutScene ()
{
	const header = document.querySelector("body > header");
	const aside = $("editor-tools");
	const sidePanels = $("side-panels") || $("changelog-wrap");
	const top = header.offsetHeight;
	aside.style.top = `${top}px`;
	sidePanels.style.top = `${top}px`;
	const left = aside.offsetWidth;
	const right = sidePanels.offsetWidth;
	const width = Math.max(64, window.innerWidth - left - right);
	const height = Math.max(64, window.innerHeight - top);
	scene.position.x = left;
	scene.position.y = top;
	scene.size.x = width;
	scene.size.y = height;
	scene.g_fixSize();
	useNearestNeighbour(scene, game.images);
	const fit = Math.min(width, height) / (CHUNK_SIZE * (EDITOR_VIEW_CHUNK_RADIUS * 2 + 1) * SPRITE_SIZE_PX);
	if (editorZoom == null)
	{ editorZoom = fit; }
	else
	{ editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
	view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
	frameNeighborhood();
}

function zoomEditor (direction)
{
	if (!view)
	{ return; }
	const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
	editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
	scheduleEditorZoom();
}

let editorZoomRaf = 0;
function scheduleEditorZoom ()
{
	if (editorZoomRaf)
	{ return; }
	editorZoomRaf = requestAnimationFrame(() =>
	{
		editorZoomRaf = 0;
		if (!view)
		{ return; }
		view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
		frameNeighborhood();
	});
}

function requestChunks (coords)
{
	if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
	{ return; }
	for (const coord of coords)
	{
		try
		{
			socket.send({
				type: MessageType.editorLoadChunk,
				chunkX: coord.chunkX,
				chunkY: coord.chunkY,
				dimensionId: selectedDimensionId
			});
		}
		catch (_)
		{ break; }
	}
}

function doLoadNeighborhood (x, y)
{
	chunkX = x;
	chunkY = y;
	$("coords").textContent = `${chunkX}, ${chunkY}`;
	requestChunks(neighborhoodCoords(x, y));
	requestEditorMinimap();
}

function requestEditorMinimap ()
{
	editorMinimap?.setCenter();
	if (minimapRequestTimer)
	{ return; }
	minimapRequestTimer = setTimeout(() =>
	{
		minimapRequestTimer = 0;
		if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
		{ return; }
		socket.send({
			type: MessageType.editorRequestMinimap,
			chunkX,
			chunkY,
			dimensionId: selectedDimensionId
		});
	}, 40);
}

function loadNeighborhood (x, y)
{
	if ((x !== chunkX || y !== chunkY) && isDraftDirty())
	{
		showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
		return;
	}
	doLoadNeighborhood(x, y);
}

function requestNeighbors ()
{
	requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
}

function anyModalOpen ()
{
	return settingsModal?.isOpen()
		|| paletteModal?.isOpen()
		|| tileConfigModal?.isOpen()
		|| questsModal?.isOpen()
		|| dialoguesModal?.isOpen()
		|| giftsModal?.isOpen()
		|| dimensionPicker?.isOpen()
		|| !$("unsaved-chunk-modal")?.hidden
		|| !$("global-changelog-modal")?.hidden
		|| !$("dimension-picker-modal")?.hidden;
}

function updateHoverStatus (local)
{
	const el = $("hover-status-text");
	if (!el)
	{ return; }
	if (!local)
	{
		el.textContent = "Hover a tile for coordinates";
		return;
	}
	const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
	const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
	el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
}

function updateTooltip (local, options = {})
{
	if (!options.keepStatus)
	{ updateHoverStatus(local); }
	const tip = $("tile-tooltip");
	if (!tip || !local || !draft)
	{
		if (tip)
		{ tip.hidden = true; }
		view?.clearSpawnRangeHighlight();
		return;
	}
	const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
	const spawner = spawnerAt(local.x, local.y);
	const lines = [];
	if (block)
	{
		const def = BLOCK_DEFINITIONS[block.typeId];
		lines.push(def?.displayName ?? `Block ${block.typeId}`);
		if (block.config && Object.keys(block.config).length)
		{
			for (const [key, value] of Object.entries(block.config))
			{ lines.push(`${key}: ${value}`); }
		}
	}
	if (spawner)
	{
		const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
		if (isItemSpawnerConfig(config))
		{
			lines.push("Spawner · Item Spawner");
			lines.push(`appearance: ${config.appearance}`);
			lines.push(`items: ${(config.items ?? []).length}`);
			lines.push(`spawnRange: ${config.spawnRangeTiles}`);
			lines.push(`respawn: ${config.respawnDelaySeconds}s`);
			lines.push(`id: ${config.spawnerId}`);
			view.setSpawnRangeHighlight(
				local.tileX,
				local.tileY,
				config.spawnRangeTiles,
				config.spawnRangeTiles
			);
		}
		else
		{
			const mob = mobDefinition(config.mobTypeId);
			lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
			lines.push(`maxAlive: ${config.maxAlive}`);
			lines.push(`spawnRange: ${config.spawnRangeTiles}`);
			lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
			lines.push(`id: ${config.spawnerId}`);
			view.setSpawnRangeHighlight(
				local.tileX,
				local.tileY,
				config.spawnRangeTiles,
				config.maxWanderRangeTiles
			);
		}
	}
	else
	{ view.clearSpawnRangeHighlight(); }
	if (!lines.length)
	{
		tip.hidden = true;
		return;
	}
	tip.hidden = false;
	tip.textContent = lines.join("\n");
	const canvas = scene.canvas;
	const rect = canvas.getBoundingClientRect();
	const size = view.tileSize();
	const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
	const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
	tip.style.left = `${screenX}px`;
	tip.style.top = `${screenY}px`;
}

async function main ()
{
	editorMinimap = initEditorMinimap({
		canvas: $("editor-minimap"),
		caption: $("editor-minimap-caption"),
		getCenter ()
		{
			return { chunkX, chunkY, dimensionId: selectedDimensionId };
		},
		onChunkClick (x, y)
		{
			loadNeighborhood(x, y);
		}
	});

	const authStatus = await fetchAuthStatus();
	const signIn = document.getElementById("auth-sign-in");
	const signOut = document.getElementById("auth-sign-out");
	if (signIn)
	{
		signIn.hidden = !!authStatus?.authenticated;
		signIn.href = loginUrl("/editor");
	}
	if (signOut)
	{
		signOut.hidden = !authStatus?.authenticated;
		signOut.href = logoutUrl("/editor");
	}
	if (!authStatus.authenticated)
	{
		$("who").textContent = "Sign in required";
		$("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
		return;
	}

	const accountLabel = authStatus.username ?? authStatus.authSubject ?? "Signed in";
	$("who").textContent = `${accountLabel} · loading sprites…`;

	catalog = await loadSpriteCatalog();
	imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
	await preloadCatalogImages(game, catalog, {
		onProgress ({ loaded, total })
		{
			$("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
		}
	});
	applySpriteSheets(game.images, catalog);
	scene = new Scene(250, 56, 64, 64);
	scene.backgroundColor.r = 0;
	scene.backgroundColor.g = 0;
	scene.backgroundColor.b = 0;
	game.loadScene(scene);
	view = new WorldView(game, scene, catalog);
	view.followPlayer = false;
	view.natureTintEnabled = false;
	view.setGraphicsPrefs(loadGraphicsSettings());
	syncSeasonControls(view.worldSeason ?? seasonIdAt());
	layoutScene();

	function editorImageUrl (name)
	{
		const sprite = game.images[name];
		const html = sprite?.g_image;
		if (html && typeof html.toDataURL === "function")
		{
			try
			{ return html.toDataURL("image/png"); }
			catch (_)
			{ /* fall through */ }
		}
		return imageUrlByName.get(name) ?? null;
	}

	const paletteOptions = {
		catalog,
		imageUrlFor: editorImageUrl,
		getSelection: () => tool,
		getDimensionId: () => selectedDimensionId,
		onSelect (next)
		{
			selectTool(next);
		}
	};
	palettePanel = initPalettePanel(paletteOptions);
	paletteModal = initPaletteModal(paletteOptions);
	selectTool(tool);

	tileConfigModal = initTileConfigModal({
		socket: {
			send (payload)
			{
				socket?.send(payload);
			}
		},
		MessageType,
		getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
		getQuests: () => questsModal?.getQuests?.() ?? [],
		describeWorldTile,
		centerEditorOnTile,
		getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
			id: dim.dimensionId,
			label: dim.displayName || dim.dimensionId,
			disabled: !!dim.deletedAt,
			hint: dim.deletedAt ? "soft-deleted" : undefined
		})),
		onSave (ctx, config)
		{
			if (!draft)
			{ return; }
			if (ctx.kind === "doorway")
			{
				const index = ctx.localY * CHUNK_SIZE + ctx.localX;
				draft.blocks[index] = {
					typeId: BlockType.doorway,
					state: config.state || "door",
					config: {
						targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
						tileX: Number(config.tileX) || 0,
						tileY: Number(config.tileY) || 0
					}
				};
				view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
					ground: draft.grounds[index],
					block: draft.blocks[index],
					light: draft.light[index]
				});
				afterDraftMutation();
				return;
			}
			if (ctx.kind === "door")
			{
				const index = ctx.localY * CHUNK_SIZE + ctx.localX;
				const existing = draft.blocks[index];
				if (!existing || existing.typeId !== BlockType.door)
				{ return; }
				const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
				const nextConfig = normalizeDoorConfig({
					...prev,
					when: config.when,
					blockedMessage: config.blockedMessage
				});
				draft.blocks[index] = {
					typeId: BlockType.door,
					state: existing.state,
					config: nextConfig
				};
				view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
					ground: draft.grounds[index],
					block: draft.blocks[index],
					light: draft.light[index]
				});
				afterDraftMutation();
				return;
			}
			if (ctx.kind === "fishing-spot")
			{
				const index = ctx.localY * CHUNK_SIZE + ctx.localX;
				const existing = draft.blocks[index];
				draft.blocks[index] = {
					typeId: BlockType.fishingSpot,
					state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
					config: { fishes: [...(config.fishes ?? [])] }
				};
				view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
					ground: draft.grounds[index],
					block: draft.blocks[index],
					light: draft.light[index]
				});
				afterDraftMutation();
				return;
			}
			draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
			draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
			syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
			afterDraftMutation();
		},
		onRemove (ctx)
		{
			if (!draft)
			{ return; }
			if (ctx.kind === "door")
			{
				const index = ctx.localY * CHUNK_SIZE + ctx.localX;
				const existing = draft.blocks[index];
				if (!existing || existing.typeId !== BlockType.door)
				{ return; }
				const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
				delete prev.when;
				delete prev.requirements;
				delete prev.blockedMessage;
				delete prev.denyMessage;
				draft.blocks[index] = {
					typeId: BlockType.door,
					state: existing.state,
					config: normalizeDoorConfig(prev)
				};
				view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
					ground: draft.grounds[index],
					block: draft.blocks[index],
					light: draft.light[index]
				});
				afterDraftMutation();
				return;
			}
			if (ctx.kind === "doorway")
			{
				const index = ctx.localY * CHUNK_SIZE + ctx.localX;
				draft.blocks[index] = null;
				view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
					ground: draft.grounds[index],
					block: draft.blocks[index],
					light: draft.light[index]
				});
				afterDraftMutation();
				return;
			}
			if (ctx.kind === "fishing-spot")
			{
				const index = ctx.localY * CHUNK_SIZE + ctx.localX;
				draft.blocks[index] = null;
				view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
					ground: draft.grounds[index],
					block: draft.blocks[index],
					light: draft.light[index]
				});
				afterDraftMutation();
				return;
			}
			draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
			syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
			afterDraftMutation();
		}
	});

	const ticker = new GameObject(0, 0, null, 10);
	ticker.update = (dt) =>
	{
		hoverLocal = null;
		const canvas = scene.canvas;
		const rect = canvas.getBoundingClientRect();
		const mouseX = GameInput.mousePosition.x - rect.left;
		const mouseY = GameInput.mousePosition.y - rect.top;
		const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
		if (overCanvas && draft && !anyModalOpen())
		{
			const tile = view.screenToTile(mouseX, mouseY);
			const localX = tile.tileX - chunkX * CHUNK_SIZE;
			const localY = tile.tileY - chunkY * CHUNK_SIZE;
			const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
			const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
			updateHoverStatus({
				tileX: tile.tileX,
				tileY: tile.tileY,
				x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
				y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
				chunkX: hoverChunkX,
				chunkY: hoverChunkY
			});
			if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
			{
				hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
				view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
				updateTooltip(hoverLocal);
				if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
				{ paintAt(localX, localY); }
			}
			else
			{
				hoverLocal = null;
				view.clearTilePreview();
				updateTooltip(null, { keepStatus: true });
			}
		}
		else
		{
			view.clearTilePreview();
			updateTooltip(null);
		}
		view.update(dt);
		frameNeighborhood();
	};
	scene.addObject(ticker);
	window.addEventListener("resize", layoutScene);

	accountWhoLabel = accountLabel;
	$("who").textContent = `${accountLabel} · connecting…`;

	function setWhoConnected (label, isAdmin)
	{
		accountWhoLabel = label;
		$("who").textContent = `${label}${isAdmin ? " · admin" : " · not admin"}`;
	}

	function resubscribeEditorSession ({ reloadMap })
	{
		socket.send({ type: MessageType.editorLoadSettings });
		socket.send({ type: MessageType.editorLoadGameAdmins });
		socket.send({ type: MessageType.editorConsoleSubscribe });
		requestDimensions();
		if (reloadMap)
		{
			loadNeighborhood(chunkX, chunkY);
			return;
		}
		const coords = neighborhoodCoords(chunkX, chunkY).filter((coord) =>
		{
			if (coord.chunkX === chunkX && coord.chunkY === chunkY)
			{ return !draft || !isSelectedChunkDirty(); }
			return !dirtyNeighborChunks.has(chunkKey(coord.chunkX, coord.chunkY));
		});
		requestChunks(coords);
		syncSaveButton();
	}

	socket = new GameSocket(defaultSocketUrl(), (message) =>
	{
		if (message.type === MessageType.session)
		{
			const wasReady = sessionReady;
			sessionAuthSubject = message.authSubject ?? null;
			sessionReady = true;
			socket.notifySessionEstablished();
			const label = message.username ?? message.authSubject ?? "Unknown";
			setWhoConnected(label, !!message.isAdmin);
			if (!message.isAdmin)
			{
				$("error").textContent = "Admin access required.";
				return;
			}
			$("error").textContent = "";
			const restartBtn = document.getElementById("editor-restart-now");
			if (restartBtn)
			{
				restartBtn.hidden = false;
				restartBtn.disabled = false;
			}
			resubscribeEditorSession({ reloadMap: !wasReady });
		}
		else if (message.type === MessageType.editorSettings
			|| message.type === MessageType.editorGameAdmins)
		{ settingsModal.handleMessage(message); }
		else if (message.type === MessageType.editorConsoleSnapshot)
		{ applyConsoleSnapshot(message.lines); }
		else if (message.type === MessageType.editorConsoleLine)
		{ appendConsoleLine(message.line); }
		else if (message.type === MessageType.editorDimensions)
		{
			applyDimensionsList(message);
		}
		else if (message.type === MessageType.editorQuests)
		{
			questsModal?.handleMessage(message);
			settingsModal?.handleMessage(message);
			dialoguesModal?.handleMessage(message);
			tileConfigModal?.handleMessage(message);
		}
		else if (message.type === MessageType.editorDialogues)
		{
			dialoguesModal?.handleMessage(message);
			tileConfigModal?.handleMessage(message);
			questsModal?.handleMessage(message);
		}
		else if (message.type === MessageType.editorGiftCharacters
			|| message.type === MessageType.editorGiftSent)
		{ giftsModal?.handleMessage(message); }
		else if (message.type === MessageType.editorGlobalChangelog)
		{ renderGlobalChangelog(message.changelog ?? []); }
		else if (message.type === MessageType.editorMinimap)
		{ editorMinimap?.apply(message); }
		else if (message.type === MessageType.editorChunk)
		{
			const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);
			if (msgDim !== selectedDimensionId)
			{ return; }
			const isSaveAck = pendingSaveAcks.delete(
				editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)
			);
			if (isSaveAck)
			{ requestEditorMinimap(); }
			if (message.settings)
			{ view.setSettings(message.settings); }
			if (!inEditorView(message.chunkX, message.chunkY))
			{ return; }
			if (message.chunkX === chunkX && message.chunkY === chunkY)
			{ showSelectedChunk(message, { isSaveAck }); }
			else
			{
				const key = chunkKey(message.chunkX, message.chunkY);
				neighborSpawnersByChunk.set(key, message.data.spawners ?? []);
				if (!dirtyNeighborChunks.has(key))
				{
					view.applySnapshot(snapshotFromPayload(message));
					syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
				}
			}
			pruneView();
		}
		else if (message.type === MessageType.editorRevisionApplied)
		{
			applyInFlight = false;
			setRevisionState({
				activeRevisionId: message.activeRevisionId,
				pendingRevisionId: message.pendingRevisionId
			});
			const status = $("apply-status");
			status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
			status.className = "hint ok";
			requestDimensions();
			requestChunks(neighborhoodCoords(chunkX, chunkY));
		}
		else if (message.type === MessageType.forceLogout)
		{
			$("who").textContent = "Server restarting…";
			$("error").textContent = message.reason || "Server shutting down.";
		}
		else if (message.type === MessageType.error)
		{
			$("error").textContent = message.message;
			if (giftsModal?.isOpen())
			{ giftsModal.handleError?.(message.message); }
			pendingCreatedDimensionId = null;
			pendingSaveAcks.clear();
			navigateAfterSave = false;
			dimensionPicker?.setValue(selectedDimensionId);
			if (applyInFlight)
			{
				applyInFlight = false;
				$("apply-status").textContent = "";
				$("apply-status").className = "hint";
				updateRevisionUI();
			}
		}
	}, {
		autoReconnect: true,
		onOpen ()
		{
			if (sessionReady)
			{ $("who").textContent = `${accountWhoLabel} · reconnected, waiting for session…`; }
		},
		onReconnecting ({ attempt, delayMs })
		{
			$("who").textContent = `${accountWhoLabel} · reconnecting…`;
			if (sessionReady)
			{
				$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept."
					+ ` (attempt ${attempt}, retry in ${Math.round(delayMs / 100) / 10}s)`;
			}
		},
		onClose (event)
		{
			if (event.code === 1000)
			{ return; }
			const authOrRestart = {
				4401: "Sign in expired or missing. Use Sign out, then sign in again.",
				1011: "Server could not verify your account with auth.timfalken.com.",
				1001: "Server is restarting. Reload this page in a moment."
			};
			if (authOrRestart[event.code])
			{
				sessionReady = false;
				$("who").textContent = "Connection failed";
				$("error").textContent = authOrRestart[event.code];
				return;
			}
			if (sessionReady)
			{
				$("who").textContent = `${accountWhoLabel} · reconnecting…`;
				$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
				persistDirtyDraftBackup();
				return;
			}
			const reasons = {
				1006: "Connection dropped before the editor session started."
			};
			const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
			$("who").textContent = "Connection failed";
			$("error").textContent = detail;
		},
		onError ()
		{
			if (sessionReady)
			{
				$("who").textContent = `${accountWhoLabel} · reconnecting…`;
				$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
				return;
			}
			$("who").textContent = "Connection failed";
			$("error").textContent = "Could not open a live connection to the server.";
		}
	});
	settingsModal = initSettingsModal({
		socket,
		MessageType,
		getAuthSubject: () => sessionAuthSubject,
		onApplied (settings)
		{
			view.setSettings(settings);
		},
		onPreviewNight (hour)
		{
			view.nightPreview = hour;
			$("night").value = String(hour);
			$("night-label").textContent = Number(hour).toFixed(1);
		}
	});
	dimensionPicker = initDimensionPickerModal({
		onSelect (id)
		{
			selectDimension(id);
		},
		onCreate (rawId, displayName)
		{
			const id = normalizeDimensionId(rawId);
			$("error").textContent = "";
			pendingCreatedDimensionId = id;
			socket.send({
				type: MessageType.editorCreateDimension,
				dimensionId: id,
				displayName: displayName ?? rawId.trim()
			});
		}
	});
	dimensionPicker.setOptions([{
		id: OVERWORLD_ID,
		label: "Overworld"
	}]);
	dimensionPicker.setValue(OVERWORLD_ID);
	dimensionSettings = initDimensionSettings({
		socket,
		MessageType,
		GROUND_DEFINITIONS,
		OVERWORLD_ID,
		getSelectedDimensionId: () => selectedDimensionId,
		getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
		isOverworld
	});

function collectEditorSpawners ()
{
	const byId = new Map();
	function add (row)
	{
		const id = String(row?.spawnerId ?? "").trim();
		if (!id)
		{ return; }
		byId.set(id, {
			spawnerId: id,
			mobTypeId: row.mobTypeId ?? null,
			dimensionId: row.dimensionId ?? OVERWORLD_ID,
			tileX: row.tileX | 0,
			tileY: row.tileY | 0
		});
	}
	for (const row of questsModal?.getServerSpawners?.() ?? [])
	{ add(row); }
	function addChunk (cx, cy, dim, spawners)
	{
		for (const entry of spawners ?? [])
		{
			const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
			if (isItemSpawnerConfig(config))
			{ continue; }
			add({
				spawnerId: config.spawnerId,
				mobTypeId: config.mobTypeId,
				dimensionId: dim,
				tileX: cx * CHUNK_SIZE + (entry.localX | 0),
				tileY: cy * CHUNK_SIZE + (entry.localY | 0)
			});
		}
	}
	if (draft)
	{ addChunk(chunkX, chunkY, selectedDimensionId, draft.spawners); }
	for (const [key, data] of dirtyNeighborChunks)
	{
		const [cx, cy] = key.split(",").map(Number);
		if (!Number.isFinite(cx) || !Number.isFinite(cy))
		{ continue; }
		addChunk(cx, cy, selectedDimensionId, data.spawners);
	}
	for (const [key, spawners] of neighborSpawnersByChunk)
	{
		const [cx, cy] = key.split(",").map(Number);
		if (!Number.isFinite(cx) || !Number.isFinite(cy))
		{ continue; }
		addChunk(cx, cy, selectedDimensionId, spawners);
	}
	return [...byId.values()].sort((a, b) => a.spawnerId.localeCompare(b.spawnerId));
}

	questsModal = initQuestsModal({
		socket,
		MessageType,
		describeWorldTile,
		centerEditorOnTile,
		getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
			id: dim.dimensionId,
			label: dim.displayName || dim.dimensionId,
			disabled: dim.deletedAt != null,
			hint: dim.deletedAt != null ? "soft-deleted" : null
		})),
		getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
			!mobTypeId || String(row.mobTypeId) === String(mobTypeId)
		)
	});
	dialoguesModal = initDialoguesModal({
		socket,
		MessageType,
		describeWorldTile,
		centerEditorOnTile,
		getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
			id: dim.dimensionId,
			label: dim.displayName || dim.dimensionId,
			disabled: dim.deletedAt != null,
			hint: dim.deletedAt != null ? "soft-deleted" : null
		})),
		getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
			!mobTypeId || String(row.mobTypeId) === String(mobTypeId)
		)
	});
	giftsModal = initGiftsModal({ socket, MessageType });
	initSidePanelTabs();
	game.startGame();
	useNearestNeighbour(scene, game.images);
	try
	{ await socket.connect(); }
	catch (error)
	{
		// autoReconnect keeps retrying; surface the first failure without aborting the editor UI
		if (!sessionReady)
		{
			$("who").textContent = "Connection failed";
			$("error").textContent = error?.message || "Could not open a live connection to the server.";
		}
	}
}

$("tool").textContent = selectedToolLabel();
$("tool-erase").addEventListener("click", () =>
{
	selectTool({ kind: "erase" });
});

$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
$("copy-chunk")?.addEventListener("click", () => copySelectedChunk());
$("paste-chunk")?.addEventListener("click", () => pasteSelectedChunk());
$("clear-chunk")?.addEventListener("click", () => clearSelectedChunk());

function isTypingTarget (target)
{
	if (!(target instanceof Element))
	{ return false; }
	const tag = target.tagName;
	if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT")
	{ return true; }
	return !!target.closest("[contenteditable='true']");
}

window.addEventListener("keydown", (event) =>
{
	if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
	{ return; }
	if (anyModalOpen() || isTypingTarget(event.target))
	{ return; }
	if (event.key === "ArrowUp")
	{
		event.preventDefault();
		loadNeighborhood(chunkX, chunkY - 1);
	}
	else if (event.key === "ArrowDown")
	{
		event.preventDefault();
		loadNeighborhood(chunkX, chunkY + 1);
	}
	else if (event.key === "ArrowLeft")
	{
		event.preventDefault();
		loadNeighborhood(chunkX - 1, chunkY);
	}
	else if (event.key === "ArrowRight")
	{
		event.preventDefault();
		loadNeighborhood(chunkX + 1, chunkY);
	}
});
$("open").addEventListener("change", () =>
{
	if (isSelectedDimensionSoftDeleted())
	{
		$("open").checked = !!draft?.open;
		return;
	}
	if (draft)
	{
		draft.open = $("open").checked;
		view.setChunkOpen(chunkX, chunkY, draft.open);
		afterDraftMutation();
	}
});
$("save").addEventListener("click", () =>
{
	saveSelectedChunk();
});
$("unsaved-chunk-cancel")?.addEventListener("click", () =>
{
	pendingNavigate = null;
	navigateAfterSave = false;
	hideUnsavedModal();
});
$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
{
	pendingNavigate = null;
	navigateAfterSave = false;
	hideUnsavedModal();
});
$("unsaved-chunk-discard")?.addEventListener("click", () =>
{
	const next = pendingNavigate;
	hideUnsavedModal();
	pendingNavigate = null;
	navigateAfterSave = false;
	discardUnsavedDraft();
	if (!next)
	{ return; }
	const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
	if (nextDim !== selectedDimensionId)
	{
		selectedDimensionId = nextDim;
		syncDimensionUi();
		clearNeighborhoodView();
	}
	doLoadNeighborhood(next.chunkX, next.chunkY);
});
$("unsaved-chunk-save")?.addEventListener("click", () =>
{
	hideUnsavedModal();
	if (!pendingNavigate)
	{ return; }
	navigateAfterSave = true;
	if (!saveSelectedChunk())
	{
		navigateAfterSave = false;
		const next = pendingNavigate;
		pendingNavigate = null;
		if (next)
		{
			const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
			if (nextDim !== selectedDimensionId)
			{
				selectedDimensionId = nextDim;
				syncDimensionUi();
				clearNeighborhoodView();
			}
			doLoadNeighborhood(next.chunkX, next.chunkY);
		}
	}
});
$("apply").addEventListener("click", () =>
{
	if (!pendingRevisionId || applyInFlight)
	{ return; }
	$("error").textContent = "";
	const status = $("apply-status");
	status.textContent = "Applying…";
	status.className = "hint";
	applyInFlight = true;
	updateRevisionUI();
	socket.send({ type: MessageType.editorApplyRevision });
});
document.getElementById("editor-restart-now")?.addEventListener("click", () =>
{
	if (!socket)
	{ return; }
	const ok = window.confirm(
		"Restart the server now?\n\nAll players and editor sessions will disconnect. "
		+ "systemd will start a fresh process and pull the latest code from git."
	);
	if (!ok)
	{ return; }
	const restartBtn = document.getElementById("editor-restart-now");
	if (restartBtn)
	{ restartBtn.disabled = true; }
	$("who").textContent = "Restarting server…";
	$("error").textContent = "";
	socket.send({ type: MessageType.editorRestartNow });
});
$("night").addEventListener("input", () =>
{
	view.nightPreview = Number($("night").value);
	$("night-label").textContent = view.nightPreview.toFixed(1);
});
$("season").addEventListener("change", () =>
{
	applySeasonPreview($("season").value);
});

function showGlobalChangelog (visible)
{
	const backdrop = $("global-changelog-backdrop");
	const modal = $("global-changelog-modal");
	if (backdrop)
	{ backdrop.hidden = !visible; }
	if (modal)
	{ modal.hidden = !visible; }
}

function renderGlobalChangelog (changelog)
{
	const log = $("global-changelog");
	if (!log)
	{ return; }
	log.innerHTML = "";
	if (!changelog.length)
	{
		log.innerHTML = "<p class=\"hint\">No edits logged yet.</p>";
		return;
	}
	const kindLabel = {
		chunk: "Chunk",
		settings: "Settings",
		quest: "Quest",
		dialogue: "Dialogue"
	};
	for (const entry of changelog)
	{
		const item = document.createElement("article");
		const who = entry.editorDisplayName || entry.editor_admin_id;
		const kind = kindLabel[entry.kind] || entry.kind || "Edit";
		const scope = entry.scope ? ` · ${entry.scope}` : "";
		item.innerHTML = `<header>${kind}${scope} · ${who} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
		const list = document.createElement("ul");
		for (const bullet of entry.diffEntries ?? [])
		{
			const li = document.createElement("li");
			li.textContent = bullet;
			list.append(li);
		}
		item.append(list);
		log.append(item);
	}
	log.scrollTop = 0;
}

document.getElementById("open-global-changelog")?.addEventListener("click", () =>
{
	const log = $("global-changelog");
	if (log)
	{ log.innerHTML = "<p class=\"hint\">Loading…</p>"; }
	showGlobalChangelog(true);
	socket.send({ type: MessageType.editorLoadGlobalChangelog });
});
document.getElementById("global-changelog-close")?.addEventListener("click", () => showGlobalChangelog(false));
document.getElementById("global-changelog-backdrop")?.addEventListener("click", () => showGlobalChangelog(false));

function syncSeasonControls (season)
{
	const next = season === SeasonId.spring
		|| season === SeasonId.fall
		|| season === SeasonId.winter
		|| season === SeasonId.summer
		? season
		: seasonIdAt();
	$("season").value = next;
	view?.setWorldSeason(next);
}

function applySeasonPreview (season)
{
	syncSeasonControls(season);
}

function cycleToolState (direction)
{
	if (tool.kind === "erase" || tool.kind === "spawner")
	{ return; }
	const layer = tool.kind === "ground" ? "ground" : "block";
	const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
	if (definitionUsesNeighborConnect(def))
	{ return; }
	if (tool.kind === "block" && def?.id === BlockType.flower)
	{ return; }
	const allStates = statesForType(catalog, layer, def.key);
	const seasonal = seasonalCycleStates(allStates);
	const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
	if (states.length < 2)
	{ return; }
	tool.state = cycleState(states, tool.state, direction);
	notifyToolChanged();
	const season = seasonIdFromVisualState(tool.state);
	if (season)
	{ applySeasonPreview(season); }
	if (!draft || !hoverLocal)
	{ return; }
	const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
	if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
	{ paintAt(hoverLocal.x, hoverLocal.y); }
	else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
	{ paintAt(hoverLocal.x, hoverLocal.y); }
}

document.addEventListener("wheel", (event) =>
{
	if (!scene?.canvas || anyModalOpen())
	{ return; }
	const rect = scene.canvas.getBoundingClientRect();
	if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
	{ return; }
	event.preventDefault();
	if (event.shiftKey)
	{
		cycleToolState(event.deltaY < 0 ? 1 : -1);
		if (hoverLocal)
		{ view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
		return;
	}
	zoomEditor(event.deltaY < 0 ? 1 : -1);
}, { passive: false });

document.addEventListener("contextmenu", (event) =>
{
	if (!scene?.canvas || anyModalOpen() || !draft)
	{ return; }
	const rect = scene.canvas.getBoundingClientRect();
	if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
	{ return; }
	event.preventDefault();
	const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
	const localX = tile.tileX - chunkX * CHUNK_SIZE;
	const localY = tile.tileY - chunkY * CHUNK_SIZE;
	if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
	{ return; }
	const spawner = spawnerAt(localX, localY);
	if (spawner)
	{
		const ctx = {
			localX,
			localY,
			tileX: tile.tileX,
			tileY: tile.tileY,
			config: { ...spawner.config }
		};
		if (isItemSpawnerConfig(spawner.config))
		{ tileConfigModal.openItemSpawner(ctx); }
		else
		{ tileConfigModal.openSpawner(ctx); }
		return;
	}
	const index = localY * CHUNK_SIZE + localX;
	const block = draft.blocks[index];
	if (block?.typeId === BlockType.doorway)
	{
		tileConfigModal.openDoorway({
			localX,
			localY,
			tileX: tile.tileX,
			tileY: tile.tileY,
			state: block.state ?? "door",
			config: block.config ? { ...block.config } : {}
		});
		return;
	}
	if (block?.typeId === BlockType.door)
	{
		tileConfigModal.openDoor({
			localX,
			localY,
			tileX: tile.tileX,
			tileY: tile.tileY,
			state: block.state,
			config: block.config ? { ...block.config } : {}
		});
		return;
	}
	if (block?.typeId === BlockType.fishingSpot)
	{
		tileConfigModal.openFishingSpot({
			localX,
			localY,
			tileX: tile.tileX,
			tileY: tile.tileY,
			config: block.config ? { ...block.config } : { fishes: [] }
		});
	}
});

main().catch((error) =>
{
	$("error").textContent = error.message;
	console.error(error);
});
