/* ============================================================
   analytics.js - Fire-and-forget visit logger. On page load it
   pings log.php, which appends the visit to visits.csv server-side.
   Sends the true external referrer + screen hints; IP, User-Agent
   and language are read from the request headers by log.php.
   Fails silently (e.g. when opened from file:// with no PHP).
   ============================================================ */
(function () {
  "use strict";

  function logVisit() {
    try {
      var params = new URLSearchParams();
      params.set("ref", document.referrer || "");
      params.set("page", location.pathname + location.search);
      params.set("screen", (window.screen ? screen.width + "x" + screen.height : "") +
                           " @" + (window.devicePixelRatio || 1));

      // sendBeacon survives page unload and doesn't block; fall back to fetch.
      if (navigator.sendBeacon) {
        navigator.sendBeacon("log.php", params);
      } else {
        fetch("log.php", { method: "POST", body: params, keepalive: true }).catch(function () {});
      }
    } catch (e) { /* never let logging break the page */ }
  }

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