<script>
  let { sendMessage = async (message) => {} } = $props();

  let value = $state('');
  let disabled = $state(false);

  async function onsubmit(event) {
    event.preventDefault();
    disabled = true;
    try {
      await sendMessage(value);
      event.target.closest('form')?.reset();
    } finally {
      disabled = false;
    }
  }

  function onkeydown(event) {
    if (disabled) {
      event.preventDefault();
      return;
    }

    let modifier = event.shiftKey || event.altKey || event.ctrlKey || event.metaKey;
    if (!modifier && event.key === 'Enter') {
      event.preventDefault();
      event.target.closest('form')?.requestSubmit();
    }
  }

  function onpaste(event) {
    if (disabled) {
      event.preventDefault();
    }
  }
</script>

<form {onsubmit}>
  <textarea bind:value class="hidden" {disabled}></textarea>
  <div
    contenteditable="plaintext-only"
    class={{
      textarea: true,
      disabled
    }}
    bind:innerText={value}
    {onkeydown}
    {onpaste}
    placeholder="Say something..."
  ></div>
  <button type="submit">&raquo;</button>
</form>
