import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { WagmiProvider } from 'wagmi'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ThirdwebProvider } from '@thirdweb-dev/react'
import { config } from './config/wagmi'
import { AdminProvider } from './contexts/AdminContext'
import { ErrorBoundary } from './components/ErrorBoundary'
import BridgePage from './pages/BridgePage'
import SwapPage from './pages/SwapPage'
import ReservePage from './pages/ReservePage'
import HistoryPage from './pages/HistoryPage'
import AdminPanel from './pages/AdminPanel'
import DocsPage from './pages/DocsPage'
import WalletsDemoPage from './pages/WalletsDemoPage'
import Layout from './components/layout/Layout'
import ToastProvider from './components/ui/ToastProvider'

// Configure QueryClient to handle contract revert errors gracefully
// Don't retry on contract revert errors (expected when contracts aren't deployed)
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: (failureCount, error: any) => {
        // Don't retry on contract revert errors (CALL_EXCEPTION)
        // These are expected when contracts aren't deployed at the specified addresses
        if (error?.code === 'CALL_EXCEPTION' || error?.message?.includes('call revert exception')) {
          return false;
        }
        // Retry other errors up to 2 times
        return failureCount < 2;
      },
    },
  },
})
const THIRDWEB_CLIENT_ID = import.meta.env.VITE_THIRDWEB_CLIENT_ID || '542981292d51ec610388ba8985f027d7'

function App() {
  return (
    <ErrorBoundary>
      <ThirdwebProvider clientId={THIRDWEB_CLIENT_ID}>
        <WagmiProvider config={config}>
          <QueryClientProvider client={queryClient}>
            <BrowserRouter
              future={{
                v7_startTransition: true,
                v7_relativeSplatPath: true,
              }}
            >
              <ToastProvider />
              <AdminProvider>
                <Layout>
                  <Routes>
                    <Route path="/" element={<BridgePage />} />
                    <Route path="/swap" element={<SwapPage />} />
                    <Route path="/reserve" element={<ReservePage />} />
                    <Route path="/history" element={<HistoryPage />} />
                    <Route path="/admin" element={<AdminPanel />} />
                    <Route path="/docs" element={<DocsPage />} />
                    <Route path="/wallets" element={<WalletsDemoPage />} />
                  </Routes>
                </Layout>
              </AdminProvider>
            </BrowserRouter>
          </QueryClientProvider>
        </WagmiProvider>
      </ThirdwebProvider>
    </ErrorBoundary>
  )
}

export default App

