(function ($, Drupal, once, drupalSettings) {
  Drupal.behaviors.apiMonitorAiChat = {
    attach: function (context, settings) {
      // Add a delayed second message with options when the chat starts.
      $(once('ai-chat-init', '#chat-display', context)).each(function() {
        const $chatBox = $(this);
        setTimeout(function() {
          const secondMsg = `
            <div class="ai-msg initial">
              <strong>AI:</strong> Posso aiutarti a:
              <ul style="list-style: none; padding-left: 0; margin-top: 10px;">
                <li style="margin-bottom: 8px;">🔌 Eseguire un test dell'endpoint e fornire informazioni utili</li>
                <li>💻 Generare uno snippet per l'integrazione dell'endpoint con il linguaggio a te necessario</li>
              </ul>
            </div>`;
          $chatBox.append(secondMsg);
          $chatBox.scrollTop($chatBox[0].scrollHeight);
        }, 1500); // 1.5 seconds delay
      });

      $(once('ai-chat', '#send-question', context)).on('click', function () {
        const $btn = $(this);
        const $wrapper = $btn.closest('.api-monitor-ai-wrapper');
        const $question = $('#question-input');
        const $chatBox = $wrapper.find('#chat-display');
        const apiId = $wrapper.data('api-id');
        const providerId = $wrapper.data('provider-id');
        let questionUser = $question.val();

        if (!questionUser) {
          $btn.prop('disabled', true).text('Errore 001: Communication problem');
          return;
        }

        $btn.prop('disabled', true).text('L\'IA he\'s thinking...');
        $chatBox.append(`<div class="user-msg"><strong>Tu:</strong> ${questionUser}</div>`);
        $chatBox.append(`<div class="ai-msg loading"><em>L'AI sta scrivendo...</em></div>`);

        $.ajax({
          url: Drupal.url('admin/config/api-monitor/ai-assistant/ask'),
          type: 'POST',
          contentType: 'application/json',
          dataType: 'json',
          data: JSON.stringify({
            question: questionUser,
            api_id: apiId,
            provider_id: providerId
          }),
          success: function (response) {
            $question.val('');
            $('.loading').remove();
            $chatBox.append(`<div class="ai-msg"><strong>AI:</strong> ${response.answer}</div>`);
          },
          error: function (xhr) {
            $('.loading').remove();
            let errorMsg = 'Impossibile ottenere una risposta dall\'assistente.';
            if (xhr.responseJSON && xhr.responseJSON.answer) {
              errorMsg = xhr.responseJSON.answer;
            }
            $chatBox.append(`<div class="ai-msg error"><strong>Errore:</strong> ${errorMsg}</div>`);
            console.error('AJAX Error:', xhr);
          },
          complete: function () {
            $btn.prop('disabled', false).text('Invia domanda');
            // Scroll to bottom.
            $chatBox.scrollTop($chatBox[0].scrollHeight);
          }
        });
      });
    }
  };
})(jQuery, Drupal, once, drupalSettings);
