// Written by retoor@molodetz.nl

// This JavaScript class defines a custom HTML element for a chat input widget, featuring a text area and an upload button. It handles user input and triggers events for input changes and message submission.

// Includes standard DOM manipulation methods; no external imports used.

// MIT License: This code is open-source and can be reused and distributed under the terms of the MIT License.

class ChatInputElement extends HTMLElement {
  _chatWindow = null 
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.component = document.createElement('div');
    this.shadowRoot.appendChild(this.component);
  }
  set chatWindow(value){
    this._chatWindow = value 

  }
  get chatWindow(){
    return this._chatWindow 
  }
  get channelUid() {
    return this.chatWindow.channel.uid
  }
  connectedCallback() {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = '/base.css';
    this.component.appendChild(link);

    this.container = document.createElement('div');
    this.container.classList.add('chat-input');
    this.container.innerHTML = `
      <textarea placeholder="Type a message..." rows="2"></textarea>
      <upload-button></upload-button>
    `;
    this.textBox = this.container.querySelector('textarea');
    this.uploadButton = this.container.querySelector('upload-button');
    this.uploadButton.chatInput = this 
    this.textBox.addEventListener('input', (e) => {
      this.dispatchEvent(new CustomEvent('input', { detail: e.target.value, bubbles: true }));
      const message = e.target.value;
      const button = this.container.querySelector('button');
      button.disabled = !message;
    });

    this.textBox.addEventListener('change', (e) => {
      e.preventDefault();
      this.dispatchEvent(new CustomEvent('change', { detail: e.target.value, bubbles: true }));
      console.error(e.target.value);
    });

    this.textBox.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        const message = e.target.value.trim();
        if (!message) return;
        this.dispatchEvent(new CustomEvent('submit', { detail: message, bubbles: true }));
        e.target.value = '';
      }
    });

    this.component.appendChild(this.container);
  }
}

customElements.define('chat-input', ChatInputElement);
