<!--
Phase 23 Report View — cargo routes section. The wire `routes[]`
groups by source planet; each entry inside a route is one
(loadType, destination) pair. The section flattens both to a single
table — anchor jumps into a single visual unit even when the player
has many routes.
-->
<script lang="ts">
	import { getContext } from "svelte";

	import { i18n } from "$lib/i18n/index.svelte";
	import {
		RENDERED_REPORT_CONTEXT_KEY,
		type RenderedReportSource,
	} from "$lib/rendered-report.svelte";
	import { planetLabel } from "./format";

	const rendered = getContext<RenderedReportSource | undefined>(
		RENDERED_REPORT_CONTEXT_KEY,
	);
	const report = $derived(rendered?.report ?? null);
	const planets = $derived(report?.planets ?? []);

	const rows = $derived.by(() => {
		const out: {
			sourcePlanetNumber: number;
			loadType: string;
			destinationPlanetNumber: number;
		}[] = [];
		for (const route of report?.routes ?? []) {
			for (const entry of route.entries) {
				out.push({
					sourcePlanetNumber: route.sourcePlanetNumber,
					loadType: entry.loadType,
					destinationPlanetNumber: entry.destinationPlanetNumber,
				});
			}
		}
		return out;
	});
</script>

<section
	id="report-cargo-routes"
	class="grid-section"
	data-testid="report-section-cargo-routes"
>
	<h2>{i18n.t("game.report.section.cargo_routes.title")}</h2>

	{#if report === null}
		<p class="status">{i18n.t("game.report.loading")}</p>
	{:else if rows.length === 0}
		<p class="status" data-testid="cargo-routes-empty">
			{i18n.t("game.report.section.cargo_routes.empty")}
		</p>
	{:else}
		<table class="grid" data-testid="cargo-routes-table">
			<thead>
				<tr>
					<th>{i18n.t("game.report.section.cargo_routes.column.source")}</th>
					<th>{i18n.t("game.report.section.cargo_routes.column.load")}</th>
					<th>{i18n.t("game.report.section.cargo_routes.column.destination")}</th>
				</tr>
			</thead>
			<tbody>
				{#each rows as r (`${r.sourcePlanetNumber}/${r.loadType}`)}
					<tr
						data-testid="cargo-routes-row"
						data-source={r.sourcePlanetNumber}
						data-load={r.loadType}
					>
						<td>{planetLabel(r.sourcePlanetNumber, planets)}</td>
						<td>{r.loadType}</td>
						<td>{planetLabel(r.destinationPlanetNumber, planets)}</td>
					</tr>
				{/each}
			</tbody>
		</table>
	{/if}
</section>

<style>
	.grid-section h2 {
		margin: 0 0 0.5rem;
		font-size: 1.05rem;
		color: #e8eaf6;
	}
	.status {
		margin: 0;
		color: #888;
		font-size: 0.9rem;
	}
	.grid {
		border-collapse: collapse;
		width: 100%;
		font-variant-numeric: tabular-nums;
		font-size: 0.9rem;
	}
	.grid th,
	.grid td {
		padding: 0.4rem 0.6rem;
		text-align: left;
		border-bottom: 1px solid #1c2240;
	}
	.grid th {
		color: #aab;
		text-transform: uppercase;
		letter-spacing: 0.04em;
		font-size: 0.75rem;
	}
	.grid tbody tr:hover {
		background: #11172a;
	}
</style>
