{% if IsLogin %}
  {% if IsSubscribed or not IsLimiteReached %}
    <div class="chat-input-container mb-5">
      <div class="textarea-wrapper">
        <div class="control" id="textarea-control">
          <textarea {% if not IsLogin or not HaveKey %}disabled{% endif %}
                    class="textarea has-fixed-size"
                    placeholder="Type your message here..."
                    name="message"
                    oninput="toggleSendButton()"
                    id="chat-input-textarea"></textarea>
        </div>
        <div class="button-group">
          <hx hx-get="/loadSettings" hx-trigger="load" hx-swap="outerHTML" hx-target="this"></hx>
          <hx hx-get="/loadUsageKPI" hx-trigger="load" hx-swap="outerHTML" hx-target="this"></hx>
          <hx hx-get="/loadConversationSelection" hx-trigger="load" hx-swap="outerHTML" hx-target="this"></hx>
          <hx hx-get="/loadModelSelection" hx-trigger="load" hx-swap="outerHTML" hx-target="this"></hx>
          <button disabled
                  type="submit"
                  class="send-button button is-primary is-small"
                  hx-post="/generatePlaceholder"
                  hx-swap="beforeend"
                  hx-target="#chat-messages"
                  id="chat-input-send-btn"
                  class="chat-input"
                  hx-include="[name='message']"
                  hx-vals="js:{selectedLLMIds: getSelectedModelsIDs()}"
                  onclick="onClickSendButton()">
            <span class="icon">
              <i class="fa-solid fa-chevron-right"></i>
            </span>
          </button>
        </div>
      </div>
    </div>
  {% endif %}
{% endif %}

<script>
  var textareaControl = document.getElementById('textarea-control');

  // Every 0.01s check if the text area have htmx-request class, if yes, add the class is-loading
  setInterval(function () {
    if (textareaControl === null) {
      return;
    }
    if (textareaControl.classList.contains('htmx-request')) {
      textareaControl.classList.add('is-loading');
    } else {
      textareaControl.classList.remove('is-loading');
    }
    toggleSendButton();
  }, 10);

  function updateIcons() {
    if (window.innerWidth < 450) {
      var elements = document.getElementsByClassName('message-icon');
      for (var i = 0; i < elements.length; i++) {
        elements[i].classList.remove('is-48x48');
        elements[i].classList.add('is-32x32');
        elements[i].parentElement.style = "padding-right: 0;";
      }
    } else {
      var elements = document.getElementsByClassName('message-icon');
      for (var i = 0; i < elements.length; i++) {
        elements[i].classList.remove('is-32x32');
        elements[i].classList.add('is-48x48');
        elements[i].parentElement.style = "";
      }
    }
  }

  // Run when the element is added
  document.addEventListener('htmx:afterSwap', updateIcons);

  // Run every 0.01s
  setInterval(updateIcons, 100);

  document.getElementById('chat-input-textarea').addEventListener('focus', function () {
    var buttons = document.getElementsByClassName('to-reduce-opacity');
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].style.opacity = 0.2;
    }
  });

  document.getElementById('chat-input-textarea').addEventListener('blur', function () {
    var buttons = document.getElementsByClassName('to-reduce-opacity');
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].style.opacity = 1;
    }
  });

  const textarea = document.querySelector('#chat-input-textarea');
  textarea.addEventListener('keydown', handleTextareaKeydown);

  document.addEventListener('htmx:afterSwap', toggleSendButton)

  function toggleSendButton() {
    // check if generate-multiple-messages exists 
    var generateMultipleMessages = document.getElementById('generate-multiple-messages');
    document.getElementById('chat-input-send-btn').disabled = textarea.value.trim().length === 0 || document.getElementsByClassName('selected icon-llm').length === 0 || generateMultipleMessages !== null;
    // Do the same for all element with an id that start with redo-button- or edit-button-
    const buttons = document.querySelectorAll('[id^="redo-button-"], [id^="edit-button-"]');
    if (document.getElementsByClassName('selected icon-llm').length === 0 || generateMultipleMessages !== null) {
      buttons.forEach(button => button.classList.add('is-static'));
    } else {
      buttons.forEach(button => button.classList.remove('is-static'));
    }
  }

  function generatePlaceholder() {
    return `
<div class="message-user mt-3 message-placeholder wasm-placeholder">
    <div class="columns is-mobile">
        <div class="column is-narrow" id="icon-column">
            <figure class="image is-48x48 message-icon" style="flex-shrink: 0;">
                <img src="icons/bouvai2.png" alt="User Image">
            </figure>
        </div>
        <div class="column" id="content-column" style="width: 100px;">
            <div class="is-flex is-align-items-start">
                <div class="message-content" style="width: 100%%; overflow-y: hidden;">
                    <div class="message-header">
                        <p>You</p>
                    </div>
                    <div class="message-body">
                        <div class="content" style="overflow-x: auto; width: 100%%;">
                          <p>Rendering...</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="is-flex is-justify-content mt-2">
                <div style="height: 30px;"></div>
            </div>
        </div>
    </div>
</div>
<div class="message-bot mt-3 message-placeholder">
    <div class="columns is-mobile">
        <div class="column is-narrow" id="icon-column">
            <figure class="image is-48x48 message-icon" style="flex-shrink: 0;">
                <img src="icons/bouvai2.png" alt="User Image">
            </figure>
        </div>
        <div class="column" id="content-column" style="width: 100px;">
            <div class="is-flex is-align-items-start">
                <div class="message-content">
                    <div class='message-header'>
                        <p>Waiting...</p>
                    </div>
                    <div class="message-body">
                        <div class="content">
                            <br>
                            <img src="/puff.svg" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="is-flex is-justify-content mt-2">
                <div style="height: 30px;"></div>
            </div>
        </div>
    </div>
</div>
`
  }

  function onClickSendButton() {
    // TODO: Add the message placeholder using WASM
    messagesPlaceholderHTML = generatePlaceholder(textarea.value);
    document.getElementById('chat-messages').insertAdjacentHTML('beforeend', messagesPlaceholderHTML);

    setTimeout(function () {
      textarea.value = '';
      toggleSendButton();
    }, 20);
  }

  function updateIcon(icon, ConversationAreaId) {
    var selectedIcon = document.getElementById('selectedIcon-' + ConversationAreaId);
    selectedIcon.src = icon;
  }

  function handleTextareaKeydown(event) {
    if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && event.target === textarea && textarea.value.trim() !== '' && document.getElementsByClassName('selected icon-llm').length !== 0) {
      // Check if the cursor is in the textarea
      // Trigger the same action as the send button
      document.getElementById('chat-input-send-btn').click();
    }
  }
</script>
