<script lang="ts">
	import { resolve } from "$app/paths";
	import File from "$icon/file";
	import FileSymlink from "$icon/file-symlink";
	import Folder from "$icon/folder";
	import FolderInput from "$icon/folder-input";
	import TimeAgo from "$lib/components/ui/TimeAgo.svelte";
	import type { TreeEntrySummary } from "./types";

	interface Props {
		ownerHandle: string;
		repoName: string;
		ref: string;
		entries: TreeEntrySummary[];
		path?: string;
	}

	let { ownerHandle, repoName, ref, entries, path = "" }: Props = $props();

	const base = $derived(`/${ownerHandle}/${repoName}`);
	const encodedRef = $derived(encodeURIComponent(ref));

	const linkFor = (entry: TreeEntrySummary) => {
		const target = path ? `${path}/${entry.name}` : entry.name;
		const kind = entry.kind === "directory" ? "tree" : "blob";
		return `${base}/${kind}/${encodedRef}/${target}`;
	};

	const iconFor = (entry: TreeEntrySummary) => {
		switch (entry.kind) {
			case "directory":
				return Folder;
			case "submodule":
				return FolderInput;
			case "symlink":
				return FileSymlink;
			default:
				return File;
		}
	};
</script>

<div class="min-w-0 md:border-r md:border-border-default md:pr-2">
	{#each entries as entry (entry.name)}
		{@const Glyph = iconFor(entry)}
		<div class="grid grid-cols-3 items-center gap-4 py-1">
			<a
				href={resolve(linkFor(entry) as "/")}
				class="col-span-2 flex min-w-0 items-center gap-2 text-foreground-default no-underline hover:underline"
			>
				<Glyph
					class={`size-4 shrink-0 ${entry.kind === "directory" ? "fill-current" : ""}`}
					aria-hidden="true"
				/>
				<span class="truncate">{entry.name}</span>
			</a>
			<div class="col-span-1 text-right text-sm text-foreground-subtle">
				{#if entry.lastCommitHash && entry.lastCommitWhen}
					<a
						href={resolve(`${base}/commit/${entry.lastCommitHash}` as "/")}
						class="text-foreground-subtle no-underline hover:underline"
						title={entry.lastCommitMessage}
					>
						<TimeAgo value={entry.lastCommitWhen} />
					</a>
				{/if}
			</div>
		</div>
	{/each}
</div>
