import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import type { ReactElement } from 'react';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import ReportEditor from './pages/ReportEditor';
import ReportManage from './pages/ReportManage';
import ReportView from './pages/ReportView';
import TemplateManage from './pages/TemplateManage';
import UserManage from './pages/UserManage';
import SystemSettings from './pages/SystemSettings';
import { AuthProvider, useAuth } from './auth/AuthContext';

function RequireAuth({ children }: { children: ReactElement }) {
  const { user, isLoading } = useAuth();

  if (isLoading && !user) {
    return <div className="min-h-screen bg-bg flex items-center justify-center text-sm font-semibold text-text-muted">正在恢复登录态...</div>;
  }

  if (!user) {
    return <Navigate to="/" replace />;
  }

  return children;
}

export default function App() {
  return (
    <AuthProvider>
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/dashboard" element={<RequireAuth><Dashboard /></RequireAuth>} />
          <Route path="/report-editor" element={<RequireAuth><ReportEditor /></RequireAuth>} />
          <Route path="/report-manage" element={<RequireAuth><ReportManage /></RequireAuth>} />
          <Route path="/report-view/:id" element={<RequireAuth><ReportView /></RequireAuth>} />
          <Route path="/template-manage" element={<RequireAuth><TemplateManage /></RequireAuth>} />
          <Route path="/user-manage" element={<RequireAuth><UserManage /></RequireAuth>} />
          <Route path="/system-settings" element={<RequireAuth><SystemSettings /></RequireAuth>} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </Router>
    </AuthProvider>
  );
}
