<script lang="ts">
	import { resolve } from "$app/paths";
	import type { TreeEntrySummary } from "./types";

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

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

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

	const crumbs = $derived.by(() => {
		const parts = path.split("/").filter(Boolean);
		return [
			{ name: repoName, href: `${base}/tree/${encodedRef}`, last: parts.length === 0 },
			...parts.map((name, index) => ({
				name,
				href: `${base}/tree/${encodedRef}/${parts.slice(0, index + 1).join("/")}`,
				last: index === parts.length - 1
			}))
		];
	});

	const folders = $derived(
		entries.filter((entry) => entry.kind === "directory" || entry.kind === "submodule").length
	);
	const files = $derived(entries.length - folders);
	const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
</script>

<div class="mb-3 flex items-center justify-between gap-2 text-sm">
	<div class="flex min-w-0 items-center gap-3">
		<div
			class="flex w-fit items-center gap-1 overflow-x-auto rounded border border-border-default bg-background-inset px-3 py-2 whitespace-nowrap"
		>
			{#each crumbs as crumb (crumb.href)}
				{#if crumb.last}
					<span class="text-foreground-default" aria-current="page">{crumb.name}</span>
				{:else}
					<a
						href={resolve(crumb.href as "/")}
						class="text-foreground-muted no-underline hover:underline">{crumb.name}</a
					>
					<span class="text-foreground-muted" aria-hidden="true">/</span>
				{/if}
			{/each}
		</div>

		<div class="flex items-center gap-2 text-foreground-muted">
			{#if folders > 0}
				<span>{plural(folders, "folder")}</span>
			{/if}
			{#if folders > 0 && files > 0}
				<span aria-hidden="true">&middot;</span>
			{/if}
			{#if files > 0}
				<span>{plural(files, "file")}</span>
			{/if}
		</div>
	</div>

	<div
		class="hidden w-fit items-center gap-1 rounded border border-border-default bg-background-inset p-2 whitespace-nowrap text-foreground-muted md:flex"
	>
		at <a
			href={resolve(`${base}/tree/${encodedRef}` as "/")}
			class="text-foreground-default no-underline hover:underline">{ref}</a
		>
	</div>
</div>
