import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export function Analytics() {
  const location = useLocation();

  useEffect(() => {
    // Inject Google Tag Manager
    const gtmId = import.meta.env.VITE_GTM_ID;
    if (gtmId) {
      const script = document.createElement("script");
      script.innerHTML = `
        (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','${gtmId}');
      `;
      document.head.appendChild(script);

      const noscript = document.createElement("noscript");
      noscript.innerHTML = `<iframe src="https://www.googletagmanager.com/ns.html?id=${gtmId}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
      document.body.insertBefore(noscript, document.body.firstChild);
    }

    // Inject Google Analytics (if separate from GTM)
    const gaId = import.meta.env.VITE_GA_MEASUREMENT_ID;
    if (gaId) {
      const scriptGa = document.createElement("script");
      scriptGa.async = true;
      scriptGa.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
      document.head.appendChild(scriptGa);

      const scriptInline = document.createElement("script");
      scriptInline.innerHTML = `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '${gaId}');
      `;
      document.head.appendChild(scriptInline);
    }

    // Inject Google Ads (if separate from above GA tag)
    const adsId = import.meta.env.VITE_GOOGLE_ADS_ID;
    if (adsId && adsId !== gaId) {
      const scriptAds = document.createElement("script");
      scriptAds.async = true;
      scriptAds.src = `https://www.googletagmanager.com/gtag/js?id=${adsId}`;
      document.head.appendChild(scriptAds);

      const scriptInline = document.createElement("script");
      scriptInline.innerHTML = `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '${adsId}');
      `;
      document.head.appendChild(scriptInline);
    }

    // Inject Meta/Facebook Pixel
    const pixelId = import.meta.env.VITE_FB_PIXEL_ID;
    if (pixelId) {
      const script = document.createElement("script");
      script.innerHTML = `
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init', '${pixelId}');
        fbq('track', 'PageView');
      `;
      document.head.appendChild(script);

      const noscript = document.createElement("noscript");
      noscript.innerHTML = `<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=${pixelId}&ev=PageView&noscript=1" />`;
      document.body.appendChild(noscript);
    }
  }, []);

  // Track page views on route change
  useEffect(() => {
    // GA PageView
    const gaId = import.meta.env.VITE_GA_MEASUREMENT_ID;
    if (gaId && typeof window !== "undefined" && (window as any).gtag) {
      (window as any).gtag("config", gaId, {
        page_path: location.pathname + location.search,
      });
    }

    // FB Pixel PageView
    const pixelId = import.meta.env.VITE_FB_PIXEL_ID;
    if (pixelId && typeof window !== "undefined" && (window as any).fbq) {
      (window as any).fbq('track', 'PageView');
    }
  }, [location]);

  return null;
}
