// Vitest component coverage for the F8-05 production-controls
// subsection of the planet inspector. The pre-F8-05 surface was four
// segmented main buttons (auto-submitting on click) plus a contextual
// sub-row; F8-05 replaced it with two `<select>`s (main / target) and
// a green ✓ apply / yellow ✗ cancel pair on the same row. The apply
// gate is the new behaviour: row state is dirty when the user picked
// something different from the planet's current effective production,
// and only then can the player commit via the ✓.
//
// The tests drive the component against a real `OrderDraftStore`
// (with `fake-indexeddb` standing in for the browser's IDB factory)
// so the collapse-by-`planetNumber` rule remains exercised. The
// active-target derivation is covered by a table-driven pass over the
// canonical engine display strings.

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

import { i18n } from "../src/lib/i18n/index.svelte";
import type {
	ReportPlanet,
	ScienceSummary,
	ShipClassSummary,
} from "../src/api/game-state";
import Production from "../src/lib/inspectors/planet/production.svelte";
import {
	ORDER_DRAFT_CONTEXT_KEY,
	OrderDraftStore,
} from "../src/sync/order-draft.svelte";
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";

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

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

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

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 localPlanet(
	overrides: Partial<ReportPlanet> & Pick<ReportPlanet, "number">,
): ReportPlanet {
	return {
		name: "Earth",
		x: 0,
		y: 0,
		kind: "local",
		owner: null,
		size: 1000,
		resources: 5,
		industryStockpile: 0,
		materialsStockpile: 0,
		industry: 100,
		population: 100,
		colonists: 0,
		production: null,
		freeIndustry: 100,
		...overrides,
	};
}

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

function mountProduction(
	planet: ReportPlanet,
	localShipClass: ShipClassSummary[] = [],
	localScience: ScienceSummary[] = [],
) {
	const context = new Map<unknown, unknown>([
		[ORDER_DRAFT_CONTEXT_KEY, draft],
	]);
	return render(Production, {
		props: { planet, localShipClass, localScience },
		context,
	});
}

function getMain(ui: ReturnType<typeof mountProduction>): HTMLSelectElement {
	return ui.getByTestId("inspector-planet-production-main") as HTMLSelectElement;
}

function getTarget(
	ui: ReturnType<typeof mountProduction>,
): HTMLSelectElement {
	return ui.getByTestId(
		"inspector-planet-production-target",
	) as HTMLSelectElement;
}

