/* eslint-disable no-underscore-dangle */
import { useEffect, useState } from 'react';
const defaultComplianceStates = ['CA', 'CO', 'CT', 'VA'];
const useIsComplianceLocation = function useIsComplianceLocation(opts = {}) {
  const {
    states = defaultComplianceStates
  } = opts;
  const [isComplianceLocation, setIsComplianceLocation] = useState(false);
  useEffect(() => {
    let timestampStart;
    const findUserLocation = callback => {
      const checkUserLocation = timestamp => {
        if (timestampStart === undefined) {
          timestampStart = timestamp;
        }
        const elapsed = timestamp - timestampStart;
        // Wait up to 10 seconds for OneTrust's geolocation to be set
        if (window.__otccpaooLocation == null && elapsed < 10000) {
          window.requestAnimationFrame(checkUserLocation);
        } else if (window.__otccpaooLocation != null) {
          if (callback != null) {
            callback(window.__otccpaooLocation);
          }
        }
      };
      window.requestAnimationFrame(checkUserLocation);
    };
    const getUserLocation = callback => {
      if (window.localStorage != null) {
        const userLocationStorage = window.localStorage.getItem('user_location');
        if (userLocationStorage != null) {
          const userLocation = JSON.parse(userLocationStorage);
          callback(userLocation);
        } else {
          findUserLocation(callback);
        }
      } else {
        findUserLocation(callback);
      }
    };
    const showHideLinks = userLocation => {
      setIsComplianceLocation(states.includes(userLocation.state.toUpperCase()));
    };
    getUserLocation(showHideLinks);
  }, [states]);
  return isComplianceLocation;
};
export default useIsComplianceLocation;