// public/visitor-tracking.jsx
// window.visitorTracker — initializes PostHog, manages the engagement gate,
// and debounces sync PATCHes to /api/sync-visitor.
//
// Load order: must be loaded BEFORE email-gate.jsx and app.jsx in index.html.

(function () {
  // === Config ===
  // PostHog key + host are injected into the page via Vite's HTML env
  // substitution. index.html sets window.POSTHOG_KEY = "%VITE_POSTHOG_KEY%"
  // and window.POSTHOG_HOST = "%VITE_POSTHOG_HOST%" before this script
  // loads — the values come from .env at build time. Falls back to the
  // public host directly if unset (e.g. local dev without env).
  var POSTHOG_KEY = window.POSTHOG_KEY || "";
  var POSTHOG_HOST = window.POSTHOG_HOST || "https://us.i.posthog.com";
  var SYNC_ENDPOINT = "/api/sync-visitor";
  var SYNC_DEBOUNCE_MS = 2000;
  var SCHEMA_VERSION = 1;

  // Refuse to init without a real key — avoids accidentally sending events to
  // an empty/test project if .env is missing.
  if (!POSTHOG_KEY || POSTHOG_KEY.indexOf("phc_") !== 0) {
    console.warn("visitor-tracker: POSTHOG_KEY not set or invalid; tracker disabled");
    window.visitorTracker = {
      init: function () {},
      onEmailSubmit: function () {},
      onProfileChange: function () {},
      onProductOpen: function () {},
      onProductClose: function () {},
    };
    return;
  }

  // === Feature flag (rollback path) ===
  var enabled = typeof window.VISITOR_TRACKING_ENABLED === "undefined" || window.VISITOR_TRACKING_ENABLED === true;
  if (!enabled) {
    window.visitorTracker = {
      init: function () {},
      onEmailSubmit: function () {},
      onProfileChange: function () {},
      onProductOpen: function () {},
      onProductClose: function () {},
    };
    return;
  }

  // === PostHog SDK loader (official snippet, 2026-01-30 defaults) ===
  !(function (t, e) {
    var o, n, p, r;
    e.__SV ||
      (window.posthog && window.posthog.__loaded) ||
      ((window.posthog = e),
      (e._i = []),
      (e.init = function (i, s, a) {
        function g(t, e) {
          var o = e.split(".");
          2 == o.length && ((t = t[o[0]]), (e = o[1])),
            (t[e] = function () {
              t.push([e].concat(Array.prototype.slice.call(arguments, 0)));
            });
        }
        ((p = t.createElement("script")).type = "text/javascript"),
          (p.crossOrigin = "anonymous"),
          (p.async = !0),
          (p.src = s.api_host.replace(".i.posthog.com", "-assets.i.posthog.com") + "/static/array.js"),
          (r = t.getElementsByTagName("script")[0]).parentNode.insertBefore(p, r);
        var u = e;
        for (
          void 0 !== a ? (u = e[a] = []) : (a = "posthog"),
            u.people = u.people || [],
            u.toString = function (t) {
              var e = "posthog";
              return "posthog" !== a && (e += "." + a), t || (e += " (stub)"), e;
            },
            u.people.toString = function () {
              return u.toString(1) + ".people (stub)";
            },
            o =
              "Mi Ri init Vi Gi Rr Wi Ji Bi capture calculateEventProperties tn register register_once register_for_session unregister unregister_for_session an getFeatureFlag getFeatureFlagPayload getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSurveysLoaded onSessionId getSurveys getActiveMatchingSurveys renderSurvey displaySurvey cancelPendingSurvey canRenderSurvey canRenderSurveyAsync un identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset setIdentity clearIdentity get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException addExceptionStep captureLog startExceptionAutocapture stopExceptionAutocapture loadToolbar get_property getSessionProperty nn Xi createPersonProfile setInternalOrTestUser sn Hi cn opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_explicit_consent_status is_capturing clear_opt_in_out_capturing Ki debug Lr rn getPageViewId captureTraceFeedback captureTraceMetric Di".split(
                " "
              ),
            n = 0;
          n < o.length;
          n++
        )
          g(u, o[n]);
        e._i.push([i, s, a]);
      }),
      (e.__SV = 1));
  })(document, window.posthog || []);

  posthog.init(POSTHOG_KEY, {
    api_host: POSTHOG_HOST,
    ui_host: "https://us.posthog.com",
    defaults: "2026-01-30",
    person_profiles: "identified_only",
    persistence: "localStorage+cookie",
    cross_subdomain_cookie: true,
    respect_dnt: true,
    autocapture: true,
    capture_pageview: true,
    loaded: function (ph) {
      if (/bot|crawler|spider|preview|fetch|headless/i.test(navigator.userAgent)) {
        ph.opt_out_capturing();
      }
      try {
        var qs = new URLSearchParams(window.location.search);
        var gclid = qs.get("gclid");
        if (gclid) ph.register({ gclid: gclid });
      } catch (_) {}
    },
  });

  // === Engagement gate (per-tab sessionStorage) ===
  var GATE_KEY = "r-vt-engaged";
  function gateActive() {
    try { return sessionStorage.getItem(GATE_KEY) === "1"; } catch (_) { return false; }
  }
  function tripGate() {
    try { sessionStorage.setItem(GATE_KEY, "1"); } catch (_) {}
  }

  // === Snapshot state ===
  var snapshot = {
    email: null,
    engaged: false,
    profile: {},
    productsViewed: [],
    lastProductViewed: null,
    firstReferrer: null,
    firstUtm: null,
    firstDeviceType: null,
    firstGclid: null,
    posthogDistinctId: null,
    isNewSession: true,
  };
  function readPosthogProps() {
    try {
      snapshot.posthogDistinctId = posthog.get_distinct_id();
      snapshot.firstReferrer = posthog.get_property("$initial_referrer") || null;
      snapshot.firstDeviceType = posthog.get_property("$device_type") || null;
      snapshot.firstGclid = posthog.get_property("gclid") || null;
      var utm = {
        source: posthog.get_property("$initial_utm_source") || undefined,
        medium: posthog.get_property("$initial_utm_medium") || undefined,
        campaign: posthog.get_property("$initial_utm_campaign") || undefined,
      };
      snapshot.firstUtm = utm.source || utm.medium || utm.campaign ? utm : null;
    } catch (_) {}
  }

  // === Debounced sync ===
  var syncTimer = null;
  function buildPayload() {
    return {
      version: SCHEMA_VERSION,
      email: snapshot.email,
      engaged: snapshot.engaged,
      profile: snapshot.profile,
      productsViewed: snapshot.productsViewed,
      lastProductViewed: snapshot.lastProductViewed,
      posthogDistinctId: snapshot.posthogDistinctId,
      firstReferrer: snapshot.firstReferrer,
      firstUtm: snapshot.firstUtm,
      firstDeviceType: snapshot.firstDeviceType,
      firstGclid: snapshot.firstGclid,
      isNewSession: snapshot.isNewSession,
      ts: Date.now(),
    };
  }
  function flushNow(useBeacon) {
    if (!snapshot.email) return;
    readPosthogProps();
    var body = JSON.stringify(buildPayload());
    if (useBeacon && navigator.sendBeacon) {
      try {
        navigator.sendBeacon(SYNC_ENDPOINT, new Blob([body], { type: "application/json" }));
        return;
      } catch (_) {}
    }
    fetch(SYNC_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: body,
      keepalive: true,
    }).catch(function () {});
  }
  function scheduleSync() {
    if (syncTimer) clearTimeout(syncTimer);
    syncTimer = setTimeout(function () { flushNow(false); }, SYNC_DEBOUNCE_MS);
  }

  document.addEventListener("visibilitychange", function () {
    if (document.visibilityState === "hidden") flushNow(true);
  });

  // === Public API ===
  window.visitorTracker = {
    init: function () {},
    onEmailSubmit: function (email) {
      if (!email) return;
      snapshot.email = String(email).trim().toLowerCase();
      try { posthog.identify(snapshot.email); } catch (_) {}
      posthog.capture("email_submitted");
      scheduleSync();
    },
    onProfileChange: function (field, value, eligibleCount) {
      if (!snapshot.profile) snapshot.profile = {};
      snapshot.profile[field] = value;
      posthog.capture("profile_updated", { field: field, new_value: value, eligible_count: eligibleCount });
      if (snapshot.engaged) scheduleSync();
    },
    onProductOpen: function (productId, meta) {
      var firstTime = !gateActive();
      if (firstTime) {
        tripGate();
        snapshot.engaged = true;
        posthog.capture("engagement_gate_tripped", { product_id: productId });
      }
      snapshot.lastProductViewed = productId;
      if (snapshot.productsViewed.indexOf(productId) === -1) snapshot.productsViewed.push(productId);
      posthog.capture("product_opened", Object.assign({ product_id: productId }, meta || {}));
      scheduleSync();
    },
    onProductClose: function (productId, timeOpenMs) {
      posthog.capture("product_closed", { product_id: productId, time_open_ms: timeOpenMs });
    },
  };
})();
