import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { HelmetProvider } from 'react-helmet-async';
import './index.css';
import App from './App.tsx';

declare global {
  interface Window {
    dataLayer: unknown[];
    gtag: (...args: unknown[]) => void;
  }
}

function ensureFavicon() {
  const iconHref = '/appicon.png?v=5';
  const appleHref = '/apple-touch-icon.png?v=5';
  const shortcutHref = '/appicon.png?v=5';

  const iconSelectors = [
    'link[rel="icon"][sizes="32x32"]',
    'link[rel="icon"][sizes="192x192"]',
  ];

  iconSelectors.forEach((selector) => {
    const element = document.querySelector<HTMLLinkElement>(selector) ?? document.createElement('link');
    element.rel = 'icon';
    element.type = 'image/png';
    element.href = iconHref;
    if (!element.getAttribute('sizes')) {
      element.setAttribute('sizes', '32x32');
    }
    if (!element.parentNode) {
      document.head.appendChild(element);
    }
  });

  const apple = document.querySelector<HTMLLinkElement>('link[rel="apple-touch-icon"]') ?? document.createElement('link');
  apple.rel = 'apple-touch-icon';
  apple.href = appleHref;
  if (!apple.parentNode) {
    document.head.appendChild(apple);
  }

  const shortcut = document.querySelector<HTMLLinkElement>('link[rel="shortcut icon"]') ?? document.createElement('link');
  shortcut.rel = 'shortcut icon';
  shortcut.href = shortcutHref;
  if (!shortcut.parentNode) {
    document.head.appendChild(shortcut);
  }
}

ensureFavicon();

function initGoogleAnalytics() {
  const measurementId = import.meta.env.VITE_GA_MEASUREMENT_ID;
  if (!measurementId) return;

  const script = document.createElement('script');
  script.async = true;
  script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
  document.head.appendChild(script);

  window.dataLayer = window.dataLayer || [];
  window.gtag = (...args: unknown[]) => {
    window.dataLayer.push(args);
  };

  window.gtag('js', new Date());
  window.gtag('config', measurementId, {
    page_path: window.location.pathname + window.location.search,
    anonymize_ip: true,
  });
}

initGoogleAnalytics();

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <HelmetProvider>
      <App />
    </HelmetProvider>
  </StrictMode>,
);
