<script lang="ts">
	import { applicationStore } from '$lib/ApplicationsStore.svelte';
	import { onMount } from 'svelte';

	const { title, status_id }: { title: string; status_id: string } = $props();

	onMount(() => {
		applicationStore.loadAll();
	});

	let filter = $state('');

	let sorted = $derived(
		applicationStore.all.filter((i) => {
			return i.status_id === status_id;
		})
	);

	let internal = $derived(
		sorted.filter((i) => {
			if (!filter) {
				return true;
			}
			const f = new RegExp(filter, 'ig');

			let x = i.title;

			if (i.company) {
				x = `${x} @ ${i.company}`;
			}

			return x.match(f);
		})
	);
</script>

{#if sorted.length > 0}
	<div class="card p-3 rounded-lg">
		<h1 class="flex gap-2">
			{title} ({internal.length})
			<input bind:value={filter} placeholder="search" class="flex-grow text-blue-500" />
		</h1>
		<div class="flex flex-wrap gap-4">
			{#each internal as item}
				<button
					class="card p-2 my-2 bg-slate-100 text-left"
					onclick={async () => {
						applicationStore.loadItem = item;
						window.scrollTo({
							top: 0,
							behavior: 'smooth'
						});
					}}
				>
					<div>
						<h2 class="text-lg text-blue-500">
							{item.title}
							{#if item.company}
								<div class="text-violet-800">
									@ {item.company}
								</div>
							{/if}
						</h2>
					</div>
				</button>
			{/each}
		</div>
	</div>
{/if}
