"use client";
import Script from "next/script";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { Waitlist } from "@/components/Waitlist";
import { ApiError, api, errorText } from "@/lib/api";
/** Google's "G" mark (branding guidelines: unmodified, on the left of the label). */
function GoogleMark() {
return (
);
}
/** The e-mail address inside Google's ID token (only for prefilling a form; the backend verifies the token). */
function tokenEmail(credential: string): string {
try {
const part = credential.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
const bytes = Uint8Array.from(atob(part), (c) => c.charCodeAt(0));
const email = JSON.parse(new TextDecoder().decode(bytes)).email;
return typeof email === "string" ? email : "";
} catch {
return "";
}
}
/**
* "Continue with Google" in the site's own button style. Google's real
* (rendered, invisible) button lies on top of it and receives the click, so
* the sign-in still returns an ID token.
*/
export function GoogleLogin({
clientId,
target,
inviteToken = null,
}: {
clientId: string;
target: string;
/** From an invitation link: lets in any Google account. */
inviteToken?: string | null;
}) {
const router = useRouter();
const slot = useRef(null);
const [ready, setReady] = useState(false);
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
/** Set when the address has no invitation: offer the waitlist for it. */
const [uninvited, setUninvited] = useState(null);
const onCredential = useCallback(
async (response: GoogleCredentialResponse) => {
setBusy(true);
setError(null);
setUninvited(null);
try {
await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken } });
router.replace(target);
router.refresh();
} catch (e) {
if (e instanceof ApiError && e.code === "not_invited") setUninvited(tokenEmail(response.credential));
else setError(errorText(e));
setBusy(false);
}
},
[router, target, inviteToken],
);
useEffect(() => {
const google = window.google;
if (!ready || !google || !slot.current) return;
google.accounts.id.initialize({ client_id: clientId, callback: onCredential, ux_mode: "popup", itp_support: true });
google.accounts.id.renderButton(slot.current, {
theme: "outline",
size: "large",
text: "continue_with",
shape: "rectangular",
locale: "hu",
width: Math.min(400, slot.current.clientWidth || 400),
});
}, [ready, clientId, onCredential]);
return (