Spaces:
Runtime error

File size: 1,303 Bytes
2834243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// ====== UI helpers ======
const chatEl = document.getElementById("chat");
const form = document.getElementById("chatForm");
const input = document.getElementById("msgInput");

function addMsg(text, who = "bot") {
  const div = document.createElement("div");
  div.className = `msg ${who}`;
  div.textContent = text;
  chatEl.appendChild(div);
  chatEl.scrollTop = chatEl.scrollHeight;
}

// ====== Llamada al backend ======
async function askBackend(message) {
  const resp = await fetch("/api/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ message })
  });
  if (!resp.ok) throw new Error("Error en el servidor");
  const data = await resp.json();
  return data.reply || "No tengo respuesta ahora.";
}

// ====== Manejo del formulario ======
form.addEventListener("submit", async (e) => {
  e.preventDefault();
  const text = input.value.trim();
  if (!text) return;

  addMsg(text, "user");
  input.value = "";
  addMsg("Pensando...");

  try {
    const reply = await askBackend(text);
    // quita "Pensando..."
    chatEl.lastElementChild.remove();
    addMsg(reply, "bot");
  } catch (err) {
    chatEl.lastElementChild.remove();
    addMsg("Hubo un problema al responder. Intenta de nuevo.", "bot");
    console.error(err);
  }
});