<script lang="ts">
	import { untrack } from "svelte";
	import { getAuth } from "$lib/auth.svelte";
	import { createBobbinClient } from "$lib/api/client";
	import { IdentityCache } from "$lib/api/identity";
	import VouchCard from "../VouchCard.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, fetchVouchesPage, type VouchCursors } from "../pages";
	import type { VouchData } from "../types";

	interface Props {
		initial: VouchData[];
		cursors: VouchCursors;
		total: number;
		did: string;
		isSelf: boolean;
		profileHandle: string;
	}

	let { initial, cursors: initialCursors, total, did, isSelf, profileHandle }: Props = $props();

	const auth = getAuth();

	// shared across pages so repeat dids only resolve once
	let identityCache: IdentityCache | undefined;

	const profileLabel = $derived(isSelf ? "you" : profileHandle);
	const pager = createCursorPager<VouchData, VouchCursors>(
		{ items: untrack(() => initial), cursor: untrack(() => initialCursors) },
		(cursors) => {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			identityCache ??= new IdentityCache(ctx);
			return fetchVouchesPage(ctx, { did, cursors, cache: identityCache }).then((next) => ({
				items: next.items,
				cursor: next.cursors
			}));
		},
		(cursors) => Boolean(cursors?.incoming ?? cursors?.outgoing)
	);
	const vouches = $derived(pager.items);
	const pages = $derived(pageCount(total, PROFILE_PAGE_LIMIT));
</script>

<Section
	title="Vouches"
	empty={vouches.length === 0}
	emptyMessage="No vouches yet."
	listClass="relative ml-5 flex flex-col gap-6 border border-transparent px-4"
>
	<div class="absolute inset-y-8 z-0 w-0.5 bg-border-default"></div>
	{#each vouches as vouch (vouch.uri)}
		<VouchCard {vouch} {profileLabel} />
	{/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>
