<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 { fetchVouchesPage, type VouchCursors } from "../pages";
	import VouchCard from "../VouchCard.svelte";
	import Section from "$lib/components/ui/Section.svelte";
	import LoadMore from "$lib/components/ui/LoadMore.svelte";
	import type { VouchData } from "../types";

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

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

	const auth = getAuth();

	let extra = $state<VouchData[]>([]);
	let cursors = $state(untrack(() => initialCursors));
	let loading = $state(false);
	let failed = $state(false);
	// shared across pages so repeat dids only resolve once
	let identityCache: IdentityCache | undefined;

	const profileLabel = $derived(isSelf ? "you" : profileHandle);
	// incoming and outgoing pages interleave, so the merged list re-sorts on append
	const vouches = $derived(
		[...initial, ...extra].sort(
			(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
		)
	);
	const exhausted = $derived(cursors.incoming === null && cursors.outgoing === null);

	const loadMore = async () => {
		if (loading || exhausted) return;
		loading = true;
		failed = false;
		try {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			identityCache ??= new IdentityCache(ctx);
			const next = await fetchVouchesPage(ctx, { did, cursors, cache: identityCache });
			extra = [...extra, ...next.items];
			cursors = next.cursors;
		} catch {
			failed = true;
		} finally {
			loading = false;
		}
	};
</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}
	{#if !exhausted}
		<LoadMore {loading} {failed} onclick={loadMore} />
	{/if}
</Section>
