/* global amplitude */
let amplitudeConfigured = false;
let identifiedAmplitudeUserId = null;

function getAmplitudeGlobal() {
  return /** @type {any} */ (window).amplitude;
}

function cleanAmplitudeProperties(properties = {}) {
  return Object.fromEntries(
    Object.entries(properties).filter(([, value]) => value !== undefined && value !== null && value !== '')
  );
}

function currentAmplitudeRoute() {
  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 '/insights';
}

function configureAmplitudeAnalytics(config) {
  const apiKey = config?.amplitudeApiKey;
  if (!apiKey || amplitudeConfigured) return;
  const sessionReplaySampleRate = typeof config?.amplitudeSessionReplaySampleRate === 'number'
    ? config.amplitudeSessionReplaySampleRate
    : 0.1;
  const amp = getAmplitudeGlobal();
  if (!amp?.initAll) return;
  amp.initAll(apiKey, {
    analytics: {
      autocapture: {
        attribution: true, // captures marketing attribution user properties
        pageViews: true, // captures [Amplitude] Page Viewed
        sessions: true, // captures [Amplitude] Start Session and End Session
        formInteractions: false,
        fileDownloads: true, // captures [Amplitude] File Downloaded
        elementInteractions: true, // captures [Amplitude] Element Clicked and Element Changed
        frustrationInteractions: true, // captures rage, dead, error, and thrashed-cursor interactions
        networkTracking: false,
        webVitals: true, // captures [Amplitude] Web Vitals
      },
      remoteConfig: {
        fetchRemoteConfig: true, // fetches remote analytics configuration
      },
    },
    sessionReplay: {
      sampleRate: sessionReplaySampleRate, // enables Session Replay
    },
    engagement: {}, // enables Guides & Surveys
  });
  amplitudeConfigured = true;
}

function identifyAmplitudeUser(me) {
  const profileId = me?.profile?.id;
  const amp = getAmplitudeGlobal();
  if (!amplitudeConfigured || !profileId || !amp?.setUserId) return;
  if (identifiedAmplitudeUserId === profileId) return;
  identifiedAmplitudeUserId = profileId;
  amp.setUserId(profileId);
  if (amp?.Identify && amp?.identify) {
    const identify = new amp.Identify();
    if (me?.organization?.id) identify.set('organization_id', me.organization.id);
    if (me?.organization?.currentPlan) identify.set('current_plan', me.organization.currentPlan);
    if (me?.role) identify.set('workspace_role', me.role);
    amp.identify(identify);
  }
}

function resetAmplitudeUser() {
  identifiedAmplitudeUserId = null;
  const amp = getAmplitudeGlobal();
  if (amplitudeConfigured && amp?.reset) amp.reset();
}

function trackAmplitudeEvent(eventName, properties = {}) {
  const amp = getAmplitudeGlobal();
  if (!amplitudeConfigured || !amp?.track || !eventName) return;
  amp.track(eventName, {
    ...cleanAmplitudeProperties(properties),
    route: currentAmplitudeRoute(),
  });
}

window.configureAmplitudeAnalytics = configureAmplitudeAnalytics;
window.identifyAmplitudeUser = identifyAmplitudeUser;
window.resetAmplitudeUser = resetAmplitudeUser;
window.trackAmplitudeEvent = trackAmplitudeEvent;
