const main = document.querySelector('main') as HTMLTextAreaElement;

(async () => {
	const loader = document.querySelector('#loader') as HTMLElement;
	loader.style.display = 'block';
	try {
		await render();
	} catch (e) {
		main.textContent = e instanceof Error ? e.message : String(e);
	}
	loader.style.display = 'none';
})();

async function render(): Promise<void> {
	const corps: Corporation[] = await fetch('corps.json').then((r) => r.json());
	corps.sort((a, b) => (a.headquartersAddress?.lines.find((line) => line.type === 'SYSTEM')!.entity.naturalId ?? '\uffff')
			.localeCompare(b.headquartersAddress?.lines.find((line) => line.type === 'SYSTEM')!.entity.naturalId ?? '\uffff'));
	main.innerHTML = `<table>
		<thead>
			<tr>
				<th>code</th>
				<th>name</th>
				<th>shareholders</th>
				<th>HQ</th>
			</tr>
		</thead>
		<tbody>
			${corps.map(renderCorpRow).join('')}
		</tbody>
	</table>`;
}

function renderCorpRow(corp: Corporation): string {
	let hq = '';
	if (corp.headquartersAddress !== null) {
		const planet = corp.headquartersAddress.lines.find((line) => line.type === 'PLANET')!.entity;
		hq = planet.name;
		if (planet.name !== planet.naturalId)
			hq += ` (${planet.naturalId})`;
		if (!corp.headquartersFinished)
			hq += ' [unfinished]';
	}
	return `<tr>
		<td>${corp.code}</td>
		<td>${corp.name}</td>
		<td>${corp.shareholders.length}</td>
		<td>${hq}</td>
	</tr>`;
}

interface Corporation {
	name: string;
	code: string;
	headquartersAddress: {lines: {type: 'SYSTEM' | 'PLANET', entity: {name: string, naturalId: string}}[]} | null;
	headquartersFinished: boolean;
	shareholders: {}[];
}
