import '@docsearch/css';
import '../styles/index.css';
import Script from 'next/script';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import * as gtag from 'utils/analytics';

export function reportWebVitals({ id, name, label, value }) {
  // Use `window.gtag` if you initialized Google Analytics as this example:
  // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_document.js
  window.gtag('event', name, {
    event_category:
      label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
    value: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
    event_label: id, // id unique to current page load
    non_interaction: true, // avoids affecting bounce rate.
  });
}

function MyApp({ Component, pageProps }) {
  const router = useRouter();
  useEffect(() => {
    const handleRouteChange = url => {
      gtag.pageview(url);
    };
    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return (
    <>
      <Script
        strategy="afterInteractive"
        src="https://buttons.github.io/buttons.js"
      />
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
      />
      <Script
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${gtag.GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;

@@ -469,16 +469,71 @@
 ment.js%0A
+  typeof window != 'undefined' &&%0A    window.gtag &&%0A  
   window
@@ -555,24 +555,26 @@
 name, %7B%0A    
+  
 event_catego
@@ -577,16 +577,18 @@
 tegory:%0A
+  
       la
@@ -653,16 +653,18 @@
 c',%0A    
+  
 value: M
@@ -740,16 +740,18 @@
 ntegers%0A
+  
     even
@@ -801,16 +801,18 @@
 oad%0A    
+  
 non_inte
@@ -859,16 +859,18 @@
 e rate.%0A
+  
   %7D);%0A%7D%0A

Tweak web vitals code