<script lang="ts">
    import CollectionsGrid from '$lib/components/CollectionsGrid.svelte';
    import MangaGridSkeleton from '$lib/components/MangaGridSkeleton.svelte';
    import LoadMore from '$lib/components/LoadMore.svelte';
    import { listMyCollections, type CollectionSummary } from '$lib/api/collections';

    let { data } = $props();

    async function fetchMore(offset: number) {
        const p = await listMyCollections({ limit: data.pageSize, offset });
        return { items: p.items, total: p.page.total };
    }
</script>

<h1>Collections</h1>

{#await data.result}
    <MangaGridSkeleton count={6} />
{:then r}
    {#if !r.authenticated}
        <p class="status">
            <a href="/login">Sign in</a> to see and manage your collections.
        </p>
    {:else if r.error}
        <p class="error" role="alert">{r.error}</p>
    {:else if r.collections.length === 0}
        <p class="status" data-testid="collections-empty">
            You don't have any collections yet. Open any manga and use
            <strong>Add to collection</strong> to start one.
        </p>
    {:else}
        <LoadMore initial={r.collections as CollectionSummary[]} total={r.total} {fetchMore}>
            {#snippet children(items: CollectionSummary[])}
                <CollectionsGrid collections={items} />
            {/snippet}
        </LoadMore>
    {/if}
{/await}

<style>
    .status {
        color: var(--text-muted);
    }

    .error {
        color: var(--danger);
    }
</style>
