class ChatWidget {
  constructor() {
    this.fab = document.getElementById('chatFab');
    this.popup = document.getElementById('chatPopup');
    if (!this.fab || !this.popup) return;
    this.close = document.getElementById('chatClose');
    this.body = document.getElementById('chatPopupBody');
    this.input = document.getElementById('chatPopupInput');
    this.send = document.getElementById('chatPopupSend');
    this.fab.addEventListener('click', () => this.popup.classList.toggle('open'));
    if (this.close) this.close.addEventListener('click', () => this.popup.classList.remove('open'));
    if (this.send) this.send.addEventListener('click', () => this.sendMsg());
    if (this.input) this.input.addEventListener('keydown', e => {
      if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.sendMsg(); }
    });
  }

  escapeHtml(t) {
    const d = document.createElement('div');
    d.textContent = t;
    return d.innerHTML;
  }

  async sendMsg() {
    const msg = this.input.value.trim();
    if (!msg) return;
    this.input.value = '';
    this.body.innerHTML += '<div class="chat-msg user"><div class="msg-body" dir="auto">' + this.escapeHtml(msg) + '</div></div>';
    this.body.scrollTop = this.body.scrollHeight;
    const loadingId = 'popup-loading-' + Date.now();
    this.body.innerHTML += '<div class="chat-msg ai" id="' + loadingId + '"><div class="chat-loading"><span></span><span></span><span></span></div></div>';
    this.body.scrollTop = this.body.scrollHeight;
    try {
      const res = await fetch((window.API_BASE || '/api.php') + '?route=/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: msg })
      });
      const data = await res.json();
      document.getElementById(loadingId).outerHTML = '<div class="chat-msg ai"><div class="msg-label">Peak AI</div><div class="msg-body" dir="auto">' + this.escapeHtml(data.reply || data.error) + '</div></div>';
    } catch (e) {
      document.getElementById(loadingId).outerHTML = '<div class="chat-msg ai"><div class="msg-label">Peak AI</div><div class="msg-body" style="color:#f87171;">Connection error.</div></div>';
    }
    this.body.scrollTop = this.body.scrollHeight;
  }
}
