<script lang="ts">
	import { untrack } from "svelte";
	import { getAuth } from "$lib/auth.svelte";
	import { createBobbinClient } from "$lib/api/client";
	import FollowCard from "../FollowCard.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, fetchPeoplePage } from "../pages";
	import type { PersonData } from "../types";

	interface Props {
		initial: PersonData[];
		cursor?: string;
		total: number;
		did: string;
		direction: "followers" | "following";
		title: string;
		emptyMessage: string;
	}

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

	const auth = getAuth();

	const pager = createCursorPager(
		{ items: untrack(() => initial), cursor: untrack(() => initialCursor) },
		(cursor) => {
			const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
			return fetchPeoplePage(ctx, {
				did,
				viewerDid: auth.currentDid ?? undefined,
				direction,
				cursor
			});
		}
	);
	const people = $derived(pager.items);
	const pages = $derived(pageCount(total, PROFILE_PAGE_LIMIT));
</script>

<Section {title} empty={people.length === 0} {emptyMessage} listClass="flex flex-col gap-8">
	{#each people as person (person.did)}
		<FollowCard {person} />
	{/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>
