import { Toaster } from '@/components/ui/toaster'
import { SSRProvider } from 'react-aria'
import { HeroUIProvider } from '@heroui/react'
import { AuthContextProvider } from '@Config/AuthContext'
import ReactDOM from 'react-dom/client'
import {
  createBrowserRouter,
  Navigate,
  RouterProvider,
  isRouteErrorResponse,
  useRouteError,
} from 'react-router-dom'
import './index.css'
import { Suspense, lazy, useEffect } from 'react'
import './i18n'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Toaster as SonnerToaster } from '@/components/ui/sonner'
import 'react-photo-view/dist/react-photo-view.css'
import useCtaAutoTracking from './Hooks/useCtaAutoTracking'
import React from 'react'
import { useTranslation } from 'react-i18next'

// Critical components loaded synchronously
import { LoadingPage } from '@Pages'

// Lazy load all route components for better code splitting
const App = lazy(() => import('./App/App'))
const AppLayout = lazy(() => import('./Layout/AppLayout'))
const LoggedRoute = lazy(() => import('./Routes/LoggedRoute'))
const ProtectedRoute = lazy(() => import('./Routes/ProtectedRoute'))

// Landing pages - lazy loaded
//const LandingPage = lazy(() => import('~/Pages/Global/landing/landing'))
const LandingPage = lazy(
  () => import('~/Pages/Global/landingPages/mainLanding/MainLanding'),
)

// const SocialSuiteLanding = lazy(() =>
//   import('@Pages').then(m => ({ default: m.LandingPage })),
// )
const WorkSuiteLanding = lazy(() =>
  import('@Pages').then(m => ({ default: m.WorkSuiteLanding })),
)
const LandingEsp = lazy(() =>
  import('@Pages').then(m => ({ default: m.LandingEsp })),
)
const Landing = lazy(() => import('@Pages').then(m => ({ default: m.Landing })))
const NotFound = lazy(() => import('./features/not-found'))
const Save50HoursAMonth = lazy(
  () => import('~/features/landing-pages/save-50-hours-a-month'),
)
const StartLeading = lazy(
  () => import('~/features/landing-pages/start-leading'),
)
const UltimateTool = lazy(
  () => import('~/features/landing-pages/ultimate-tool'),
)

// Auth pages - lazy loaded
const Login = lazy(() => import('@Pages').then(m => ({ default: m.Login })))
const SignUp = lazy(() => import('@Pages').then(m => ({ default: m.SignUp })))
const ResetPassword = lazy(() =>
  import('@Pages').then(m => ({ default: m.ResetPassword })),
)
const TokenLogin = lazy(() =>
  import('@Pages').then(m => ({ default: m.TokenLogin })),
)
const Redirect = lazy(() =>
  import('@Pages').then(m => ({ default: m.Redirect })),
)

// Legal pages - lazy loaded
const PrivacyPolicy = lazy(() =>
  import('@Pages').then(m => ({ default: m.PrivacyPolicy })),
)
const Terms = lazy(() => import('@Pages').then(m => ({ default: m.Terms })))
const CookiePolicy = lazy(() =>
  import('@Pages').then(m => ({ default: m.CookiePolicy })),
)
const McpConnectorDocs = lazy(() =>
  import('@Pages').then(m => ({ default: m.McpConnectorDocs })),
)

// Pricing & Features - lazy loaded
const NewPricing = lazy(() =>
  import('@Pages').then(m => ({ default: m.NewPricing })),
)
const Pricing = lazy(() => import('@Pages').then(m => ({ default: m.Pricing })))
const FeaturesPage = lazy(() =>
  import('@Pages').then(m => ({ default: m.FeaturesPage })),
)

// Welcome flow - lazy loaded
const Welcome = lazy(() => import('@Pages').then(m => ({ default: m.Welcome })))
const UserDemographics = lazy(
  () => import('./Pages/App/Welcome/Components/Demographics'),
)
const Finish = lazy(() => import('~/Pages/App/Welcome/Components/Finish'))

