<script lang="ts">
	import type { PageData } from './$types';
	import AuctionResult from '$lib/AuctionResult.svelte';
	import Pager from '$lib/Pager.svelte';
	import { fade } from 'svelte/transition';

	export let data: PageData;

	function buildQueryString({ page, pageSize }: { page: number; pageSize: number }): string {
		const qs = [
			data.query === '' ? data.query : `query=${data.query}`,
			page <= 1 ? '' : `page=${page}`,
			`limit=${pageSize}`
		]
			.filter((x) => x !== '')
			.join('&');

		return qs !== '' ? `/?${qs}` : qs;
	}

	$: hasResults = data?.results?.length || 0;
</script>

{#if hasResults}
	<section in:fade>
		<h1 class="pb-5 text-lg">Found {data.found} Upcoming & Live Auctions</h1>
		<Pager
			page={data.page + 1}
			itemCount={data.found}
			pageSize={data.limit}
			createUrl={buildQueryString}
		/>
	</section>

	{#key data.results}
		<ul class="flex flex-col m-0 p-0 justify-between pr-10">
			{#each data.results as auction, i}
				<li id="catalog-{auction.id}" class="pb-5" in:fade={{ delay: i * 90 }}>
					<AuctionResult {auction} />
				</li>
			{/each}
		</ul>
	{/key}

	<Pager
		page={data.page + 1}
		itemCount={data.found}
		pageSize={data.limit}
		createUrl={buildQueryString}
	/>
{:else}
	<section class="flex w-full flex-col justify-center text-center" in:fade out:fade>
		<h1 class="text-2xl">No auctions found.</h1>
		{#if data.query !== ''}
			<a href="/">Start Over</a>
		{/if}
		{#if data.query !== 'watch'}
			<p>
				Try searching <em><a href="/?query=watch">Watch</a></em>
			</p>
		{/if}
	</section>
{/if}
