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

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

	let filter = $state('');
</script>

<div class="card p-3 rounded-lg flex flex-col">
	<h1 class="flex gap-2">
		Applied <input bind:value={filter} placeholder="search" class="flex-grow text-blue-500" />
	</h1>
	<div class="overflow-auto flex-grow">
		{#each applicationStore.applyed.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);
		}) as item}
			<button
				class="card p-2 my-2 bg-slate-100 w-full text-left"
				onclick={async () => {
                    item.views = await get(`view/${item.id}`);
                    item.events = await get(`events/${item.id}`);
					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>
					<a
						href={item.url}
						class="text-violet-600 overflow-hidden whitespace-nowrap block"
					>
						{item.url}
					</a>
				</div>
			</button>
		{/each}
	</div>
</div>