const Publish = lazy(() => import('@Pages').then(m => ({ default: m.Publish })))
const History = lazy(() => import('@Pages').then(m => ({ default: m.History })))
const SocialCalendar = lazy(() =>
  import('@Pages').then(m => ({ default: m.SocialCalendar })),
)
// const Analytics = lazy(() =>
//   import('@Pages').then(m => ({ default: m.Analytics })),
// )
const StorageV2 = lazy(() =>
  import('@Pages').then(m => ({ default: m.StorageV2 })),
)
const SocialAccounts = lazy(() =>
  import('@Pages').then(m => ({ default: m.SocialAccounts })),
)
const PostApproval = lazy(() =>
  import('@Pages').then(m => ({ default: m.PostApproval })),
)
const Invitation = lazy(() =>
  import('@Pages').then(m => ({ default: m.Invitation })),
)
const Integrations = lazy(() => import('~/Pages/App/Integrations'))
const GoogleDriveCallback = lazy(
  () => import('~/Pages/App/Integrations/GoogleDriveCallback'),
)
const OAuthConsentPage = lazy(() => import('~/Pages/OAuth/OAuthConsentPage'))

// Inbox - lazy loaded
// const TabLayout = lazy(() => import('./Pages/App/Inbox/Main'))
// const Inbox = lazy(() => import('./Pages/App/Inbox/Inbox'))
// const Comments = lazy(() => import('./Pages/App/Inbox/Comments'))
// const Mentions = lazy(() => import('./Pages/App/Inbox/Mentions'))

// Bots - lazy loaded
const Bots = lazy(() => import('@Pages').then(m => ({ default: m.Bots })))
const EditBot = lazy(() => import('@Pages').then(m => ({ default: m.EditBot })))
const NewBot = lazy(() => import('@Pages').then(m => ({ default: m.NewBot })))

// Planily - lazy loaded
const Planily = lazy(() => import('@Pages').then(m => ({ default: m.Planily })))
const PlanilyDashboard = lazy(() =>
  import('@Pages').then(m => ({ default: m.PlanilyDashboard })),
)
const Agenda = lazy(() => import('@Pages').then(m => ({ default: m.Agenda })))
const PlanilyTasks = lazy(() =>
  import('@Pages').then(m => ({ default: m.PlanilyTasks })),
)
const PlanilyFiles = lazy(() =>
  import('@Pages').then(m => ({ default: m.PlanilyFiles })),
)
const ProjectSettings = lazy(() =>
  import('@Pages').then(m => ({ default: m.ProjectSettings })),
)
const ProjectMembers = lazy(() =>
  import('@Pages').then(m => ({ default: m.ProjectMembers })),
)
const ProjectStatus = lazy(() =>
  import('@Pages').then(m => ({ default: m.ProjectStatus })),
)
const Permissions = lazy(() => import('@Planily/Pages/Permissions'))
const Categories = lazy(() => import('@Planily/Pages/Categories'))
const Groups = lazy(() => import('@Planily/Pages/Groups'))
const Trash = lazy(() => import('./Pages/App/Planily/Pages/Trash'))
const Communications = lazy(() =>
  import('@Pages').then(m => ({ default: m.Communications })),
)
const Chat = lazy(() => import('@Pages').then(m => ({ default: m.Chat })))
const Meetings = lazy(() =>
  import('@Pages').then(m => ({ default: m.Meetings })),
)
const MeetingRoom = lazy(() =>
  import('@Pages').then(m => ({ default: m.MeetingRoom })),
)
const JoinMeeting = lazy(() => import('./Pages/App/Planily/Pages/JoinMeeting'))
const Documents = lazy(() =>
  import('@Pages').then(m => ({ default: m.Documents })),
)
const Document = lazy(() =>
  import('@Pages').then(m => ({ default: m.Document })),
)
const Brainstorming = lazy(() =>
  import('@Pages').then(m => ({ default: m.Brainstorming })),
)

