<script>
	export let pairs;

	/** @typedef Normalized
	 * @property {string} name
	 * @property {string} aud
	 * @property {Array<string>} groups
	 * @property {Array<string>} teachers
	 */

	/**
	 * @param {Object} pairs_list
	 * @returns {Array<Normalized>}
	 */
	function normalize_many_pairs(pairs_list) {
		/** @type {Object<string, Normalized>} */
		let normalized = {};

		pairs_list.schedulePairs.forEach((pair) => {
			const name = `${pair.subject} ${pair.aud}`;
			if (name in normalized) {
				if (!normalized[name].teachers.includes(pair.teacher)) {
					normalized[name].teachers.push(pair.teacher);
				}
				if (!normalized[name].groups.includes(pair.group)) {
					normalized[name].groups.push(pair.group);
				}
			} else {
				normalized[name] = {
					name: pair.subject,
					aud: pair.aud,
					groups: [pair.group],
					teachers: [pair.teacher],
				};
			}
		});

		/** @type {Array<Normalized>} */
		const normalized_array = Object.entries(normalized).map((el) => el[1]);
		return normalized_array;
	}
</script>

{#if pairs.schedulePairs.length === 1}
	<div
		class="w-full m-2
		border-[1px] rounded-xl border-[var(--w-border)] dark:border-[var(--b-border)]
		{pairs.isCurrentPair ? 'bg-[var(--w-blue)] dark:bg-[var(--b-blue)]' : ''}
		"
	>
		<div
			class="border-b-[1px] border-[var(--w-border)] dark:border-[var(--b-border)]"
		>
			<h1 class="m-2 mb-1">
				{pairs.N}) {pairs.time.replace("-", " - ")}
			</h1>
		</div>
		<div class="p-2">
			<h1>
				{pairs.schedulePairs[0].subject}
			</h1>
			<h1>
				{pairs.schedulePairs[0].aud}
				<a
					target="_blank"
					href="https://www.usue.ru/raspisanie/getteams/?prepod={pairs
						.schedulePairs[0].teacher}"
					class="underline"
				>
					{pairs.schedulePairs[0].teacher}
				</a>
			</h1>
			<h1>
				{pairs.schedulePairs[0].group}
			</h1>
		</div>
	</div>
{:else if pairs.schedulePairs.length > 1}
	{@const normalized = normalize_many_pairs(pairs)}
	{@const end_index = normalized.length - 1}
	<div
		class="w-full m-2
		border-[1px] rounded-xl border-[var(--w-border)] dark:border-[var(--b-border)]
		{pairs.isCurrentPair ? 'bg-[var(--w-blue)] dark:bg-[var(--b-blue)]' : ''}"
	>
		<div class="border-b-2 border-[var(--border)]">
			<h1 class="m-2 mb-1">
				{pairs.N}) {pairs.time.replace("-", " - ")}
			</h1>
		</div>
		{#each normalized as pair, i}
			<div
				class="p-2
				{i === end_index ? '' : 'border-b-[1px] border-[var(--border)]'}"
			>
				<h1>
					{pair.name}
				</h1>
				<h1>
					Ауд: {pair.aud}
				</h1>
				<div class="flex flex-col">
					{#each pair.teachers as teacher}
						<a
							target="_blank"
							href="https://www.usue.ru/raspisanie/getteams/?prepod={teacher}"
							class="underline w-fit"
						>
							{teacher}
						</a>
					{/each}
				</div>

				<div class="flex flex-col">
					{#each pair.groups as group}
						<h1>
							{group}
						</h1>
					{/each}
				</div>
			</div>
		{/each}
	</div>
{/if}
