{# PostHog browser snippet — included from <head> in base.html / base_login.html.
   Renders nothing when the integration is disabled (no POSTHOG_API_KEY set on
   the server). The `posthog_config` Jinja global is wired up once at app
   startup in app/web/router.py from src.observability.get_posthog().

   Privacy posture:
     * Session replay is masked-by-default (`maskAllInputs: true` plus a CSS
       selector covering data cells / inputs). Operator can append a custom
       selector via POSTHOG_REPLAY_MASK_SELECTOR.
     * `person_profiles: 'identified_only'` keeps anonymous visits out of the
       people table.
     * Identification respects POSTHOG_IDENTIFY_PII (none/id/email/full).
#}
{% if posthog_config and posthog_config.enabled %}
<script>
  !function(t,e){var o,n,p,r;e.__SV||(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="init me ws ys ps bs capture je Di ks register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty Es $s createPersonProfile Is opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing Ss debug I As getPageViewId captureTraceFeedback captureTraceMetric".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_config.api_key_public }}", {
    api_host: "{{ posthog_config.host }}",
    person_profiles: "identified_only",
    capture_pageview: true,
    capture_pageleave: true,
    autocapture: false,
    {% if posthog_config.replay_enabled %}
    session_recording: {
      maskAllInputs: true,
      maskTextSelector: "[data-sensitive], .data-cell, .query-result, .sql-output, code, pre{% if posthog_config.replay_mask_selector_extra %}, {{ posthog_config.replay_mask_selector_extra }}{% endif %}",
      recordCrossOriginIframes: false
    },
    disable_session_recording: false,
    {% else %}
    disable_session_recording: true,
    {% endif %}
    loaded: function (ph) {
      // Tag every browser event with deployment environment + release
      // and (when a user is logged in) user_id + email/name. register()
      // values are sticky (localStorage-persisted) and apply to every
      // event — $pageview, $exception, $autocapture, etc. — so the
      // event-detail view in PostHog shows who the user was inline,
      // without clicking through to the person profile. Mirrors the
      // backend's super_properties + user_props_for_event so cross-
      // referencing client and server events doesn't require a join.
      var _superProps = {
        environment: {{ posthog_config.environment|tojson }}{% if posthog_config.release %},
        release: {{ posthog_config.release|tojson }}{% endif %}
      };
      {% set _u = posthog_user_block(request) %}
      {% if _u %}
      _superProps.user_id = {{ _u.distinct_id|tojson }};
      {% if _u.props.email %}
      _superProps.user_email = {{ _u.props.email|tojson }};
      {% endif %}
      {% if _u.props.name %}
      _superProps.user_name = {{ _u.props.name|tojson }};
      {% endif %}
      {% endif %}
      ph.register(_superProps);
      {% if _u %}
      ph.identify({{ _u.distinct_id|tojson }}, {{ _u.props|tojson }});
      {% endif %}
    }
  });
  window.addEventListener("error", function (e) {
    try {
      if (window.posthog && typeof posthog.captureException === "function") {
        posthog.captureException(e.error || new Error(e.message || "window.error"));
      }
    } catch (_err) {}
  });
  window.addEventListener("unhandledrejection", function (e) {
    try {
      if (window.posthog && typeof posthog.captureException === "function") {
        posthog.captureException(e.reason || new Error("unhandledrejection"));
      }
    } catch (_err) {}
  });
</script>
{% endif %}
