---
const { entryId } = Astro.props;
const backendHost = import.meta.env.PUBLIC_BACKEND_HOST;
---

<style is:global>
  .emoji-button {
    border: none;
    @apply text-lg rounded-full p-2;
  }

  .emoji-buttons-container {
    @apply flex flex-row flex-wrap gap-2;
  }
</style>

<form
  id="emoji-reaction-form"
  hx-post=`${backendHost}/api/blog/forms/emoji`
  hx-target="#reaction-buttons"
  hx-trigger="submit delay:0.5s">
  <input type="hidden" name="postId" value=`${entryId}` />
  <div
    id="reaction-buttons"
    hx-get=`${backendHost}/api/blog/forms/emoji?postId=${entryId}`
    hx-trigger="load"
    hx-swap="innerHTML">
    <div class="emoji-buttons-container">
      <button name="emojiInput" value="👍" type="submit" class="emoji-button">
        &nbsp;👍&nbsp;
      </button>
      <button name="emojiInput" value="👎" type="submit" class="emoji-button">
        &nbsp;👎&nbsp;
      </button>
      <button name="emojiInput" value="😀" type="submit" class="emoji-button">
        &nbsp;😀&nbsp;
      </button>
      <button name="emojiInput" value="😑" type="submit" class="emoji-button">
        &nbsp;😑&nbsp;
      </button>
      <button name="emojiInput" value="🤢" type="submit" class="emoji-button">
        &nbsp;🤢&nbsp;
      </button>
      <button name="emojiInput" value="👀" type="submit" class="emoji-button">
        &nbsp;👀&nbsp;
      </button>
    </div>
  </div>
  <div id="emoji-form-error-container" class="mt-4">
    <p id="emoji-form-error-text" class="text-red-600"></p>
  </div>
</form>

<script>
  function showError(errorString: string) {
    const errorTextElement = document.getElementById("emoji-form-error-text");

    if (errorTextElement) {
      errorTextElement.innerText = errorString;
    }

    setTimeout(() => {
      if (errorTextElement) {
        errorTextElement.innerText = "";
      }
    }, 5000);
  }

  const formElement = document.getElementById("emoji-reaction-form");

  if (formElement) {
    formElement.addEventListener(
      "htmx:sendError" as keyof HTMLElementEventMap,
      (event) => {
        // @ts-ignore detail attribute is added by htmx
        if (event.detail.elt.id != "reaction-buttons") {
          showError(
            "Sunucuya ulaşılamadığı için tepkiniz kaydedilemedi, biraz bekledikten sonra tekrar deneyebilirsiniz."
          );
        }
      }
    );

    formElement.addEventListener(
      "htmx:responseError" as keyof HTMLElementEventMap,
      () => {
        showError(
          "Sunucudan kaynaklanan bir hatadan dolayı tepkiniz kaydedilemedi, biraz bekledikten sonra tekrar deneyebilirsiniz."
        );
      }
    );
  }
</script>