// Teams - lazy loaded
const Teams = lazy(() => import('@Pages').then(m => ({ default: m.Teams })))
const Members = lazy(() => import('@Pages').then(m => ({ default: m.Members })))
const MyTeams = lazy(() => import('@Pages').then(m => ({ default: m.MyTeams })))
const Roles = lazy(() => import('@Pages').then(m => ({ default: m.Roles })))
// const Socialsuite = lazy(() => import('~/Pages/App/Teams/pages/socialsuite'))
const Worksuite = lazy(() => import('~/Pages/App/Teams/pages/worksuite'))

// Settings - lazy loaded
const Settings = lazy(() =>
  import('@Pages').then(m => ({ default: m.Settings })),
)
const MyProfile = lazy(() =>
  import('@Pages').then(m => ({ default: m.MyProfile })),
)
const PlanUsage = lazy(() =>
  import('@Pages').then(m => ({ default: m.PlanUsage })),
)
const Tickets = lazy(() => import('@Pages').then(m => ({ default: m.Tickets })))
const Ticket = lazy(() => import('@Pages').then(m => ({ default: m.Ticket })))
const Workspaces = lazy(() =>
  import('@Pages').then(m => ({ default: m.Workspaces })),
)

// Billing - lazy loaded
const Billing = lazy(() => import('~/Pages/App/Billing/Plans/Billing'))
const Plans = lazy(() => import('~/Pages/App/Billing/Plans/plans'))
const PublishPlans = lazy(() => import('~/Pages/App/Billing/Tabs/PublishPlans'))
const PlanilyPlans = lazy(() => import('~/Pages/App/Billing/Tabs/PlanilyPlans'))
const Pays = lazy(() => import('@Pages').then(m => ({ default: m.Pays })))
const Success = lazy(() => import('@Pages').then(m => ({ default: m.Success })))

// Referrals - lazy loaded
const ReferralsPage = lazy(() =>
  import('@Pages').then(m => ({ default: m.ReferralsPage })),
)
const Referrals = lazy(() =>
  import('@Pages').then(m => ({ default: m.Referrals })),
)
const ReferralsDashboard = lazy(() =>
  import('@Pages').then(m => ({ default: m.ReferralsDashboard })),
)
const Conditions = lazy(() =>
  import('@Pages').then(m => ({ default: m.Conditions })),
)

const Contacts = lazy(() => import('~/Pages/App/Contacts'))

// Notifications - lazy loaded
const Notifications = lazy(() =>
  import('@Pages').then(m => ({ default: m.Notifications })),
)
const NotificationList = lazy(() =>
  import('@Pages').then(m => ({ default: m.NotificationList })),
)

// Other - lazy loaded
const FirebaseActionHandler = lazy(
  () => import('./Pages/Global/EmailVerification'),
)
const MaintenancePage = lazy(() => import('./Pages/Global/MaintenancePage'))

// Solutions - lazy loaded
const Solutions = lazy(() => import('~/Pages/Global/microsites/solutions'))

const Home = lazy(() => import('./Pages/App/Home/home'))



// Import solutionsRoutes dynamically - will be loaded when Solutions route is accessed
import { solutionsRoutes } from '~/Pages/Global/microsites/solutions/router'

// Define a flag for maintenance mode (all routes show MaintenancePage; toggle off when Firebase/app is back)
const isInMaintenance = true

// Maintenance Router
const maintenanceRouter = createBrowserRouter([
  {
    path: '*',
    element: <MaintenancePage />, // Maintenance mode for all paths
  },
])

// Lightweight loading component for better UX
// eslint-disable-next-line react-refresh/only-export-components
const RouteLoader = () => (
  <div className="flex h-screen w-full items-center justify-center">
    <LoadingPage />
  </div>
)

