/* global window */
// Room-signals store — platform side of the shared-room signal loop.
// Merges the seeded signals (ROOM_SIGNALS in data.jsx) with live signals the
// slack-app capture endpoint persists to slack-app/room-signals.json (same
// static-file polling pattern as slack-bridge.js / events.json). Components
// read via window.RoomSignals and re-render on "nudge-room-signal-update".

(function () {
  var LIVE_URL = "slack-app/room-signals.json";
  var POLL_MS = 3000;
  var live = [];
  var lastSig = "";

  function all() {
    var seed = window.ROOM_SIGNALS || [];
    return seed.concat(live).sort(function (a, b) { return (b.ts || 0) - (a.ts || 0); });
  }

  window.RoomSignals = {
    list: function (dealId) {
      var rows = all();
      if (!dealId) return rows;
      var id = String(dealId).toLowerCase();
      return rows.filter(function (s) { return s.dealId === id; });
    },
    countFor: function (dealId) { return this.list(dealId).length; },
  };

  function poll() {
    fetch(LIVE_URL, { cache: "no-store" })
      .then(function (r) { if (!r.ok) throw 0; return r.text(); })
      .then(function (txt) {
        if (txt === lastSig) return;
        lastSig = txt;
        var parsed;
        try { parsed = JSON.parse(txt); } catch (e) { return; }
        if (!Array.isArray(parsed)) return;
        live = parsed;
        window.dispatchEvent(new CustomEvent("nudge-room-signal-update"));
      })
      .catch(function () { /* slack-app not running / file absent — seeds only */ });
  }

  poll();
  setInterval(poll, POLL_MS);
})();
