import { useEffect } from "react";
import { useAuth } from "react-oidc-context";
import { useNavigate } from "react-router-dom";
import { userManager } from "../../lib/auth";

export default function AuthCallbackPage() {
  const auth = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    // 팝업으로 열린 경우 signinPopupCallback 처리
    if (window.opener) {
      userManager.signinPopupCallback().catch((error) => {
        console.error("Popup callback failed:", error);
      });
      return;
    }

    if (auth.isAuthenticated) {
      const returnTo =
        typeof auth.user?.state === "object" &&
        auth.user?.state !== null &&
        "returnTo" in auth.user.state &&
        typeof auth.user.state.returnTo === "string"
          ? auth.user.state.returnTo
          : "/chart";
      navigate(returnTo, { replace: true });
    } else if (auth.error) {
      console.error("Auth Error:", auth.error);
      navigate("/login", { replace: true });
    }
  }, [auth.isAuthenticated, auth.error, navigate, auth.user?.state]);

  return <div>Loading Auth...</div>;
}
