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 evoInstanceEl = this.shadowRoot.getElementById("instance");
const evoFromEl = this.shadowRoot.getElementById("evoFrom");
const evoToEl = this.shadowRoot.getElementById("evoTo");
const evoPushEl = this.shadowRoot.getElementById("pushName");
const evoTextEl = this.shadowRoot.getElementById("evoText");
const sendEvoEl = this.shadowRoot.getElementById("sendEvo");
const sendAction = async () => {
const instance = evoInstanceEl.value.trim() || "Piaf";
const from = evoFromEl.value.trim() || "5491133230322@s.whatsapp.net"; // cliente
const to = evoToEl.value.trim() || "5491137887040@s.whatsapp.net"; // canal/destino
const text = evoTextEl.value.trim();
const pushName = evoPushEl.value.trim();
if (!from || !text) {
alert("Falta from o text");
return;
}
const nowSec = Math.floor(Date.now() / 1000);
const genId = () =>
(self.crypto?.randomUUID?.() || `${Date.now()}${Math.random()}`)
.replace(/-/g, "")
.slice(0, 22)
.toUpperCase();
const payload = {
body: {
event: "messages.upsert",
instance,
data: {
key: {
// remoteJid debe ser el cliente (buyer)
remoteJid: from,
fromMe: false,
id: genId(),
participant: "",
addressingMode: "pn",
},
pushName: pushName || "SimUser",
status: "DELIVERY_ACK",
message: { conversation: text },
messageType: "conversation",
messageTimestamp: nowSec,
instanceId: genId(),
source: "sim",
},
date_time: new Date().toISOString(),
sender: from,
server_url: "http://localhost",
apikey: "SIM",
},
};
const data = await api.simEvolution(payload);
this.shadowRoot.getElementById("raw").textContent = JSON.stringify(data, null, 2);
console.log("[evolution sim] webhook response:", data);
if (!data.ok) {
this.append("bot", "Error en Evolution Sim.");
return;
}
emit("ui:selectedChat", { chat_id: from });
this.append("user", text);
this.append("bot", `[Evolution] enviado (sim): ${text}`);
evoTextEl.value = "";
};
sendEvoEl.onclick = sendAction;
evoTextEl.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendAction();
}
});
this._unsub = on("conversation:upsert", (c) => {
const chat_id = evoFromEl.value.trim() || "5491133230322@s.whatsapp.net";
if (c.chat_id === chat_id) {
// placeholder: 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);