jQuery(document).ready(function($) {

  var conversationsMap = {};
  var unansweredLoaded = false;

  window.MindwecoPagination.options.itemsPerPage = 100;
  window.MindwecoPagination.options.scrollOffset = 150;

  $('.datepicker').datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true,
    maxDate: 0,
    showAnim: 'fadeIn',
    showButtonPanel: true,
    beforeShow: function(input, inst) {
      setTimeout(function() {
        inst.dpDiv.css({
          marginTop: '5px'
        });
      }, 0);
    }
  });

  $('#start-date').on('change', function() {
    var startDate = $(this).datepicker('getDate');
    $('#end-date').datepicker('option', 'minDate', startDate);
    $(this).addClass('has-value');
  });

  $('#end-date').on('change', function() {
    var endDate = $(this).datepicker('getDate');
    $('#start-date').datepicker('option', 'maxDate', endDate);
    $(this).addClass('has-value');
    applyConversationDateFilter();
  });

  $(document).on('click', '.mindweco-conversations-wrap .mindweco-nav-tab', function(e) {
    e.preventDefault();

    var tab = $(this).data('tab');
    $('.mindweco-conversations-wrap .mindweco-nav-tab').removeClass('nav-tab-active');
    $(this).addClass('nav-tab-active');
    $('.mindweco-conversations-wrap .tab-content').hide();
    $('#tab-' + tab).show();

    if (tab === 'unanswered_questions' && !unansweredLoaded) {
      loadUnansweredQuestions($('#start-date').val(), $('#end-date').val());
    }
  });

  function applyConversationDateFilter() {
    var startDate = $('#start-date').val();
    var endDate = $('#end-date').val();
    if (!startDate || !endDate) {
      return;
    }

    var activeTab = $('.mindweco-conversations-wrap .nav-tab-active').data('tab');

    if (activeTab === 'unanswered_questions') {
      loadUnansweredQuestions(startDate, endDate);
    } else {
      unansweredLoaded = false;
    }

    loadConversationsByDate(startDate, endDate, activeTab === 'unanswered_questions');
  }

  $('#clear-filter').on('click', function() {
    $('#start-date, #end-date').val('').removeClass('has-value');
    window.MindwecoPagination.clearFilter('conversations-container');
    var activeTab = $('.mindweco-conversations-wrap .nav-tab-active').data('tab');

    if (activeTab === 'unanswered_questions') {
      loadUnansweredQuestions();
      loadTodayConversations();
    } else {
      unansweredLoaded = false;
      loadTodayConversations();
    }
    MindwecoToast.info('Filters cleared');
  });

  loadTodayConversations();

  $('.load-convs').on('click', function() {
    loadTodayConversations();
    loadUnansweredQuestions();
    $('#start-date, #end-date').val('').removeClass('has-value');
    $('#start-date, #end-date').datepicker('option', {
      minDate: null,
      maxDate: 0
    });
  });

  $('#close-modal').on('click', function() {
    $('#session-modal').fadeOut(300);
  });

  $('#close-conversation-modal').on('click', function() {
    $('#conversation-modal').fadeOut(300);
  });

  $(document).on('click', '#session-modal, #conversation-modal', function(e) {
    if (e.target.id === 'session-modal' || e.target.id === 'conversation-modal') {
      $(this).fadeOut(300);
    }
  });

  $(document).on('keyup', function(e) {
    if (e.key === 'Escape') {
      $('.modal-overlay').fadeOut(300);
    }
  });

  function escapeHtml(str) {
    if (str === null || str === undefined) return '';
    return String(str).replace(/[&<>"']/g, function(char) {
      return {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      } [char];
    });
  }

  function formatConversationDate(value) {
    if (!value) return 'N/A';
    var normalized = String(value);
    if (normalized.indexOf('T') === -1) {
      normalized = normalized.replace(' ', 'T') + 'Z';
    }
    var date = new Date(normalized);
    if (isNaN(date.getTime())) return 'N/A';
    return date.toLocaleString(undefined, {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }

  function loadConversationsByDate(startDate, endDate, silent) {
    $('#loading-spinner').addClass('active').show();
    $.ajax({
      url: mindwecoDataKnowledgeRepository.ajax_url,
      type: 'POST',
      data: {
        action: 'mindweco_get_conversations_by_date',
        nonce: mindwecoDataKnowledgeRepository.nonce,
        start_date: startDate,
        end_date: endDate
      },
      success: function(response) {
        $('#loading-spinner').removeClass('active').hide();
        if (response.success) {
          displayConversationsGrid(response.data.conversations, response.data.total || response.data.conversations.length);
          if (silent) {
            return;
          }
          if (response.data.conversations.length > 0) {
            MindwecoToast.success('Conversations loaded successfully');
          } else {
            MindwecoToast.warning('No conversations available for this date');
          }
        }
      },
      error: function() {
        $('#loading-spinner').removeClass('active').hide();
        MindwecoToast.error('Failed to load conversations');
      }
    });
  }

  function renderConversationTableRow(conv, $container) {
    conversationsMap[conv.id] = conv;

    var questionCount = parseInt(conv.total_questions, 10) || 0;
    var time = new Date((conv.created_at || '') + 'Z').toLocaleString(undefined, {
      year: 'numeric',
      month: 'short',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });

    var safeCookieId = escapeHtml(conv.cookie_id || 'Unknown Session');
    var safeIp = escapeHtml(conv.ip_address || '::1');
    var safePlatform = escapeHtml(conv.platform || 'Win32');
    var safeId = escapeHtml(conv.id || '');
    var safeQuestionLabel = questionCount === 1 ? '1 question' : questionCount + ' questions';

    if (!$container.find('.conversations-table').length) {
      $container.append(
        '<div class="conversations-table-wrap">' +
        '  <table class="conversations-table">' +
        '    <thead>' +
        '      <tr>' +
        '        <th>Date</th>' +
        '        <th>IP Address</th>' +
        '        <th>Platform</th>' +
        '        <th>Questions</th>' +
        '        <th>Download Conversation</th>' +
        '        <th>Actions</th>' +
        '      </tr>' +
        '    </thead>' +
        '    <tbody></tbody>' +
        '  </table>' +
        '</div>'
      );
    }

    var html = '';
    html += '<tr class="conversation-row">';
    html += '    <span class="session-icon" aria-hidden="true">';
    html += '      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
    html += '        <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path>';
    html += '        <circle cx="9" cy="7" r="4"></circle>';
    html += '        <path d="M22 21v-2a4 4 0 0 0-3-3.87"></path>';
    html += '        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>';
    html += '      </svg>';
    html += '    </span>';
    html += '    <span class="session-id">' + safeCookieId + '</span>';
    html += '  </td>';
    html += '  <td data-label="Date">' + escapeHtml(time) + '</td>';
    html += '  <td data-label="IP Address">' + safeIp + '</td>';
    html += '  <td data-label="Platform">' + safePlatform + '</td>';
    html += '  <td data-label="Questions"><span class="question-count">' + escapeHtml(safeQuestionLabel) + '</span></td>';
    html += '  <td data-label="Download Conversation">';
    html += '    <button type="button" class="table-action btn-download-chat " data-id="' + safeId + '">Download Conversation</button>';
    html += '  </td>';
    html += '  <td data-label="Actions">';
    html += '    <div class="conversation-table-actions">';
    html += '      <button type="button" class="table-action btn-view-conversation" data-id="' + safeId + '">See Chat</button>';
    html += '      <button type="button" class="table-action btn-view-details" data-id="' + safeId + '">Conversation Info</button>';
    html += '      <button type="button" class="btn-delete-conversation" data-id="' + safeId + '" title="Delete Conversation" aria-label="Delete Conversation">';
    html += '        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
    html += '          <polyline points="3 6 5 6 21 6"></polyline>';
    html += '          <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path>';
    html += '          <path d="M10 11v6"></path>';
    html += '          <path d="M14 11v6"></path>';
    html += '        </svg>';
    html += '      </button>';
    html += '    </div>';
    html += '  </td>';
    html += '</tr>';

    $container.find('.conversations-table tbody').append(html);
  }

  function displayConversationsGrid(conversations, total) {
    if (conversations.length === 0) {
      $('#conversations-results').html(
        '<div class="empty-state">' +
        '<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#d1d5db" stroke-width="1.5">' +
        '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>' +
        '</svg>' +
        '<h3>No Conversations Found</h3>' +
        '<p>No conversations found for this date range</p>' +
        '</div>'
      );
      return;
    }

    $('#conversations-results').html(
      '<div class="results-header">' +
      '<h3>Conversations <span class="results-count">' + total + '</span></h3>' +
      '</div>' +
      '<div id="conversations-container" class="conversations-table-container"></div>'
    );

    conversationsMap = {};
    if (window.MindwecoPagination && typeof window.MindwecoPagination.init === 'function') {
      window.MindwecoPagination.init('conversations-container', conversations, renderConversationTableRow);
    }
  }

  function renderUnansweredQuestionTableRow(question, $container) {
    var askedTime = question.created_at ?
      new Date(question.created_at.replace(' ', 'T') + 'Z').toLocaleString(undefined, {
        year: 'numeric',
        month: 'short',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      }) :
      'N/A';
    var safeConversationId = escapeHtml(question.conversation_id || '');
    var safeQuestion = escapeHtml(question.question_text || 'N/A');
    var safeIp = escapeHtml(question.ip_address || 'N/A');
    var safePlatform = escapeHtml(question.platform || 'N/A');

    if (!$container.find('.conversations-table').length) {
      $container.append(
        '<div class="conversations-table-wrap">' +
        '  <table class="conversations-table unanswered-table">' +
        '    <thead>' +
        '      <tr>' +
        '        <th>Asked</th>' +
        '        <th>Question</th>' +
        '        <th>IP Address</th>' +
        '        <th>Platform</th>' +
        '        <th>Actions</th>' +
        '      </tr>' +
        '    </thead>' +
        '    <tbody></tbody>' +
        '  </table>' +
        '</div>'
      );
    }

    var html = '';
    html += '<tr class="conversation-row">';
    html += '  <td data-label="Asked">' + escapeHtml(askedTime) + '</td>';
    html += '  <td class="question-cell" data-label="Question">' + safeQuestion + '</td>';
    html += '  <td data-label="IP Address">' + safeIp + '</td>';
    html += '  <td data-label="Platform">' + safePlatform + '</td>';
    html += '  <td data-label="Actions">';
    html += '    <div class="conversation-table-actions">';
    html += '      <button type="button" class="table-action btn-view-conversation" data-id="' + safeConversationId + '">See Chat</button>';
    html += '    </div>';
    html += '  </td>';
    html += '</tr>';

    $container.find('.conversations-table tbody').append(html);
  }

  function renderUnansweredQuestionsTable(questions, total) {
    if (!questions.length) {
      if (window.MindwecoPagination && typeof window.MindwecoPagination.destroy === 'function') {
        window.MindwecoPagination.destroy('unanswered-container');
      }
      $('#unanswered-results').html(
        '<div class="empty-state">' +
        '<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#d1d5db" stroke-width="1.5">' +
        '<path d="M20 6L9 17l-5-5"></path>' +
        '</svg>' +
        '<h3>No Unanswered Questions</h3>' +
        '<p>All recorded questions have responses.</p>' +
        '</div>'
      );
      return;
    }

    $('#unanswered-results').html(
      '<div class="results-header">' +
      '  <h3>Unanswered Questions <span class="results-count">' + total + '</span></h3>' +
      '</div>' +
      '<div id="unanswered-container" class="conversations-table-container"></div>'
    );

    if (window.MindwecoPagination && typeof window.MindwecoPagination.init === 'function') {
      window.MindwecoPagination.init('unanswered-container', questions, renderUnansweredQuestionTableRow);
    }
  }

  function loadUnansweredQuestions(startDate, endDate) {
    if (window.MindwecoPagination && typeof window.MindwecoPagination.destroy === 'function') {
      window.MindwecoPagination.destroy('unanswered-container');
    }

    $('#unanswered-results').html(
      '<div class="loading-state d-flex align-items-center justify-content-center">' +
      '<div class="spinner is-active"></div>' +
      '<p>Loading unanswered questions...</p>' +
      '</div>'
    );

    var requestData = {
      action: 'mindweco_get_unanswered_questions',
      nonce: mindwecoDataKnowledgeRepository.nonce
    };

    if (startDate && endDate) {
      requestData.start_date = startDate;
      requestData.end_date = endDate;
    }

    $.ajax({
      url: mindwecoDataKnowledgeRepository.ajax_url,
      type: 'POST',
      data: requestData,
      success: function(response) {
        if (response.success) {
          unansweredLoaded = true;
          renderUnansweredQuestionsTable(response.data.questions || [], response.data.total || 0);
        } else {
          unansweredLoaded = false;
          MindwecoToast.error(response.data || 'Failed to load unanswered questions');
        }
      },
      error: function() {
        unansweredLoaded = false;
        MindwecoToast.error('Failed to load unanswered questions');
        $('#unanswered-results').html(
          '<div class="error-state">' +
          '<h3>Error Loading Unanswered Questions</h3>' +
          '</div>'
        );
      }
    });
  }

  $(document).on('click', '.btn-view-conversation', function(e) {
    e.stopPropagation();
    loadConversationQA($(this).data('id'));
  });

  $(document).on('click', '.btn-download-chat', function(e) {
    e.stopPropagation();
    downloadConversationPdf($(this).data('id'));
  });

  $(document).on('click', '.btn-view-details', function(e) {
    e.stopPropagation();
    var conv = conversationsMap[$(this).data('id')];
    if (conv) {
      showSessionDetails(conv);
    } else {
      MindwecoToast.error('Unable to load conversation details');
    }
  });

  $(document).on('click', '.btn-delete-conversation', function(e) {
    e.stopPropagation();
    var convId = $(this).data('id');
    var $btn = $(this);
    MindwecoModal.confirm(
      'Delete Conversation',
      'Are you sure you want to delete this conversation? This action cannot be undone.',
      function() {
        deleteConversation(convId, $btn);
      },
      'Delete',
      'btn-danger'
    );
  });

  function deleteConversation(convId, $btn) {
    var originalHtml = $btn.html();
    $btn.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Deleting...');
    $.ajax({
      url: mindwecoDataKnowledgeRepository.ajax_url,
      type: 'POST',
      data: {
        action: 'mindweco_delete_conversation',
        nonce: mindwecoDataKnowledgeRepository.nonce,
        conversation_id: convId
      },
      success: function(response) {
        if (response.success) {
          delete conversationsMap[convId];
          $btn.closest('.conversation-row').fadeOut(300, function() {
            $(this).remove();
          });
          MindwecoToast.success('Conversation deleted successfully');
        } else {
          MindwecoToast.error(response.data || 'Failed to delete conversation');
          $btn.prop('disabled', false).html(originalHtml);
        }
      },
      error: function() {
        MindwecoToast.error('Failed to delete conversation. Please try again.');
        $btn.prop('disabled', false).html(originalHtml);
      }
    });
  }

  function downloadConversationPdf(convId) {
    if (!convId) {
      MindwecoToast.error('Unable to download conversation');
      return;
    }

    var url = mindwecoDataKnowledgeRepository.ajax_url +
      '?action=mindweco_download_conversation_pdf' +
      '&nonce=' + encodeURIComponent(mindwecoDataKnowledgeRepository.nonce) +
      '&conversation_id=' + encodeURIComponent(convId);

    window.location.href = url;
  }

  function loadTodayConversations() {
    $('#loading-spinner').addClass('active').show();
    $('#conversations-results').html(
      '<div class="loading-state d-flex align-items-center justify-content-center">' +
      '<div class="spinner is-active"></div>' +
      '<p>Loading today\'s conversations...</p>' +
      '</div>'
    );
    $.ajax({
      url: mindwecoDataKnowledgeRepository.ajax_url,
      type: 'POST',
      data: {
        action: 'mindweco_get_today_conversations',
        nonce: mindwecoDataKnowledgeRepository.nonce
      },
      success: function(response) {
        $('#loading-spinner').removeClass('active').hide();
        if (response.success && response.data.conversations.length > 0) {
          displayConversationsGrid(response.data.conversations, response.data.total);
        } else {
          $('#conversations-results').html(
            '<div class="empty-state">' +
            '<h3>No conversations today</h3>' +
            '<p>There are no conversations for today.</p>' +
            '</div>'
          );
        }
      },
      error: function() {
        $('#loading-spinner').removeClass('active').hide();
        MindwecoToast.error('Failed to load today\'s conversations');
        $('#conversations-results').html(
          '<div class="error-state">' +
          '<h3>Error Loading Today\'s Conversations</h3>' +
          '</div>'
        );
      }
    });
  }

  function loadConversationQA(convId) {
    $('#conversation-modal-content').html(
      '<div class="loading-state d-flex align-items-center justify-content-center">' +
      '<div class="spinner is-active"></div>' +
      '<p>Loading conversation...</p>' +
      '</div>'
    );
    $('#conversation-modal').fadeIn(300);
    $.ajax({
      url: mindwecoDataKnowledgeRepository.ajax_url,
      type: 'POST',
      data: {
        action: 'mindweco_get_conversations',
        nonce: mindwecoDataKnowledgeRepository.nonce,
        conversation_id: convId
      },
      success: function(response) {
        if (response.success && response.data && response.data.mode === 'messages' && response.data.messages.length > 0) {
          displayConversationMessages(response.data.messages, convId);
        } else if (response.success && response.data.length > 0) {
          displayConversationQA(response.data, convId);
        } else {
          $('#conversation-modal-content').html(
            '<div class="error-state">' +
            '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="1.5">' +
            '<circle cx="12" cy="12" r="10"></circle>' +
            '<line x1="15" y1="9" x2="9" y2="15"></line>' +
            '<line x1="9" y1="9" x2="15" y2="15"></line>' +
            '</svg>' +
            '<h3>No Messages Found</h3>' +
            '<p>No chat messages found for this conversation</p>' +
            '</div>'
          );
        }
      },
      error: function() {
        $('#conversation-modal-content').html(
          '<div class="error-state">' +
          '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="1.5">' +
          '<circle cx="12" cy="12" r="10"></circle>' +
          '<line x1="15" y1="9" x2="9" y2="15"></line>' +
          '<line x1="9" y1="9" x2="15" y2="15"></line>' +
          '</svg>' +
          '<h3>Error Loading Conversation</h3>' +
          '<p>Failed to load conversation. Please try again.</p>' +
          '</div>'
        );
      }
    });
  }

  function showSessionDetails(conv) {
    function renderInfoTable(rows) {
      var table = '<table class="conversation-info-table"><tbody>';
      rows.forEach(function(row) {
        table += '<tr>';
        table += '  <th scope="row">' + escapeHtml(row.label) + '</th>';
        table += '  <td>' + row.value + '</td>';
        table += '</tr>';
      });
      table += '</tbody></table>';
      return table;
    }

    var html = '';
    html += '<div class="info-section">';
    html += '  <div class="info-section-header">';
    html += '    <div class="info-section-icon">';
    html += '      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
    html += '        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>';
    html += '        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>';
    html += '      </svg>';
    html += '    </div>';
    html += '    <h3>Session Information</h3>';
    html += '  </div>';
    html += renderInfoTable([
      { label: 'Session ID', value: escapeHtml(conv.cookie_id || 'N/A') },
      { label: 'IP Address', value: escapeHtml(conv.ip_address || 'N/A') },
      { label: 'Screen Resolution', value: escapeHtml(conv.screen_resolution || 'N/A') },
      { label: 'Platform', value: escapeHtml(conv.platform || 'N/A') },
      { label: 'Timezone', value: escapeHtml(conv.timezone || 'N/A') },
      { label: 'Language', value: escapeHtml(conv.language_accepted || 'N/A') }
    ]);
    html += '</div>';
    html += '<div class="info-section">';
    html += '  <div class="info-section-header">';
    html += '    <div class="info-section-icon">';
    html += '      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
    html += '        <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>';
    html += '        <line x1="8" y1="21" x2="16" y2="21"></line>';
    html += '        <line x1="12" y1="17" x2="12" y2="21"></line>';
    html += '      </svg>';
    html += '    </div>';
    html += '    <h3>Browser & Device</h3>';
    html += '  </div>';
    html += renderInfoTable([
      { label: 'User Agent', value: escapeHtml(conv.user_agent || 'N/A') }
    ]);
    html += '</div>';
    html += '<div class="info-section">';
    html += '  <div class="info-section-header">';
    html += '    <div class="info-section-icon">';
    html += '      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
    html += '        <polyline points="9 18 15 12 9 6"></polyline>';
    html += '      </svg>';
    html += '    </div>';
    html += '    <h3>Navigation Details</h3>';
    html += '  </div>';
    html += renderInfoTable([
      { label: 'Referrer', value: escapeHtml(conv.referrer || 'N/A') }
    ]);
    html += '</div>';
    html += '<div class="info-section">';
    html += '  <div class="info-section-header">';
    html += '    <div class="info-section-icon">';
    html += '      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">';
    html += '        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>';
    html += '      </svg>';
    html += '    </div>';
    html += '    <h3>Conversation Statistics</h3>';
    html += '  </div>';
    html += renderInfoTable([
      { label: 'Total Questions', value: escapeHtml(parseInt(conv.total_questions, 10) || 0) },
      { label: 'First Question At', value: escapeHtml(conv.first_question_at ? new Date(conv.first_question_at + 'Z').toLocaleString() : 'N/A') },
      { label: 'Conversation Created', value: escapeHtml(conv.created_at ? new Date(conv.created_at + 'Z').toLocaleString() : 'N/A') }
    ]);
    html += '</div>';
  
    $('#modal-content').html(html);
    $('#session-modal .modal-title').html('Session #' + escapeHtml(conv.id || '') + ' - Complete Details');
    $('#session-modal').fadeIn(300);
    loadConversationInfoMessages(conv.id);
  }

  function loadConversationInfoMessages(convId) {
    if (!convId) {
      $('#conversation-info-messages').html('<div class="conversation-info-messages-empty">No messages found for this conversation.</div>');
      return;
    }

    $.ajax({
      url: mindwecoDataKnowledgeRepository.ajax_url,
      type: 'POST',
      data: {
        action: 'mindweco_get_conversations',
        nonce: mindwecoDataKnowledgeRepository.nonce,
        conversation_id: convId
      },
      success: function(response) {
        if (response.success && response.data && response.data.mode === 'messages' && response.data.messages.length > 0) {
          renderConversationInfoMessages(response.data.messages);
        } else if (response.success && response.data && response.data.length > 0) {
          renderConversationInfoMessages(flattenLocalConversationMessages(response.data));
        } else {
          $('#conversation-info-messages').html('<div class="conversation-info-messages-empty">No messages found for this conversation.</div>');
        }
      },
      error: function() {
        $('#conversation-info-messages').html('<div class="conversation-info-messages-empty">Unable to load messages.</div>');
      }
    });
  }

  function flattenLocalConversationMessages(questions) {
    var messages = [];
    questions.forEach(function(qa) {
      messages.push({
        role: 'user',
        kind: 'conversation_question',
        message: qa.question_text || '',
        timestamp: qa.created_at || ''
      });
      if (qa.response_text) {
        messages.push({
          role: 'bot',
          kind: 'conversation_answer',
          message: qa.response_text,
          timestamp: qa.response_at || qa.created_at || ''
        });
      }
    });
    return messages;
  }

  function renderConversationInfoMessages(messages) {
    var html = '';

    messages.forEach(function(message) {
      var role = message.role || 'bot';
      var label = role === 'operator' ? 'Operator' : (role === 'user' ? 'User' : 'Assistant');
      var className = role === 'operator' ? 'conversation-message-operator' : (role === 'user' ? 'conversation-message-question' : 'conversation-message-answer');
      var time = formatConversationDate(message.timestamp);

      html += '<section class="conversation-info-message conversation-message ' + className + '">';
      html += '  <div class="conversation-message-label">' + escapeHtml(label) + '</div>';
      html += '  <div class="conversation-message-text">' + escapeHtml(message.message || 'N/A') + '</div>';
      html += '  <div class="conversation-message-time">' + escapeHtml(time) + '</div>';
      html += '</section>';
    });

    $('#conversation-info-messages').html(html || '<div class="conversation-info-messages-empty">No messages found for this conversation.</div>');
  }

  function displayConversationQA(questions, convId) {
    var firstAsked = questions[0] && questions[0].created_at ?
      new Date(questions[0].created_at.replace(' ', 'T') + 'Z').toLocaleString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      }) :
      'N/A';
    var lastItem = questions[questions.length - 1] || {};
    var lastActivity = (lastItem.response_at || lastItem.created_at) ?
      new Date((lastItem.response_at || lastItem.created_at).replace(' ', 'T') + 'Z').toLocaleString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      }) :
      'N/A';

    var html = '';
    html += '<div class="conversation-detail-view">';
    html += '  <div class="conversation-detail-summary">';
    html += '    <div class="conversation-summary-main">';
    html += '      <span class="conversation-summary-kicker">Conversation Details</span>';
    html += '      <strong>Question and Answer History</strong>';
    html += '      <span class="conversation-summary-id">Reference: ' + escapeHtml(convId) + '</span>';
    html += '    </div>';
    html += '    <div class="conversation-summary-stats">';
    html += '      <div class="conversation-summary-stat"><span>Total Questions</span><strong>' + escapeHtml(String(questions.length)) + '</strong></div>';
    html += '      <div class="conversation-summary-stat"><span>First Question</span><strong>' + escapeHtml(firstAsked) + '</strong></div>';
    html += '      <div class="conversation-summary-stat"><span>Last Activity</span><strong>' + escapeHtml(lastActivity) + '</strong></div>';
    html += '    </div>';
    html += '  </div>';
    html += '  <div class="conversation-timeline">';

    questions.forEach(function(qa, index) {
      var askedTime = qa.created_at ?
        new Date(qa.created_at.replace(' ', 'T') + 'Z').toLocaleString(undefined, {
          month: 'short',
          day: 'numeric',
          year: 'numeric',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }) :
        'N/A';
      var answeredTime = qa.response_at ?
        new Date(qa.response_at.replace(' ', 'T') + 'Z').toLocaleString(undefined, {
          month: 'short',
          day: 'numeric',
          year: 'numeric',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }) :
        null;

      html += '<article class="conversation-entry">';
      html += '  <div class="conversation-entry-marker">' + escapeHtml(String(index + 1)) + '</div>';
      html += '  <div class="conversation-entry-content">';
      html += '    <div class="conversation-entry-meta">';
      html += '      <strong>Question & Answer ' + escapeHtml(String(index + 1)) + '</strong>';
      html += '      <span>Asked: ' + escapeHtml(askedTime) + '</span>';
      html += '    </div>';
      html += '    <section class="conversation-message conversation-message-question">';
      html += '      <div class="conversation-message-label">Question</div>';
      html += '      <div class="conversation-message-text">' + escapeHtml(qa.question_text || 'N/A') + '</div>';
      html += '    </section>';
      html += '    <section class="conversation-message conversation-message-answer">';
      html += '      <div class="conversation-message-label">Answer</div>';
      html += '      <div class="conversation-message-text">' + escapeHtml(qa.response_text || 'No response recorded.') + '</div>';
      if (answeredTime) {
        html += '      <div class="conversation-message-time">Answered: ' + escapeHtml(answeredTime) + '</div>';
      }
      html += '    </section>';
      html += '  </div>';
      html += '</article>';
    });
    html += '  </div>';
    html += '</div>';

    $('#conversation-modal-content').html(html);
    $('#conversation-modal .modal-title').html(
      'Conversation Details'
    );
  }

  function displayConversationMessages(messages, convId) {
    var firstTime = messages[0] && messages[0].timestamp ? formatConversationDate(messages[0].timestamp) : 'N/A';
    var lastItem = messages[messages.length - 1] || {};
    var lastActivity = lastItem.timestamp ? formatConversationDate(lastItem.timestamp) : 'N/A';

    var html = '';
    html += '<div class="conversation-detail-view">';
    html += '  <div class="conversation-detail-summary">';
    html += '    <div class="conversation-summary-main">';
    html += '      <span class="conversation-summary-kicker">Conversation Details</span>';
    html += '      <strong>Full Chat History</strong>';
    html += '      <span class="conversation-summary-id">Reference: ' + escapeHtml(convId) + '</span>';
    html += '    </div>';
    html += '    <div class="conversation-summary-stats">';
    html += '      <div class="conversation-summary-stat"><span>Total Messages</span><strong>' + escapeHtml(String(messages.length)) + '</strong></div>';
    html += '      <div class="conversation-summary-stat"><span>First Message</span><strong>' + escapeHtml(firstTime) + '</strong></div>';
    html += '      <div class="conversation-summary-stat"><span>Last Activity</span><strong>' + escapeHtml(lastActivity) + '</strong></div>';
    html += '    </div>';
    html += '  </div>';
    html += '  <div class="conversation-timeline">';

    messages.forEach(function(message, index) {
      var role = message.role || 'bot';
      var label = role === 'operator' ? 'Operator' : (role === 'user' ? 'User' : 'Assistant');
      var time = formatConversationDate(message.timestamp);
      var className = role === 'operator' ? 'conversation-message-operator' : (role === 'user' ? 'conversation-message-question' : 'conversation-message-answer');

      html += '<article class="conversation-entry">';
      html += '  <div class="conversation-entry-marker">' + escapeHtml(String(index + 1)) + '</div>';
      html += '  <div class="conversation-entry-content">';
      html += '    <div class="conversation-entry-meta">';
      html += '      <strong>' + escapeHtml(label + ' Message') + '</strong>';
      html += '      <span>' + escapeHtml(time) + '</span>';
      html += '    </div>';
      html += '    <section class="conversation-message ' + className + '">';
      html += '      <div class="conversation-message-label">' + escapeHtml(label) + '</div>';
      html += '      <div class="conversation-message-text">' + escapeHtml(message.message || 'N/A') + '</div>';
      if (message.kind) {
        html += '      <div class="conversation-message-time">Type: ' + escapeHtml(message.kind) + '</div>';
      }
      html += '    </section>';
      html += '  </div>';
      html += '</article>';
    });

    html += '  </div>';
    html += '</div>';

    $('#conversation-modal-content').html(html);
    $('#conversation-modal .modal-title').html('Conversation Details');
  }

  $(document).on('click', '.conversation-download-pdf', function(e) {
    e.preventDefault();
    downloadConversationPdf($(this).data('id'));
  });

});
