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

export default <P extends object>(WrappedComponent: React.ComponentType<P>) => {
  const trackingId = window.blocklet?.GA_MEASUREMENT_ID || '';
  const trackPage = (page: string, title = document.title) => {
    if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
      return;
    }

    if (trackingId) {
      ReactGA.send({ hitType: 'pageview', page, title });
    }
  };

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

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

  // @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} />;
  };
};
