const messageInput = document.getElementById("message-input");
const sendBtn = document.getElementById("send-btn");
const messageList = document.getElementById("message-list");
const saveBtn = document.getElementById("save-btn");
const chatMessages = document.getElementById("chat-messages");

let lastMessageCount = 0;

// Send message
async function sendMessage() {
  const message = messageInput.value.trim();
  if (!message) return;

  try {
    const response = await fetch("/send", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message }),
    });

    if (response.ok) {
      messageInput.value = "";
      await fetchMessages();
    }
  } catch (err) {
    console.error("Failed to send message:", err);
  }
}

// Fetch all messages
async function fetchMessages() {
  try {
    const response = await fetch("/chat/all");
    const messages = await response.json();

    messageList.innerHTML = "";
    messages.forEach((msg) => {
      const li = document.createElement("li");
      li.className = "p-2 bg-gray-100 rounded";
      li.innerHTML = `
                <div class="text-sm text-gray-600">${new Date(
                  msg.timestamp
                ).toLocaleString()}</div>
                <div class="font-medium">${msg.message}</div>
            `;
      messageList.appendChild(li);
    });

    // Auto-scroll to bottom
    chatMessages.scrollTop = chatMessages.scrollHeight;
    lastMessageCount = messages.length;
  } catch (err) {
    console.error("Failed to fetch messages:", err);
  }
}

// Poll for updates
async function pollForUpdates() {
  try {
    const response = await fetch(`/poll?lastCheck=${lastMessageCount}`);
    const data = await response.json();

    if (data.updated) {
      await fetchMessages();
    }
  } catch (err) {
    console.error("Poll failed:", err);
  }
}

// Save chat
async function saveChat() {
  try {
    const response = await fetch("/chat/save", { method: "POST" });
    if (response.ok) {
      alert("Chat saved successfully!");
    } else {
      alert("Failed to save chat");
    }
  } catch (err) {
    console.error("Failed to save chat:", err);
    alert("Failed to save chat");
  }
}

// Event listeners
sendBtn.addEventListener("click", sendMessage);
messageInput.addEventListener("keypress", (e) => {
  if (e.key === "Enter") sendMessage();
});
saveBtn.addEventListener("click", saveChat);

// Initial load and start polling
fetchMessages();
setInterval(pollForUpdates, 2000);
