<script lang="ts">
	import { resolve } from "$app/paths";
	import { encodePathSegments } from "./urls";

	interface Props {
		ownerHandle: string;
		repoName: string;
		ref: string;
		// repo-relative path, empty at the tree root
		path: string;
	}

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

	const treeBase = $derived(`/${ownerHandle}/${repoName}/tree/${encodeURIComponent(ref)}`);

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

<div
	class="flex w-fit items-center gap-1 overflow-x-auto rounded-sm border border-border-default bg-background-canvas px-3 py-1 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>
