<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";
	import type { SelectOption } from "$lib/components/ui/selectField";

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

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

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

	// no counts in the headings: the knot caps how many refs it hands back, so the length here
	// is the loaded count rather than the repo's total, and it would not track the filter either
	const options = $derived<SelectOption[]>([
		...branches.map((branch) => ({
			value: branch,
			hint: branch === defaultBranch ? "default" : undefined,
			group: "Branches"
		})),
		...(tags.length > 0
			? tags.map((tag) => ({ value: tag, group: "Tags" }))
			: [{ value: "No tags found", disabled: true, group: "Tags" }])
	]);

	const onSelect = (value: string) => {
		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
			rich
			{options}
			value={current}
			{onSelect}
			label="Switch branch or tag"
			searchPlaceholder="Find a branch or tag…"
			emptyLabel="No branch or tag matches"
			class="md:min-w-48"
		>
			{#snippet footer()}
				<div class="flex items-center gap-4 px-2 py-1.5">
					<a href={resolve(`${base}/branches` as "/")}> View all branches </a>
					<a href={resolve(`${base}/tags` as "/")}>View all tags</a>
				</div>
			{/snippet}
		</Select>
	</div>
	<a
		href={resolve(`${base}/compare?base=${encodeURIComponent(current)}` as "/")}
		class="flex items-center rounded-sm 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>
