<script lang="ts">
	import { asset } from '$app/paths';
	import { permission as currentPerms } from '$lib/core/stores/permissions';
	import { page } from '$app/stores';
	import { get } from 'svelte/store';
	import Spinner from '$lib/components/ui/spinner/spinner.svelte';
	import { departmentStore } from '$lib/core/stores/departments';
	import { socketStore } from '$lib/core/stores/websocketStore';
	import { goto } from '$app/navigation';
	import { addNotification } from '$lib/core/stores/noti';
	import { browser } from '$app/environment';
	import { setCookieOnNonBrowser } from '$lib/helpers/cookie';
	import { referenceFromPage} from '$lib/core/stores/recipeStore';

	let enabledAccessibleCountries: string[] = $state([]);

	const refPage = get(referenceFromPage);

	function onCountrySelected(cnt: string) {
		departmentStore.set(cnt);
		if (browser && 'cookieStore' in window) cookieStore.set('department', cnt);
		else setCookieOnNonBrowser('department', cnt);
		addNotification(`INFO:Selected ${cnt}`);
		setTimeout(async () => {
			console.log(get(departmentStore));
			
			if (refPage === 'sheet') {
				await goto('/sheet/overview');
			} else {
				await goto('/recipe/overview');
			}
		}, 1000);
	}

	// read or write permission
	let userCurrentPerms = get(currentPerms).filter((x) => {
		if (refPage === 'sheet') {
			return x.startsWith('document.write');
		}
		return x.startsWith('document.read');
	});
	// show country by enabled `document.read.{country}`
	enabledAccessibleCountries = userCurrentPerms.map((x) => x.split('.')[2]);

	// update every 30s
	if (enabledAccessibleCountries.length == 0) {
		setTimeout(() => {
			// read or write permission
			let userCurrentPerms = get(currentPerms).filter((x) => {
				if (refPage === 'sheet') {
					return x.startsWith('document.write');
				}
				return x.startsWith('document.read');
			});
			// show country by enabled `document.read.{country}`
			enabledAccessibleCountries = userCurrentPerms.map((x) => x.split('.')[2]);

			if (enabledAccessibleCountries.length == 1) {
				onCountrySelected(enabledAccessibleCountries[0]);
			}
		}, 1000);
	}

	if (enabledAccessibleCountries.length == 1) {
		onCountrySelected(enabledAccessibleCountries[0]);
	}
</script>

<h1 class="m-8 text-4xl font-bold">Country Selection</h1>
<p class="m-8 text-muted-foreground">Select country to view/edit recipe</p>

{#if enabledAccessibleCountries.length == 0}
	<div class="flex h-max w-max items-center justify-center">
		<Spinner class="size-48" />
	</div>
{:else}
	<div class="m-8 grid grid-flow-dense grid-cols-5 gap-4">
		{#each enabledAccessibleCountries as country}
			<div>
				<button class="hover:cursor-pointer" onclick={() => onCountrySelected(country)}>
					<img src={asset(`/departments/logo/${country}_plate.png`)} alt={country} loading="lazy" />
				</button>
			</div>
		{/each}
	</div>
{/if}
