import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
class ChatSimulator extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
`;
}
connectedCallback() {
const fromEl = this.shadowRoot.getElementById("from");
const chatEl = this.shadowRoot.getElementById("chat");
const resetEl = this.shadowRoot.getElementById("reset");
const sendEl = this.shadowRoot.getElementById("send");
resetEl.onclick = () => {
this.shadowRoot.getElementById("log").innerHTML = "";
this.shadowRoot.getElementById("raw").textContent = "—";
const phone = (fromEl.value || "+5491100000000").trim();
chatEl.value = `sim:${phone}`;
this.append("bot", "Chat reseteado (solo UI). Enviá un mensaje para generar runs.");
};
sendEl.onclick = async () => {
const text = this.shadowRoot.getElementById("text").value.trim();
if (!text) return;
const from_phone = fromEl.value.trim();
const chat_id = chatEl.value.trim();
if (!from_phone || !chat_id) return alert("Falta teléfono o chat_id");
this.append("user", text);
this.shadowRoot.getElementById("text").value = "";
const data = await api.simSend({ chat_id, from_phone, text });
this.shadowRoot.getElementById("raw").textContent = JSON.stringify(data, null, 2);
if (!data.ok) {
this.append("bot", "Error en simulación.");
return;
}
this.append("bot", data.reply);
emit("ui:selectedChat", { chat_id });
};
// si querés, cuando llega un upsert de conversación simulada, podés auto-seleccionarla
this._unsub = on("conversation:upsert", (c) => {
const chat_id = this.shadowRoot.getElementById("chat").value.trim();
if (c.chat_id === chat_id) {
// no-op, pero podrías reflejar estado/intent acá si querés
}
});
}
disconnectedCallback() {
this._unsub?.();
}
append(who, text) {
const log = this.shadowRoot.getElementById("log");
const el = document.createElement("div");
el.className = "msg " + (who === "user" ? "user" : "bot");
el.textContent = text;
log.appendChild(el);
log.scrollTop = log.scrollHeight;
}
}
customElements.define("chat-simulator", ChatSimulator);