import { useLocation } from 'react-router-dom';
import { useMount, useDeepCompareEffect } from 'ahooks';
import ReactGA from 'react-ga4';
import { googleAnalyticsMeasurementId } from './env';

if (googleAnalyticsMeasurementId) {
  ReactGA.initialize(googleAnalyticsMeasurementId);
}

export { ReactGA };
export default <P extends object>(WrappedComponent: React.ComponentType<P>) => {
  const trackPage = (page: string, title = document.title) => {
    if (googleAnalyticsMeasurementId) {
      ReactGA.send({ hitType: 'pageview', page, title });
    }
  };

  const trackEvent = (category: string, action: string, label: string, value: number) => {
    if (googleAnalyticsMeasurementId) {
      ReactGA.event({ category, action, label, value, transport: 'beacon' });
    }
  };

  // @ts-ignore
  window.trackPage = trackPage;
  // @ts-ignore
  window.trackEvent = trackEvent;

  return function TrackedComponent(props: P) {
    const location = useLocation();

    useMount(() => {
      trackPage(location.pathname);
    });

    useDeepCompareEffect(() => {
      trackPage(location.pathname);
    }, [location.pathname]);

    return <WrappedComponent {...props} />;
  };
};
