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

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

  let { id, at, body, renderedBody, editable = false } = $props();
  let deleteArmed = $state(false);

  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} {onmouseleave} role="article">
  <div class="handle chip bg-surface-700 absolute -top-6 right-0">
    {at}
    {#if editable}
      <button onclick={onDelete}>&#x1F5D1;&#xFE0F;</button>
    {/if}
  </div>
  <section use:scroll class="py-1 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;
  }
</style>
