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

	export const pipelineSearch = tv({
		slots: {
			form: "flex w-full",
			field: "relative flex w-full items-center",
			input: "w-full",
			clear: "absolute right-0.5"
		},
		variants: {
			// room for the clear button so the text does not run under it
			filled: {
				true: { input: "pr-9" },
				false: {}
			}
		},
		defaultVariants: {
			filled: false
		}
	});
</script>

<script lang="ts">
	import { page } from "$app/state";
	import Search from "$icon/search";
	import X from "$icon/x";
	import Button from "$lib/components/ui/Button.svelte";
	import Input from "$lib/components/ui/Input.svelte";
	import type { PipelineFilter } from "./pipeline";

	interface Props {
		/** kept in the form so searching does not reset the tab */
		filter: PipelineFilter;
	}

	let { filter }: Props = $props();

	let form: HTMLFormElement;
	// seed from the url so the query (and the clear button) survive a submit
	let value = $state(page.url.searchParams.get("q") ?? "");

	const clear = () => {
		value = "";
		form.requestSubmit();
	};

	const classes = $derived(pipelineSearch({ filled: value !== "" }));
</script>

<form bind:this={form} class={classes.form()} method="GET">
	{#if filter !== "all"}
		<input type="hidden" name="trigger" value={filter} />
	{/if}

	<div class={classes.field()}>
		<Input
			bind:value
			type="text"
			name="q"
			placeholder="Search pipelines..."
			aria-label="Search pipelines"
			iconLeft={Search}
			class={classes.input()}
		/>
		{#if value}
			<Button
				type="button"
				variant="ghost"
				size="sm"
				icon={X}
				onclick={clear}
				aria-label="Clear search"
				class={classes.clear()}
			/>
		{/if}
	</div>
</form>
