<script lang="ts">
	import { untrack } from "svelte";
	import { resolve } from "$app/paths";
	import { getAuth } from "$lib/auth.svelte";
	import { createBobbinClient } from "$lib/api/client";
	import { IdentityCache } from "$lib/api/identity";
	import { fetchStarredPage } from "../pages";
	import RepoCard from "$lib/components/repo/RepoCard.svelte";
	import Card from "$lib/components/ui/Card.svelte";
	import Section from "$lib/components/ui/Section.svelte";
	import LoadMore from "$lib/components/ui/LoadMore.svelte";
	import type { StarData } from "../types";

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

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

	const auth = getAuth();

	let extra = $state<StarData[]>([]);
	let cursor = $state(untrack(() => initialCursor));
	let loading = $state(false);
	let failed = $state(false);
	// shared across pages so repeat repo owners only resolve once
	let identityCache: IdentityCache | undefined;

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

	const loadMore = async () => {
		if (loading || !cursor) return;
		loading = true;
		failed = false;
		try {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			identityCache ??= new IdentityCache(ctx);
			const next = await fetchStarredPage(ctx, {
				did,
				viewerDid: auth.currentDid ?? undefined,
				cursor,
				cache: identityCache
			});
			extra = [...extra, ...next.items];
			cursor = next.cursor;
		} catch {
			failed = true;
		} finally {
			loading = false;
		}
	};
</script>

<Section title="Starred" empty={stars.length === 0} emptyMessage="No stars yet.">
	{#each stars as star (star.uri)}
		{#if star.kind === "repo"}
			<RepoCard repo={star.repo} />
		{:else}
			<Card shadow={false} class="flex items-center gap-2">
				<a
					href={resolve(`/${star.ownerHandle}/strings/${star.rkey}` as "/")}
					class="truncate font-bold text-foreground-default no-underline hover:underline"
				>
					{star.ownerHandle}/{star.rkey}
				</a>
			</Card>
		{/if}
	{/each}
	{#if cursor}
		<LoadMore {loading} {failed} onclick={loadMore} />
	{/if}
</Section>
