import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './styles/globals.css'
import { getPaymentMode } from './features/payments/lib/paymentMode'

(() => {
  const html = document.documentElement
  try {
    if (html.classList.contains('dark')) {
      html.classList.remove('dark')
    }
    document.body.classList.remove('dark')
    html.style.colorScheme = 'light'
    html.setAttribute('data-theme', 'light')
  } catch {
  }
})()

// Validate payment gateway mode on startup
const mode = getPaymentMode()
if (!['CORE', 'SNAP'].includes(mode)) {
  throw new Error(`Invalid PAYMENT_GATEWAY_MODE: ${mode}. Must be 'CORE' or 'SNAP'`)
}
console.log(`[PAYMENT] Mode: ${mode}`)

// Load Snap.js script conditionally for Snap mode
if (mode === 'SNAP') {
  const script = document.createElement('script')
  script.src = 'https://app.sandbox.midtrans.com/snap/snap.js'
  script.setAttribute('data-client-key', import.meta.env.VITE_MIDTRANS_CLIENT_KEY || '')
  script.async = true
  document.head.appendChild(script)

  script.onload = () => {
    console.log('[SNAP] Snap.js loaded successfully')
  }

  script.onerror = () => {
    console.error('[SNAP] Failed to load Snap.js')
  }
}

import { AppRouter } from './app/router'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient({
  defaultOptions: { queries: { refetchOnWindowFocus: false, retry: 2 } },
})

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <AppRouter />
    </QueryClientProvider>
  </StrictMode>,
)
