<script lang="ts">
	import { browser } from "$app/environment";
	import InfiniteScroll from "svelte-infinite-scroll";

	import Button from "$lib/components/Button.svelte";
	import Card from "$lib/components/community/Card.svelte";
	import Input from "$lib/components/fields/Input.svelte";
	import Radio from "$lib/components/fields/Radio.svelte";
	import { COMMUNITY_FILTER_OPTIONS } from "$lib/utils/index.js";
	import GoTop from "$lib/components/GoTop.svelte";

	export let data;

	let form = {
		filter: "likes",
		page: "0",
	}

	$: elementScroll = browser ? document?.getElementById('app') : undefined;

	const fetchMore = async () => {
		form = {...form, page: (Number(form.page) + 1).toString()};
		const request = await fetch(`/api/community?${new URLSearchParams(form)}`);
		const response = await request.json();
		data = {...data, cards: [...data.cards, ...response.cards ]};
	}
</script>

<svelte:head>
	<title>Community Gallery</title>
	<meta name="description" content="Svelte demo app" />
</svelte:head>

<h1 class="text-white font-semibold text-2xl">
  Community Gallery
</h1>
<div class="flex items-center justify-between mt-5">
	<Radio options={COMMUNITY_FILTER_OPTIONS} value="{form.filter}" onChange={(filter) => form = {...form, filter }} />
	<div class="items-center justify-end gap-5 hidden lg:flex">
		<Button icon="ic:round-plus" theme="dark" size="lg">Upload own Image</Button>
		<Button icon="fluent:glance-horizontal-sparkles-16-filled" href="/generate" theme="pink" size="lg">Generate</Button>
	</div>
	<div class="items-center justify-end gap-3 flex lg:hidden">
		<Button icon="ic:round-plus" theme="dark" size="md">Upload own Image</Button>
		<Button icon="fluent:glance-horizontal-sparkles-16-filled" href="/generate" theme="pink" size="md">Generate</Button>
	</div>
</div>
<div class="mt-5 max-w-sm">
	<Input placeholder="Filter by prompt, model..." />
</div>
<div class="mx-auto grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 2xl:grid-cols-5 gap-5 mt-8 lg:mt-10">
	{#each data.cards as card}
		<Card card={card} />
	{/each}
	<InfiniteScroll
		elementScroll="{elementScroll ?? undefined}"
		threshold={100}
		hasMore={data.total_items > data.cards.length}
		on:loadMore={fetchMore}
	/>
	<GoTop />
</div>