<script lang="ts">
	import { goto } from "$app/navigation";
	import { resolve } from "$app/paths";
	import GitCompare from "$icon/git-compare";
	import Select from "$lib/components/ui/Select.svelte";

	interface Props {
		ownerHandle: string;
		repoName: string;
		current: string;
		branches: string[];
		tags: string[];
	}

	let { ownerHandle, repoName, current, branches, tags }: Props = $props();

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

	const onchange = (event: Event) => {
		const value = (event.currentTarget as HTMLSelectElement).value;
		if (value === current) return;
		void goto(resolve(`${base}/tree/${encodeURIComponent(value)}` as "/"));
	};
</script>

<div class="flex min-w-0 flex-1 items-stretch gap-2">
	<div class="max-w-32 sm:max-w-64">
		<!-- the ref lives in the url so navigation updates it, no two way binding -->
		<Select value={current} {onchange} aria-label="Switch branch or tag">
			<!-- a commit sha or a ref past the knot's cap still needs a label -->
			{#if !branches.includes(current) && !tags.includes(current)}
				<option value={current}>{current}</option>
			{/if}
			<optgroup label={`Branches (${branches.length})`}>
				{#each branches as branch (branch)}
					<option value={branch}>{branch}</option>
				{/each}
			</optgroup>
			<optgroup label={`Tags (${tags.length})`}>
				{#each tags as tag (tag)}
					<option value={tag}>{tag}</option>
				{:else}
					<option disabled>No tags found</option>
				{/each}
			</optgroup>
		</Select>
	</div>
	<a
		href={resolve(`${base}/compare?base=${encodeURIComponent(current)}` as "/")}
		class="flex items-center rounded border border-border-default px-2 text-foreground-muted no-underline hover:bg-background-subtle hover:no-underline"
		title="Compare branches or tags"
		aria-label="Compare branches or tags"
	>
		<GitCompare class="size-4" aria-hidden="true" />
	</a>
</div>
