./knowledge-base/frontend/src/auth/ProtectedRoute.tsx

/**
 * 認証ガードコンポーネント
 *
 * - 認証状態ロード中: ローディング表示
 * - 未認証: Okta ログインページへ自動リダイレクト
 * - 認証済み: 子コンポーネントを描画
 */
import { useEffect } from "react";
import { Box, CircularProgress } from "@mui/material";
import { useAuth } from "./AuthContext";
import type { ReactNode } from "react";

interface ProtectedRouteProps {
  children: ReactNode;
}

export function ProtectedRoute({ children }: ProtectedRouteProps) {
  const { isAuthenticated, isLoading, login } = useAuth();

  useEffect(() => {
    // ロード完了 かつ 未認証 → Okta ログインページへ
    if (!isLoading && !isAuthenticated) {
      login();
    }
  }, [isLoading, isAuthenticated, login]);

  // ロード中 or 未認証(リダイレクト待機中)はスピナーを表示
  if (isLoading || !isAuthenticated) {
    return (
      <Box
        sx={{
          minHeight: "100vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <CircularProgress />
      </Box>
    );
  }

  return <>{children}</>;
}