import { useEffect } from 'react'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { useAuthStore } from './stores/auth'
import AppLayout from './layouts/AppLayout'
import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import Agents from './pages/Agents'
import Windows from './pages/Windows'
import AgentDetail from './pages/AgentDetail'
import ProxmoxServers from './pages/ProxmoxServers'
import Customers from './pages/Customers'
import SettingsPage from './pages/SettingsPage'
import Tunnels from './pages/Tunnels'
import Firmware from './pages/Firmware'
import AuditLog from './pages/AuditLog'

function ProtectedRoute({ children }) {
  const { isAuthenticated, loading } = useAuthStore()

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-950">
        <div className="text-gray-500">Laden...</div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  return children
}

export default function App() {
  const checkAuth = useAuthStore((s) => s.checkAuth)

  useEffect(() => {
    checkAuth()
  }, [])

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route
          path="/"
          element={
            <ProtectedRoute>
              <AppLayout />
            </ProtectedRoute>
          }
        >
          <Route index element={<Dashboard />} />
          <Route path="agents" element={<Agents />} />
          <Route path="agents/:id" element={<AgentDetail />} />
          <Route path="windows" element={<Windows />} />
          <Route path="proxmox" element={<ProxmoxServers />} />
          <Route path="tunnels" element={<Tunnels />} />
          <Route path="customers" element={<Customers />} />
          <Route path="firmware" element={<Firmware />} />
          <Route path="settings" element={<SettingsPage />} />
          <Route path="audit" element={<AuditLog />} />
        </Route>
      </Routes>
    </BrowserRouter>
  )
}
