// assets/js/site.js
(function(){
  let timerVisitors = null;
  let timerListeners = null;
  let inFlightVisitors = false;
  let inFlightListeners = false;

  async function updateVisitors(){
    if (inFlightVisitors || !document.getElementById('visitorsOnline')) return;
    inFlightVisitors = true;
    try{
      const r = await fetch('/api/ping.php', {cache:'no-store', credentials:'same-origin'});
      const j = await r.json();
      if (j && j.ok) document.getElementById('visitorsOnline').textContent = j.online;
    }catch(e){}
    finally{ inFlightVisitors = false; }
  }

  async function updateListeners(){
    if (inFlightListeners || !document.getElementById('currentListeners')) return;
    inFlightListeners = true;
    try{
      const r = await fetch('/api/stats.php', {cache:'no-store', credentials:'same-origin'});
      const j = await r.json();
      if (j && j.ok) document.getElementById('currentListeners').textContent = j.listeners;
    }catch(e){}
    finally{ inFlightListeners = false; }
  }

  document.addEventListener('DOMContentLoaded', function(){
    updateVisitors();
    setTimeout(updateListeners, 250);
    timerVisitors = setInterval(updateVisitors, 30000);
    timerListeners = setInterval(updateListeners, 60000);
  });

  window.addEventListener('pagehide', function(){
    if (timerVisitors) clearInterval(timerVisitors);
    if (timerListeners) clearInterval(timerListeners);
  });
})();