// eslint-disable-next-line react-refresh/only-export-components
function AppRouteErrorBoundary() {
  const error = useRouteError()
  const { t } = useTranslation(['global'])

  let title = t('global:route_error.title')
  let message = t('global:route_error.unexpected')

  if (isRouteErrorResponse(error)) {
    title = t('global:route_error.status', { status: error.status })
    if (error.status === 404) {
      message = t('global:route_error.not_found')
    }
  } else if (error instanceof Error) {
    if (error.message.includes('removeChild')) {
      message = t('global:route_error.video_problem')
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-neutral-50 px-4 dark:bg-neutral-950">
      <div className="w-full max-w-md rounded-2xl border border-neutral-200 bg-white p-6 text-center shadow-sm dark:border-neutral-800 dark:bg-neutral-900">
        <h1 className="text-lg font-semibold text-neutral-900 dark:text-neutral-100">
          {title}
        </h1>
        <p className="mt-2 text-sm text-neutral-600 dark:text-neutral-400">
          {message}
        </p>
        <div className="mt-5 flex items-center justify-center gap-2">
          <button
            type="button"
            onClick={() => window.location.reload()}
            className="cursor-pointer rounded-lg bg-pastel-purple px-4 py-2 text-sm font-medium text-white transition hover:bg-pastel-purple/90 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-100"
          >
            {t('global:route_error.reload')}
          </button>
          <button
            type="button"
            onClick={() => {
              window.location.href = '/app/dashboard'
            }}
            className="cursor-pointer rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium text-neutral-700 transition hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-200 dark:hover:bg-neutral-800"
          >
            {t('global:route_error.go_home')}
          </button>
        </div>
      </div>
    </div>
  )
}

// Helper to wrap routes with Suspense for lazy loading
const withSuspense = (Component: React.ReactNode) => (
  <Suspense fallback={<RouteLoader />}>{Component}</Suspense>
)

const router = createBrowserRouter([
  {
    path: '*',
    element: withSuspense(<NotFound />),
  },
  {
    path: '/google-drive/callback',
    element: withSuspense(<GoogleDriveCallback />),
  },
  {
    path: '/solutions',
    element: withSuspense(<Solutions />),
    children: solutionsRoutes,
  },
  {
    path: '/morehours',
    element: withSuspense(<Save50HoursAMonth />),
  },
  {
    path: '/start-leading',
    element: withSuspense(<StartLeading />),
  },
  {
    path: '/ultimate-tool',
    element: withSuspense(<UltimateTool />),
  },
  {
    element: withSuspense(<AppLayout />),
    errorElement: <AppRouteErrorBoundary />,
    children: [
      {
        path: '/',
        element: withSuspense(
          <LoggedRoute>
            <LandingPage />
          </LoggedRoute>,
        ),
      },
      // {
      //   path: '/es',
      //   element: withSuspense(<SocialSuiteLanding language="es" />),
      // },
      {
        path: '/landingesp',
        element: withSuspense(<LandingEsp />),
      },
      {
        path: '/pricing',
        element: withSuspense(<NewPricing />),
      },
      {
        path: '/features',
        element: withSuspense(<FeaturesPage />),
      },
      {
        path: '/pricing/en',
        element: withSuspense(<Pricing language="en" />),
      },
      {
        path: '/pricing/es',
        element: withSuspense(<Pricing language="es" />),
      },
      {
        path: '/landing-page',
        element: withSuspense(<Landing />),
      },
      {
        path: '/worksuite',
        element: withSuspense(<WorkSuiteLanding />),
      },
      // {
      //   path: '/socialsuite',
      //   element: withSuspense(<SocialSuiteLanding />),
      // },
      {
        path: '/login',
        element: withSuspense(<Login />),
      },
      {
        path: '/signup',
        element: withSuspense(<SignUp />),
      },
      {
        path: '/reset',
        element: withSuspense(<ResetPassword />),
      },
      {
        path: '/privacy',
        element: withSuspense(<PrivacyPolicy />),
      },
      {
        path: '/terms',
        element: withSuspense(<Terms />),
      },
      {
        path: '/cookies',
        element: withSuspense(<CookiePolicy />),
      },
      {
        path: '/docs/mcp',
        element: withSuspense(<McpConnectorDocs />),
      },
      {
        path: '/loading',
        element: <LoadingPage />,
      },
      {
        path: '/referrals',
        element: withSuspense(<ReferralsPage />),
      },
      {
        path: '/firebase-action',
        element: withSuspense(<FirebaseActionHandler />),
      },
      {
        path: '/welcome',
        element: withSuspense(
          <ProtectedRoute>
            <Welcome />
          </ProtectedRoute>,
        ),
        children: [
          //{
          //   path: '',
          //   element: <GreetingStep />,
          //},
          {
            path: '',
            element: withSuspense(<UserDemographics />),
          },
          // {
          //   path: 'plans',
          //   element: <PricingTable />,
          // },
          // {
          //   path: 'accounts',
          //   element: <AccountSetup />,
          // },
          // {
          //   path: 'checkout-success',
          //   element: <CheckoutSuccessful />,
          // },
          {
            path: 'finish',
            element: withSuspense(<Finish />),
          },
        ],
      },
      {
        path: '/app',
        element: withSuspense(
          <ProtectedRoute>
            <App />
          </ProtectedRoute>,
        ),
        children: [
          {
            path: 'dashboard',
            element: withSuspense(<Home />),
          },
          {
            path: 'contacts',
            element: withSuspense(<Contacts />),
          },
          {
            path: 'integrations',
            element: withSuspense(<Integrations />),
          },
          {
            path: 'publish',
            element: withSuspense(<Publish />),
          },
          {
            path: 'publish/history',
            element: withSuspense(<History />),
          },
          // {
          //   path: 'inbox',
          //   element: withSuspense(<TabLayout />),
          //   children: [
          //     {
          //       path: '',
          //       element: withSuspense(<Inbox />),
          //     },
          //     {
          //       path: 'comments',
          //       element: withSuspense(<Comments />),
          //     },
          //     {
          //       path: 'mentions',
          //       element: withSuspense(<Mentions />),
          //     },
          //   ],
          // },
          {
            path: 'publish/socialCalendar',
            element: withSuspense(<SocialCalendar />),
          },
          {
            path: 'tasks',
            element: <Navigate to="/app/planily" />,
          },
          {
            path: 'planily',
            element: withSuspense(<Planily />),
            children: [
              {
                path: ':projectId',
                children: [
                  {
                    path: '',
                    element: withSuspense(<PlanilyDashboard />),
                  },
                  {
                    path: 'dashboard',
                    element: withSuspense(<PlanilyDashboard />),
                  },
                  {
                    path: 'agenda',
                    element: withSuspense(<Agenda />),
                  },
                  {
                    path: 'view/:viewId',
                    element: withSuspense(<PlanilyTasks />),
                  },
                  {
                    path: 'settings',
                    element: withSuspense(<ProjectSettings />),
                  },
                  {
                    path: 'members',
                    element: withSuspense(<ProjectMembers />),
                  },
                  {
                    path: 'status',
                    element: withSuspense(<ProjectStatus />),
                  },
                  {
                    path: 'permissions',
                    element: withSuspense(<Permissions />),
                  },
                  {
                    path: 'categories',
                    element: withSuspense(<Categories />),
                  },
                  {
                    path: 'groups',
                    element: withSuspense(<Groups />),
                  },
                  {
                    path: 'communications',
                    element: withSuspense(<Communications />),
                    children: [
                      {
                        path: 'chats',
                        element: withSuspense(<Chat />),
                      },
                      {
                        path: 'meetings',
                        element: withSuspense(<Meetings />),
                      },
                      {
                        path: 'meetings/:meetingId',
                        element: withSuspense(<MeetingRoom />),
                      },
                    ],
                  },
                  {
                    path: 'documents',
                    element: withSuspense(<PlanilyFiles />),
                    children: [
                      {
                        path: '',
                        element: withSuspense(<Documents />),
                      },
                      {
                        path: ':documentId',
                        element: withSuspense(<Document />),
                      },
                      {
                        path: 'files',
                        element: withSuspense(<Brainstorming />),
                      },
                    ],
                  },
                  {
                    path: 'trash',
                    element: withSuspense(<Trash />),
                  },
                ],
              },
            ],
          },

          {
            path: 'bots',
            element: withSuspense(<Bots />),
          },
          {
            path: 'bots/:botId',
            element: withSuspense(<EditBot />),
          },
          {
            path: 'bots/new/:botType',
            element: withSuspense(<NewBot />),
          },
          // {
          //   path: 'analytics',
          //   element: withSuspense(<Analytics />),
          // },
          {
            path: 'referrals',
            element: withSuspense(<Referrals />),
            children: [
              {
                path: 'main',
                element: withSuspense(<ReferralsDashboard />),
              },
              {
                path: 'conditions',
                element: withSuspense(<Conditions />),
              },
            ],
          },
          {
            path: 'teams',
            element: withSuspense(<Teams />),
            children: [
              {
                path: 'members',
                element: withSuspense(<Members />),
              },
              {
                path: 'myTeams',
                element: withSuspense(<MyTeams />),
              },
              {
                path: 'roles',
                element: withSuspense(<Roles />),
              },
              // {
              //   path: 'socialsuite',
              //   element: withSuspense(<Socialsuite />),
              // },
              {
                path: 'worksuite',
                element: withSuspense(<Worksuite />),
              },
            ],
          },
          {
            path: 'storage',
            children: [
              {
                index: true,
                element: withSuspense(<StorageV2 />),
              },
              {
                path: 'shared',
                element: withSuspense(<StorageV2 />),
              },
              {
                path: 'shared/:folderId',
                element: withSuspense(<StorageV2 />),
              },
              {
                path: ':folderId',
                element: withSuspense(<StorageV2 />),
              },
              {
                path: 'trash',
                element: withSuspense(<StorageV2 />),
              },
              {
                path: 'trash/:folderId',
                element: withSuspense(<StorageV2 />),
              },
            ],
            // element:
            //   process.env.NODE_ENV === 'development' ? (
            //     <StorageV2 />
            //   ) : (
            //     <Storage />
            //   ),
          },
          {
            path: 'help',
            element: <h1>Help page</h1>,
          },
          {
            path: 'notifications',
            element: withSuspense(<Notifications />),
            children: [
              {
                path: 'new',
                element: withSuspense(<NotificationList />),
              },
              {
                path: 'read',
                element: withSuspense(<NotificationList read />),
              },
            ],
          },
          {
            path: 'settings',
            element: withSuspense(<Settings />),
            children: [
              {
                path: 'myProfile',
                element: withSuspense(<MyProfile />),
              },
              {
                path: 'planUsage',
                element: withSuspense(<PlanUsage />),
              },
              {
                path: 'tickets',
                element: withSuspense(<Tickets />),
              },
              {
                path: 'tickets/:ticketId',
                element: withSuspense(<Ticket />),
              },
              {
                path: 'workspaces',
                element: withSuspense(<Workspaces />),
              },

            ],
          },
          {
            path: 'socialAccounts',
            element: withSuspense(<SocialAccounts />),
          },
          {
            path: 'billing',
            element: withSuspense(<Billing />),
          },
          {
            path: 'billing/plans',
            element: withSuspense(<Plans />),
          },
          {
            path: 'billing/publish',
            element: withSuspense(<PublishPlans />),
          },
          {
            path: 'billing/planily',
            element: withSuspense(<PlanilyPlans />),
          },
          {
            path: 'billing/addons',
            element: withSuspense(<Pays />),
          },
          {
            path: 'billing/success',
            element: withSuspense(<Success />),
          },
          {
            path: 'postApproval',
            element: withSuspense(<PostApproval />),
          },
        ],
      },
      {
        path: '/app/invitation',
        element: withSuspense(
          <ProtectedRoute>
            <Invitation />
          </ProtectedRoute>,
        ),
      },
      {
        path: '/auth/*',
        element: withSuspense(<Redirect />),
      },
      {
        path: '/google-drive/callback',
        element: withSuspense(<GoogleDriveCallback />),
      },
      {
        path: '/oauth/consent',
        element: withSuspense(
          <ProtectedRoute>
            <OAuthConsentPage />
          </ProtectedRoute>,
        ),
      },
      {
        path: '/token-login',
        element: withSuspense(<TokenLogin />),
      },
      {
        path: '/join/:slug',
        element: withSuspense(<JoinMeeting />),
      },
    ],
  },
])

// Optimized QueryClient configuration for better performance
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      // Reduce refetch frequency to improve performance
      staleTime: 1000 * 60 * 5, // 5 minutes
      gcTime: 1000 * 60 * 10, // 10 minutes (formerly cacheTime)
      refetchOnWindowFocus: false,
      retry: 1,
    },
  },
})

