$(document).ready(function () {
  const ip = $("#ip").val();
  const sender = $("#sender").val();

  function loadChat() {
    $.get("chat.php", { action: "get", ip: ip }, function (data) {
      $("#chat-box").html(data);
      $("#chat-box").scrollTop($("#chat-box")[0].scrollHeight);
    });
  }

  // Load chat initially
  loadChat();

  // Auto refresh every 2 seconds
  setInterval(loadChat, 2000);

  // Send message
  $("#sendBtn").click(function () {
    const message = $("#message").val().trim();
    if (message === "") return;

    $.post("chat.php", { sender: sender, message: message, ip: ip }, function () {
      $("#message").val("");
      loadChat();
    });
  });

  // Send on Enter key
  $("#message").keypress(function (e) {
    if (e.which === 13) {
      $("#sendBtn").click();
    }
  });
});
