(function () {
  'use strict';

  const SESSION_KEY = 'aria_session_id';
  let sessionId = localStorage.getItem(SESSION_KEY) || '';
  let history = [];
  let isOpen = false;
  let isTyping = false;

  const GREETING = "Hi! I'm Aria, the Dealspace assistant. Ask me anything about how Dealspace works, pricing, or security.";

  function init() {
    // Launcher
    const launcher = document.createElement('div');
    launcher.id = 'aria-launcher';
    launcher.innerHTML = `
      <div id="aria-bubble">Chat with Aria</div>
      <button id="aria-btn" aria-label="Chat with Aria">
        <svg fill="none" viewBox="0 0 24 24" stroke="#0a1628" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-3 3-3-3z"/>
        </svg>
      </button>`;
    document.body.appendChild(launcher);

    // Chat window
    const win = document.createElement('div');
    win.id = 'aria-window';
    win.setAttribute('role', 'dialog');
    win.setAttribute('aria-label', 'Chat with Aria');
    win.innerHTML = `
      <div id="aria-header">
        <div id="aria-avatar">✨</div>
        <div id="aria-header-text">
          <div id="aria-header-name">Aria</div>
          <div id="aria-header-status">● Online</div>
        </div>
        <button id="aria-close" aria-label="Close chat">&times;</button>
      </div>
      <div id="aria-messages" role="log" aria-live="polite"></div>
      <div id="aria-compose">
        <textarea id="aria-input" rows="1" placeholder="Ask me anything..." aria-label="Message"></textarea>
        <button id="aria-send" aria-label="Send">
          <svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
          </svg>
        </button>
      </div>`;
    document.body.appendChild(win);

    document.getElementById('aria-btn').addEventListener('click', toggleChat);
    document.getElementById('aria-close').addEventListener('click', closeChat);
    document.getElementById('aria-send').addEventListener('click', sendMessage);
    document.getElementById('aria-input').addEventListener('keydown', function (e) {
      if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
      autoResize(this);
    });
    document.getElementById('aria-input').addEventListener('input', function () { autoResize(this); });
  }

  function autoResize(el) {
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 100) + 'px';
  }

  function toggleChat() {
    isOpen ? closeChat() : openChat();
  }

  function openChat() {
    isOpen = true;
    document.getElementById('aria-window').classList.add('open');
    document.getElementById('aria-input').focus();
    if (history.length === 0) {
      appendMessage('bot', GREETING);
    }
  }

  function closeChat() {
    isOpen = false;
    document.getElementById('aria-window').classList.remove('open');
  }

  function appendMessage(role, text) {
    const el = document.getElementById('aria-messages');
    const div = document.createElement('div');
    div.className = 'aria-msg ' + role;
    div.textContent = text;
    el.appendChild(div);
    el.scrollTop = el.scrollHeight;
    return div;
  }

  function showTyping() {
    const el = document.getElementById('aria-messages');
    const div = document.createElement('div');
    div.className = 'aria-typing';
    div.id = 'aria-typing-indicator';
    div.innerHTML = '<span></span><span></span><span></span>';
    el.appendChild(div);
    el.scrollTop = el.scrollHeight;
  }

  function hideTyping() {
    const el = document.getElementById('aria-typing-indicator');
    if (el) el.remove();
  }

  async function sendMessage() {
    if (isTyping) return;
    const input = document.getElementById('aria-input');
    const text = input.value.trim();
    if (!text) return;

    input.value = '';
    input.style.height = 'auto';
    appendMessage('user', text);
    history.push({ role: 'user', content: text });

    isTyping = true;
    document.getElementById('aria-send').disabled = true;
    showTyping();

    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ session_id: sessionId, message: text, history })
      });

      const data = await res.json();
      hideTyping();

      if (data.session_id) {
        sessionId = data.session_id;
        localStorage.setItem(SESSION_KEY, sessionId);
      }

      const reply = data.reply || "Sorry, I'm having trouble right now. Please try again.";
      appendMessage('bot', reply);
      history.push({ role: 'assistant', content: reply });

    } catch (e) {
      hideTyping();
      appendMessage('bot', "Something went wrong. Please try again in a moment.");
    } finally {
      isTyping = false;
      document.getElementById('aria-send').disabled = false;
      document.getElementById('aria-input').focus();
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
