import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import { BrowserRouter } from 'react-router-dom'
import { AuthProvider } from './providers/AuthProvider'
import { SubscriptionProvider } from './providers/SubscriptionProvider'
import { Toaster } from './components/ui/toaster'

// Determine BrowserRouter basename to support both subdomain (root '/') and main domain under '/app'
const getBasename = () => {
  // Prefer runtime detection to support various hosting setups
  const { hostname, pathname } = window.location

  // If running on dedicated app subdomain, app is served from root
  if (hostname === 'app.zautomator.com') {
    return '/'
  }

  // If app is served under '/app' path on main domain, use '/app' as basename
  if (pathname === '/app' || pathname.startsWith('/app/')) {
    return '/app'
  }

  // Fallback to Vite-provided base URL
  const baseUrl = import.meta.env.BASE_URL || '/'
  if (baseUrl === './') return '/'
  if (!baseUrl.startsWith('/')) return `/${baseUrl}`
  return baseUrl
}

const basename = getBasename()

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