const INTERCOM_APP_ID = 'afnx84bc';
const INTERCOM_WIDGET_URL = `https://widget.intercom.io/widget/${INTERCOM_APP_ID}`;
const INTERCOM_SESSION_DURATION_MS = 86400000;

let intercomLoaderInjected = false;
let identifiedIntercomUserId = null;
/** @type {Promise<unknown>|null} */
let identifyInFlight = null;

function getIntercomGlobal() {
  return /** @type {any} */ (window).Intercom;
}

function setIntercomGlobal(value) {
  /** @type {any} */ (window).Intercom = value;
}

function installIntercomStub() {
  if (typeof getIntercomGlobal() === 'function') return;
  const queue = function intercomQueuedCall() {
    queue.c(arguments);
  };
  queue.q = [];
  queue.c = function intercomEnqueue(args) {
    queue.q.push(args);
  };
  setIntercomGlobal(queue);
}

function injectIntercomLoader() {
  if (intercomLoaderInjected) return;
  intercomLoaderInjected = true;
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.async = true;
  script.src = INTERCOM_WIDGET_URL;
  const firstScript = document.getElementsByTagName('script')[0];
  if (firstScript?.parentNode) {
    firstScript.parentNode.insertBefore(script, firstScript);
  } else {
    document.head.appendChild(script);
  }
}

function intercomDisplayName(profile) {
  if (profile?.displayName) return profile.displayName;
  const nameParts = [profile?.firstName, profile?.lastName].filter(Boolean);
  return nameParts.length ? nameParts.join(' ') : undefined;
}

async function fetchIntercomToken() {
  const apiFetch = /** @type {any} */ (window).apiFetch;
  if (typeof apiFetch !== 'function') return null;
  try {
    const result = await apiFetch('/api/intercom/jwt');
    return result?.token || null;
  } catch (error) {
    // Endpoint returns 503 when INTERCOM_MESSENGER_SECRET is unset (e.g. local
    // dev). Any other failure is also fail-closed: skip Intercom rather than
    // boot with a spoofable identity.
    return null;
  }
}

async function identifyIntercomUser(me) {
  const profileId = me?.profile?.id;
  if (!profileId) return;
  if (identifiedIntercomUserId === profileId) return;
  if (identifyInFlight) return identifyInFlight;

  identifyInFlight = (async () => {
    const token = await fetchIntercomToken();
    if (!token) return;
    if (identifiedIntercomUserId === profileId) return;
    identifiedIntercomUserId = profileId;
    installIntercomStub();
    injectIntercomLoader();
    const intercomClient = getIntercomGlobal();
    if (typeof intercomClient !== 'function') return;
    intercomClient('boot', {
      app_id: INTERCOM_APP_ID,
      intercom_user_jwt: token,
      name: intercomDisplayName(me.profile),
      session_duration: INTERCOM_SESSION_DURATION_MS,
    });
  })();

  try {
    await identifyInFlight;
  } finally {
    identifyInFlight = null;
  }
}

function resetIntercomUser() {
  identifiedIntercomUserId = null;
  const intercomClient = getIntercomGlobal();
  if (typeof intercomClient === 'function') {
    intercomClient('shutdown');
  }
}

window.identifyIntercomUser = identifyIntercomUser;
window.resetIntercomUser = resetIntercomUser;
