// Regression: navigating back to the map after creating a science
// must not leave the canvas blank. Replays the user-reported flow:
// boot, go to /map, navigate to /designer/science, save a science,
// navigate to /map, assert the renderer mounts cleanly (no
// `data-testid="map-mount-error"` overlay) and the canvas surface
// is non-empty.

import { fromJson, type JsonValue } from "@bufbuild/protobuf";
import { expect, test, type Page } from "@playwright/test";
import { ByteBuffer } from "flatbuffers";

import { ExecuteCommandRequestSchema } from "../../src/proto/galaxy/gateway/v1/edge_gateway_pb";
import { UUID } from "../../src/proto/galaxy/fbs/common";
import {
	CommandPayload,
	CommandScienceCreate,
	UserGamesOrder,
	UserGamesOrderGet,
} from "../../src/proto/galaxy/fbs/order";
import { GameReportRequest } from "../../src/proto/galaxy/fbs/report";
import { forgeExecuteCommandResponseJson } from "./fixtures/sign-response";
import {
	buildMyGamesListPayload,
	type GameFixture,
} from "./fixtures/lobby-fbs";
import { buildReportPayload } from "./fixtures/report-fbs";
import {
	buildOrderGetResponsePayload,
	buildOrderResponsePayload,
	type CommandResultFixture,
} from "./fixtures/order-fbs";

const SESSION_ID = "phase-21-map-regress-session";
const GAME_ID = "21212121-cafe-cafe-cafe-cafecafecafe";

async function mockGateway(page: Page): Promise<void> {
	const game: GameFixture = {
		gameId: GAME_ID,
		gameName: "Phase 21 Map Regress",
		gameType: "private",
		status: "running",
		ownerUserId: "user-1",
		minPlayers: 2,
		maxPlayers: 8,
		enrollmentEndsAtMs: BigInt(Date.now() + 86_400_000),
		createdAtMs: BigInt(Date.now() - 86_400_000),
		updatedAtMs: BigInt(Date.now()),
		currentTurn: 1,
	};

	let storedOrder: CommandResultFixture[] = [];

	await page.route(
		"**/galaxy.gateway.v1.EdgeGateway/ExecuteCommand",
		async (route) => {
			const reqText = route.request().postData();
			if (reqText === null) {
				await route.fulfill({ status: 400 });
				return;
			}
			const req = fromJson(
				ExecuteCommandRequestSchema,
				JSON.parse(reqText) as JsonValue,
			);

			let resultCode = "ok";
			let payload: Uint8Array;
			switch (req.messageType) {
				case "lobby.my.games.list":
					payload = buildMyGamesListPayload([game]);
					break;
				case "user.games.report": {
					GameReportRequest.getRootAsGameReportRequest(
						new ByteBuffer(req.payloadBytes),
					).gameId(new UUID());
					payload = buildReportPayload({
						turn: 1,
						mapWidth: 4000,
						mapHeight: 4000,
						race: "Earthlings",
						players: [{ name: "Earthlings", drive: 1 }],
						localPlanets: [
							{
								number: 1,
								name: "Earth",
								x: 2000,
								y: 2000,
								size: 1000,
								resources: 5,
								population: 800,
								industry: 600,
							},
						],
					});
					break;
				}
				case "user.games.order": {
					const decoded = UserGamesOrder.getRootAsUserGamesOrder(
						new ByteBuffer(req.payloadBytes),
					);
					const length = decoded.commandsLength();
					const fixtures: CommandResultFixture[] = [];
					for (let i = 0; i < length; i++) {
						const item = decoded.commands(i);
						if (item === null) continue;
						const cmdId = item.cmdId() ?? "";
						if (item.payloadType() === CommandPayload.CommandScienceCreate) {
							const inner = new CommandScienceCreate();
							item.payload(inner);
							fixtures.push({
								kind: "createScience",
								cmdId,
								name: inner.name() ?? "",
								drive: inner.drive(),
								weapons: inner.weapons(),
								shields: inner.shields(),
								cargo: inner.cargo(),
								applied: true,
								errorCode: null,
							});
						}
					}
					storedOrder = fixtures;
					payload = buildOrderResponsePayload(GAME_ID, fixtures, Date.now());
					break;
				}
				case "user.games.order.get":
					UserGamesOrderGet.getRootAsUserGamesOrderGet(
						new ByteBuffer(req.payloadBytes),
					);
					payload = buildOrderGetResponsePayload(
						GAME_ID,
						storedOrder,
						Date.now(),
						storedOrder.length > 0,
					);
					break;
				default:
					resultCode = "internal_error";
					payload = new Uint8Array();
			}

			const body = await forgeExecuteCommandResponseJson({
				requestId: req.requestId,
				timestampMs: BigInt(Date.now()),
				resultCode,
				payloadBytes: payload,
			});
			await route.fulfill({
				status: 200,
				contentType: "application/json",
				body,
			});
		},
	);

	await page.route(
		"**/galaxy.gateway.v1.EdgeGateway/SubscribeEvents",
		async () => {
			await new Promise<void>(() => {});
		},
	);
}

