<script lang="ts">
  import type { ReactionType } from "$lib/type";
  import Add from "$lib/components/community/reactions/Add.svelte";
  import Reaction from "$lib/components/community/reactions/Reaction.svelte";
  import { userStore } from "$lib/stores/use-user";
  import UserIsLogged from "$lib/components/UserIsLogged.svelte";


  export let reactions: ReactionType[] = [];
  export let gallery_id: string;

  const groupReactionsByEmoji = (reactions: ReactionType[]) => {
    const grouped = new Set(reactions.map((reaction) => reaction.emoji));
    return Array.from(grouped).map((emoji) => {
      return {
        emoji,
        count: reactions.filter((reaction) => reaction.emoji === emoji).length,
        liked: !!reactions.find((reaction) => reaction.emoji === emoji && reaction.userId === $userStore?.sub)
      };
    });
  };

  $: groupedReactions = groupReactionsByEmoji(reactions);
</script>

<UserIsLogged>
  <div class="flex items-center justify-start gap-2 max-w-max">
    {#each groupedReactions as reaction}
      <Reaction
        emoji={reaction.emoji}
        count={reaction?.count}
        liked={reaction?.liked}
        {gallery_id}
        onReact={(emoji, id, deleted) => {
          if (deleted) {
            reactions = reactions.filter((reaction) => reaction.id !== id);
          } else {
            reactions = [...reactions, { emoji, userId: $userStore?.sub, galleryId: gallery_id, id }];
          }
        }}
      />
    {/each}
    <Add
      count={groupedReactions?.length}
      reactions={groupedReactions}
      {gallery_id}
      onAdd={(emoji, id) => {
        reactions = [...reactions, { emoji, userId: $userStore?.sub, galleryId: gallery_id, id }];
      }}
    />
  </div>
</UserIsLogged>
