// App root: auth gate + router + query client + dark mode (default).

import { useEffect, useState } from 'react'
import { Route, Switch, Redirect, useLocation } from 'wouter'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Shell } from './components/Shell'
import { LoginPage } from './pages/Login'
import { OverviewPage } from './pages/Overview'
import { RoutersPage } from './pages/Routers'
import { EventsPage } from './pages/Events'
import { CommandsPage } from './pages/Commands'
import { AlertsPage } from './pages/Alerts'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5_000,
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
})

function useAuth() {
  const [authed, setAuthed] = useState<boolean | null>(null)
  useEffect(() => {
    setAuthed(!!localStorage.getItem('c2s_token'))
    const handler = () => setAuthed(false)
    window.addEventListener('c2s:unauthorized', handler)
    return () => window.removeEventListener('c2s:unauthorized', handler)
  }, [])
  return { authed, setAuthed }
}

function Protected({ children }: { children: React.ReactNode }) {
  const { authed } = useAuth()
  const [, navigate] = useLocation()
  if (authed === null) return null
  if (!authed) {
    navigate('/login')
    return null
  }
  return <Shell>{children}</Shell>
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <div className="dark">
        <Switch>
          <Route path="/login" component={LoginPage} />
          <Route path="/"><Protected><OverviewPage /></Protected></Route>
          <Route path="/routers"><Protected><RoutersPage /></Protected></Route>
          <Route path="/events"><Protected><EventsPage /></Protected></Route>
          <Route path="/commands"><Protected><CommandsPage /></Protected></Route>
          <Route path="/alerts"><Protected><AlertsPage /></Protected></Route>
          <Route><Redirect to="/" /></Route>
        </Switch>
      </div>
    </QueryClientProvider>
  )
}
