import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter, useLocation } from 'react-router-dom'
import { HelmetProvider } from 'react-helmet-async'
import { AuthProvider } from './pages/admin/context/AuthContext'
import { ToastProvider } from './pages/admin/context/ToastContext'
import { SettingsProvider } from './pages/web/context/SettingsContext'
import AdminApp from './pages/admin/App'
import WebApp from './pages/web/App'
import './pages/admin/assets/scss/admin.scss'
import './pages/web/assets/scss/main.scss'

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props)
    this.state = { error: null }
  }
  static getDerivedStateFromError(error) {
    return { error }
  }
  render() {
    if (this.state.error) {
      return (
        <div style={{ padding: '2rem', fontFamily: 'monospace', color: '#c00' }}>
          <h2>App crashed — error details:</h2>
          <pre style={{ background: '#fff3f3', padding: '1rem', borderRadius: 6, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
            {this.state.error.toString()}
            {'\n\n'}
            {this.state.error.stack}
          </pre>
        </div>
      )
    }
    return this.props.children
  }
}

const App = () => {
  const { pathname } = useLocation()
  return pathname === '/admin' || pathname.startsWith('/admin/') ? <AdminApp /> : <WebApp />
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <ErrorBoundary>
      <HelmetProvider>
        <BrowserRouter>
          <AuthProvider>
            <ToastProvider>
              <SettingsProvider>
                <App />
              </SettingsProvider>
            </ToastProvider>
          </AuthProvider>
        </BrowserRouter>
      </HelmetProvider>
    </ErrorBoundary>
  </React.StrictMode>
)
