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

	export let data: PageData;

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

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

	$: hasResults = (data.results || []).length > 0;
	$: currentPage = data.page + 1;
	$: pageCount = Math.max(1, Math.ceil(data.found / data.limit));
</script>

{#if hasResults}
	<section in:fade>
		<h1 class="pb-5 text-lg">Found {data.found} Upcoming & Live Auctions</h1>
		<ol class="flex justify-between w-full center" style="padding: 0 10%;">
			{#if currentPage > 1}
				<li in:fade>
					<a href="/{buildQueryString({ query: data.query, page: currentPage - 1 })}"
						>&lt;Previous</a
					>
				</li>
			{:else}
				<li />
			{/if}
			<li>Page {currentPage} of {pageCount}</li>
			{#if currentPage < pageCount}
				<li in:fade>
					<a href="/{buildQueryString({ query: data.query, page: currentPage + 1 })}">Next&gt;</a>
				</li>
			{/if}
		</ol>
	</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}
{: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}
