<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 relative"
    class:bg-warning-800={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>

<style>
  .message .handle {
    display: none;
  }
  .message:hover .handle {
    display: flex;
  }
  .message-body {
    overflow: auto;
    max-width: 80vw;
    @media (width > 640px) {
      /* 21rem is width of the nav bar in full-screen mode. */
      max-width: calc(90vw - 21rem);
    }
  }
  .message-body:empty:after {
    content: '.';
    visibility: hidden;
  }
  /* Without the global selector, the Svelte CSS compiler will see this as
   * unused, and purge it from the output. However, this is "plausibly used"
   * because it may occur in renderedBody.
   */
  :global(.message-body blockquote) {
    border-left: 0.25rem solid lightgrey;
    margin-left: 0.5rem;
    padding-left: 0.5rem;
  }
  :global(.message-body pre) {
    border: 1px solid #312e81;
    border-radius: 0.25rem;
    background-color: #282555;;
    padding: 0.25rem;
  }
</style>
