<script lang="ts">
	import { untrack } from "svelte";
	import { getAuth } from "$lib/auth.svelte";
	import { createBobbinClient } from "$lib/api/client";
	import StringCard from "../StringCard.svelte";
	import Section from "$lib/components/ui/Section.svelte";
	import Pagination from "$lib/components/ui/Pagination.svelte";
	import Error from "$lib/components/ui/Error.svelte";
	import { createCursorPager, pageCount } from "../pagination.svelte";
	import { PROFILE_PAGE_LIMIT, fetchStringsPage } from "../pages";
	import type { StringCardData } from "../types";

	interface Props {
		initial: StringCardData[];
		cursor?: string;
		total: number;
		did: string;
		handle: string;
	}

	let { initial, cursor: initialCursor, total, did, handle }: Props = $props();

	const auth = getAuth();

	const pager = createCursorPager(
		{ items: untrack(() => initial), cursor: untrack(() => initialCursor) },
		(cursor) => {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			return fetchStringsPage(ctx, { did, handle, cursor });
		}
	);
	const strings = $derived(pager.items);
	const pages = $derived(pageCount(total, PROFILE_PAGE_LIMIT));
</script>

<Section title="Strings" empty={strings.length === 0} emptyMessage="No strings yet.">
	{#each strings as entry (entry.rkey)}
		<StringCard {entry} />
	{/each}
	{#snippet footer()}
		{#if pages > 1}
			<div class="mt-4 flex justify-center">
				<Pagination
					page={pager.state.page}
					total={pages}
					labels
					disabled={pager.state.kind === "loading"}
					onchange={pager.select}
					class="gap-5"
				/>
			</div>
		{/if}
		{#if pager.state.kind === "failed"}
			<Error label="couldn't load that page. try again." class="mt-2" />
		{/if}
	{/snippet}
</Section>
