<svelte:options
	customElement={{
		tag: 'eve-reputation-button',
		shadow: 'none'
	}}
/>

<script lang="ts">
	import Icon from '@iconify/svelte';
	import { getEventStore } from '$lib/stores/reputationEvent';

	let {
		direction,
		event: eventId,
		reason
	}: {
		direction: '+' | '-';
		event: string;
		reason?: string;
	} = $props();

	let publishing = $state(false);
	const eventStore = getEventStore(eventId);

	async function click() {
		const { event, loading, reputationGiven, isOwnEvent } = $eventStore;
		if (publishing || loading || reputationGiven || isOwnEvent) return;

		publishing = true;
		if (!event) {
			console.error('Event not found');
			publishing = false;
			return;
		}
		const tags = [
			['p', event.pubkey],
			['e', event.id!]
		];
		if (reason) tags.push(['reason', reason]);
		try {
			await window.eve.publish({
				pubkey: await window.eve.getPublicKey(),
				kind: 7,
				content: direction,
				tags,
				created_at: Math.floor(Date.now() / 1000)
			});
		} catch (e) {
			console.error('Failed to publish reputation event', e);
		} finally {
			publishing = false;
		}
	}
</script>

<button
	class="btn btn-primary btn-circle"
	onclick={click}
	disabled={publishing ||
		$eventStore.loading ||
		$eventStore.reputationGiven ||
		$eventStore.isOwnEvent}
>
	{#if publishing || $eventStore.loading}
		<Icon icon="mdi:loading" />
	{:else if direction === '+'}
		<Icon icon="mdi:plus" />
	{:else if direction === '-'}
		<Icon icon="mdi:minus" />
	{/if}
</button>
