const POSTHOG_DEFAULT_HOST = 'https://r.armature.tech';
const POSTHOG_DEFAULT_UI_HOST = 'https://us.posthog.com';
const POSTHOG_METHODS = 'init capture identify reset get_distinct_id register register_once unregister opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing'.split(' ');

let postHogConfigured = false;
let postHogListenersInstalled = false;
let lastPostHogPageviewUrl = null;
let identifiedPostHogUserId = null;

function getPostHogGlobal() {
  return /** @type {any} */ (window).posthog;
}

function setPostHogGlobal(value) {
  /** @type {any} */ (window).posthog = value;
}

function installPostHogStub() {
  if (getPostHogGlobal()?.__SV) return;
  const queue = getPostHogGlobal() || [];
  setPostHogGlobal(queue);
  queue._i = queue._i || [];
  queue.people = queue.people || [];
  queue.toString = () => 'posthog (stub)';
  queue.people.toString = () => 'posthog.people (stub)';
  for (const method of POSTHOG_METHODS) {
    queue[method] = function postHogQueuedMethod() {
      queue.push([method].concat(Array.prototype.slice.call(arguments, 0)));
    };
  }
  queue.init = function initPostHog(projectToken, config, name) {
    const target = name ? (queue[name] = queue[name] || []) : queue;
    target.people = target.people || [];
    for (const method of POSTHOG_METHODS) {
      target[method] = function namedPostHogQueuedMethod() {
        target.push([method].concat(Array.prototype.slice.call(arguments, 0)));
      };
    }
    const script = document.createElement('script');
    const apiHost = String(config?.api_host || POSTHOG_DEFAULT_HOST);
    script.type = 'text/javascript';
    script.crossOrigin = 'anonymous';
    script.async = true;
    script.src = `${apiHost.replace('.i.posthog.com', '-assets.i.posthog.com')}/static/array.js`;
    const firstScript = document.getElementsByTagName('script')[0];
    firstScript.parentNode.insertBefore(script, firstScript);
    queue._i.push([projectToken, config, name]);
  };
  queue.__SV = 1;
}

function currentPostHogRoute() {
  if (window.location.pathname && window.location.pathname !== '/auth/callback') {
    return `${window.location.pathname}${window.location.search || ''}`;
  }
  const hashPath = String(window.location.hash || '').replace(/^#/, '');
  if (hashPath && hashPath.startsWith('/')) return hashPath;
  return '/dashboard';
}

function capturePostHogPageview() {
  const posthogClient = getPostHogGlobal();
  if (!postHogConfigured || !posthogClient?.capture) return;
  const currentUrl = window.location.href;
  if (currentUrl === lastPostHogPageviewUrl) return;
  lastPostHogPageviewUrl = currentUrl;
  posthogClient.capture('$pageview', {
    $current_url: currentUrl,
    route: currentPostHogRoute(),
  });
}

function installPostHogRouteListeners() {
  if (postHogListenersInstalled) return;
  postHogListenersInstalled = true;
  const captureSoon = () => {
    window.requestAnimationFrame(capturePostHogPageview);
  };
  const pushState = window.history.pushState;
  const replaceState = window.history.replaceState;
  window.history.pushState = function postHogPushState() {
    const result = pushState.apply(this, arguments);
    captureSoon();
    return result;
  };
  window.history.replaceState = function postHogReplaceState() {
    const result = replaceState.apply(this, arguments);
    captureSoon();
    return result;
  };
  window.addEventListener('popstate', captureSoon);
}

function configurePostHogAnalytics(config) {
  const projectToken = config?.posthogProjectToken;
  if (!projectToken || postHogConfigured) return;
  const posthogHost = config.posthogHost || POSTHOG_DEFAULT_HOST;
  installPostHogStub();
  getPostHogGlobal().init(projectToken, {
    api_host: posthogHost,
    ui_host: config.posthogUiHost || POSTHOG_DEFAULT_UI_HOST,
    capture_pageview: false,
    autocapture: false,
    defaults: '2026-01-30',
    person_profiles: 'identified_only',
  });
  postHogConfigured = true;
  installPostHogRouteListeners();
  window.requestAnimationFrame(capturePostHogPageview);
}

function identifyPostHogUser(me) {
  const profileId = me?.profile?.id;
  const posthogClient = getPostHogGlobal();
  if (!postHogConfigured || !profileId || !posthogClient?.identify) return;
  if (identifiedPostHogUserId === profileId) return;
  identifiedPostHogUserId = profileId;
  posthogClient.identify(profileId, {});
}

function resetPostHogUser() {
  identifiedPostHogUserId = null;
  const posthogClient = getPostHogGlobal();
  if (postHogConfigured && posthogClient?.reset) posthogClient.reset();
}

window.configurePostHogAnalytics = configurePostHogAnalytics;
window.identifyPostHogUser = identifyPostHogUser;
window.resetPostHogUser = resetPostHogUser;
window.capturePostHogPageview = capturePostHogPageview;
