<div class="ab-card" style="height:70vh; display:flex; flex-direction:column;">
  <div class="ab-card-header">
    <h2><i class="bi bi-robot me-2 text-primary"></i>AI Assistant</h2>
    <select class="form-select form-select-sm" id="abAssistantBl" style="width:auto;">
      <option value="1">Homecare</option>
      <option value="2">Cleaner</option>
    </select>
  </div>
  <div class="ab-card-body flex-fill overflow-auto" id="abChatLog" style="background:var(--ab-canvas);">
    <div class="d-flex gap-2 mb-3">
      <div class="ab-mini-avatar"><i class="bi bi-robot"></i></div>
      <div class="ab-card p-2" style="max-width:70%; border:none;">
        Hi! I can search customers and leads, book appointments, generate reports, answer questions, and summarize conversations. What do you need?
      </div>
    </div>
  </div>
  <div class="ab-card-body border-top pt-3">
    <form id="abChatForm" class="d-flex gap-2">
      <input type="text" class="form-control" id="abChatInput" placeholder="Ask me anything..." autocomplete="off" required>
      <button type="submit" class="btn btn-primary"><i class="bi bi-send"></i></button>
    </form>
    <div class="form-text" id="abChatStatus"></div>
  </div>
</div>

<script>
(function () {
  var history = [];
  var conversationId = null;
  var log = document.getElementById('abChatLog');

  function appendMessage(role, text) {
    var isUser = role === 'user';
    var row = document.createElement('div');
    row.className = 'd-flex gap-2 mb-3' + (isUser ? ' flex-row-reverse' : '');
    row.innerHTML = '<div class="ab-mini-avatar">' + (isUser ? 'You' : '<i class="bi bi-robot"></i>') + '</div>' +
      '<div class="ab-card p-2" style="max-width:70%; border:none; ' + (isUser ? 'background:var(--ab-primary-100);' : '') + '">' + text.replace(/\n/g, '<br>') + '</div>';
    log.appendChild(row);
    log.scrollTop = log.scrollHeight;
  }

  document.getElementById('abChatForm').addEventListener('submit', function (e) {
    e.preventDefault();
    var input = document.getElementById('abChatInput');
    var message = input.value.trim();
    if (!message) return;

    appendMessage('user', message);
    input.value = '';
    document.getElementById('abChatStatus').textContent = 'Thinking…';

    abFetch('<?= base_url('ai-assistant/ask') ?>', {
      method: 'POST',
      body: {
        message: message,
        history: history,
        business_line_id: document.getElementById('abAssistantBl').value,
        conversation_id: conversationId
      }
    }).then(function (res) {
      appendMessage('assistant', res.data.reply);
      history.push({ role: 'user', content: message });
      history.push({ role: 'assistant', content: res.data.reply });
      conversationId = res.data.conversation_id;
      document.getElementById('abChatStatus').textContent = res.data.tool_calls_made.length
        ? 'Used: ' + res.data.tool_calls_made.map(function (t) { return t.name; }).join(', ')
        : '';
    }).catch(function (err) {
      appendMessage('assistant', err.message || 'Something went wrong.');
      document.getElementById('abChatStatus').textContent = '';
    });
  });
})();
</script>
