const API_URL = "/coba/api/tanya/";
const chatBox = document.getElementById("chatBox");
const input = document.getElementById("questionInput");
const sendBtn = document.getElementById("sendBtn");

function addMessage(text, sender) {
  const div = document.createElement("div");
  div.className = `message ${sender}`;
  div.innerHTML = text;
  chatBox.appendChild(div);
  chatBox.scrollTop = chatBox.scrollHeight;
  return div;
}

async function sendQuestion() {
  const question = input.value.trim();
  if (!question) return;

  addMessage(question, "user");
  input.value = "";

  const botMsg = addMessage("⏳ Sedang memproses...", "bot");

  try {
    const res = await fetch(API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ pertanyaan: question }),
    });

    if (!res.ok) {
      throw new Error("Server error");
    }

    const data = await res.json();
    botMsg.innerHTML = data.jawaban || "Tidak ditemukan jawaban.";
  } catch (err) {
    botMsg.innerHTML = "❌ Gagal menghubungi server.";
  }
}

sendBtn.addEventListener("click", sendQuestion);

input.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
    sendQuestion();
  }
});
