"use strict";

// RN port of web messageNotificationManager — no DOM, queues pending
// notifications until a callback subscriber registers, dedupes within a
// short window.

class MessageNotificationManager {
  callbacks = new Set();
  pending = [];
  maxPending = 50;
  pendingTtlMs = 30_000;
  dedupeWindowMs = 5000;
  recentlyDelivered = new Map();
  addCallback(callback) {
    this.callbacks.add(callback);
    this.flushPending();
    return () => {
      this.callbacks.delete(callback);
    };
  }
  getCallbackCount() {
    return this.callbacks.size;
  }
  flushPending() {
    if (this.callbacks.size === 0 || this.pending.length === 0) {
      return;
    }
    const now = Date.now();
    const valid = this.pending.filter(item => now - item.ts <= this.pendingTtlMs);
    this.pending = [];
    valid.forEach(item => {
      this.callbacks.forEach(cb => cb(item.message, item.roomName, item.senderName, item.roomJID));
    });
  }
  buildDedupeKey(message, roomJID) {
    const msgId = String(message?.xmppId || message?.id || '').trim();
    if (msgId) {
      return `${roomJID}:${msgId}`;
    }
    return null;
  }
  shouldSkipDuplicate(message, roomJID) {
    const now = Date.now();
    const key = this.buildDedupeKey(message, roomJID);
    if (!key) {
      return false;
    }
    const prev = this.recentlyDelivered.get(key) || 0;
    if (prev && now - prev < this.dedupeWindowMs) {
      return true;
    }
    this.recentlyDelivered.set(key, now);
    if (this.recentlyDelivered.size > 500) {
      const threshold = now - this.dedupeWindowMs;
      this.recentlyDelivered.forEach((ts, k) => {
        if (ts < threshold) {
          this.recentlyDelivered.delete(k);
        }
      });
    }
    return false;
  }
  showNotification(message, roomName, senderName, roomJID) {
    const body = typeof message?.body === 'string' ? message.body.trim() : '';
    if (!body) {
      return;
    }
    if (this.shouldSkipDuplicate(message, roomJID)) {
      return;
    }
    if (this.callbacks.size > 0) {
      this.callbacks.forEach(cb => cb(message, roomName, senderName, roomJID));
    } else {
      this.pending.push({
        message,
        roomName,
        senderName,
        roomJID,
        ts: Date.now()
      });
      if (this.pending.length > this.maxPending) {
        this.pending = this.pending.slice(-this.maxPending);
      }
    }
  }
}
export const messageNotificationManager = new MessageNotificationManager();
//# sourceMappingURL=messageNotificationManager.js.map