import { useEffect, useMemo } from "react" import { authStore, type TokenPair } from "@/auth/store.ts" import { API_BASE } from "@/sdkClient.ts" import { useLocation, useNavigate } from "react-router-dom" import { cn } from "@/lib/utils.ts" import { Button } from "@/components/ui/button.tsx" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card.tsx" function openPopup(url: string, name = "gsot-auth", w = 520, h = 640) { const y = window.top!.outerHeight / 2 + window.top!.screenY - h / 2 const x = window.top!.outerWidth / 2 + window.top!.screenX - w / 2 return window.open( url, name, `toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=${w},height=${h},top=${y},left=${x}` ) } async function startAuth(provider: "google" | "github") { const params = new URLSearchParams({ mode: "spa", origin: window.location.origin, }) const res = await fetch(`${API_BASE}/auth/${provider}/start?` + params, { method: "POST", }) if (!res.ok) throw new Error("Failed to start auth") const data = await res.json() return data.auth_url as string } export const Login = () => { const navigate = useNavigate() const loc = useLocation() const to = useMemo(() => { const p = new URLSearchParams(loc.search).get("to") || "/me" try { // prevent absolute URLs & open redirects const url = new URL(p, window.location.origin) return url.origin === window.location.origin ? url.pathname + url.search : "/me" } catch { return "/me" } }, [loc.search]) useEffect(() => { if (authStore.get()?.access_token) { navigate(to, { replace: true }) } }, [navigate, to]) useEffect(() => { const onMsg = (ev: MessageEvent) => { const okType = typeof ev.data === "object" && ev.data?.type === "autoglue:auth" if (!okType) return const tokens: TokenPair = ev.data.payload authStore.set(tokens) navigate(to, { replace: true }) } window.addEventListener("message", onMsg) return () => window.removeEventListener("message", onMsg) }, [navigate, to]) const login = async (provider: "google" | "github") => { const url = await startAuth(provider) const win = openPopup(url) if (!win) alert("Please allow popups to sign in.") } return (