import { Component, type ReactNode } from 'react'
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import Home from './pages/Home'
import CreateLottery from './pages/CreateLottery'
import LotteryDetail from './pages/LotteryDetail'
import EditLottery from './pages/EditLottery'

class ErrorBoundary extends Component<{ children: ReactNode }, { error: string | null }> {
  state = { error: null }
  static getDerivedStateFromError(e: Error) { return { error: e.message } }
  render() {
    if (this.state.error) {
      return (
        <div style={{ padding: 20, fontFamily: 'monospace', color: '#c00' }}>
          <b>Render Error</b>
          <pre style={{ whiteSpace: 'pre-wrap', fontSize: 12 }}>{this.state.error}</pre>
          <p style={{ fontSize: 11, color: '#666' }}>
            initData: {window.Telegram?.WebApp?.initData?.slice(0, 60) || '(empty)'}
          </p>
        </div>
      )
    }
    return this.props.children
  }
}

export default function App() {
  return (
    <ErrorBoundary>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/create" element={<CreateLottery />} />
          <Route path="/lottery/:id" element={<LotteryDetail />} />
          <Route path="/lottery/:id/edit" element={<EditLottery />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </BrowserRouter>
    </ErrorBoundary>
  )
}
