/**
 * 应用根组件
 * - 路由配置：登录页 + 后台管理布局（嵌套子路由）+ H5用户端（/pms/*）
 * - 未认证时自动跳转到登录页
 */

import { useEffect } from 'react';
import {
  BrowserRouter,
  Routes,
  Route,
  Navigate,
} from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';
import { useH5AuthStore } from '@/h5/auth';
import AdminLayout from '@/layouts/AdminLayout';
import Login from '@/pages/Login';
import Dashboard from '@/pages/Dashboard';
import Devices from '@/pages/devices';
import CabinetDetail from '@/pages/devices/cabinet';
import ChargeRecords from '@/pages/charge-records';
import DeviceLogs from '@/pages/device-logs';
import Energy from '@/pages/energy';
import Users from '@/pages/settings/users';
import Roles from '@/pages/settings/roles';
import OperationLogs from '@/pages/settings/operation-logs';
import { h5Routes } from '@/h5/routes';

/** 路由守卫：未认证时等待恢复，恢复失败则跳转到登录页 */
function RequireAuth({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, loading } = useAuthStore();
  if (loading) {
    return null; // 等待恢复完成
  }
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }
  return <>{children}</>;
}

/** 已登录用户访问登录页时重定向到 Dashboard */
function RedirectIfAuth({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuthStore();
  if (isAuthenticated) {
    return <Navigate to="/dashboard" replace />;
  }
  return <>{children}</>;
}

export default function App() {
  const restore = useAuthStore((s) => s.restore);
  const restoreH5 = useH5AuthStore((s) => s.restore);

  /** 应用启动时从 localStorage 恢复认证状态 */
  useEffect(() => {
    restore();
    restoreH5();
  }, [restore, restoreH5]);

  return (
    <BrowserRouter>
      <Routes>
        {/* 登录页 */}
        <Route
          path="/login"
          element={
            <RedirectIfAuth>
              <Login />
            </RedirectIfAuth>
          }
        />

        {/* 后台管理布局（需认证） */}
        <Route
          element={
            <RequireAuth>
              <AdminLayout />
            </RequireAuth>
          }
        >
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/devices" element={<Devices />} />
          <Route path="/devices/cabinet/:id" element={<CabinetDetail />} />
          <Route path="/charge-records" element={<ChargeRecords />} />
          <Route path="/device-logs" element={<DeviceLogs />} />
          <Route path="/energy" element={<Energy />} />
          <Route path="/settings/users" element={<Users />} />
          <Route path="/settings/roles" element={<Roles />} />
          <Route path="/settings/operation-logs" element={<OperationLogs />} />
        </Route>

        {/* H5 用户端路由 */}
        {h5Routes}

        {/* 默认重定向到 Dashboard */}
        <Route path="*" element={<Navigate to="/dashboard" replace />} />
      </Routes>
    </BrowserRouter>
  );
}
