// Vitest coverage for the Phase 17 ship-class designer. Drives the
// component against a real `OrderDraftStore` (with `fake-indexeddb`
// standing in for the browser's IDB factory) so the local-validation
// + auto-sync side-effects are exercised end-to-end. The optimistic
// overlay arrives through a synthetic `RenderedReportSource` instead
// of a live report so the tests do not have to thread a full
// `GameStateStore` boot.

import "@testing-library/jest-dom/vitest";
import "fake-indexeddb/auto";
import { fireEvent, render, waitFor } from "@testing-library/svelte";
import {
	afterEach,
	beforeEach,
	describe,
	expect,
	test,
	vi,
} from "vitest";

import { i18n } from "../src/lib/i18n/index.svelte";
import type { GameReport, ShipClassSummary } from "../src/api/game-state";
import {
	ORDER_DRAFT_CONTEXT_KEY,
	OrderDraftStore,
} from "../src/sync/order-draft.svelte";
import { RENDERED_REPORT_CONTEXT_KEY } from "../src/lib/rendered-report.svelte";
import {
	CORE_CONTEXT_KEY,
	type CoreHandle,
} from "../src/lib/core-context.svelte";
import { loadWasmCoreForTest } from "./setup-wasm";
import type { Core } from "../src/platform/core/index";
import { IDBCache } from "../src/platform/store/idb-cache";
import { openGalaxyDB, type GalaxyDB } from "../src/platform/store/idb";
import type { Cache } from "../src/platform/store/index";
import type { IDBPDatabase } from "idb";
import { EMPTY_SHIP_GROUPS } from "./helpers/empty-ship-groups";

const GAME_ID = "11111111-2222-3333-4444-555555555555";

const pageMock = vi.hoisted(() => ({
	url: new URL("http://localhost/games/g1/designer/ship-class"),
	params: { id: "g1" } as Record<string, string>,
}));

const gotoMock = vi.hoisted(() => vi.fn());

vi.mock("$app/state", () => ({
	page: pageMock,
}));

vi.mock("$app/navigation", () => ({
	goto: gotoMock,
}));

import DesignerShipClass from "../src/lib/active-view/designer-ship-class.svelte";

let db: IDBPDatabase<GalaxyDB>;
let dbName: string;
let cache: Cache;
let draft: OrderDraftStore;

beforeEach(async () => {
	dbName = `galaxy-designer-${crypto.randomUUID()}`;
	db = await openGalaxyDB(dbName);
	cache = new IDBCache(db);
	draft = new OrderDraftStore();
	await draft.init({ cache, gameId: GAME_ID });
	i18n.resetForTests("en");
	pageMock.params = { id: "g1" };
	gotoMock.mockClear();
});

afterEach(async () => {
	draft.dispose();
	db.close();
	await new Promise<void>((resolve) => {
		const req = indexedDB.deleteDatabase(dbName);
		req.onsuccess = () => resolve();
		req.onerror = () => resolve();
		req.onblocked = () => resolve();
	});
});

function shipClass(
	overrides: Partial<ShipClassSummary> & Pick<ShipClassSummary, "name">,
): ShipClassSummary {
	return {
		drive: 0,
		armament: 0,
		weapons: 0,
		shields: 0,
		cargo: 0,
		...overrides,
	};
}

function makeReport(localShipClass: ShipClassSummary[] = []): GameReport {
	return {
		turn: 1,
		mapWidth: 1000,
		mapHeight: 1000,
		planetCount: 0,
		planets: [],
		race: "",
		localShipClass,
		routes: [],
		localPlayerDrive: 0,
		localPlayerWeapons: 0,
		localPlayerShields: 0,
		localPlayerCargo: 0,
		...EMPTY_SHIP_GROUPS,
	};
}

function mountDesigner(opts: {
	classId?: string;
	report?: GameReport | null;
	core?: Core | null;
}) {
	const report = opts.report ?? makeReport();
	pageMock.params = opts.classId
		? { id: "g1", classId: opts.classId }
		: { id: "g1" };
	const renderedReport = { get report() { return report; } };
	const coreHandle: CoreHandle = { core: opts.core ?? null };
	const context = new Map<unknown, unknown>([
		[ORDER_DRAFT_CONTEXT_KEY, draft],
		[RENDERED_REPORT_CONTEXT_KEY, renderedReport],
		[CORE_CONTEXT_KEY, coreHandle],
	]);
	return render(DesignerShipClass, { context });
}

