<script lang="ts">
	import { Button } from "$lib/components/ui/button/index.js";
	import { UseClipboard } from "$lib/hooks/use-clipboard.svelte";
	import { cn } from "$lib/utils";
	import * as m from '$lib/paraglide/messages';
	import CheckIcon from "@lucide/svelte/icons/check";
	import CopyIcon from "@lucide/svelte/icons/copy";
	import XIcon from "@lucide/svelte/icons/x";
	import { scale } from "svelte/transition";
	import type { CopyButtonProps } from "./types";

	let {
		ref = $bindable(null),
		text,
		icon,
		animationDuration = 500,
		variant = "ghost",
		size: sizeProp = "icon",
		onCopy,
		class: className,
		tabindex = -1,
		children,
		...rest
	}: CopyButtonProps = $props();

	let resolvedSize = $derived(sizeProp === "icon" && children ? "default" : sizeProp);

	let clipboard = new UseClipboard();
</script>

<Button
	bind:ref
	{variant}
	size={resolvedSize}
	{tabindex}
	class={cn("flex items-center gap-2", className)}
	type="button"
	name="copy"
	onclick={async () => {
		const status = await clipboard.copy(text);

		onCopy?.(status);
	}}
>
	{#if clipboard.status === "success"}
		<div in:scale={{ duration: animationDuration, start: 0.85 }}>
			<CheckIcon tabindex={-1} strokeWidth={1.8} />
			<span class="sr-only">{m.copy_button_copied_sr()}</span>
		</div>
	{:else if clipboard.status === "failure"}
		<div in:scale={{ duration: animationDuration, start: 0.85 }}>
			<XIcon tabindex={-1} strokeWidth={1.8} />
			<span class="sr-only">{m.copy_button_failed_sr()}</span>
		</div>
	{:else}
		<div in:scale={{ duration: animationDuration, start: 0.85 }}>
			{#if icon}
				{@render icon()}
			{:else}
				<CopyIcon tabindex={-1} strokeWidth={1.8} />
			{/if}
			<span class="sr-only">{m.copy_button_copy_sr()}</span>
		</div>
	{/if}
	{@render children?.()}
</Button>
