<script lang="ts">
	import { resolve } from "$app/paths";
	import Ellipsis from "$icon/ellipsis";
	import Tag from "$lib/components/ui/Tag.svelte";
	import TimeAgo from "$lib/components/ui/TimeAgo.svelte";
	import type { CommitSummary } from "./types";

	interface Props {
		ownerHandle: string;
		repoName: string;
		commits: CommitSummary[];
		tagsByCommit?: Record<string, string[]>;
	}

	let { ownerHandle, repoName, commits, tagsByCommit = {} }: Props = $props();

	const base = $derived(`/${ownerHandle}/${repoName}`);
	let expanded = $state<Record<string, boolean>>({});
</script>

<div class="flex flex-col gap-6">
	{#each commits as commit (commit.hash)}
		<div>
			<div class="flex items-start gap-1">
				<a
					href={resolve(`${base}/commit/${commit.hash}` as "/")}
					class="text-base text-foreground-default no-underline hover:underline"
				>
					{commit.subject}
				</a>
				{#if commit.body}
					<button
						type="button"
						class="mt-1 shrink-0 cursor-pointer rounded bg-background-inset px-1 py-0.5 text-foreground-muted hover:bg-background-muted"
						aria-expanded={expanded[commit.hash] === true}
						aria-label="Toggle commit body"
						onclick={() => (expanded[commit.hash] = !expanded[commit.hash])}
					>
						<Ellipsis class="size-3" aria-hidden="true" />
					</button>
				{/if}
			</div>

			{#if commit.body && expanded[commit.hash]}
				<p class="mt-1 pb-2 text-sm whitespace-pre-wrap text-foreground-muted">{commit.body}</p>
			{/if}

			<div
				class="mt-2 flex flex-wrap items-center gap-2 text-paragraph-regular text-foreground-subtle"
			>
				<a
					href={resolve(`${base}/commit/${commit.hash}` as "/")}
					title={commit.changeId ? `jj change id: ${commit.changeId}` : undefined}
					class="rounded bg-background-inset px-2 py-0.5 font-mono text-foreground-muted no-underline hover:underline"
				>
					{commit.shortHash}
				</a>
				{#if commit.authorName}
					<span class="truncate">{commit.authorName}</span>
				{/if}
				{#if commit.when}
					<span aria-hidden="true">&middot;</span>
					<TimeAgo value={commit.when} />
				{/if}
				{#each tagsByCommit[commit.hash] ?? [] as name (name)}
					<Tag color="gray" class="font-mono">{name}</Tag>
				{/each}
			</div>
		</div>
	{/each}
</div>
