/* ============================================================
   livecount.js - Shows how many visitors were seen in the last
   60 minutes in a small corner badge, outside the console.

   Lightweight by design so it never competes with the game loop:
   - one small fetch(), no per-frame work, no game-state access;
   - polls at a slow interval (60s) instead of continuously;
   - pauses entirely while the tab is hidden and refreshes on
     return; fails silently (e.g. opened from file:// with no PHP).
   ============================================================ */
(function () {
  "use strict";

  var POLL_MS = 60000;   // refresh once a minute — plenty for a "last hour" figure
  var el, numEl, timer = null;

  function render(n) {
    if (!el) return;
    numEl.textContent = n;
    // singular/plural + reveal only once we have a real number
    el.querySelector("[data-word]").textContent = n === 1 ? "visitor" : "visitors";
    el.hidden = false;
  }

  function poll() {
    // keepalive + no-store: cheap, cache-proof, survives navigation
    fetch("count.php", { cache: "no-store" })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (d) {
        if (d && typeof d.visitors === "number") render(d.visitors);
      })
      .catch(function () { /* offline / no PHP: leave badge hidden */ });
  }

  function start() {
    if (timer !== null) return;
    poll();                       // immediate refresh
    timer = setInterval(poll, POLL_MS);
  }
  function stop() {
    if (timer !== null) { clearInterval(timer); timer = null; }
  }

  function init() {
    el = document.getElementById("live-count");
    if (!el) return;
    numEl = el.querySelector("[data-num]");

    // Only poll while the page is actually visible — saves the
    // network (and battery) when the game is in a background tab.
    document.addEventListener("visibilitychange", function () {
      if (document.hidden) stop(); else start();
    });
    if (!document.hidden) start();
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
