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

declare global {
  interface Window {
    adsbygoogle?: unknown[];
  }
}

function setupGoogleAds() {
  const env = (import.meta as ImportMeta & { env?: Record<string, string | undefined> }).env;
  const adsenseClient = env?.VITE_ADSENSE_CLIENT?.trim();

  if (!adsenseClient || !/^ca-pub-\d{16}$/.test(adsenseClient)) {
    return;
  }

  const existingScript = document.querySelector<HTMLScriptElement>(
    'script[src*="pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"]',
  );

  if (!existingScript) {
    const script = document.createElement("script");
    script.async = true;
    script.crossOrigin = "anonymous";
    script.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${adsenseClient}`;
    document.head.appendChild(script);
  }

  const existingMeta = document.querySelector<HTMLMetaElement>('meta[name="google-adsense-account"]');
  if (!existingMeta) {
    const meta = document.createElement("meta");
    meta.name = "google-adsense-account";
    meta.content = adsenseClient;
    document.head.appendChild(meta);
  }

  const autoAdsEnabled = (env?.VITE_ADSENSE_AUTO_ADS ?? "true").toLowerCase() === "true";
  if (autoAdsEnabled) {
    window.adsbygoogle = window.adsbygoogle || [];
    window.adsbygoogle.push({
      google_ad_client: adsenseClient,
      enable_page_level_ads: true,
    });
  }
}

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