import { useAuth } from "react-oidc-context";
import { Navigate, Outlet, useLocation, useNavigate } from "react-router-dom";
import { t } from "../../lib/i18n";

export default function AuthGuard() {
  const auth = useAuth();
  const location = useLocation();
  const navigate = useNavigate();
  const searchParams = new URLSearchParams(location.search);
  const shareToken = searchParams.get("token");
  const isPlaywrightBypass =
    typeof window !== "undefined" &&
    (window.location.hostname === "127.0.0.1" ||
      window.location.hostname === "localhost") &&
    window.localStorage.getItem("playwright_auth_bypass") === "1";

  // 공유 토큰이 있는 경우 인증 체크를 건너뜁니다 (Public View)
  if (shareToken || isPlaywrightBypass) {
    return <Outlet />;
  }

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

  if (auth.error) {
    return <div>Auth Error: {auth.error.message}</div>;
  }

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

  // 조직도 앱은 일반 사용자(user)도 볼 수 있어야 하므로 접근 제한을 해제합니다.
  const isDenied = false; // normalizedRole === "guest";

  if (isDenied) {
    return (
      <div className="min-h-screen grid place-items-center bg-background text-foreground p-6">
        <div className="max-w-lg w-full rounded-xl border border-border bg-card p-6 space-y-4">
          <h1 className="text-xl font-semibold">
            {t("msg.dev.auth.access_denied_title", "접근 권한이 없습니다.")}
          </h1>
          <p className="text-sm text-muted-foreground">
            {t(
              "msg.dev.auth.access_denied_description",
              "조직도를 볼 수 있는 권한이 없습니다.",
            )}
          </p>
          <button
            type="button"
            className="inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90"
            onClick={() => {
              auth.removeUser();
              navigate("/login");
            }}
          >
            {t("ui.common.back_to_login", "로그인으로 돌아가기")}
          </button>
        </div>
      </div>
    );
  }

  return <Outlet />;
}
