import { ShieldHalf } from "lucide-react";
import { useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";

function AuthCallbackPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const token = searchParams.get("token");
    if (token) {
      window.localStorage.setItem("admin_session", token);

      // 만약 팝업창에서 실행 중이라면 부모 창에 알리고 닫기
      if (window.opener) {
        window.opener.postMessage({ type: "LOGIN_SUCCESS", token }, "*");
        window.close();
      } else {
        // 일반 리다이렉트 방식인 경우 홈으로 이동
        navigate("/", { replace: true });
      }
    } else {
      console.error("No token found in callback URL");
      navigate("/login", { replace: true });
    }
  }, [navigate, searchParams]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-background">
      <div className="flex flex-col items-center gap-4">
        <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/15 text-primary shadow-lg animate-pulse">
          <ShieldHalf size={32} />
        </div>
        <div className="text-lg font-semibold">인증 완료 중...</div>
        <p className="text-sm text-muted-foreground">
          세션을 동기화하고 있습니다.
        </p>
      </div>
    </div>
  );
}

export default AuthCallbackPage;
