"use client";

import Script from "next/script";
import { PropsWithChildren, useEffect } from "react";

const GA_ID = process.env.NEXT_PUBLIC_GA_ID;
const AMPLITUDE_ID = process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY;

export function AnalyticsProvider({ children }: PropsWithChildren) {
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (GA_ID && !(window as any).gtag) {
      (window as any).gtag = function gtag() {
        (window as any).dataLayer = (window as any).dataLayer || [];
        (window as any).dataLayer.push(arguments);
      };
      (window as any).gtag("js", new Date());
    }
  }, []);

  return (
    <>
      {GA_ID ? (
        <>
          <Script src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} strategy="afterInteractive" />
          <Script id="ga-init" strategy="afterInteractive">
            {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', '${GA_ID}');
            `}
          </Script>
        </>
      ) : null}
      {AMPLITUDE_ID ? (
        <Script id="amplitude-init" strategy="afterInteractive">
          {`
            (function(e,t){var n=e.amplitude||{_q:[],_iq:{}};var r=t.createElement("script");r.type="text/javascript";
            r.integrity="sha384-u+axhNOGMO4EgbUjKiugBC93akSZhULC7d8AhguUu1dZifPn1ejIFAnPO2qF6zXK";r.crossOrigin="anonymous";
            r.async=true;r.src="https://cdn.amplitude.com/libs/amplitude-8.17.0-min.gz.js";r.onload=function(){
            if(!e.amplitude.runQueuedFunctions){console.log("Amplitude snippet has failed.");}};
            var i=t.getElementsByTagName("script")[0];i.parentNode.insertBefore(r,i);
            function s(e,t){e.prototype[t]=function(){this._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return this}}
            var o=function(){this._q=[];return this};var a=["add","append","clearAll","prepend","set","setOnce","unset"];
            for(var c=0;c<a.length;c++){s(o,a[c])}n.Identify=o;var l=function(){this._q=[];return this};var u=["setProductId","setQuantity","setPrice","setRevenueType","setEventProperties"];
            for(var p=0;p<u.length;p++){s(l,u[p])}n.Revenue=l;var d=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain",
            "setDeviceId","enableTracking","setGlobalUserProperties","identify","clearUserProperties","setGroup","logRevenueV2","regenerateDeviceId","groupIdentify","onInit",
            "logEventWithTimestamp","logEventWithGroups","setSessionId","resetSessionId","getDeviceId","getUserId","setMinTimeBetweenSessionsMillis","setEventUploadThreshold","setUseDynamicConfig"];
            function v(e){function t(t){e[t]=function(){e._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return e}}
            for(var n=0;n<d.length;n++){t(d[n])}}v(n);e.amplitude=n;
            n.getInstance=function(e){e=(!e||e.length===0?"$default_instance":e).toLowerCase();if(!Object.prototype.hasOwnProperty.call(n._iq,e)){n._iq[e]={_q:[]};v(n._iq[e])}
            return n._iq[e]}; })(window,document);
            amplitude.getInstance().init('${AMPLITUDE_ID}');
          `}
        </Script>
      ) : null}
      {children}
    </>
  );
}
