import { useMemo } from 'react';
import trackAnalyticsEvent from './trackAnalyticsEvent';

const trackedExperiments: { [key: string]: true } = {};

const useExperimentBranch = (experimentSlug: string, options: string[]) => {
  const branch = useMemo(() => {
    if (typeof localStorage !== 'undefined') {
      const cachedBranch = localStorage.getItem(`${experimentSlug}-experiment-branch`);
      const branch = cachedBranch || options[Math.floor(Math.random() * options.length)];
      localStorage.setItem(`${experimentSlug}-experiment-branch`, branch);
      if (!cachedBranch && !trackedExperiments[experimentSlug]) {
        trackedExperiments[experimentSlug] = true;
        trackAnalyticsEvent({
          name: 'Experiment Branch Assigned',
          properties: {
            experiment: experimentSlug,
            branch,
          },
        });
      }
      return branch;
    } else {
      return null;
    }
  }, [experimentSlug, options]);
  return branch;
};

export default useExperimentBranch;
