/*
  analytics.js — Save Pet
  All three integrations are OFF by default and only load their
  external script (and only then make any network request) once
  you flip the matching *_ENABLED flag and ID in config.js.
*/
window.SP = window.SP || {};

SP.Analytics = (function () {
  "use strict";
  let gaReady = false;

  function initGA() {
    if (!SP.Config.GA_ENABLED || !SP.Config.GA_MEASUREMENT_ID) return;
    try {
      const s1 = document.createElement("script");
      s1.async = true;
      s1.src = "https://www.googletagmanager.com/gtag/js?id=" + SP.Config.GA_MEASUREMENT_ID;
      document.head.appendChild(s1);
      window.dataLayer = window.dataLayer || [];
      window.gtag = function () { window.dataLayer.push(arguments); };
      window.gtag("js", new Date());
      window.gtag("config", SP.Config.GA_MEASUREMENT_ID);
      gaReady = true;
    } catch (e) { /* analytics must never break the game */ }
  }

  function initGTM() {
    if (!SP.Config.GTM_ENABLED || !SP.Config.GTM_ID) return;
    try {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
      const s = document.createElement("script");
      s.async = true;
      s.src = "https://www.googletagmanager.com/gtm.js?id=" + SP.Config.GTM_ID;
      document.head.appendChild(s);
    } catch (e) { /* ignore */ }
  }

  function initClarity() {
    if (!SP.Config.CLARITY_ENABLED || !SP.Config.CLARITY_PROJECT_ID) return;
    try {
      (function (c, l, a, r, i) {
        c[a] = c[a] || function () { (c[a].q = c[a].q || []).push(arguments); };
        const t = l.createElement(r); t.async = 1; t.src = "https://www.clarity.ms/tag/" + i;
        const y = l.getElementsByTagName(r)[0]; y.parentNode.insertBefore(t, y);
      })(window, document, "clarity", "script", SP.Config.CLARITY_PROJECT_ID);
    } catch (e) { /* ignore */ }
  }

  function track(eventName, params) {
    try {
      if (gaReady && typeof window.gtag === "function") window.gtag("event", eventName, params || {});
      if (window.dataLayer && SP.Config.GTM_ENABLED) window.dataLayer.push(Object.assign({ event: eventName }, params || {}));
    } catch (e) { /* ignore */ }
  }

  function init() {
    initGA(); initGTM(); initClarity();
    track("game_loaded", { game: "save_pet", version: SP.Config.VERSION });
  }

  return { init: init, track: track };
})();
