<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: {
			spaced: {
				true: "gap-2",
				false: [
					"items-stretch gap-0 overflow-hidden rounded-sm border border-border-default bg-background-subtle dark:bg-background-canvas",
					"*:relative *:border-y-0",
					"[&>*: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]",
					// children overlap by 1px so adjacent borders collapse into a single seam, which
					// also means a child's fill paints into its neighbour's border column. ghost
					// segments have a transparent border and nothing to repaint there, so every
					// bordered child has to sit above them — otherwise hovering a ghost rubs out the
					// selected segment's border on whichever edge they share.
					"[&>*:not([data-variant=ghost])]:z-10",
					// the group clips overflow, so an outward focus ring gets cut off at its edges and
					// by bordered neighbours. draw it inside the child instead.
					"[&>*:focus-visible]:-outline-offset-2"
				]
			}
		},
		defaultVariants: {
			spaced: false
		}
	});

	export type ButtonGroupVariants = VariantProps<typeof buttonGroup>;

	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, ...rest }: Props = $props();

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

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