describe("ship-class designer (new mode)", () => {
	test("renders the form with a Save button disabled by default", () => {
		const ui = mountDesigner({});
		expect(
			ui.getByTestId("active-view-designer-ship-class"),
		).toHaveAttribute("data-mode", "new");
		expect(ui.getByTestId("designer-ship-class-save")).toBeDisabled();
		expect(ui.getByTestId("designer-ship-class-error")).toHaveTextContent(
			"name cannot be empty",
		);
	});

	test("Save adds a createShipClass to the draft after a valid edit", async () => {
		const ui = mountDesigner({});
		const nameInput = ui.getByTestId("designer-ship-class-input-name");
		await fireEvent.input(nameInput, { target: { value: "Drone" } });
		const driveInput = ui.getByTestId("designer-ship-class-input-drive");
		await fireEvent.input(driveInput, { target: { value: "1" } });

		await waitFor(() =>
			expect(ui.getByTestId("designer-ship-class-save")).not.toBeDisabled(),
		);
		await fireEvent.click(ui.getByTestId("designer-ship-class-save"));
		await waitFor(() => expect(draft.commands).toHaveLength(1));
		const cmd = draft.commands[0]!;
		if (cmd.kind !== "createShipClass") throw new Error("wrong kind");
		expect(cmd.name).toBe("Drone");
		expect(cmd.drive).toBe(1);
		expect(cmd.armament).toBe(0);
		await waitFor(() =>
			expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/ship-classes"),
		);
	});

	test("rejects a duplicate name from the overlay before any sync", async () => {
		const ui = mountDesigner({
			report: makeReport([
				shipClass({ name: "Scout", drive: 1 }),
			]),
		});
		await fireEvent.input(
			ui.getByTestId("designer-ship-class-input-name"),
			{ target: { value: "Scout" } },
		);
		await fireEvent.input(
			ui.getByTestId("designer-ship-class-input-drive"),
			{ target: { value: "1" } },
		);
		await waitFor(() =>
			expect(ui.getByTestId("designer-ship-class-error")).toHaveTextContent(
				"already exists",
			),
		);
		expect(ui.getByTestId("designer-ship-class-save")).toBeDisabled();
	});

	test("rejects nonzero armament with zero weapons", async () => {
		const ui = mountDesigner({});
		await fireEvent.input(
			ui.getByTestId("designer-ship-class-input-name"),
			{ target: { value: "Bad" } },
		);
		await fireEvent.input(
			ui.getByTestId("designer-ship-class-input-armament"),
			{ target: { value: "1" } },
		);
		await fireEvent.input(
			ui.getByTestId("designer-ship-class-input-drive"),
			{ target: { value: "1" } },
		);
		await waitFor(() =>
			expect(ui.getByTestId("designer-ship-class-error")).toHaveTextContent(
				"armament and weapons must be both zero or both nonzero",
			),
		);
	});

	test("Cancel navigates back without mutating the draft", async () => {
		const ui = mountDesigner({});
		await fireEvent.click(ui.getByTestId("designer-ship-class-cancel"));
		expect(draft.commands).toHaveLength(0);
		expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/ship-classes");
	});
});

describe("ship-class designer (view mode)", () => {
	test("renders the read-only summary plus Delete + Back affordances", () => {
		const ui = mountDesigner({
			classId: "Cruiser",
			report: makeReport([
				shipClass({
					name: "Cruiser",
					drive: 15,
					armament: 1,
					weapons: 15,
					shields: 15,
					cargo: 0,
				}),
			]),
		});
		expect(
			ui.getByTestId("active-view-designer-ship-class"),
		).toHaveAttribute("data-mode", "view");
		expect(ui.getByTestId("designer-ship-class-view-name")).toHaveTextContent(
			"Cruiser",
		);
		expect(ui.getByTestId("designer-ship-class-view-drive")).toHaveTextContent(
			"15",
		);
		expect(
			ui.getByTestId("designer-ship-class-view-armament"),
		).toHaveTextContent("1");
		expect(ui.getByTestId("designer-ship-class-delete")).toBeInTheDocument();
		expect(ui.getByTestId("designer-ship-class-back")).toBeInTheDocument();
	});

	test("Delete adds a removeShipClass and navigates back", async () => {
		const ui = mountDesigner({
			classId: "Cruiser",
			report: makeReport([shipClass({ name: "Cruiser", drive: 15 })]),
		});
		await fireEvent.click(ui.getByTestId("designer-ship-class-delete"));
		await waitFor(() => expect(draft.commands).toHaveLength(1));
		const cmd = draft.commands[0]!;
		if (cmd.kind !== "removeShipClass") throw new Error("wrong kind");
		expect(cmd.name).toBe("Cruiser");
		await waitFor(() =>
			expect(gotoMock).toHaveBeenCalledWith("/games/g1/table/ship-classes"),
		);
	});

	test("renders a not-found message when the class is missing from the overlay", () => {
		const ui = mountDesigner({
			classId: "Ghost",
			report: makeReport([]),
		});
		expect(
			ui.getByTestId("designer-ship-class-not-found"),
		).toHaveTextContent("Ghost");
	});
});

