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

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

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

	const auth = getAuth();

	let extra = $state<StringCardData[]>([]);
	let cursor = $state(untrack(() => initialCursor));
	let loading = $state(false);
	let failed = $state(false);

	const strings = $derived([...initial, ...extra]);

	const loadMore = async () => {
		if (loading || !cursor) return;
		loading = true;
		failed = false;
		try {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			const next = await fetchStringsPage(ctx, { did, handle, cursor });
			extra = [...extra, ...next.items];
			cursor = next.cursor;
		} catch {
			failed = true;
		} finally {
			loading = false;
		}
	};
</script>

<Section title="Strings" empty={strings.length === 0} emptyMessage="No strings yet.">
	{#each strings as entry (entry.rkey)}
		<StringCard {entry} />
	{/each}
	{#if cursor}
		<LoadMore {loading} {failed} onclick={loadMore} />
	{/if}
</Section>
