(function() {
  const chatLog = document.getElementById('chat-log');
  const chatForm = document.getElementById('chat-form');
  const chatInput = document.getElementById('chat-input');
  const chatSend = document.getElementById('chat-send');
  const sendText = document.querySelector('.ai-chat__send-text');

  const welcomeText = getText('ai-welcome');
  const waitingText = getText('ai-waiting');
  const errorText = getText('ai-error');
  const placeholderText = getText('ai-placeholder');
  const sendingText = getText('ai-sending');
  const labelUser = getText('ai-label-user') || 'You';
  const labelSystem = getText('ai-label-system') || 'Assistant';
  const sendLabel = sendText ? sendText.textContent : '';

  if (placeholderText) {
    chatInput.setAttribute('placeholder', placeholderText);
  }

  const pageSessionId = document.body.getAttribute('data-session-id');
  let sessionId = pageSessionId || getStoredSession();

  addMessage('system', welcomeText);

  chatForm.addEventListener('submit', function(event) {
    event.preventDefault();
    submitPrompt();
  });

  chatInput.addEventListener('keydown', function(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      submitPrompt();
    }
  });

  function submitPrompt() {
    const prompt = chatInput.value.trim();
    if (!prompt || chatSend.disabled) {
      return;
    }

    addMessage('user', prompt);
    chatInput.value = '';
    setPending(true);

    const pendingNode = addMessage('system', waitingText, true);

    const payload = new URLSearchParams({
      prompt,
      sessionId: sessionId || ''
    });

    fetch('/app/api/ai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: payload
    })
    .then(response => response.json())
    .then(data => {
      if (data && data.success && data.resource) {
        sessionId = data.resource.sessionId || sessionId;
        if (!pageSessionId) {
          storeSession(sessionId);
        }
        const replyText = data.resource.text || errorText;
        updatePending(pendingNode, replyText, false);
      } else {
        updatePending(pendingNode, data && data.message ? data.message : errorText, false);
      }
    })
    .catch(err => {
      const message = errorText ? errorText : 'Request failed.';
      updatePending(pendingNode, message + ' ' + err.message, false);
    })
    .finally(() => {
      setPending(false);
    });
  }

  function addMessage(role, text, isPending) {
    if (!text) {
      return null;
    }

    const bubble = document.createElement('div');
    bubble.classList.add('ai-chat__message');
    if (role === 'user') {
      bubble.classList.add('ai-chat__message--user', 'text-bg-primary');
    } else {
      bubble.classList.add('ai-chat__message--system', 'bg-secondary', 'text-body', 'border');
    }

    if (isPending) {
      bubble.classList.add('ai-chat__message--pending');
    }

    const label = document.createElement('div');
    label.classList.add('ai-chat__label');
    label.textContent = role === 'user' ? labelUser : labelSystem;

    const content = document.createElement('p');
    content.textContent = text;

    bubble.appendChild(label);
    bubble.appendChild(content);
    chatLog.appendChild(bubble);
    scrollToBottom();
    return bubble;
  }

  function updatePending(node, text, keepPending) {
    if (!node) {
      return;
    }
    node.classList.remove('ai-chat__message--pending');
    if (keepPending === true) {
      node.classList.add('ai-chat__message--pending');
    }
    const content = node.querySelector('p');
    if (content) {
      content.textContent = text;
    }
    scrollToBottom();
  }

  function setPending(isPending) {
    chatSend.disabled = isPending;
    chatInput.disabled = isPending;
    chatSend.classList.toggle('is-loading', isPending);
    if (sendText) {
      sendText.textContent = isPending ? (sendingText || sendLabel) : sendLabel;
    }
  }

  function scrollToBottom() {
    chatLog.scrollTop = chatLog.scrollHeight;
  }

  function getText(id) {
    const el = document.getElementById(id);
    return el ? el.textContent.trim() : '';
  }

  function getStoredSession() {
    try {
      return window.localStorage.getItem('aiChatSession');
    } catch (e) {
      return '';
    }
  }

  function storeSession(id) {
    if (!id) {
      return;
    }
    try {
      window.localStorage.setItem('aiChatSession', id);
    } catch (e) {
      return;
    }
  }
})();
