<script lang="ts">
	import { version } from '$app/environment';
	import { frontpageQuery } from '$gql/Queries';
	import { ComicSort, SortDirection } from '$gql/graphql';
	import { codename } from '$lib/Meta';
	import { href } from '$lib/Navigation';
	import { fadeDefault } from '$lib/Transitions';
	import logo from '$lib/assets/logo.webp';
	import ComicCard from '$lib/components/ComicCard.svelte';
	import Guard from '$lib/components/Guard.svelte';
	import Head from '$lib/components/Head.svelte';
	import Carousel from '$lib/containers/Carousel.svelte';
	import { getContextClient } from '@urql/svelte';
	import { fade } from 'svelte/transition';

	const bookmarkLink = href('comics', {
		filter: { include: { bookmarked: true } },
		sort: { on: ComicSort.Random, seed: dailySeed() }
	});
	const recentLink = href('comics', {
		sort: { on: ComicSort.CreatedAt, direction: SortDirection.Descending }
	});
	const favouriteLink = href('comics', {
		filter: { include: { favourite: true } },
		sort: { on: ComicSort.Random, seed: dailySeed() }
	});

	function dailySeed() {
		const date = new Date();
		return +`${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`;
	}

	let query = $derived(frontpageQuery(getContextClient(), { seed: dailySeed() }));
	let recent = $derived($query.data?.recent);
	let favourites = $derived($query.data?.favourites);
	let bookmarked = $derived($query.data?.bookmarked);
</script>

<Head section="Home" />

{#if $query.data}
	<div class="flex flex-col justify-center gap-16 xl:flex-row">
		<div class="flex flex-col items-center gap-1">
			<img src={logo} width="512" height="512" class="min-w-[400px]" alt="" />
			<h1 class="text-4xl font-medium">
				<span>hircine</span>
				<span>{version}</span>
			</h1>
			<h2 class="text-2xl font-light text-zinc-400">{codename}</h2>
		</div>
		<div class="flex flex-col gap-8" in:fade={fadeDefault}>
			{#if recent && recent.count > 0}
				<Carousel title="Recently added" href={recentLink}>
					{#each recent.edges as comic (comic.id)}
						<ComicCard coverOnly {comic} />
					{/each}
				</Carousel>
			{/if}
			{#if favourites && favourites.count > 0}
				<Carousel title="Favourites" href={favouriteLink}>
					{#each favourites.edges as comic (comic.id)}
						<ComicCard coverOnly {comic} />
					{/each}
				</Carousel>
			{/if}
			{#if bookmarked && bookmarked.count > 0}
				<Carousel title="Bookmarks" href={bookmarkLink}>
					{#each bookmarked.edges as comic (comic.id)}
						<ComicCard coverOnly {comic} />
					{/each}
				</Carousel>
			{/if}
		</div>
	</div>
{:else}
	<Guard result={query} />
{/if}
