// @ts-nocheck
import { type MeInstance } from 'src/types/instance';
import { type MeUser } from 'src/types/user';

const apiKey = import.meta.env.VITE_CLARITY_ID;

export const setUser = async (user: MeUser, instance: MeInstance) => {
  if (!apiKey) {
    return;
  }
  ((c, l, a, r, i, t, y) => {
    c[a] =
      c[a] ||
      function () {
        (c[a].q = c[a].q || []).push(arguments);
      };
    t = l.createElement(r);
    t.async = 1;
    t.src = 'https://www.clarity.ms/tag/' + i;
    y = l.getElementsByTagName(r)[0];
    y.parentNode.insertBefore(t, y);
    window.clarity?.(
      'identify',
      `${user.id}`,
      null,
      null,
      `${user.employeeInternalId}`,
    );
    window.clarity('set', 'userId', `${instance.id}`); // window.clarity?.('identify',... is not working for some reason. this line replaces it
    window.clarity?.('set', 'username', `${user.employeeInternalId}`);
    window.clarity('set', 'instanceId', `${instance.id}`);
    window.clarity('set', 'instanceName', `${instance.name}`);
  })(window, document, 'clarity', 'script', apiKey);
};

export const clearUser = () => {
  window.clarity = null;
};
