Branchwell

AI Resource Pro / website · airesourcepro.com / src / app / login / page.tsx

1"use client";
2
3import { Suspense, useCallback, useEffect, useRef, useState } from "react";
4import { useSearchParams } from "next/navigation";
5import Script from "next/script";
6
7type Provider = "google" | "apple";
8
9type Challenge = { nonce: string; providers: Record<Provider, string>; appleReturnURL: string };
10
11declare global {
12 interface Window {
13 google?: { accounts: { id: {
14 initialize(options: { client_id: string; nonce: string; callback(result: { credential: string }): void; ux_mode: "popup" }): void;
15 renderButton(element: HTMLElement, options: { type: "standard"; theme: "outline"; shape: "pill"; size: "large"; text: "continue_with"; width: number; logo_alignment: "left" }): void;
16 } } };
17 AppleID?: { auth: {
18 init(options: { clientId: string; scope: string; redirectURI: string; usePopup: boolean; nonce: string; state: string }): void;
19 signIn(): Promise<{ authorization: { id_token: string; state: string } }>;
20 } };
21 }
22}
23
24const ERRORS: Record<string, string> = {
25 no_auth_code: "Sign-in was interrupted. Please try again.",
26 auth_error: "Sign-in failed. Please try again.",
27};
28
29function LoginForm() {
30 const params = useSearchParams();
31 const next = params.get("next") || "/account";
32 const [pending, setPending] = useState<Provider | null>(null);
33 const [error, setError] = useState<string | null>(ERRORS[params.get("error") ?? ""] ?? null);
34
35 const [challenge, setChallenge] = useState<Challenge | null>(null);
36 const [googleReady, setGoogleReady] = useState(false);
37 const [appleReady, setAppleReady] = useState(false);
38 const [challengeError, setChallengeError] = useState(false);
39 const googleButton = useRef<HTMLDivElement>(null);
40
41 const refreshChallenge = useCallback(async () => {
42 setChallenge(null);
43 setChallengeError(false);
44 try {
45 const response = await fetch("/api/auth/identity/challenge", { method: "POST" });
46 if (!response.ok) throw new Error("Could not start sign-in.");
47 setChallenge(await response.json() as Challenge);
48 } catch {
49 setChallengeError(true);
50 }
51 }, []);
52
53 useEffect(() => { void refreshChallenge(); }, [refreshChallenge]);
54
55 const completeSignIn = useCallback(async (provider: Provider, token: string) => {
56 setPending(provider);
57 setError(null);
58 try {
59 const response = await fetch("/api/auth/identity", {
60 method: "POST", headers: { "Content-Type": "application/json" },
61 body: JSON.stringify({ provider, token }),
62 });
63 if (!response.ok) throw new Error("Sign-in unavailable.");
64 window.location.assign(`/auth/callback?next=${encodeURIComponent(next)}`);
65 } catch {
66 setError(ERRORS.auth_error);
67 setPending(null);
68 await refreshChallenge();
69 }
70 }, [next, refreshChallenge]);
71
72 useEffect(() => {
73 const google = window.google?.accounts.id;
74 const element = googleButton.current;
75 if (!challenge || !googleReady || !google || !element) return;
76 google.initialize({
77 client_id: challenge.providers.google, nonce: challenge.nonce, ux_mode: "popup",
78 callback: ({ credential }) => { void completeSignIn("google", credential); },
79 });
80 let lastWidth = 0;
81 const render = () => {
82 const width = Math.min(element.clientWidth, 400);
83 if (!width || width === lastWidth) return;
84 lastWidth = width;
85 element.replaceChildren();
86 google.renderButton(element, {
87 type: "standard", theme: "outline", shape: "pill", size: "large", text: "continue_with",
88 width, logo_alignment: "left",
89 });
90 };
91 const observer = new ResizeObserver(render);
92 observer.observe(element);
93 return () => { observer.disconnect(); element.replaceChildren(); };
94 }, [challenge, completeSignIn, googleReady]);
95
96 const signInWithApple = async () => {
97 const apple = window.AppleID?.auth;
98 if (!apple || !challenge) return;
99 setPending("apple");
100 setError(null);
101 try {
102 apple.init({
103 clientId: challenge.providers.apple, scope: "email",
104 redirectURI: challenge.appleReturnURL, usePopup: true, nonce: challenge.nonce, state: challenge.nonce,
105 });
106 const { authorization } = await apple.signIn();
107 if (authorization.state !== challenge.nonce) throw new Error("Sign-in was interrupted.");
108 await completeSignIn("apple", authorization.id_token);
109 } catch (failure) {
110 setPending(null);
111 if (typeof failure === "object" && failure !== null && "error" in failure && failure.error === "popup_closed_by_user") return;
112 setError(ERRORS.auth_error);
113 await refreshChallenge();
114 }
115 };
116
117 const buttonClass =
118 "flex h-10 w-full items-center justify-center gap-3 rounded-full font-mono text-[12.5px] font-semibold uppercase tracking-[0.07em] transition-colors disabled:pointer-events-none disabled:opacity-50";
119
120 return (
121 <div className="w-full max-w-md">
122 <Script src="https://accounts.google.com/gsi/client" onReady={() => setGoogleReady(true)} onError={() => setError("Google sign-in couldn’t load. Refresh to try again.")} />
123 <Script src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js" onReady={() => setAppleReady(true)} onError={() => setError("Apple sign-in couldn’t load. Refresh to try again.")} />
124 <p className="label">
125 <i />
126 Free account
127 </p>
128 <h1 className="display-title mt-6 text-[clamp(44px,6vw,80px)]">Sign in</h1>
129 <p className="mt-5 text-[17px] leading-relaxed text-[var(--mist)]">
130 Save tutorials and track what you&apos;ve finished. New here? Signing in creates your free account.
131 </p>
132 {error && (
133 <p role="alert" className="mt-8 rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-sm">{error}</p>
134 )}
135 <div className="mt-10 max-w-[400px] space-y-3">
136 {challengeError && <button className={buttonClass} onClick={() => void refreshChallenge()}>Retry sign-in</button>}
137 <div ref={googleButton} className={`min-h-10 w-full rounded-full ${!googleReady || !challenge ? "border border-foreground/15" : ""} ${pending ? "pointer-events-none opacity-50" : ""}`} aria-busy={!googleReady || !challenge} />
138 {pending === "google" && <p role="status" className="text-sm text-[var(--mist)]">Signing in…</p>}
139 <button
140 onClick={() => void signInWithApple()}
141 disabled={!appleReady || !challenge || !!pending}
142 className={`${buttonClass} border border-foreground/25 text-foreground hover:border-foreground/60`}
143 >
144 <svg className="h-[18px] w-[18px]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
145 <path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z" />
146 </svg>
147 {pending === "apple" ? "Connecting…" : "Continue with Apple"}
148 </button>
149 </div>
150 <p className="mt-8 text-xs text-[var(--ash)]">
151 By signing in you agree to the <a href="/account-rules" className="text-link">account rules</a>. Read the{" "}
152 <a href="/privacy" className="text-link">Privacy Policy</a>.
153 </p>
154 </div>
155 );
156}
157
158export default function LoginPage() {
159 return (
160 <div className="page flex min-h-[80vh] items-center justify-center">
161 <Suspense>
162 <LoginForm />
163 </Suspense>
164 </div>
165 );
166}