import { useAuth } from "react-oidc-context";
import { Navigate, Outlet, useLocation } from "react-router-dom";

export default function AuthGuard() {
  const auth = useAuth();
  const location = useLocation();
  const isTest =
    (window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean })
      ._IS_TEST_MODE === true;

  if (isTest) {
    return <Outlet />;
  }

  if (auth.isLoading || auth.activeNavigator) {
    return <div>Loading...</div>;
  }

  if (auth.error) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center p-4 text-center">
        <div className="mb-4 text-destructive">
          <h2 className="text-xl font-bold">인증 오류</h2>
          <p>{auth.error.message}</p>
        </div>
      </div>
    );
  }

  if (!auth.isAuthenticated) {
    const returnTo = `${location.pathname}${location.search}${location.hash}`;
    return (
      <Navigate
        to={`/login?returnTo=${encodeURIComponent(returnTo)}`}
        replace
      />
    );
  }

  return <Outlet />;
}
