<script lang="ts">
	import type { Game, Series } from '$lib/types';
	import GameCard from './GameCard.svelte';
	import SeriesCard from './SeriesCard.svelte';

	let {
		games,
		series = [],
		loggedIn,
		filter = ''
	}: { games: Game[]; series?: Series[]; loggedIn: boolean; filter?: string } = $props();

	type GameItem = { kind: 'game' } & Game;
	type SeriesItem = { kind: 'series' } & Series;
	type Item = GameItem | SeriesItem;

	const allItems = $derived<Item[]>(
		[
			...games.map((g) => ({ kind: 'game' as const, ...g })),
			...series.map((s) => ({ kind: 'series' as const, ...s }))
		].sort((a, b) => a.title.localeCompare(b.title))
	);

	const filtered = $derived(
		filter.trim()
			? allItems.filter(
					(item) =>
						item.title.toLowerCase().includes(filter.toLowerCase()) ||
						(item.kind === 'game' && item.genre.toLowerCase().includes(filter.toLowerCase()))
				)
			: allItems
	);
</script>

{#if filtered.length === 0}
	<p class="text-gray-500 text-center py-16">No games found.</p>
{:else}
	<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
		{#each filtered as item (item.kind + item.id)}
			{#if item.kind === 'game'}
				<GameCard game={item} {loggedIn} />
			{:else}
				<SeriesCard series={item} {loggedIn} />
			{/if}
		{/each}
	</div>
{/if}
