import { useEffect, useState } from 'react';
import { PrivacyConsent } from '../types.js';

export const useUserToken = () => {
  const [utk, setUtk] = useState<string | null>(null);

  useEffect(() => {
    let privacyConsent: PrivacyConsent;
    let isMounted = true;

    const areAnalyticsAllowed = () => {
      if (!privacyConsent) {
        return false;
      }
      return privacyConsent.categories
        ? privacyConsent.categories.analytics
        : privacyConsent.allowed;
    };

    const onTrackingCodeLoaded = (_utk: string | null) => {
      if (!privacyConsent || !_utk || !isMounted) {
        // Exit if utk and privacy consent cannot be obtained, or component unmounted
        return;
      }

      if (areAnalyticsAllowed()) {
        setUtk(_utk);
      } else {
        setUtk(null);
      }
    };

    if (window._hsq?.push) {
      window._hsq.push([
        'addPrivacyConsentListener',
        (_consent: PrivacyConsent) => {
          privacyConsent = _consent;

          if (window.__hsUserToken && areAnalyticsAllowed()) {
            if (isMounted) {
              setUtk(window.__hsUserToken);
            }
          } else {
            window._hsq?.push(['addUserTokenListener', onTrackingCodeLoaded]);
          }
        },
      ]);
    }

    return () => {
      isMounted = false;
    };
  }, []);

  return { utk };
};
