<script lang="ts">
	import { untrack } from "svelte";
	import { page } from "$app/state";
	import { resolve } from "$app/paths";
	import { getAuth } from "$lib/auth.svelte";
	import { createBobbinClient } from "$lib/api/client";
	import { fetchReposPage } from "../pages";
	import RepoCard from "$lib/components/repo/RepoCard.svelte";
	import Section from "$lib/components/ui/Section.svelte";
	import LoadMore from "$lib/components/ui/LoadMore.svelte";
	import { repoKey, type RepoCardData } from "../types";
	import Search from "$icon/search";
	import X from "$icon/x";

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

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

	const auth = getAuth();

	let extra = $state<RepoCardData[]>([]);
	let cursor = $state(untrack(() => initialCursor));
	let loading = $state(false);
	let failed = $state(false);

	const repos = $derived([...initial, ...extra]);
	let searchQuery = $derived(page.url.searchParams.get("q") ?? "");

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

<Section
	empty={repos.length === 0}
	emptyMessage={searchQuery ? `No repositories match "${searchQuery}".` : "No repositories found."}
>
	{#snippet header()}
		<div class="mb-4">
			<form class="relative flex" method="GET">
				<input type="hidden" name="tab" value="repos" />
				<div class="relative flex flex-1">
					<input
						class="peer flex-1 rounded-l border border-border-default bg-background-default py-1.5 pr-10 pl-3 outline-none focus:border-border-strong focus:ring-1 focus:ring-border-strong"
						type="text"
						name="q"
						value={searchQuery}
						placeholder="Search repositories..."
					/>
					<a
						href={resolve(`${page.url.pathname}?tab=repos` as "/")}
						class="absolute top-1/2 right-3 hidden -translate-y-1/2 text-foreground-subtle peer-not-placeholder-shown:block hover:text-foreground-default"
					>
						<X class="size-4" />
					</a>
				</div>
				<button
					type="submit"
					class="rounded-r border border-l-0 border-border-default bg-background-default p-2 text-foreground-subtle hover:bg-background-subtle hover:text-foreground-default"
				>
					<Search class="size-4" />
				</button>
			</form>
		</div>
	{/snippet}
	{#each repos as repo (repoKey(repo))}
		<RepoCard {repo} showOwner={false} />
	{/each}
	{#if cursor}
		<LoadMore {loading} {failed} onclick={loadMore} />
	{/if}
</Section>