describe("planet inspector — production controls", () => {
	test("renders the main select with localised options and ✓/✗ icons", () => {
		// No production is set on the seeded planet → the select falls
		// back to the documented `industry` default (an owned planet
		// always produces something on the engine side, so there is no
		// "(none)" placeholder option).
		const ui = mountProduction(localPlanet({ number: 1 }));
		const main = getMain(ui);
		expect(main.value).toBe("industry");
		const labels = Array.from(main.options).map((o) => o.textContent?.trim());
		expect(labels).toEqual([
			"industry",
			"materials",
			"research",
			"build ship",
		]);
		// No secondary select until research / ship is chosen.
		expect(
			ui.queryByTestId("inspector-planet-production-target"),
		).toBeNull();
		// The row is dirty against the seeded `production: null`, so
		// both icon buttons are enabled — the player can either ✓ to
		// confirm the default or ✗ to revert (back to industry again).
		expect(
			ui.getByTestId("inspector-planet-production-apply"),
		).not.toBeDisabled();
		expect(
			ui.getByTestId("inspector-planet-production-cancel"),
		).not.toBeDisabled();
	});

	test("Industry default + ✓ emits a CAP setProductionType command", async () => {
		const ui = mountProduction(localPlanet({ number: 7 }));
		expect(getMain(ui).value).toBe("industry");
		const apply = ui.getByTestId("inspector-planet-production-apply");
		expect(apply).not.toBeDisabled();
		await fireEvent.click(apply);
		await waitFor(() => expect(draft.commands).toHaveLength(1));
		const cmd = draft.commands[0]!;
		expect(cmd.kind).toBe("setProductionType");
		if (cmd.kind !== "setProductionType") return;
		expect(cmd.planetNumber).toBe(7);
		expect(cmd.productionType).toBe("CAP");
		expect(cmd.subject).toBe("");
	});

	test("Materials pick + ✓ emits a MAT setProductionType command", async () => {
		const ui = mountProduction(localPlanet({ number: 7 }));
		await fireEvent.change(getMain(ui), { target: { value: "materials" } });
		await fireEvent.click(ui.getByTestId("inspector-planet-production-apply"));
		await waitFor(() => expect(draft.commands).toHaveLength(1));
		const cmd = draft.commands[0]!;
		if (cmd.kind !== "setProductionType") throw new Error("wrong kind");
		expect(cmd.productionType).toBe("MAT");
	});

	test("Research pick reveals the target select and apply stays disabled until a tech is chosen", async () => {
		const ui = mountProduction(localPlanet({ number: 7 }));
		expect(
			ui.queryByTestId("inspector-planet-production-target"),
		).toBeNull();
		await fireEvent.change(getMain(ui), { target: { value: "research" } });
		const target = getTarget(ui);
		expect(target.value).toBe("");
		expect(
			ui.getByTestId("inspector-planet-production-apply"),
		).toBeDisabled();
		await fireEvent.change(target, { target: { value: "DRIVE" } });
		await fireEvent.click(ui.getByTestId("inspector-planet-production-apply"));
		await waitFor(() => expect(draft.commands).toHaveLength(1));
		const cmd = draft.commands[0]!;
		if (cmd.kind !== "setProductionType") throw new Error("wrong kind");
		expect(cmd.productionType).toBe("DRIVE");
		expect(cmd.subject).toBe("");
	});

	test("Research target with a science name emits a SCIENCE subject", async () => {
		const ui = mountProduction(localPlanet({ number: 7 }), [], [
			{ name: "Genetics", drive: 0, weapons: 0, shields: 0, cargo: 0 },
		]);
		await fireEvent.change(getMain(ui), { target: { value: "research" } });
		await fireEvent.change(getTarget(ui), { target: { value: "Genetics" } });
		await fireEvent.click(ui.getByTestId("inspector-planet-production-apply"));
		await waitFor(() => expect(draft.commands).toHaveLength(1));
		const cmd = draft.commands[0]!;
		if (cmd.kind !== "setProductionType") throw new Error("wrong kind");
		expect(cmd.productionType).toBe("SCIENCE");
		expect(cmd.subject).toBe("Genetics");
	});

	test("Build-Ship with no classes shows the empty placeholder option", async () => {
		const ui = mountProduction(localPlanet({ number: 7 }), []);
		await fireEvent.change(getMain(ui), { target: { value: "ship" } });
		expect(
			ui.getByTestId("inspector-planet-production-ship-empty"),
		).toBeInTheDocument();
		expect(
			ui.getByTestId("inspector-planet-production-apply"),
		).toBeDisabled();
	});

	test("Build-Ship + class pick + ✓ emits a SHIP setProductionType command", async () => {
		const ui = mountProduction(localPlanet({ number: 7 }), [
			shipClass({ name: "Scout" }),
			shipClass({ name: "Destroyer" }),
		]);
		await fireEvent.change(getMain(ui), { target: { value: "ship" } });
		await fireEvent.change(getTarget(ui), { target: { value: "Scout" } });
		await fireEvent.click(ui.getByTestId("inspector-planet-production-apply"));
		await waitFor(() => expect(draft.commands).toHaveLength(1));
		const cmd = draft.commands[0]!;
		if (cmd.kind !== "setProductionType") throw new Error("wrong kind");
		expect(cmd.productionType).toBe("SHIP");
		expect(cmd.subject).toBe("Scout");
	});

	test("Cancel resets the row to the current effective production without emitting", async () => {
		const ui = mountProduction(
			localPlanet({ number: 7, production: "Capital" }),
		);
		const main = getMain(ui);
		expect(main.value).toBe("industry");
		await fireEvent.change(main, { target: { value: "research" } });
		expect(
			ui.getByTestId("inspector-planet-production-cancel"),
		).not.toBeDisabled();
		await fireEvent.click(
			ui.getByTestId("inspector-planet-production-cancel"),
		);
		expect(getMain(ui).value).toBe("industry");
		expect(draft.commands).toEqual([]);
	});

	test("Apply gate is closed while the row matches the current effective production", () => {
		const ui = mountProduction(
			localPlanet({ number: 7, production: "Drive" }),
		);
		// On mount the parser seeds research + DRIVE, so the apply
		// button is inert until the player actually changes something.
		expect(
			ui.getByTestId("inspector-planet-production-apply"),
		).toBeDisabled();
		expect(
			ui.getByTestId("inspector-planet-production-cancel"),
		).toBeDisabled();
	});

	test("active main derivation seeds the select from planet.production", () => {
		const cases: ReadonlyArray<{
			production: string | null;
			expected: "industry" | "materials" | "research" | "ship";
		}> = [
			{ production: "Capital", expected: "industry" },
			{ production: "Material", expected: "materials" },
			{ production: "Drive", expected: "research" },
			{ production: "Weapons", expected: "research" },
			{ production: "Shields", expected: "research" },
			{ production: "Cargo", expected: "research" },
			{ production: "Scout", expected: "ship" },
			// Falls back to the documented `industry` default when the
			// engine display string is missing or unrecognised.
			{ production: "-", expected: "industry" },
			{ production: null, expected: "industry" },
			{ production: "UnknownThing", expected: "industry" },
		];
		for (const tc of cases) {
			const ui = mountProduction(
				localPlanet({ number: 1, production: tc.production }),
				[shipClass({ name: "Scout" })],
			);
			expect(getMain(ui).value).toBe(tc.expected);
			ui.unmount();
		}
	});

	test("active target seeds the secondary select for research display strings", () => {
		const cases: ReadonlyArray<{
			production: string;
			expected: "DRIVE" | "WEAPONS" | "SHIELDS" | "CARGO";
		}> = [
			{ production: "Drive", expected: "DRIVE" },
			{ production: "Weapons", expected: "WEAPONS" },
			{ production: "Shields", expected: "SHIELDS" },
			{ production: "Cargo", expected: "CARGO" },
		];
		for (const tc of cases) {
			const ui = mountProduction(
				localPlanet({ number: 1, production: tc.production }),
			);
			expect(getMain(ui).value).toBe("research");
			expect(getTarget(ui).value).toBe(tc.expected);
			ui.unmount();
		}
	});

	test("target select seeds the ship class when production is a class name", () => {
		const ui = mountProduction(
			localPlanet({ number: 1, production: "Scout" }),
			[shipClass({ name: "Scout" }), shipClass({ name: "Destroyer" })],
		);
		expect(getMain(ui).value).toBe("ship");
		expect(getTarget(ui).value).toBe("Scout");
	});
});
