import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
class ConversationList extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.conversations = [];
this.selected = null;
this.shadowRoot.innerHTML = `
`;
}
connectedCallback() {
this.shadowRoot.getElementById("refresh").onclick = () => this.refresh();
this.shadowRoot.getElementById("q").oninput = () => {
clearTimeout(this._t);
this._t = setTimeout(() => this.refresh(), 250);
};
this.shadowRoot.getElementById("status").onchange = () => this.refresh();
this.shadowRoot.getElementById("state").onchange = () => this.refresh();
this._unsub1 = on("conversation:upsert", (conv) => {
const idx = this.conversations.findIndex(x => x.chat_id === conv.chat_id);
if (idx >= 0) this.conversations[idx] = conv;
else this.conversations.unshift(conv);
this.render();
});
this.refresh();
}
disconnectedCallback() {
this._unsub1?.();
}
dot(status) {
const cls = status === "ok" ? "ok" : (status === "warn" ? "warn" : "err");
return ``;
}
async refresh() {
const q = this.shadowRoot.getElementById("q").value || "";
const status = this.shadowRoot.getElementById("status").value || "";
const state = this.shadowRoot.getElementById("state").value || "";
const data = await api.conversations({ q, status, state });
this.conversations = data.items || [];
this.render();
}
render() {
const list = this.shadowRoot.getElementById("list");
list.innerHTML = "";
for (const c of this.conversations) {
const el = document.createElement("div");
el.className = "item" + (c.chat_id === this.selected ? " active" : "");
el.innerHTML = `
state: ${c.state}
intent: ${c.intent}
last: ${new Date(c.last_activity).toLocaleTimeString()}
`;
el.onclick = () => {
this.selected = c.chat_id;
this.render();
emit("ui:selectedChat", { chat_id: c.chat_id });
};
list.appendChild(el);
}
}
}
customElements.define("conversation-list", ConversationList);