<template>
	<button
		v-tooltip.noDelay.bottom="isFavorited ? i18n.ts.unfavorite : i18n.ts.favorite"
		class="button _button"
		:class="{ favorited: isFavorited }"
		:disabled="busy"
		@click.stop="toggleFavorite()"
	>
		<i
			class="ph-bookmark-simple ph-bold ph-lg"
			:class="{ 'ph-fill': isFavorited }"
		></i>
	</button>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { Note } from "iceshrimp-sdk/built/entities";
import { $i } from "@/account";
import { i18n } from "@/i18n";
import * as os from "@/os";
import { pleaseLogin } from "@/scripts/please-login";

const props = defineProps<{
	note: Note;
}>();

const isFavorited = ref(false);
const busy = ref(false);

onMounted(async () => {
	if (!$i) return;

	const state = await os.api("notes/state", {
		noteId: props.note.id,
	});

	isFavorited.value = state.isFavorited;
});

async function toggleFavorite(): Promise<void> {
	pleaseLogin();
	if (busy.value) return;

	busy.value = true;
	const favorite = !isFavorited.value;

	try {
		await os.apiWithDialog(
			favorite ? "notes/favorites/create" : "notes/favorites/delete",
			{
				noteId: props.note.id,
			},
		);
		isFavorited.value = favorite;
	} finally {
		busy.value = false;
	}
}
</script>

<style lang="scss" scoped>
.button {
	&.favorited {
		color: var(--accent);
	}
}
</style>
