<script lang="ts">
	import ApplicationSearchBar from '$lib/ApplicationSearchBar.svelte';
	import type { Application } from '$lib/ApplicationsStore.svelte';
	import { statusStore } from '$lib/Types.svelte';

	let {
		application,
		onreload
	}: {
		application?: Application;
		onreload: (item: Application) => void;
	} = $props();

	let dialogElement: HTMLDialogElement;

	function docKey(e: KeyboardEvent) {
		if (e.ctrlKey && e.code === 'KeyK') {
			dialogElement.showModal();
			e.stopPropagation();
			e.preventDefault();
			return;
		}
	}

	$effect(() => {
		document.addEventListener('keydown', docKey, false);
		return () => {
			document.removeEventListener('keydown', docKey);
		};
	});

	let internal: Application[] = $state([]);
</script>

<dialog class="card max-w-[50vw]" bind:this={dialogElement}>
	<ApplicationSearchBar bind:result={internal} excludeApplication={application} />
	<div class="overflow-y-auto overflow-x-hidden flex-grow p-2">
		<!-- TODO loading screen -->
		{#each internal as item}
			<div class="card p-2 my-2 bg-slate-100 max-w-full" role="none">
				<button
					class="text-left max-w-full"
					type="button"
					onclick={() => {
						dialogElement.close();
						onreload(item);
					}}
				>
					<h2 class="text-lg text-blue-500 flex justify-between">
						<div>
							{item.title}
							{#if item.company}
								<div class="text-violet-800">
									@ {item.company}
								</div>
							{/if}
						</div>
					</h2>
					<span>
						{statusStore.nodesR[item.status_id]?.name ?? 'NOT FOUND'}
					</span>
				</button>
			</div>
		{/each}
	</div>
</dialog>
