const API_URL = "/indira/api/tanya/";

const chatBox = document.getElementById("chatBox");
const input = document.getElementById("questionInput");
const sendBtn = document.getElementById("sendBtn");
const typing = document.getElementById("typingIndicator");

/* =====================
   UTIL
===================== */
function scrollBottom() {
  chatBox.scrollTop = chatBox.scrollHeight;
}

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

/* Streaming kata-per-kata */
function streamText(el, text, speed = 160) {
  const words = text.split(" ");
  let i = 0;
  el.innerHTML = "";

  const interval = setInterval(() => {
    el.innerHTML += (i === 0 ? "" : " ") + words[i];
    i++;
    scrollBottom();

    if (i >= words.length) {
      clearInterval(interval);
    }
  }, speed);
}

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

  // disable input sementara
  input.disabled = true;
  sendBtn.disabled = true;

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

  // tampilkan typing indicator
  if (typing) {
    typing.style.display = "flex";
    scrollBottom();
  }

  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();

    // sembunyikan typing
    if (typing) typing.style.display = "none";

    // bubble bot kosong
    const botMsg = addMessage("", "bot");

    const jawaban =
      data.jawaban && data.jawaban.trim()
        ? data.jawaban
        : "Tidak ditemukan jawaban.";

    // streaming jawaban
    streamText(botMsg, jawaban);

  } catch (err) {
    if (typing) typing.style.display = "none";

    const botMsg = addMessage("", "bot");
    streamText(
      botMsg,
      "❌ Gagal menghubungi server. Silakan coba lagi."
    );
  } finally {
    // aktifkan kembali input
    input.disabled = false;
    sendBtn.disabled = false;
    input.focus();
  }
}

/* =====================
   EVENT
===================== */
sendBtn.addEventListener("click", sendQuestion);

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