// eslint-disable-next-line react-refresh/only-export-components
function TrackingBoot() {
  useCtaAutoTracking()

  useEffect(() => {
    const params = new URLSearchParams(window.location.search)
    const ref = params.get('ref')

    if (ref) {
      const sanitizedCode = ref.replace(/[^a-zA-Z0-9_]/g, '').substring(0, 20)

      if (sanitizedCode.length >= 3) {
        localStorage.setItem('affiliate_code', sanitizedCode)
      }
    }
  }, [])

  return null
}

// Preload critical routes on idle
if (typeof window !== 'undefined') {
  // Use requestIdleCallback to preload routes without blocking main thread
  const preloadRoutes = () => {
    // Preload landing page component
    import('~/Pages/Global/landing/landing')
    // Preload auth routes
    import('@Pages').then(m => {
      // Accessing exports triggers the module loading
      m.Login
      m.SignUp
    })
  }

  if ('requestIdleCallback' in window) {
    requestIdleCallback(preloadRoutes)
  } else {
    // Fallback for browsers without requestIdleCallback
    setTimeout(preloadRoutes, 1)
  }
}

// When a new deployment is pushed, old lazy-loaded chunk hashes no longer exist
// on the CDN and the browser receives an HTML 404 instead of JS, causing a
// "text/html is not a valid JavaScript MIME type" error. Vite fires this event
// so we can automatically reload to fetch the fresh HTML with the new chunk URLs.
window.addEventListener('vite:preloadError', () => {
  window.location.reload()
})

/**
 * @name index
 * @desc This file is the entry point of the application. It renders the App.tsx file into the div element with id="root" in the index.html file.
 * @return React App component.
 */
ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <SSRProvider>
      <HeroUIProvider>
        <QueryClientProvider client={queryClient}>
          <ReactQueryDevtools
            initialIsOpen={false}
            buttonPosition="bottom-right"
          />
          <AuthContextProvider>
            <Suspense fallback={<LoadingPage />}>
              <TrackingBoot />
              <RouterProvider
                router={isInMaintenance ? maintenanceRouter : router}
              />
            </Suspense>
            <Toaster />
            <SonnerToaster
            // toastOptions={{
            //   classNames: {
            //     title: '!text-zinc-500 dark:!text-zinc-300',
            //   },
            // }}
            />
          </AuthContextProvider>
        </QueryClientProvider>
      </HeroUIProvider>
    </SSRProvider>
  </React.StrictMode>,
)

export { router }
