import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";

const GA_MEASUREMENT_ID = "G-GN9Q9BBCF9";

const initializeGoogleAnalytics = () => {
  if (typeof window === "undefined" || typeof document === "undefined") return;

  const gaScriptSelector = `script[src*="googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}"]`;
  if (!document.querySelector(gaScriptSelector)) {
    const script = document.createElement("script");
    script.async = true;
    script.src = `https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`;
    document.head.appendChild(script);
  }

  const win = window as Window & {
    dataLayer?: unknown[];
    gtag?: (...args: unknown[]) => void;
  };

  win.dataLayer = win.dataLayer || [];
  if (!win.gtag) {
    win.gtag = (...args: unknown[]) => {
      win.dataLayer?.push(args);
    };
  }

  win.gtag("js", new Date());
  win.gtag("config", GA_MEASUREMENT_ID);
};

// Defer GA initialization to not block initial render
if ("requestIdleCallback" in window) {
  (window as any).requestIdleCallback(initializeGoogleAnalytics);
} else {
  setTimeout(initializeGoogleAnalytics, 2000);
}

createRoot(document.getElementById("root")!).render(<App />);

