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(' ');
const MIXPANEL_DEFAULT_API_HOST = 'https://api-js.mixpanel.com';
const MIXPANEL_METHODS = 'disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking start_batch_senders people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user'.split(' ');
const MIXPANEL_CONSENT_STORAGE_KEY = 'armature.mixpanelConsent';

let postHogConfigured = false;
let postHogListenersInstalled = false;
let lastPostHogPageviewUrl = null;
let identifiedPostHogUserId = null;
let mixpanelConfigured = false;
let mixpanelListenersInstalled = false;
let lastMixpanelPageviewUrl = null;
let identifiedMixpanelUserId = null;
let pendingMixpanelConfig = null;

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

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

function getMixpanelGlobal() {
  return /** @type {any} */ (window).mixpanel;
}

function setMixpanelGlobal(value) {
  /** @type {any} */ (window).mixpanel = 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 currentAnalyticsRoute() {
  return currentPostHogRoute();
}

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 captureMixpanelPageview() {
  const mixpanelClient = getMixpanelGlobal();
  if (!mixpanelConfigured || !mixpanelClient?.track) return;
  const currentUrl = window.location.href;
  if (currentUrl === lastMixpanelPageviewUrl) return;
  lastMixpanelPageviewUrl = currentUrl;
  mixpanelClient.track('page_viewed', {
    current_url: currentUrl,
    route: currentAnalyticsRoute(),
  });
}

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 installMixpanelStub() {
  if (getMixpanelGlobal()?.__SV) return;
  const mixpanel = getMixpanelGlobal() || [];
  setMixpanelGlobal(mixpanel);
  mixpanel._i = mixpanel._i || [];
  mixpanel.people = mixpanel.people || [];
  mixpanel.toString = () => 'mixpanel (stub)';
  mixpanel.people.toString = () => 'mixpanel.people (stub)';
  function createStub(target, method) {
    const parts = method.split('.');
    if (parts.length === 2) {
      target[parts[0]] = target[parts[0]] || [];
      target[parts[0]][parts[1]] = function mixpanelPeopleQueuedMethod() {
        target.push([method].concat(Array.prototype.slice.call(arguments, 0)));
      };
      return;
    }
    target[method] = function mixpanelQueuedMethod() {
      target.push([method].concat(Array.prototype.slice.call(arguments, 0)));
    };
  }
  for (const method of MIXPANEL_METHODS) createStub(mixpanel, method);
  mixpanel.init = function initMixpanel(projectToken, config, name) {
    const target = name ? (mixpanel[name] = mixpanel[name] || []) : mixpanel;
    target.people = target.people || [];
    for (const method of MIXPANEL_METHODS) createStub(target, method);
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.crossOrigin = 'anonymous';
    script.async = true;
    script.src = 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js';
    const firstScript = document.getElementsByTagName('script')[0];
    firstScript.parentNode.insertBefore(script, firstScript);
    const initArgs = [projectToken, config, name || 'mixpanel'];
    mixpanel._i.push(initArgs);
  };
  mixpanel.__SV = 1.2;
}

function hasMixpanelConsent() {
  try {
    return window.localStorage.getItem(MIXPANEL_CONSENT_STORAGE_KEY) === 'granted';
  } catch {
    return false;
  }
}

function installMixpanelRouteListeners() {
  if (mixpanelListenersInstalled) return;
  mixpanelListenersInstalled = true;
  const captureSoon = () => {
    window.requestAnimationFrame(captureMixpanelPageview);
  };
  const pushState = window.history.pushState;
  const replaceState = window.history.replaceState;
  window.history.pushState = function mixpanelPushState() {
    const result = pushState.apply(this, arguments);
    captureSoon();
    return result;
  };
  window.history.replaceState = function mixpanelReplaceState() {
    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 configureMixpanelAnalytics(config) {
  const projectToken = config?.mixpanelProjectToken;
  if (!projectToken || mixpanelConfigured) return;
  pendingMixpanelConfig = config;
  if (config.mixpanelRequiresConsent && !hasMixpanelConsent()) return;
  installMixpanelStub();
  getMixpanelGlobal().init(projectToken, {
    api_host: config.mixpanelApiHost || MIXPANEL_DEFAULT_API_HOST,
    debug: false,
    persistence: 'localStorage',
    track_pageview: false,
    ignore_dnt: false,
    batch_requests: true,
  });
  mixpanelConfigured = true;
  installMixpanelRouteListeners();
  window.requestAnimationFrame(captureMixpanelPageview);
}

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 identifyMixpanelUser(me) {
  const profileId = me?.profile?.id;
  const mixpanelClient = getMixpanelGlobal();
  if (!mixpanelConfigured || !profileId || !mixpanelClient?.identify) return;
  if (identifiedMixpanelUserId === profileId) return;
  identifiedMixpanelUserId = profileId;
  mixpanelClient.identify(profileId);
}

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

function resetMixpanelUser() {
  identifiedMixpanelUserId = null;
  const mixpanelClient = getMixpanelGlobal();
  if (mixpanelConfigured && mixpanelClient?.reset) mixpanelClient.reset();
}

function configureProductAnalytics(config) {
  configurePostHogAnalytics(config);
  configureMixpanelAnalytics(config);
}

function identifyAnalyticsUser(me) {
  identifyPostHogUser(me);
  identifyMixpanelUser(me);
}

function resetAnalyticsUser() {
  resetPostHogUser();
  resetMixpanelUser();
}

function setMixpanelConsent(granted) {
  try {
    window.localStorage.setItem(MIXPANEL_CONSENT_STORAGE_KEY, granted ? 'granted' : 'denied');
  } catch {
    // Ignore storage failures. Consent can be supplied again in the next session.
  }
  if (granted) {
    const mixpanelClient = getMixpanelGlobal();
    if (mixpanelConfigured && mixpanelClient?.opt_in_tracking) {
      mixpanelClient.opt_in_tracking();
      window.requestAnimationFrame(captureMixpanelPageview);
      return;
    }
    if (pendingMixpanelConfig) configureMixpanelAnalytics(pendingMixpanelConfig);
    return;
  }
  resetMixpanelUser();
  getMixpanelGlobal()?.opt_out_tracking?.();
}

window.configurePostHogAnalytics = configurePostHogAnalytics;
window.identifyPostHogUser = identifyPostHogUser;
window.resetPostHogUser = resetPostHogUser;
window.capturePostHogPageview = capturePostHogPageview;
window.configureMixpanelAnalytics = configureMixpanelAnalytics;
window.identifyMixpanelUser = identifyMixpanelUser;
window.resetMixpanelUser = resetMixpanelUser;
window.captureMixpanelPageview = captureMixpanelPageview;
window.configureProductAnalytics = configureProductAnalytics;
window.identifyAnalyticsUser = identifyAnalyticsUser;
window.resetAnalyticsUser = resetAnalyticsUser;
window.setMixpanelConsent = setMixpanelConsent;
