<script module lang="ts">
	import { tv } from "tailwind-variants";

	export const pipelineToolbar = tv({
		slots: {
			// same grid as IssueToolbar: group, search, count. search gets its own row on mobile.
			root: "grid grid-cols-[auto_1fr_auto] gap-2",
			search: "col-span-3 sm:col-span-1 sm:col-start-2",
			group: "sm:row-start-1",
			count:
				"col-start-3 row-start-2 self-center justify-self-end typography-paragraph-small whitespace-nowrap text-foreground-muted sm:row-start-1",
			qualifier: "hidden sm:inline"
		}
	});
</script>

<script lang="ts">
	import { page } from "$app/state";
	import { resolve } from "$app/paths";
	import GitCommitHorizontal from "$icon/git-commit-horizontal";
	import GitPullRequest from "$icon/git-pull-request";
	import Layers2 from "$icon/layers-2";
	import Button from "$lib/components/ui/Button.svelte";
	import ButtonGroup, { segmentProps } from "$lib/components/ui/ButtonGroup.svelte";
	import type { PipelineFilter } from "./pipeline";
	import PipelineSearch from "./PipelineSearch.svelte";

	interface Props {
		ownerHandle: string;
		repoName: string;
		filter: PipelineFilter;
		/** how many runs match the tab and query */
		total: number;
	}

	let { ownerHandle, repoName, filter, total }: Props = $props();

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

	// keep the query when switching tabs
	const segmentHref = (kind: PipelineFilter) => {
		const query = page.url.searchParams.get("q");
		const suffix = query ? `&q=${encodeURIComponent(query)}` : "";
		return resolve(`${base}?trigger=${kind}${suffix}` as "/");
	};

	const classes = pipelineToolbar();
</script>

<div class={classes.root()}>
	<div class={classes.search()}>
		<PipelineSearch {filter} />
	</div>

	<ButtonGroup class={classes.group()}>
		<!-- no manual segment: the appview only filters push and pull request -->
		<Button href={segmentHref("all")} {...segmentProps(filter === "all")} icon={Layers2}>
			All
		</Button>
		<Button
			href={segmentHref("push")}
			{...segmentProps(filter === "push")}
			icon={GitCommitHorizontal}
		>
			Push
		</Button>
		<Button
			href={segmentHref("pull_request")}
			{...segmentProps(filter === "pull_request")}
			icon={GitPullRequest}
		>
			<!-- nbsp: a plain space between the spans gets collapsed away -->
			<span>Pull<span class={classes.qualifier()}>&nbsp;request</span></span>
		</Button>
	</ButtonGroup>

	<span class={classes.count()}>
		{total} pipeline {total === 1 ? "run" : "runs"}
	</span>
</div>
