/* eslint-disable no-underscore-dangle */
import { useEffect } from 'react';
const useInitLocalizedCompliance = function useInitLocalizedCompliance() {
  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 => {
      console.log({
        userLocation
      });
      const geoLinksEls = window.document.querySelectorAll('a[data-show-on-geo]');
      console.log({
        geoLinksEls
      });
      geoLinksEls.forEach(el => {
        if ('showOnGeo' in el.dataset) {
          const locations = el.dataset.showOnGeo.split(',').map(location => location.trim().toUpperCase());
          const linkHasLocation = locations.includes(userLocation.state.toUpperCase());
          if (linkHasLocation) {
            // eslint-disable-next-line no-param-reassign
            el.style.display = 'inline';
          }
        }
      });
    };
    getUserLocation(showHideLinks);
  }, []);
};
export default useInitLocalizedCompliance;