<script>
  import { DateTime } from 'luxon';
  import { deleteMessage } from '$lib/apiServer';

  function scroll(message) {
    message.scrollIntoView();
  }

  let { id, at, body, renderedBody, editable = false } = $props();
  let deleteArmed = $state(false);
  let atFormatted = $derived(at.toLocaleString(DateTime.DATETIME_SHORT));

  function onDelete(event) {
    event.preventDefault();
    if (deleteArmed) {
      deleteArmed = false;
      deleteMessage(id);
    } else {
      deleteArmed = true;
    }
  }

  function onmouseleave() {
    deleteArmed = false;
  }
</script>

<div class="message" class:delete-armed={deleteArmed} role="article" data-at={at} {onmouseleave}>
  <div class="handle">
    {atFormatted}
    {#if editable}
      <button onclick={onDelete}>&#x1F5D1;&#xFE0F;</button>
    {/if}
  </div>
  <section use:scroll class="message-body">
    <!-- eslint-disable-next-line svelte/no-at-html-tags -->
    {@html renderedBody}
  </section>
</div>
