(function(){
  async function updateVisitors(){
    try{
      const r = await fetch('api/ping.php', {cache:'no-store'});
      const j = await r.json();
      if (j && j.ok) {
        const el = document.getElementById('visitorsOnline');
        if (el) el.textContent = j.online;
      }
    }catch(e){}
  }

  async function updateListeners(){
    try{
      const r = await fetch('api/stats.php', {cache:'no-store'});
      const j = await r.json();
      if (j && j.ok) {
        const el = document.getElementById('currentListeners');
        if (el) el.textContent = j.listeners;
      }
    }catch(e){}
  }

  function refreshNowPlaying(){
    const el = document.getElementById('nowplaying-content');
    if (!el) return;
    fetch('nowplaying.php?ts=' + Date.now(), {cache:'no-store'})
      .then(r => r.text())
      .then(html => { if (html.trim() !== '') el.innerHTML = html; })
      .catch(() => {});
  }

  function tick(){
    updateVisitors();
    updateListeners();
    refreshNowPlaying();
  }

  document.addEventListener('DOMContentLoaded', function(){
    tick();
    setInterval(tick, 15000);
  });
})();
