(function () {
  "use strict";

  function onReady(fn) {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", fn, { once: true });
    } else {
      fn();
    }
  }

  function utm(search) {
    var params = {};
    if (!search || typeof URLSearchParams === "undefined") return params;
    var source = new URLSearchParams(search);
    ["source", "medium", "campaign", "content", "term"].forEach(function (key) {
      var value = source.get("utm_" + key);
      if (value) params["utm_" + key] = value.slice(0, 100);
    });
    return params;
  }

  onReady(function () {
    try {
      var payload = utm(window.location.search);
      payload.page_path = window.location.pathname || "/";
      payload.referrer = document.referrer || "";

      var xhr = new XMLHttpRequest();
      xhr.open("POST", "/api/analytics/collect", true);
      xhr.timeout = 2000;
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(JSON.stringify(payload));
    } catch (e) {
      return;
    }
  });
})();
