<script lang="ts">
	import { resolve } from "$app/paths";
	import { getAuth } from "$lib/auth.svelte";
	import { createBobbinClient } from "$lib/api/client";
	import { count } from "$lib/api/count";
	import { createLoad } from "$lib/action.svelte";
	import type { RepoInfo } from "./types";

	interface Props {
		repo: RepoInfo;
		/**
		 * Overrides the SSH key lookup, for deterministic stories/tests.
		 * Left unset in real usage, in which case it's figured out from the API.
		 */
		hasSshKey?: boolean;
	}

	let { repo, hasSshKey }: Props = $props();

	const auth = getAuth();
	const isOwner = $derived(auth.currentDid === repo.ownerDid);
	// same host rewrite as the clone urls
	const sshHost = $derived(
		(repo.knot === "knot1.tangled.sh" ? "tangled.org" : repo.knot)
			.replace(/^[a-z]+:\/\//, "")
			.split(/[:/]/)[0]
	);
	const remote = $derived(`git@${sshHost}:${repo.repoDid ?? `${repo.ownerHandle}/${repo.name}`}`);

	const keyStatus = createLoad(async (): Promise<boolean | undefined> => {
		if (hasSshKey !== undefined) {
			return hasSshKey;
		}

		const owner = isOwner;
		const did = auth.currentDid;
		const serviceUrl = auth.bobbinUrl;
		if (!owner || !did) return undefined;
		try {
			const ctx = createBobbinClient({ serviceUrl });
			const result = await count(ctx, "sh.tangled.publicKey.countKeys", did);
			return result.count > 0;
		} catch {
			// safe fallback: guide the owner through generating a key.
			return false;
		}
	});
</script>

{#snippet bullet(n: number)}
	<span
		class="mr-2 inline-flex size-5 shrink-0 items-center justify-center rounded-full bg-background-inset align-middle typography-monospace-small font-mono"
	>
		{n}
	</span>
{/snippet}

{#snippet codeBlock(lines: string[])}
	<pre class="overflow-x-auto rounded-sm bg-background-inset p-3 font-mono typography-paragraph-small">{lines.join(
			"\n"
		)}</pre>
{/snippet}

{#if isOwner}
	{#if keyStatus.loading || keyStatus.data === undefined}
		<div class="py-6" aria-hidden="true"></div>
	{:else if keyStatus.data}
		<div class="flex w-full place-content-center">
			<div class="flex w-fit flex-col gap-5 py-6 typography-paragraph-small">
				<p>This is an empty repository.</p>
				<div class="flex flex-col gap-2">
					<p class="text-foreground-subtle">…create a new repository on the command line</p>
					{@render codeBlock([
						`echo "# ${repo.name}" >> README.md`,
						"git init",
						"git add README.md",
						'git commit -m "initial commit"',
						`git branch -M ${repo.defaultBranch}`,
						`git remote add origin ${remote}`,
						`git push -u origin ${repo.defaultBranch}`
					])}
				</div>
				<div class="flex flex-col gap-2">
					<p class="text-foreground-subtle">
						…or push an existing repository from the command line
					</p>
					{@render codeBlock([
						`git remote add origin ${remote}`,
						`git branch -M ${repo.defaultBranch}`,
						`git push -u origin ${repo.defaultBranch}`
					])}
				</div>
			</div>
		</div>
	{:else}
		<div class="flex w-full place-content-center">
			<div class="flex w-fit flex-col gap-4 py-6 typography-paragraph-small">
				<p>This is an empty repository. To get started:</p>
				<p>
					{@render bullet(1)}First, generate a new
					<a
						href="https://git-scm.com/book/en/v2/Git-on-the-Server-Generating-Your-SSH-Public-Key"
						rel="noopener"
						class="underline">SSH key pair</a
					>.
				</p>
				<p>
					{@render bullet(2)}Then add the public key from the
					<a href={resolve("/settings/keys")} class="underline">keys page</a> in your settings.
				</p>
				<p>
					{@render bullet(3)}Configure your remote to
					<code class="rounded-sm bg-background-inset px-1 font-mono">{remote}</code>
				</p>
				<p>{@render bullet(4)}Push!</p>
			</div>
		</div>
	{/if}
{:else}
	<p class="py-6 text-center text-foreground-subtle">This is an empty repository.</p>
{/if}
