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

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

  async function onsubmit(event) {
    event.preventDefault();
    disabled = true;
    try {
      await sendMessage(value);
      value = '';
    } 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();
      form?.requestSubmit?.();
    }
  }

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

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