<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 User from "$lib/components/ui/User.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="no-underline hover:underline"
				>
					{commit.subject}
				</a>
				{#if commit.body}
					<button
						type="button"
						class="mt-1 shrink-0 cursor-pointer rounded-sm bg-background-inset px-1 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 typography-paragraph-small whitespace-pre-wrap text-foreground-muted">{commit.body}</p>
			{/if}

			<div
				class="mt-2 flex flex-wrap items-center gap-2 typography-paragraph-small text-foreground-muted"
			>
				<a
					href={resolve(`${base}/commit/${commit.hash}` as "/")}
					title={commit.changeId ? `jj change id: ${commit.changeId}` : undefined}
					class="rounded-sm bg-background-inset px-2 py-0.5 typography-monospace-small text-foreground-default no-underline hover:underline"
				>
					{commit.shortHash}
				</a>
				{#if commit.authorName}
					<User handle={commit.authorName} size="small" />
				{/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>
