<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 { get } from 'svelte/store';
  import { userStore } from "$lib/stores/use-user";

  let user = get(userStore);

  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.hf_user_id === user?.sub)
      };
    });
  };

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

{#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, hf_user_id: user?.sub, galleryId: gallery_id, id }];
      }
    }}
  />
{/each}
<Add
  count={groupedReactions?.length}
  reactions={groupedReactions}
  {gallery_id}
  onAdd={(emoji, id) => {
    reactions = [...reactions, { emoji, hf_user_id: user?.sub, galleryId: gallery_id, id }];
  }}
/>
