(function () {
  'use strict';

  var pollInterval = (window._pollInterval || 15) * 1000;
  var cliAvailable = !!window._cliAvailable;

  var elDecisions = document.getElementById('stat-decisions');
  var elAlerts    = document.getElementById('stat-alerts');
  var elBouncers  = document.getElementById('stat-bouncers');
  var elMachines  = document.getElementById('stat-machines');

  function animateTo(el, newVal) {
    if (!el) return;
    var current = parseInt(el.textContent, 10);
    if (isNaN(current) || current === newVal) {
      el.textContent = newVal;
      return;
    }
    // Brief flash transition
    el.style.opacity = '0.4';
    setTimeout(function () {
      el.textContent = newVal;
      el.style.opacity = '1';
    }, 150);
  }

  function fetchStats() {
    fetch('/api/v1/stats')
      .then(function (r) {
        if (!r.ok) throw new Error('bad response');
        return r.json();
      })
      .then(function (d) {
        animateTo(elDecisions, d.decisions);
        animateTo(elAlerts,    d.alerts);
        if (cliAvailable) {
          animateTo(elBouncers, d.bouncers);
          animateTo(elMachines, d.machines);
        }
      })
      .catch(function () {
        // silently fail — health badge in base.html covers connectivity state
      });
  }

  fetchStats();
  setInterval(fetchStats, pollInterval);
})();
