(function() {
  const widget = document.getElementById('chat-widget');
  const openBtn = document.getElementById('floating-open');
  const btnMax = document.getElementById('btn-max');
  const btnMin = document.getElementById('btn-min');
  const messagesEl = document.getElementById('messages');
  const input = document.getElementById('chat-input');
  const sendBtn = document.getElementById('send-btn');

  let conversationId = null;

  function appendMessage(role, content) {
    const div = document.createElement('div');
    div.className = 'msg ' + role;
    const b = document.createElement('div');
    b.className = 'bubble';
    b.textContent = content;
    div.appendChild(b);
    messagesEl.appendChild(div);
    messagesEl.scrollTop = messagesEl.scrollHeight;
  }

  async function sendMessage() {
    const text = input.value.trim();
    if (!text) return;
    appendMessage('user', text);
    input.value = '';

    try {
      const res = await fetch('api/send_message.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ conversation_id: conversationId, message: text })
      });
      const data = await res.json();
      if (data.ok) {
        conversationId = data.conversation_id;
        appendMessage('assistant', data.reply);
      } else {
        appendMessage('assistant', '⚠️ ' + (data.error || 'Unknown error'));
      }
    } catch (e) {
      appendMessage('assistant', '⚠️ Network error: ' + e.message);
    }
  }

  openBtn.addEventListener('click', ()=> {
    widget.classList.toggle('chat-closed');
  });
  btnMin.addEventListener('click', ()=> widget.classList.add('chat-closed'));
  btnMax.addEventListener('click', ()=> widget.classList.toggle('max'));
  sendBtn.addEventListener('click', sendMessage);
  input.addEventListener('keydown', (e)=> {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  });
})();