<script lang="ts">
  import { browser } from '$app/environment';
	import Icon from "@iconify/svelte";
  import { REACTION_EMOJIS } from "$lib/utils";
	import UserIsLogged from '$lib/components/UserIsLogged.svelte';

  export let count: number;
  export let reactions: Array<{ emoji: string, count: number }> = [];
  export let gallery_id: string;
  export let onAdd: (emoji: string, id: string) => void;

  let isOpen: boolean = false;
  $: uuid = Math.random().toString(36).substring(7);

  const handleClick = (event: MouseEvent) => {
    const target = event.target as HTMLElement;
    const addReaction = document.getElementById(uuid);
    if (!addReaction) return;

    if (!addReaction.contains(target)) {
      isOpen = false;
    }
  }
  if (browser) {
    window.addEventListener("click", handleClick);
  }

  const handleReaction = async (emoji: string) => {
    await fetch(`/api/community/reaction`, {
      method: "POST",
      body: JSON.stringify({ emoji, gallery_id }),
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then(res => res.json())
    .then(data => {
      if (!data.delete) {
        onAdd(emoji, data.id)
      }
    })
  }

  $: AVAILABLE_EMOJIS = REACTION_EMOJIS.filter(e => !reactions.find(emj => emj.emoji === e));
</script>

<div
  id="{uuid}"  
  class="rounded-full text-sm text-white/80 hover:text-white font-bold flex items-center justify-start gap-1.5 px-1.5 py-1 border border-dashed border-white/80 hover:border-white relative z-[2]"
  class:!border-white={isOpen}
  class:!text-white={isOpen}
  class:opacity-0={count >= 4}
>
  <button on:click={() => isOpen = !isOpen}>
    <Icon icon="fluent:emoji-add-16-regular" class="w-5 h-5" />
  </button>
  <div
    class={`opacity-0 pointer-events-none absolute max-w-max flex items-center justify-center bg-white px-1 py-1 rounded-full gap-0 text-xl ${count > 0 ? "-translate-y-[calc(100%+8px)] -translate-x-1/2 left-0 top-0" : "right-0 translate-x-[calc(100%+8px)]"}`}
    class:opacity-100={isOpen}
    class:pointer-events-auto={isOpen}
  >
    {#each AVAILABLE_EMOJIS as emoji}
      <UserIsLogged>
        <button
          class="w-8 h-8 hover:bg-neutral-200 rounded-full text-center flex items-center justify-center"
          on:click={() => handleReaction(emoji)}
        >
          {emoji}
        </button>
      </UserIsLogged>
    {/each}
  </div>
</div>