<script lang="ts">
	import DropDown from '$lib/components/DropDown.svelte';
	import DropDownElement from '$lib/components/DropDownElement.svelte';
	import SelectedGameGroupsStore from '$lib/stores/GameGroupFilter';
	import SelectedGameStore from '$lib/stores/GameFilter';
	import ChellarisDataStore from '$lib/stores/ChellarisData';

	// Game Selection Code
	SelectedGameStore.subscribe((selection) => {
		if (typeof $SelectedGameGroupsStore[selection] === 'undefined') {
			// Default to all available groups
			$SelectedGameGroupsStore[selection] = { gameId: $SelectedGameStore, selectedGroups: Object.values($ChellarisDataStore.games[$SelectedGameStore].groups).map((group) => group.id) };
			SelectedGameGroupsStore.update(() => $SelectedGameGroupsStore);
		}
	})

	// Game Group Selection Code
	$: {
		if (typeof localStorage !== 'undefined') {
			localStorage.setItem('gameGroupSelection', JSON.stringify($SelectedGameGroupsStore));
		}
	}

	$: selectedGameData = $SelectedGameGroupsStore[$SelectedGameStore];
	$: groupJoiner = Object.values(selectedGameData.selectedGroups).length > 2 ? ', ' : ' & ';

	const updateGroupStore = () => {
		SelectedGameGroupsStore.update(() => $SelectedGameGroupsStore);
	}

	const dropdownId = crypto.randomUUID();
</script>

<DropDown
	{dropdownId}
	dropdownTitle={(Object.values(selectedGameData.selectedGroups).length > 1 ? 'Groups ' : 'Group ') +
		Object.values(selectedGameData.selectedGroups)
			.map((selection) => $ChellarisDataStore.games[$SelectedGameStore].groups[selection]?.name)
			.join(groupJoiner)}
>
	{#each Object.values($ChellarisDataStore.games[$SelectedGameStore].groups) as group}
		{#if group}
			<DropDownElement {dropdownId}>
				<input
					id={'checkbox' + group.id}
					data-dropdown={dropdownId}
					type="checkbox"
					bind:group={selectedGameData.selectedGroups}
					on:change={updateGroupStore}
					value={group.id}
				/>
				<label for={'checkbox' + group.id} data-dropdown={dropdownId}>{group.name}</label>
			</DropDownElement>
		{/if}
	{/each}
</DropDown>

<style>
	:checked + label {
		color: var(--color-active-2);
	}

	:hover {
		color: var(--color-active-1) !important;
	}
</style>