class STTButton extends HTMLElement {
  static get observedAttributes() { return ['target']; }

  simulateTypingWithEvents(element, text, delay = 100) {
    let resolver = null;
    const promise = new Promise((resolve) => resolver = resolve);
    let index = 0;

    const triggerEvent = (type, key) => {
      const event = new KeyboardEvent(type, {
        key: key,
        bubbles: true,
        cancelable: true,
      });
      element.dispatchEvent(event);
    };

    const interval = setInterval(() => {
      if (index < text.length) {
        const char = text.charAt(index);

        triggerEvent('keydown', char);

        if (element.isContentEditable) {
          document.execCommand('insertText', false, char);
        } else {
          element.value += char;
        }

        triggerEvent('keypress', char);
        triggerEvent('keyup', char);
        index++;
      } else {
        clearInterval(interval);
        resolver();
      }
    }, delay);

    return promise;
  }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });

    const btn = document.createElement('button');
    btn.setAttribute('part', 'button');
    btn.setAttribute('aria-label', 'Start voice dictation');
    btn.innerHTML = '🎤';

    const style = document.createElement('style');
    style.textContent = `
      :host          { display:inline-block; }
      button         { all:unset; cursor:pointer; }
      button:hover   { background:#e8e8e8; }
      :host([listening]) button {
        background:#d32f2f; color:#fff;
        animation:pulse 1.2s ease-in-out infinite; }
      @keyframes pulse {
        0%,100% { transform:scale(1);   box-shadow:0 0 0 0 rgba(211,47,47,.6);}
        50%     { transform:scale(1.12);box-shadow:0 0 0 12px rgba(211,47,47,0);}
      }
    `;
    this.shadowRoot.append(style, btn);

    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) {
      console.warn('Web Speech API not supported in this browser.');
      return;
    }

    this.recog = new SR();
    this.recog.lang = 'en-US';
    this.recog.continuous = true;
    this.recog.interimResults = true;

    let interim = '';
    let committed = '';
    let previousInterim = '';

    this.recog.onresult = (e) => {
      interim = '';
      for (let i = e.resultIndex; i < e.results.length; i++) {
        const res = e.results[i];
        const alt = res[0];
        const txt = alt.transcript.trim();

        if (res.isFinal) {
          const sentence = txt.charAt(0).toUpperCase() + txt.slice(1);
          let punctuated = /[.!?]$/.test(sentence) ? sentence : sentence + '.';

          committed += punctuated + ' ';
          if (this.targetEl) {
            this.targetEl.focus();
            punctuated = punctuated.replace(/\./g, ".\n")
                                   .replace(/\?/g, "?\n")
                                   .replace(/\!/g, "!\n");

              this.targetEl.value = punctuated; // punctuated;
          this.simulateTypingWithEvents(this.targetEl, ' ', 0).then(() => {
              const chatInput = document.querySelector('chat-input');
              chatInput.finalizeMessage();
            });
          }

          previousInterim = '';
        } else {
          if (alt.confidence >= 0.85) {
            interim += txt + ' ';
          }
        }
      }

      if (interim && this.targetEl) {
        const el = this.targetEl;
        el.focus();

        if (el.isContentEditable) {
          el.innerText = el.innerText.replace(new RegExp(previousInterim + '$'), '');
        } else {
          el.value = interim
            //  el.value = interim
          //el.value = el.value.replace(new RegExp(previousInterim + '$'), interim);
        }
        document.querySelector('chat-input').sendMessage(interim); 
        this.simulateTypingWithEvents(el, ' ', 0).then(() => {
            
        })
          // this.simulateTypingWithEvents(el, interim, 0).then(() => {
       //   previousInterim = interim;
       // });
      }
    };

    this.recog.onend = () => {
      if (this.listening) {
        try {
          this.recog.start();
        } catch (e) {
          console.warn('Failed to restart speech recognition:', e);
        }
      }
    };

    btn.addEventListener('click', () => this.toggle());
  }

  attributeChangedCallback(name, _, newVal) {}

  get targetEl() {
    return document.querySelector("textarea") || null;
  }

  connectedCallback() {}

  get listening() {
    return this.hasAttribute('listening');
  }
  set listening(val) {
    if (val) this.setAttribute('listening', '');
    else this.removeAttribute('listening');
  }

  toggle() {
    if (!this.recog) return;
    if (this.listening) {
      this.recog.stop();
      this.listening = false;
    } else {
      try {
        this.recog.start();
        this.listening = true;
      } catch (e) {
        console.warn('Error starting recognition:', e);
      }
    }
  }
}

customElements.define('stt-button', STTButton);

