
window.messaging = {
    id: "#" + Date.now() + Math.random(),
    callbacks: new Set(),
    broadcast(content) {
      this.send("*", content);
    },
    send(recipientId, content) {
      localStorage.setItem("$message", JSON.stringify({ senderId: this.id, recipientId, content }));
      localStorage.removeItem("$message");
    },
    subscribe(callback) {
      this.callbacks.add(callback);
    },
    unsubscribe(callback) {
      this.callbacks.delete(callback);
    },
    onStorage(e) {
      if (e.key === "$message" && e.newValue) {
        let message = JSON.parse(e.newValue);
        if (["*", this.id].includes(message.recipientId) && this.id !== message.senderId) {
          this.callbacks.forEach(cb => cb(message));
        }
      }
    }
}
autoBind(messaging);
window.addEventListener("storage", messaging.onStorage);
