<script lang="ts">
	import type { ReactionGroup } from "./reactions";

	interface Props {
		reaction: ReactionGroup;
		ontoggle?: () => void; // null for loggedout users
		pending?: boolean;
	}

	let { reaction, ontoggle, pending = false }: Props = $props();

	const MAX_NAMES = 10;
	const title = $derived.by(() => {
		const shown = reaction.users.slice(0, MAX_NAMES);
		const more = reaction.count - shown.length;
		const names = shown.join(", ");
		return more > 0 ? `${names}, and ${more} more` : names;
	});

	const chipClass = $derived(
		`flex min-h-6 items-center justify-center gap-1.5 rounded border px-2 text-xs leading-4 text-foreground-default ${
			reaction.isReacted
				? "border-border-strong bg-background-info-subtle"
				: "border-border-default"
		}`
	);
</script>

{#if ontoggle}
	<button
		type="button"
		{title}
		disabled={pending}
		aria-pressed={reaction.isReacted}
		onclick={ontoggle}
		class={`${chipClass} cursor-pointer transition hover:border-border-strong disabled:opacity-50`}
	>
		<span>{reaction.kind}</span>
		<span>{reaction.count}</span>
	</button>
{:else}
	<span {title} class={chipClass}>
		<span>{reaction.kind}</span>
		<span>{reaction.count}</span>
	</span>
{/if}
