accesscodes/src/app/donate/page.tsx
anonymousratwastaken ebfa25d1e8 Rework donate flow into guided steps with gift options
- Split the donate page into step components and reorder the flow: intent, rank or amount, recipient, gift, upgrade target, then confirm
- Let a gift go to a player on the other edition, and allow anonymous gifts (donor is left blank in metadata)
- Look up the recipient's current rank for upgrades and disable ranks they already hold
- Validate custom amounts on the server as integers between CUSTOM_MIN and CUSTOM_MAX
- Show friendly messages for checkout errors and send users back to the step that needs fixing
- Build the Stripe appearance from the page's glow accent colour, and tint the glow to match a custom amount's unlocked tier
2026-10-24 16:40:08 +01:00

828 lines
36 KiB
TypeScript

"use client";
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { loadStripe, type Appearance } from "@stripe/stripe-js";
import {
CheckoutElementsProvider,
ContactDetailsElement,
PaymentElement,
useCheckoutElements,
} from "@stripe/react-stripe-js/checkout";
import { toast } from "sonner";
import { ArrowLeft, Loader2, Leaf } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { CUSTOM_MAX, CUSTOM_MIN, TIERS, tierForCustom, upgradePrice, type TierId } from "@/lib/donations";
import { explainCheckoutError } from "@/lib/donate-errors";
import { usePlayerLookup } from "@/lib/player-lookup";
import { useFinePointer } from "@/lib/use-fine-pointer";
import { buildStripeAppearance } from "@/lib/stripe-appearance";
import { TopBar } from "@/components/top-bar";
import { DonateGlow, glowAccentStyle, type GlowTheme } from "@/components/donate-glow";
import { DonateHand, type Intent } from "@/components/donate-hand";
import { DonatePodium, type Rank } from "@/components/donate-podium";
import { GiftStage } from "@/components/donate-gift";
import { AmountStage } from "@/components/donate-amount";
import { ConfirmStage } from "@/components/donate-confirm";
import { PlayerStage } from "@/components/donate-player";
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? "");
const DRAFT_KEY = "frg-donate-draft-v1";
const PAYMENT_STEP = "payment";
type Answers = {
intent: string;
rank: string;
upgradeTo: string;
gift: string;
platform: "java" | "bedrock";
player: string;
giftTo: string;
giftPlatform: "" | "java" | "bedrock";
anonymous: boolean;
customPounds: string;
customRecurring: boolean;
};
const EMPTY_ANSWERS: Answers = {
intent: "",
rank: "",
upgradeTo: "",
// Most donations are for the donor, so that is the starting answer.
gift: "no",
platform: "java",
player: "",
giftTo: "",
giftPlatform: "",
anonymous: false,
customPounds: "",
customRecurring: false,
};
const money = (pence: number) => `£${(pence / 100).toFixed(2)}`;
// The rank the recipient already holds, which decides what an upgrade costs.
type RankLookup = { status: "idle" | "checking" | "found" | "none" | "error"; current: TierId | null; label?: string };
const IDLE_RANK: RankLookup = { status: "idle", current: null };
function useCurrentRank(raw: string, platform: "java" | "bedrock", enabled: boolean): RankLookup {
const name = raw.trim();
const key = `${platform}:${name.toLowerCase()}`;
const [result, setResult] = useState<{ key: string; value: RankLookup } | null>(null);
const active = enabled && name.length >= 3;
useEffect(() => {
if (!active) return;
let stale = false;
const t = setTimeout(async () => {
let value: RankLookup = { status: "error", current: null };
try {
const r = await fetch(`/api/donations/verify?username=${encodeURIComponent(name)}&platform=${platform}`);
const j = await r.json();
if (r.ok && !j.error) value = j.current ? { status: "found", current: j.current, label: j.label } : { status: "none", current: null };
} catch {}
if (!stale) setResult({ key, value });
}, 400);
return () => { stale = true; clearTimeout(t); };
}, [active, key, platform, name]);
if (!active) return IDLE_RANK;
if (result?.key !== key) return { status: "checking", current: null };
return result.value;
}
// The upgrade step's podium. The recipient's current rank is looked up from
// their name: ranks at or below it stay on the podium but cannot be picked,
// and the rest show the price of the difference.
function UpgradeStage({ value, onChange, onPreview, rank, name }: {
value: string;
onChange: (v: Rank) => void;
onPreview: (id: Rank | null) => void;
rank: RankLookup;
name: string;
}) {
const current = rank.current;
const known = rank.status === "found";
// Iron is the floor: it is never an upgrade target. Until the current rank
// is known nothing is priced, and if it cannot be found nothing can be picked.
const canPick = (id: Rank) =>
id !== "iron" && rank.status !== "none" && rank.status !== "error" && !(current && !upgradePrice(current, id));
const disabled = (["iron", "gold", "diamond"] as const).filter((id) => !canPick(id));
return (
<div className="flex flex-col gap-4">
<p aria-live="polite" className={cn("min-h-5 text-center text-sm", known || rank.status === "checking" ? "text-muted-foreground" : "text-destructive")}>
{rank.status === "checking" ? "Checking their current rank…"
: known ? <>{name} is <span className="font-medium text-foreground">{rank.label}</span> now</>
: rank.status === "none" ? <>No rank found for &quot;{name}&quot;. Upgrades need an existing rank, so go back to check the name or buy a rank instead.</>
: rank.status === "error" ? "We couldn't check their rank just now. Go back and try again in a moment."
: null}
</p>
<DonatePodium
ariaLabel="Upgrade to which rank?"
value={value}
onSelect={onChange}
onPreview={onPreview}
disabled={disabled}
price={(id) => {
if (!canPick(id)) return null;
const diff = current ? upgradePrice(current, id) : null;
return diff != null ? money(diff) : null;
}}
note={(id) => (canPick(id) ? (known ? "upgrade price" : undefined) : id === "iron" ? "Starting rank" : current === id ? "Their rank" : undefined)}
/>
</div>
);
}
// What the confirm and payment steps list, worked out from the answers.
type Summary = { rows: { label: string; value: React.ReactNode }[]; total: string; perks?: string[] };
function confirmSummary(ans: Answers, rank: RankLookup): Summary {
const edition = ans.gift === "yes" ? ans.giftPlatform || ans.platform : ans.platform;
const rows: Summary["rows"] = [
{ label: "Edition", value: <span className="capitalize">{edition}</span> },
];
let total = "—";
let perks: string[] | undefined;
if (ans.intent === "rank" && ans.rank) {
const t = TIERS[ans.rank as "iron" | "gold" | "diamond"];
rows.push({ label: "Getting", value: <span className="text-primary">{t.label}</span> });
total = money(t.price);
perks = [...t.perks];
} else if (ans.intent === "patron") {
rows.push({ label: "Getting", value: <span className="text-primary">{TIERS.patron.label}</span> });
total = `${money(TIERS.patron.price)} / month`;
perks = [...TIERS.patron.perks];
} else if (ans.intent === "upgrade" && ans.upgradeTo) {
const t = TIERS[ans.upgradeTo as "gold" | "diamond"];
const diff = rank.current ? upgradePrice(rank.current, ans.upgradeTo as TierId) : null;
if (rank.label) rows.push({ label: "Current rank", value: rank.label });
rows.push({ label: "Getting", value: <span className="text-primary">{t.label}</span> });
total = diff != null ? money(diff) : "Worked out at checkout";
perks = [...t.perks];
} else if (ans.intent === "custom") {
const pounds = parseFloat(ans.customPounds);
const pence = Math.round((isNaN(pounds) ? 0 : pounds) * 100);
const unlocked = tierForCustom(pence, ans.customRecurring);
rows.push({ label: "Getting", value: unlocked ? <span className="text-primary">{TIERS[unlocked as keyof typeof TIERS].label}</span> : "Donation" });
rows.push({ label: "Frequency", value: ans.customRecurring ? "Monthly" : "One-time" });
total = `${money(pence)}${ans.customRecurring ? " / month" : ""}`;
if (unlocked) perks = [...TIERS[unlocked as keyof typeof TIERS].perks];
}
return { rows, total, perks };
}
type Pending = Summary & {
clientSecret: string;
isSub: boolean;
recipient: string;
platform: "java" | "bedrock";
// Who a gift is from; absent when it is not a gift.
from?: string;
};
function PaymentStage({ pending, glow, onBack }: { pending: Pending; glow: GlowTheme; onBack: () => void }) {
const root = useRef<HTMLElement>(null);
const [appearance, setAppearance] = useState<Appearance | null>(null);
// The accent lives on this element, so Stripe's colours are read from here.
useEffect(() => {
if (root.current) setAppearance(buildStripeAppearance(root.current));
}, []);
return (
<main ref={root} style={glowAccentStyle(glow)} className="relative z-0 min-h-dvh bg-background text-foreground font-mona">
<DonateGlow theme={glow} className="max-lg:hidden lg:right-1/2" />
{appearance ? (
<CheckoutElementsProvider
stripe={stripePromise}
options={{ clientSecret: pending.clientSecret, elementsOptions: { appearance } }}
>
<CheckoutShell pending={pending} onBack={onBack} />
</CheckoutElementsProvider>
) : (
<div className="min-h-dvh flex items-center justify-center">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
)}
</main>
);
}
function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => void }) {
const state = useCheckoutElements();
const [submitting, setSubmitting] = useState(false);
if (state.type === "loading") {
return (
<div className="min-h-dvh flex items-center justify-center">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
</div>
);
}
if (state.type === "error") {
return (
<div className="min-h-dvh flex items-center justify-center px-4">
<div className="text-center space-y-3">
<h1 className="text-xl font-semibold">Couldn&apos;t load checkout</h1>
<p className="text-sm text-muted-foreground">{state.error.message}</p>
<Button variant="outline" className="h-11 px-5 text-sm" onClick={onBack}>Back</Button>
</div>
</div>
);
}
const checkout = state.checkout;
const currency = checkout.currency;
const divisor = checkout.minorUnitsAmountDivisor || 100;
const total = checkout.total.total.minorUnitsAmount / divisor;
const fmt = (n: number) =>
new Intl.NumberFormat("en-GB", { style: "currency", currency }).format(n);
const totalText = `${fmt(total)}${pending.isSub ? " / month" : ""}`;
async function pay(e: React.FormEvent) {
e.preventDefault();
if (submitting) return;
setSubmitting(true);
try {
const result = await checkout.confirm();
if (result.type === "error") {
toast.error(result.error?.message || "Payment failed");
setSubmitting(false);
}
} catch {
toast.error("Payment failed");
setSubmitting(false);
}
}
const summary = {
recipient: pending.recipient,
platform: pending.platform,
from: pending.from,
rows: pending.rows,
total: totalText,
perks: pending.perks,
};
return (
<div className="min-h-dvh lg:h-dvh lg:overflow-hidden lg:grid lg:grid-cols-2">
<aside className="hidden lg:flex flex-col border-r border-border p-10 overflow-y-auto">
<div className="flex items-center gap-3">
<Button
onClick={onBack}
aria-label="Back"
variant="outline"
size="icon"
className="size-11 rounded-full"
>
<ArrowLeft className="size-4" />
</Button>
<span className="font-semibold">FRG Network</span>
</div>
<div className="mx-auto mt-8 w-full max-w-sm">
<ConfirmStage {...summary} />
</div>
<div className="flex-1" />
<Button onClick={onBack} variant="link" className="self-start h-11 p-0 text-sm text-foreground/80">
Change donation details
</Button>
</aside>
<section className="flex flex-col overflow-y-auto">
<header className="lg:hidden sticky top-0 z-10 backdrop-blur bg-background/80 border-b border-border">
<div className="mx-auto max-w-[400px] flex items-center gap-3 px-4 py-2">
<Button
onClick={onBack}
aria-label="Back"
variant="outline"
size="icon"
className="size-11 rounded-full"
>
<ArrowLeft className="size-4" />
</Button>
<span className="font-semibold text-sm">FRG Network</span>
<span className="ml-auto text-sm font-semibold tabular-nums">{totalText}</span>
</div>
</header>
<form onSubmit={pay} className="mx-auto w-full max-w-[400px] min-w-72 px-4 py-8 lg:my-auto space-y-6">
<div className="lg:hidden">
<ConfirmStage {...summary} compact />
</div>
<section className="space-y-2.5">
<h2 className="text-base font-semibold tracking-tight">Contact information</h2>
<ContactDetailsElement />
</section>
<section className="space-y-2.5">
<h2 className="text-base font-semibold tracking-tight">Payment method</h2>
<PaymentElement />
</section>
<div className="space-y-2">
<Button type="submit" className="w-full h-12 text-base font-semibold tabular-nums" disabled={submitting || !checkout.canConfirm}>
{submitting ? <Loader2 className="size-4 animate-spin" /> : `Pay ${totalText}`}
</Button>
{pending.isSub && (
<p className="text-center text-xs text-muted-foreground">Renews every month until cancelled.</p>
)}
</div>
<div className="flex items-start gap-2.5 text-xs text-muted-foreground">
<Leaf className="size-4 text-primary shrink-0 mt-0.5" />
<p>
FRG Network will contribute{" "}
<span className="font-semibold text-foreground">1.5% of your purchase</span> to removing
CO₂ from the atmosphere.
</p>
</div>
<div className="flex items-center justify-center gap-3 text-xs text-muted-foreground">
<span className="flex items-center gap-1.5">
Powered by
<svg width="360" height="151" viewBox="0 0 360 151" aria-label="Stripe" role="img" className="h-3 w-auto text-foreground">
<path fill="currentColor" fillRule="evenodd" clipRule="evenodd" d="M360 78.0002C360 52.4002 347.6 32.2002 323.9 32.2002C300.1 32.2002 285.7 52.4002 285.7 77.8002C285.7 107.9 302.7 123.1 327.1 123.1C339 123.1 348 120.4 354.8 116.6V96.6002C348 100 340.2 102.1 330.3 102.1C320.6 102.1 312 98.7002 310.9 86.9002H359.8C359.8 85.6002 360 80.4002 360 78.0002ZM310.6 68.5002C310.6 57.2002 317.5 52.5002 323.8 52.5002C329.9 52.5002 336.4 57.2002 336.4 68.5002H310.6Z" />
<path fill="currentColor" fillRule="evenodd" clipRule="evenodd" d="M247.1 32.2002C237.3 32.2002 231 36.8002 227.5 40.0002L226.2 33.8002H204.2V150.4L229.2 145.1L229.3 116.8C232.9 119.4 238.2 123.1 247 123.1C264.9 123.1 281.2 108.7 281.2 77.0002C281.1 48.0002 264.6 32.2002 247.1 32.2002ZM241.1 101.1C235.2 101.1 231.7 99.0002 229.3 96.4002L229.2 59.3002C231.8 56.4002 235.4 54.4002 241.1 54.4002C250.2 54.4002 256.5 64.6002 256.5 77.7002C256.5 91.1002 250.3 101.1 241.1 101.1Z" />
<path fill="currentColor" fillRule="evenodd" clipRule="evenodd" d="M169.8 26.3001L194.9 20.9001V0.600098L169.8 5.9001V26.3001Z" />
<path fill="currentColor" d="M194.9 33.9001H169.8V121.4H194.9V33.9001Z" />
<path fill="currentColor" fillRule="evenodd" clipRule="evenodd" d="M142.9 41.3001L141.3 33.9001H119.7V121.4H144.7V62.1001C150.6 54.4001 160.6 55.8001 163.7 56.9001V33.9001C160.5 32.7001 148.8 30.5001 142.9 41.3001Z" />
<path fill="currentColor" fillRule="evenodd" clipRule="evenodd" d="M92.8999 12.2002L68.4999 17.4002L68.3999 97.5002C68.3999 112.3 79.4999 123.2 94.2999 123.2C102.5 123.2 108.5 121.7 111.8 119.9V99.6002C108.6 100.9 92.7999 105.5 92.7999 90.7002V55.2002H111.8V33.9002H92.7999L92.8999 12.2002Z" />
<path fill="currentColor" fillRule="evenodd" clipRule="evenodd" d="M25.3 59.3002C25.3 55.4002 28.5 53.9002 33.8 53.9002C41.4 53.9002 51 56.2002 58.6 60.3002V36.8002C50.3 33.5002 42.1 32.2002 33.8 32.2002C13.5 32.2002 0 42.8002 0 60.5002C0 88.1002 38 83.7002 38 95.6002C38 100.2 34 101.7 28.4 101.7C20.1 101.7 9.5 98.3002 1.1 93.7002V117.5C10.4 121.5 19.8 123.2 28.4 123.2C49.2 123.2 63.5 112.9 63.5 95.0002C63.4 65.2002 25.3 70.5002 25.3 59.3002Z" />
</svg>
</span>
<span aria-hidden className="h-3 border-l border-border" />
<a href="https://stripe.com/legal/terms-of-use" target="_blank" rel="noopener noreferrer" className="hover:text-foreground transition-colors">Terms</a>
<a href="https://stripe.com/legal/privacy-policy" target="_blank" rel="noopener noreferrer" className="hover:text-foreground transition-colors">Privacy</a>
</div>
</form>
</section>
</div>
);
}
const TIER_GLOW: Record<string, GlowTheme> = { iron: "iron", gold: "gold", diamond: "diamond", patron: "purple" };
// Green until a choice is made, then a colour per intent, then per rank.
function glowFor(ans: Answers, step: string): GlowTheme {
const rankColour = step !== "intent" ? TIER_GLOW[ans.intent === "upgrade" ? ans.upgradeTo : ans.rank] : undefined;
switch (ans.intent) {
case "rank": return rankColour ?? "lime";
case "upgrade": return rankColour ?? "teal";
case "patron": return "purple";
case "custom": {
// From the amount step on, the glow climbs with the rank the amount unlocks.
const pounds = parseFloat(ans.customPounds);
if (step !== "intent" && !isNaN(pounds) && pounds >= 1) {
const unlocked = tierForCustom(Math.round(pounds * 100), ans.customRecurring);
if (unlocked && TIER_GLOW[unlocked]) return TIER_GLOW[unlocked];
}
return "blue";
}
default: return "green";
}
}
export default function DonatePage() {
return (
<Suspense fallback={<main className="min-h-dvh bg-background" />}>
<DonateFlow />
</Suspense>
);
}
// A step's question. Focus moves here when the step changes, so a screen
// reader hears the new question and a keyboard starts from the top.
function StepHeading({ title, hint }: { title: string; hint?: string }) {
return (
<div className="flex flex-col gap-1.5 text-center">
<h2 tabIndex={-1} className="text-2xl font-semibold tracking-tight text-balance outline-none">{title}</h2>
{hint && <p className="mx-auto max-w-sm text-sm/relaxed text-pretty text-muted-foreground">{hint}</p>}
</div>
);
}
// The URL is the source of truth for where the visitor is: /donate is the
// first step and /donate?step=<name> is any step, so browser back/forward
// walk the flow.
function DonateFlow() {
const finePointer = useFinePointer();
const stepParam = useSearchParams().get("step");
const [ans, setAns] = useState<Answers>(EMPTY_ANSWERS);
const [restored, setRestored] = useState(false);
const [pending, setPending] = useState<Pending | null>(null);
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
// The card or rank under the pointer or keyboard focus on the intent and
// rank steps; the glow previews it before it is chosen.
const [preview, setPreview] = useState<string | null>(null);
// An error to show on the step the visitor is about to be sent back to.
const flash = useRef<string | null>(null);
const stage = useRef<HTMLDivElement>(null);
const firstStep = useRef(true);
const set = (patch: Partial<Answers>) => {
setError(null);
// A checkout session no longer matches once an answer changes.
setPending(null);
setAns((a) => ({ ...a, ...patch }));
};
// Each navigation is its own history entry. The depth is kept in
// history.state so the Back button can pop an entry we pushed, instead of
// piling new ones on top, and falls back to replacing on a deep link.
function go(name: string | null, mode: "push" | "replace" = "push") {
const url = name ? `/donate?step=${name}` : "/donate";
const depth: number = window.history.state?.donateDepth ?? 0;
if (mode === "push") window.history.pushState({ donateDepth: depth + 1 }, "", url);
else window.history.replaceState({ donateDepth: depth }, "", url);
}
useEffect(() => {
try {
const raw = localStorage.getItem(DRAFT_KEY);
if (raw) {
const d = JSON.parse(raw) as Partial<Answers>;
// Landing on the first screen is a fresh start: only the name fields
// are carried over, so no card or option arrives pre-selected. A
// reload or deep link into a later step restores the whole draft so
// the flow picks up where it was.
const step = new URLSearchParams(window.location.search).get("step");
const fresh = step === null || step === "intent";
setAns((a) => ({
...a,
platform: d.platform === "bedrock" ? "bedrock" : d.platform === "java" ? "java" : a.platform,
player: d.player ?? a.player,
...(fresh ? {} : {
intent: d.intent ?? a.intent,
rank: d.rank ?? a.rank,
upgradeTo: d.upgradeTo ?? a.upgradeTo,
gift: d.gift === "yes" ? "yes" : d.gift === "no" ? "no" : a.gift,
giftTo: d.giftTo ?? a.giftTo,
giftPlatform: d.giftPlatform === "java" || d.giftPlatform === "bedrock" ? d.giftPlatform : a.giftPlatform,
anonymous: d.anonymous === true,
customPounds: d.customPounds ?? a.customPounds,
customRecurring: d.customRecurring ?? a.customRecurring,
}),
}));
}
} catch {}
setRestored(true);
}, []);
useEffect(() => {
if (!restored) return;
try {
localStorage.setItem(DRAFT_KEY, JSON.stringify(ans));
} catch {}
}, [restored, ans]);
// Every question is a step. Conditional steps appear based on answers. What
// a rank or amount costs does not depend on who it is for, so that comes
// first; an upgrade is priced from the recipient's rank, so it comes after.
const steps = useMemo(() => {
const s: string[] = ["intent"];
if (ans.intent === "rank") s.push("rank");
if (ans.intent === "custom") s.push("amount");
s.push("username", "gift");
if (ans.intent === "upgrade") s.push("upgrade");
s.push("confirm");
return s;
}, [ans.intent]);
const started = stepParam !== null;
const step = stepParam !== null && steps.includes(stepParam) ? stepParam : steps[0];
const current = steps.indexOf(step);
const last = step === "confirm";
const gifting = ans.gift === "yes";
const recipientName = gifting ? ans.giftTo.trim() : ans.player.trim();
const recipientPlatform = gifting ? ans.giftPlatform || ans.platform : ans.platform;
const donorLookup = usePlayerLookup(ans.platform, ans.player, step === "username");
const giftLookup = usePlayerLookup(ans.giftPlatform || ans.platform, ans.giftTo, step === "gift" && gifting && !!ans.giftPlatform);
const rank = useCurrentRank(recipientName, recipientPlatform, ans.intent === "upgrade");
const editionName = (p: string) => (p === "java" ? "Java" : "Bedrock");
// `strict` adds the checks that need a network lookup. Reload and deep-link
// routing leave it off, so a slow lookup never bounces someone backwards.
function validateStep(name: string, strict = true): string | null {
switch (name) {
case "intent": return ans.intent ? null : "Choose an option to continue.";
case "rank": return ans.rank ? null : "Choose a rank to continue.";
case "amount": {
const p = parseFloat(ans.customPounds.trim());
if (isNaN(p)) return "Enter an amount to continue.";
if (p * 100 < CUSTOM_MIN) return `The smallest donation is £${CUSTOM_MIN / 100}.`;
if (p * 100 > CUSTOM_MAX) return `The largest online donation is £${(CUSTOM_MAX / 100).toLocaleString("en-GB")}.`;
return null;
}
case "username":
if (ans.player.trim().length < 3) return "Enter your Minecraft name (3+ characters).";
if (strict && donorLookup.status === "missing") return `No ${editionName(ans.platform)} player called "${ans.player.trim()}". Check the spelling, or switch edition.`;
return null;
case "gift":
if (ans.gift === "yes") {
if (!ans.giftPlatform) return "Choose whether your friend plays Java or Bedrock.";
if (ans.giftTo.trim().length < 3) return "Enter your friend's Minecraft name (3+ characters).";
if (ans.giftTo.trim().toLowerCase() === ans.player.trim().toLowerCase() && ans.giftPlatform === ans.platform) {
return "That's your own name. Choose \"For me\" to buy it for yourself.";
}
if (strict && giftLookup.status === "missing") return `No ${editionName(ans.giftPlatform)} player called "${ans.giftTo.trim()}". Check the spelling and the edition.`;
return null;
}
return ans.gift === "no" ? null : "Choose an answer to continue.";
case "upgrade":
if (!ans.upgradeTo) return "Choose a rank to upgrade to.";
if (!strict) return null;
if (rank.status === "checking") return "Still checking their current rank. One moment.";
if (rank.status === "none") return `No rank found for "${recipientName}". Upgrades need an existing rank, so go back to check the name or buy a rank instead.`;
if (rank.status === "error") return "We couldn't check their rank just now. Try again in a moment.";
if (rank.current && !upgradePrice(rank.current, ans.upgradeTo as TierId)) return "They already have that rank or a higher one. Choose a higher rank.";
return null;
default: return null;
}
}
// Where the URL should really be: a step is only reachable once every step
// before it is answered, and payment needs a live checkout session. This
// covers reloads, deep links and stale forward entries.
function resolveStep(param: string): string {
if (param === PAYMENT_STEP && pending) return PAYMENT_STEP;
const target = steps.includes(param) ? param : "confirm";
for (const s of steps) {
if (s === target || validateStep(s, false)) return s;
}
return steps[0];
}
const resolved = restored && stepParam !== null ? resolveStep(stepParam) : null;
// True while the draft is loading or a redirect is about to happen.
const waiting = stepParam !== null && resolved !== stepParam;
useEffect(() => {
if (resolved && resolved !== stepParam) go(resolved, "replace");
}, [resolved, stepParam]);
useEffect(() => {
setError(flash.current);
flash.current = null;
}, [stepParam]);
// Hand focus to the new question. A field that takes focus itself on a
// mouse device keeps it; on a phone that would raise the keyboard, so the
// heading gets it instead.
useEffect(() => {
if (firstStep.current) { firstStep.current = false; return; }
if (finePointer && (step === "username" || step === "amount")) return;
stage.current?.querySelector<HTMLElement>("h2")?.focus({ preventScroll: true });
}, [step, finePointer]);
function goNext() {
const err = validateStep(step);
if (err) { setError(err); return; }
setError(null);
go(steps[Math.min(current + 1, steps.length - 1)]);
}
function chooseIntent(id: Intent) {
set({ intent: id });
setPreview(null);
}
function goBack() {
setError(null);
if ((window.history.state?.donateDepth ?? 0) > 0) window.history.back();
else go(current > 0 ? steps[current - 1] : null, "replace");
}
// Sends the visitor back to a step with a reason, instead of a toast on a
// screen that has nothing to fix.
function sendBack(to: string, message: string) {
flash.current = message;
go(to);
}
async function handleSubmit() {
if (submitting) return;
for (const s of steps) {
if (s === "confirm") break;
const err = validateStep(s);
if (err) { sendBack(s, err); return; }
}
const playerVal = ans.player.trim();
const giftToVal = ans.giftTo.trim();
let tier: string;
let customAmount: number | undefined;
let isUpgrade = false;
if (ans.intent === "patron") tier = "patron";
else if (ans.intent === "rank") tier = ans.rank;
else if (ans.intent === "upgrade") { tier = ans.upgradeTo; isUpgrade = true; }
else if (ans.intent === "custom") {
customAmount = Math.round(parseFloat(ans.customPounds.trim()) * 100);
tier = "custom";
} else { sendBack("intent", "Choose an option to continue."); return; }
setSubmitting(true);
try {
const res = await fetch("/api/donations/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
platform: ans.platform,
giftPlatform: gifting ? ans.giftPlatform || undefined : undefined,
username: playerVal,
tier,
customAmount,
customRecurring: ans.customRecurring || undefined,
giftTo: gifting ? giftToVal || undefined : undefined,
anonymous: gifting && ans.anonymous ? true : undefined,
upgrade: isUpgrade || undefined,
}),
});
const text = await res.text();
let j: { clientSecret?: string; error?: string } = {};
try { j = JSON.parse(text); } catch { toast.error("We couldn't start checkout. Nothing has been charged. Please try again in a moment."); return; }
if (j.clientSecret) {
const isSub = ans.intent === "patron" || (ans.intent === "custom" && ans.customRecurring);
setPending({
...confirmSummary(ans, rank),
clientSecret: j.clientSecret,
isSub,
recipient: recipientName,
platform: recipientPlatform,
from: gifting ? (ans.anonymous ? "Anonymous" : playerVal) : undefined,
});
go(PAYMENT_STEP);
} else {
const failure = explainCheckoutError(j.error ?? "", gifting);
if (failure.step) sendBack(failure.step, failure.message);
else toast.error(failure.message);
}
} catch {
toast.error("We couldn't reach checkout. Check your connection and try again. Nothing has been charged.");
} finally {
setSubmitting(false);
}
}
function onFormSubmit(e: React.FormEvent) {
e.preventDefault();
if (last) handleSubmit();
else goNext();
}
const glow: GlowTheme = glowFor(
preview && step === "intent" ? { ...ans, intent: preview }
: preview && step === "rank" ? { ...ans, rank: preview }
: ans,
step,
);
if (stepParam === PAYMENT_STEP && pending && !waiting) {
return <PaymentStage pending={pending} glow={glowFor(ans, "confirm")} onBack={() => window.history.back()} />;
}
if (waiting) {
return <main className="min-h-dvh bg-background" />;
}
if (!started) {
return (
<main style={glowAccentStyle(glow)} className="relative z-0 min-h-dvh bg-background text-foreground font-mona flex flex-col">
<DonateGlow theme={glow} />
<TopBar />
<div className="flex-1 flex items-center justify-center px-4 py-12">
<div className="max-w-md w-full text-center space-y-6">
<h1 className="text-3xl font-semibold tracking-tight">Support FRG</h1>
<p className="text-sm text-muted-foreground">Ranks are cosmetic only. Your donation keeps the server running and funds new features.</p>
<Button size="lg" onClick={() => go("intent")} className="h-11 w-full text-sm font-semibold">Donate</Button>
<p className="mx-auto max-w-xs rounded-xl bg-background/70 px-4 py-2 text-xs/relaxed text-foreground/80">Secure via Stripe · 1.5% to <a href="https://stripe.com/gb/climate" target="_blank" rel="noopener noreferrer" className="underline underline-offset-2">Stripe Climate</a></p>
</div>
</div>
</main>
);
}
const errorLine = error && step !== "amount"
? <p className="text-center text-sm text-destructive" role="alert">{error}</p>
: null;
return (
<main style={glowAccentStyle(glow)} className="relative z-0 min-h-dvh bg-background text-foreground font-mona flex flex-col">
<DonateGlow theme={glow} />
<TopBar />
<div className="flex-1 flex items-center justify-center px-4 py-8">
<div className={cn("w-full", step === "intent" ? "max-w-4xl" : "max-w-md")}>
<p className="text-center text-xs font-medium text-muted-foreground tabular-nums">
Step {current + 1}{ans.intent ? ` of ${steps.length}` : ""}
</p>
<form onSubmit={onFormSubmit} className="mt-2 flex flex-col gap-4">
<div ref={stage}>
{step === "intent" && (
<section className="flex min-w-0 flex-col gap-4">
<StepHeading title="How do you want to donate?" />
<DonateHand value={ans.intent} onSelect={chooseIntent} onPreview={setPreview} />
{errorLine}
</section>
)}
{step === "rank" && (
<section className="flex min-w-0 flex-col gap-4">
<StepHeading title="Which rank?" />
<DonatePodium value={ans.rank} onSelect={(id) => { set({ rank: id }); setPreview(null); }} onPreview={setPreview} />
{errorLine}
</section>
)}
{step === "amount" && (
<section className="flex min-w-0 flex-col gap-6">
<StepHeading title="How much?" />
<AmountStage
pounds={ans.customPounds}
recurring={ans.customRecurring}
error={error}
onPounds={(customPounds) => set({ customPounds })}
onRecurring={(customRecurring) => set({ customRecurring })}
/>
</section>
)}
{step === "username" && (
<section className="flex min-w-0 flex-col gap-4">
<StepHeading title="What's your username?" />
<PlayerStage
platform={ans.platform}
value={ans.player}
status={donorLookup.status}
resolvedName={donorLookup.name}
onChange={(player) => set({ player })}
onPlatformChange={(platform) => set({ platform })}
/>
{errorLine}
</section>
)}
{step === "gift" && (
<section className="flex min-w-0 flex-col gap-4">
<StepHeading title="Is this a gift?" />
<GiftStage
platform={ans.platform}
player={ans.player}
gift={ans.gift}
giftTo={ans.giftTo}
giftPlatform={ans.giftPlatform}
anonymous={ans.anonymous}
lookup={giftLookup}
onGift={(gift) => set({ gift })}
onGiftTo={(giftTo) => set({ giftTo })}
onGiftPlatform={(giftPlatform) => set({ giftPlatform })}
onAnonymous={(anonymous) => set({ anonymous })}
/>
{errorLine}
</section>
)}
{step === "upgrade" && (
<section className="flex min-w-0 flex-col gap-4">
<StepHeading title="Upgrade to which rank?" hint="We'll charge only the difference from the rank they have now." />
<UpgradeStage value={ans.upgradeTo} onChange={(upgradeTo) => { set({ upgradeTo }); setPreview(null); }} onPreview={setPreview} rank={rank} name={recipientName} />
{errorLine}
</section>
)}
{step === "confirm" && (
<section className="flex min-w-0 flex-col gap-5">
<StepHeading title="Confirm details" />
<ConfirmStage
recipient={recipientName}
platform={recipientPlatform}
from={gifting ? (ans.anonymous ? "Anonymous" : ans.player.trim()) : undefined}
{...confirmSummary(ans, rank)}
/>
</section>
)}
</div>
<div className="mx-auto flex w-full max-w-md items-center justify-between gap-2">
<Button type="button" variant="outline" className="h-11 px-5 text-sm" onClick={goBack}>Back</Button>
{last ? (
<Button type="submit" className="h-11 min-w-44 px-5 text-sm font-semibold" disabled={submitting || (ans.intent === "upgrade" && rank.status === "checking")}>
{submitting ? <Loader2 className="size-4 animate-spin" /> : "Continue to Stripe"}
</Button>
) : (
<Button type="submit" className="h-11 min-w-28 px-5 text-sm font-semibold">Next</Button>
)}
</div>
</form>
<p className="mx-auto mt-6 max-w-md rounded-xl bg-background/70 px-4 py-2.5 text-center text-xs/relaxed text-foreground/80">
Secure via Stripe · Refunds 7 days · Cosmetic only · 1.5% of each donation supports <a href="https://stripe.com/gb/climate" target="_blank" rel="noopener noreferrer" className="underline underline-offset-2">Stripe Climate</a> carbon removal
</p>
</div>
</div>
</main>
);
}