/**
 * 应用根组件：BrowserRouter + 登录/路由守卫 + AppShell 布局壳 + 页面路由。
 */
import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { useAuthStore } from './stores/authStore.js';
import { AppShell } from './app/AppShell.js';
import { Dashboard } from './pages/Dashboard.js';
import { NewAssessment } from './pages/NewAssessment.js';
import { AssessmentDetail } from './pages/AssessmentDetail.js';
import { Login } from './pages/Login.js';
import { RateManagement } from './pages/RateManagement.js';
import { RedlineManagement } from './pages/RedlineManagement.js';
import { CustomerManagement } from './pages/CustomerManagement.js';
import { UserManagement } from './pages/UserManagement.js';
import { WorkflowManagement } from './pages/WorkflowManagement.js';
import { SystemLogs } from './pages/SystemLogs.js';

/** 路由守卫：未登录重定向到登录页。 */
function ProtectedRoute(): JSX.Element {
  const { isAuthenticated } = useAuthStore();
  return isAuthenticated ? <Outlet /> : <Navigate to="/login" replace />;
}

/** 角色守卫：当前角色不在允许列表时重定向回首页。 */
function RoleRoute({ allow }: { readonly allow: readonly string[] }): JSX.Element {
  const { user } = useAuthStore();
  const role = user?.role ?? '';
  return allow.includes(role) ? <Outlet /> : <Navigate to="/" replace />;
}

/** 首页：系统管理员不关心业务，重定向到用户管理；其余角色看评估看板。 */
function HomeRoute(): JSX.Element {
  const { user } = useAuthStore();
  if (user?.role === '系统管理员') return <Navigate to="/users" replace />;
  return <Dashboard />;
}

export function App(): JSX.Element {
  return (
    <BrowserRouter
      future={{
        v7_startTransition: true,
        v7_relativeSplatPath: true,
      }}
    >
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route element={<ProtectedRoute />}>
          <Route element={<AppShell />}>
            <Route path="/" element={<HomeRoute />} />
            <Route path="/new" element={<NewAssessment />} />
            <Route path="/assessments/:id" element={<AssessmentDetail />} />
            {/* 费率/红线管理：仅管理层 */}
            <Route element={<RoleRoute allow={['管理层']} />}>
              <Route path="/rates" element={<RateManagement />} />
              <Route path="/redlines" element={<RedlineManagement />} />
            </Route>
            {/* 客户档案：销售 + 管理层 */}
            <Route element={<RoleRoute allow={['商务/销售', '管理层']} />}>
              <Route path="/customers" element={<CustomerManagement />} />
            </Route>
            {/* 用户管理 + 审批流程：系统管理员 */}
            <Route element={<RoleRoute allow={['系统管理员']} />}>
              <Route path="/users" element={<UserManagement />} />
              <Route path="/workflow" element={<WorkflowManagement />} />
              <Route path="/system-logs" element={<SystemLogs />} />
            </Route>
          </Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
