<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 RepoCard from "$lib/components/repo/RepoCard.svelte";
	import Card from "$lib/components/ui/Card.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, fetchStarredPage } from "../pages";
	import type { StarData } from "../types";

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

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

	const auth = getAuth();

	const pager = createCursorPager(
		{ items: untrack(() => initial), cursor: untrack(() => initialCursor) },
		(cursor) => {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			return fetchStarredPage(ctx, {
				did,
				viewerDid: auth.currentDid ?? undefined,
				cursor
			});
		}
	);
	const stars = $derived(pager.items);
	const pages = $derived(pageCount(total, PROFILE_PAGE_LIMIT));
</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}
	{#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>
