import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import './i18n'
import './index.css'
import App from './App'
import { CurrencyProvider } from './contexts/CurrencyContext'
import { getRouterBasename } from './utils/basePath'

const gaId = import.meta.env.VITE_GA_MEASUREMENT_ID
if (typeof window !== 'undefined' && gaId) {
  type GtagWindow = Window & { dataLayer: unknown[]; gtag?: (...args: unknown[]) => void }
  const w = window as unknown as GtagWindow
  w.dataLayer = w.dataLayer || []
  function gtag(...args: unknown[]) {
    w.dataLayer.push(args)
  }
  w.gtag = gtag
  gtag('js', new Date())
  gtag('config', gaId, { send_page_view: false })
  const script = document.createElement('script')
  script.async = true
  script.src = `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(gaId)}`
  document.head.appendChild(script)
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <CurrencyProvider>
      <BrowserRouter basename={getRouterBasename()}>
        <App />
      </BrowserRouter>
    </CurrencyProvider>
  </StrictMode>,
)
