<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 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}`}`);

	type KeyStatus = "checking" | "has-key" | "no-key";

	let keyStatus = $state<KeyStatus>("checking");

	$effect(() => {
		if (hasSshKey !== undefined) {
			keyStatus = hasSshKey ? "has-key" : "no-key";
			return;
		}

		if (!isOwner) return;
		const did = auth.currentDid;
		if (!did) return;

		let cancelled = false;
		keyStatus = "checking";

		(async () => {
			try {
				const ctx = createBobbinClient({ serviceUrl: auth.bobbinUrl });
				const result = await count(ctx, "sh.tangled.publicKey.countKeys", did);
				if (!cancelled) keyStatus = result.count > 0 ? "has-key" : "no-key";
			} catch {
				// safe fallback: guide the owner through generating a key.
				if (!cancelled) keyStatus = "no-key";
			}
		})();

		return () => {
			cancelled = true;
		};
	});
</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 font-mono text-xs"
	>
		{n}
	</span>
{/snippet}

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

{#if isOwner}
	{#if keyStatus === "checking"}
		<div class="py-6" aria-hidden="true"></div>
	{:else if keyStatus === "has-key"}
		<div class="flex w-full place-content-center">
			<div class="flex w-fit flex-col gap-5 py-6 text-sm">
				<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 text-sm">
				<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 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}