async function bootSession(page: Page): Promise<void> {
	await page.goto("/__debug/store");
	await expect(page.getByTestId("debug-store-ready")).toBeVisible();
	await page.waitForFunction(() => window.__galaxyDebug?.ready === true);
	await page.evaluate(() => window.__galaxyDebug!.clearSession());
	await page.evaluate(
		(id) => window.__galaxyDebug!.setDeviceSessionId(id),
		SESSION_ID,
	);
	await page.evaluate(
		(gameId) => window.__galaxyDebug!.clearOrderDraft(gameId),
		GAME_ID,
	);
}

test("returning to /map after creating a science keeps the renderer alive", async ({
	page,
}, testInfo) => {
	test.skip(
		testInfo.project.name.startsWith("chromium-mobile"),
		"phase 21 regression covers desktop layout; mobile inherits the same store",
	);

	const consoleErrors: string[] = [];
	page.on("pageerror", (err) => consoleErrors.push(`pageerror: ${err.message}`));
	page.on("console", (msg) => {
		if (msg.type() === "error") {
			consoleErrors.push(`console.error: ${msg.text()}`);
		}
	});

	await mockGateway(page);
	await bootSession(page);

	// Step 1: open /map and let the renderer mount cleanly.
	await page.goto(`/games/${GAME_ID}/map`);
	await expect(page.getByTestId("active-view-map")).toHaveAttribute(
		"data-status",
		"ready",
	);
	await expect(page.getByTestId("map-mount-error")).toHaveCount(0);

	// Step 2: navigate to the science designer via the view menu.
	await page.getByTestId("view-menu-trigger").click();
	await page.getByTestId("view-menu-item-designer-science").click();
	await expect(page.getByTestId("active-view-designer-science")).toHaveAttribute(
		"data-mode",
		"new",
	);

	// Step 3: fill the form and Save.
	await page.getByTestId("designer-science-input-name").fill("FirstStep");
	await page.getByTestId("designer-science-input-drive").fill("25");
	await page.getByTestId("designer-science-input-weapons").fill("25");
	await page.getByTestId("designer-science-input-shields").fill("25");
	await page.getByTestId("designer-science-input-cargo").fill("25");
	await page.getByTestId("designer-science-save").click();
	await expect(page.getByTestId("sciences-table")).toBeVisible();

	// Step 4: navigate back to /map.
	await page.getByTestId("view-menu-trigger").click();
	await page.getByTestId("view-menu-item-map").click();

	// Step 5: assert the map renderer mounted cleanly and there are
	// no JS exceptions (the bug report's symptom is a black canvas).
	await expect(page.getByTestId("active-view-map")).toBeVisible();
	await expect(page.getByTestId("active-view-map")).toHaveAttribute(
		"data-status",
		"ready",
	);
	await expect(page.getByTestId("map-mount-error")).toHaveCount(0);
	expect(consoleErrors, consoleErrors.join("\n")).toEqual([]);
});