describe("ship-class designer preview pane (Phase 18)", () => {
	test("hides preview while validation fails", () => {
		const ui = mountDesigner({});
		expect(
			ui.queryByTestId("designer-ship-class-preview"),
		).not.toBeInTheDocument();
	});

	test("hides preview when no Core is provided", async () => {
		const ui = mountDesigner({});
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-name"), {
			target: { value: "Drone" },
		});
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-drive"), {
			target: { value: "1" },
		});
		await waitFor(() =>
			expect(ui.getByTestId("designer-ship-class-save")).not.toBeDisabled(),
		);
		expect(
			ui.queryByTestId("designer-ship-class-preview"),
		).not.toBeInTheDocument();
	});

	test("renders five rows once form is valid and Core is ready", async () => {
		const core = await loadWasmCoreForTest();
		const report: GameReport = {
			turn: 1,
			mapWidth: 1000,
			mapHeight: 1000,
			planetCount: 0,
			planets: [],
			race: "",
			localShipClass: [],
			routes: [],
			localPlayerDrive: 1.5,
			localPlayerWeapons: 1,
			localPlayerShields: 1,
			localPlayerCargo: 1.2,
			...EMPTY_SHIP_GROUPS,
		};
		const ui = mountDesigner({ report, core });
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-name"), {
			target: { value: "Cruiser" },
		});
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-drive"), {
			target: { value: "8" },
		});
		await fireEvent.input(
			ui.getByTestId("designer-ship-class-input-armament"),
			{ target: { value: "2" } },
		);
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-weapons"), {
			target: { value: "5" },
		});
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-shields"), {
			target: { value: "3" },
		});
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-cargo"), {
			target: { value: "4" },
		});
		await waitFor(() =>
			expect(
				ui.getByTestId("designer-ship-class-preview"),
			).toBeInTheDocument(),
		);
		// Empty mass = drive + shields + cargo + (armament+1)*(weapons/2)
		// = 8 + 3 + 4 + 3 * 2.5 = 22.5
		expect(
			ui.getByTestId("designer-ship-class-preview-mass"),
		).toHaveTextContent("22.5");
		// CargoCapacity = cargoTech * (cargo + cargo²/20)
		// = 1.2 * (4 + 16/20) = 1.2 * 4.8 = 5.76
		expect(
			ui.getByTestId("designer-ship-class-preview-cargo-capacity"),
		).toHaveTextContent("5.76");
		// CarryingMass at full = capacity / cargoTech = 5.76 / 1.2 = 4.8
		// FullLoadMass = 22.5 + 4.8 = 27.3
		expect(
			ui.getByTestId("designer-ship-class-preview-full-load-mass"),
		).toHaveTextContent("27.3");
		// DriveEffective = 8 * 1.5 = 12
		// MaxSpeed = 12 * 20 / 22.5 = 10.666… → "10.67"
		expect(
			ui.getByTestId("designer-ship-class-preview-max-speed"),
		).toHaveTextContent("10.67");
		// RangeAtFull = 12 * 20 / 27.3 = 8.791… → "8.79"
		expect(
			ui.getByTestId("designer-ship-class-preview-range"),
		).toHaveTextContent("8.79");
	});

	test("preview reacts to subsequent edits", async () => {
		const core = await loadWasmCoreForTest();
		const report: GameReport = {
			turn: 1,
			mapWidth: 1000,
			mapHeight: 1000,
			planetCount: 0,
			planets: [],
			race: "",
			localShipClass: [],
			routes: [],
			localPlayerDrive: 1,
			localPlayerWeapons: 1,
			localPlayerShields: 1,
			localPlayerCargo: 1,
			...EMPTY_SHIP_GROUPS,
		};
		const ui = mountDesigner({ report, core });
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-name"), {
			target: { value: "Hauler" },
		});
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-drive"), {
			target: { value: "1" },
		});
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-cargo"), {
			target: { value: "5" },
		});
		await waitFor(() =>
			expect(
				ui.getByTestId("designer-ship-class-preview-cargo-capacity"),
			).toHaveTextContent("6.25"),
		);
		await fireEvent.input(ui.getByTestId("designer-ship-class-input-cargo"), {
			target: { value: "10" },
		});
		await waitFor(() =>
			expect(
				ui.getByTestId("designer-ship-class-preview-cargo-capacity"),
			).toHaveTextContent("15"),
		);
	});
});
