jQuery(document).ready(function($) {
  const chatBox = $('#rem-ai-chatbox');
  const chatLauncher = $('#rem-ai-chat-launcher');
  const chatClose = $('#rem-chat-close');
  const chatMessages = $('#rem-chat-messages');
  const chatInput = $('#rem-chat-text');
  const chatTyping = $('.rem-chat-status-typing');
  const chatStatus = $('.rem-chat-status-text');
  chatTyping.hide();

  // === Load previous chat history ===
  $.ajax({
    url: remAIChat.ajaxurl,
    method: 'POST',
    data: { action: 'rem_ai_chat_history' },
    success: function(response) {
      if (response.success && $.isArray(response.data) && response.data.length > 0) {
        $.each(response.data, function(index, turn) {
          const userTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
          chatMessages.append(
            '<div class="user-msg">' + turn.user + '<div class="msg-time">' + userTime + '</div></div>'
          );

          const aiTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
          chatMessages.append(
            '<div class="ai-msg">' + turn.ai + '<div class="msg-time">' + aiTime + '</div></div>'
          );
        });
        chatMessages.scrollTop(chatMessages[0].scrollHeight);
      }
    }
  });

  // Open chat
  chatLauncher.on('click', function() {
    chatBox.addClass('rem-chat-visible');
    if($('#user-local-time').is(':empty')){
      let date = new Date();
      let timeString = date.toLocaleString([], {
        hour: '2-digit',
        minute: '2-digit',
        hour12: true
      });
      $('#user-local-time').text(timeString);
    }
    $(this).hide();
    $('#rem-chat-text').focus();
  });

  // Close chat
  chatClose.on('click', function() {
    chatBox.removeClass('rem-chat-visible');
    chatLauncher.show();
  });

  // Send message
  $('#rem-chat-send').on('click', function() {
    sendMessage();
  });

  // Press Enter to send
  chatInput.on('keypress', function(e) {
    if (e.which === 13 && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  });

  function sendMessage() {
    chatTyping.show();
    chatStatus.hide();

    const msg = chatInput.val().trim();
    if (!msg) return;

    const now = new Date();
    const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });

    chatMessages.append(
      '<div class="user-msg">' + msg + '<div class="msg-time">' + timeString + '</div></div>'
    );

    chatInput.val('');
    chatMessages.scrollTop(chatMessages[0].scrollHeight);

    $.post(remAIChat.ajaxurl, { action: 'rem_ai_chat', message: msg }, function(res) {
      const aiTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
      chatMessages.append(
        '<div class="ai-msg">' + res + '<div class="msg-time">' + aiTime + '</div></div>'
      );
      chatMessages.scrollTop(chatMessages[0].scrollHeight);
      chatStatus.show();
      chatTyping.hide();      
    }).fail(function() {
      const failTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
      chatMessages.append(
        '<div class="ai-msg">Sorry, something went wrong. Please try again.<div class="msg-time">' + failTime + '</div></div>'
      );
      chatStatus.show();
      chatTyping.hide();
    });
  }

});
