<template>
    <div v-if="note" class="reacted-users">
        <div :class="$style.tabs">
            <button
                v-for="reaction in reactions"
                :key="reaction[0]"
                :class="[
                    $style.tab,
                    {
                        [$style.tabActive]:
                            tab === magReactionToLegacy(reaction[0]),
                    },
                ]"
                class="_button"
                @click="tab = magReactionToLegacy(reaction[0])"
            >
                <MagEmoji
                    ref="reactionRef"
                    :emoji="reaction[0]"
                    :is-reaction="true"
                    :normal="true"
                />

                <span style="margin-left: 4px">{{ reaction[1] }}</span>
            </button>
        </div>
        <MkUserCardMini
            v-for="user in users"
            :key="user.id"
            :user="user"
            :with-chart="false"
        />
    </div>
    <div v-else>
        <MkLoading />
    </div>
</template>

<script lang="ts" setup>
import { onMounted, watch, ref } from "vue";
import * as misskey from "calckey-js";
import MkUserCardMini from "@/components/MkUserCardMini.vue";
import * as os from "@/os";
import { endpoints, types, packed } from "magnetar-common";
import { magReactionToLegacy } from "@/scripts-mag/mag-util";

const props = defineProps<{
    noteId: string;
}>();

let tab = ref<string>();
let note = ref<packed.PackNoteBase>();
let reactions = ref<types.ReactionPair[]>();
let users = ref<misskey.entities.UserLite[]>();

watch(tab, async () => {
    const res = await os.api("notes/reactions", {
        noteId: props.noteId,
        type: tab.value,
        limit: 30,
    });

    users.value = res.map((x) => x.user);
});

onMounted(() => {
    os.magApi(endpoints.GetNoteById, {}, { id: props.noteId }).then((res) => {
        reactions.value = res.reactions;
        tab.value = magReactionToLegacy(reactions.value.map((r) => r[0])[0]);
        note.value = res;
    });
});
</script>

<style lang="scss" module>
.tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.tab {
    padding: 4px 6px;
    border: solid 1px var(--divider);
    border-radius: 6px;
}

.tabActive {
    border-color: var(--accent);
}
</style>
