<script module lang="ts">
	import { tv, type VariantProps } from "tailwind-variants";
	import type { ButtonVariants } from "./Button.svelte";

	export const buttonGroup = tv({
		base: "inline-flex items-center",
		variants: {
			// joined groups are the segmented control from Figma: the group draws the outer
			// border and the recessed surface, and each segment's own 1px border is pulled
			// onto it (-m-px) so an unselected segment shows the group's surface while a
			// selected one covers it and reads as a raised card.
			spaced: {
				true: "gap-2",
				false: [
					"gap-0 rounded border border-border-default bg-background-subtle",
					"*:relative *:-my-px",
					"[&>*:first-child]:-ml-px [&>*:last-child]:-mr-px",
					"[&>*:not(:first-child)]:-ml-px [&>*:not(:first-child)]:[--btn-radius-l:0px]",
					"[&>*:not(:last-child)]:[--btn-radius-r:0px]",
					"[&>*:focus-visible]:z-10 [&>*:hover]:z-10"
				]
			}
		},
		defaultVariants: {
			spaced: false
		}
	});

	export type ButtonGroupVariants = VariantProps<typeof buttonGroup>;

	/**
	 * Recipe for using ButtonGroup as a tab/segment switcher (e.g. Open/Closed issue filters,
	 * Write/Preview editor tabs). Per Figma, the selected segment reads as a raised, lighter
	 * surface (`default` + its inset shadow) while unselected segments are flat `ghost`
	 * buttons — never the plain `default` variant, which reads as the *hovered* state of an
	 * unselected segment. Figma also gives an unselected segment the same foreground as a
	 * selected one, where `ghost` on its own is muted, so the recipe overrides the colour
	 * here rather than changing `ghost` everywhere it's used.
	 */
	export function segmentProps(selected: boolean): {
		variant: ButtonVariants["variant"];
		insetShadow: boolean;
		class?: string;
	} {
		return selected
			? { variant: "default", insetShadow: true }
			: { variant: "ghost", insetShadow: false, class: "text-foreground-default" };
	}
</script>

<script lang="ts">
	import type { Snippet } from "svelte";

	interface Props {
		spaced?: ButtonGroupVariants["spaced"];
		class?: string;
		children: Snippet;
	}

	let { spaced = false, class: className, children }: Props = $props();

	const classes = $derived(buttonGroup({ spaced, class: className }));
</script>

<div class={classes}>
	{@render children()}
</div>
