import { useContext, useEffect, useRef } from 'react';
import { AccountContext } from '../../contexts/AccountContext';
import { AuthContext } from '../../contexts/AuthContext';
import { useAnalyticsConsent } from '../../contexts/AnalyticsConsentContext';
import { AnalyticsEvents, identifyAccount, trackEvent } from '../../utils/analytics';

/**
 * Identify on authenticated session; track Logout when session ends.
 * Mount inside AnalyticsConsentProvider.
 */
const AnalyticsSession = (): null => {
  const { account } = useContext(AccountContext);
  const { authenticated, loading } = useContext(AuthContext);
  const { hasConsent } = useAnalyticsConsent();
  const wasAuthenticatedRef = useRef<boolean | null>(null);

  useEffect(() => {
    if (!hasConsent || loading) return;

    if (account) {
      identifyAccount(account);
      wasAuthenticatedRef.current = true;
      return;
    }

    if (wasAuthenticatedRef.current && !authenticated) {
      trackEvent(AnalyticsEvents.LOGOUT);
    }

    wasAuthenticatedRef.current = authenticated;
  }, [account, authenticated, hasConsent, loading]);

  return null;
};

export default AnalyticsSession;
