"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 (

{rank.status === "checking" ? "Checking their current rank…" : known ? <>{name} is {rank.label} now : rank.status === "none" ? <>No rank found for "{name}". 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}

{ 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)} />
); } // 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: {edition} }, ]; 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: {t.label} }); total = money(t.price); perks = [...t.perks]; } else if (ans.intent === "patron") { rows.push({ label: "Getting", value: {TIERS.patron.label} }); 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: {t.label} }); 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 ? {TIERS[unlocked as keyof typeof TIERS].label} : "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(null); const [appearance, setAppearance] = useState(null); // The accent lives on this element, so Stripe's colours are read from here. useEffect(() => { if (root.current) setAppearance(buildStripeAppearance(root.current)); }, []); return (
{appearance ? ( ) : (
)}
); } function CheckoutShell({ pending, onBack }: { pending: Pending; onBack: () => void }) { const state = useCheckoutElements(); const [submitting, setSubmitting] = useState(false); if (state.type === "loading") { return (
); } if (state.type === "error") { return (

Couldn't load checkout

{state.error.message}

); } 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 (
FRG Network {totalText}

Contact information

Payment method

{pending.isSub && (

Renews every month until cancelled.

)}

FRG Network will contribute{" "} 1.5% of your purchase to removing CO₂ from the atmosphere.

Powered by Terms Privacy
); } const TIER_GLOW: Record = { 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 ( }> ); } // 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 (

{title}

{hint &&

{hint}

}
); } // The URL is the source of truth for where the visitor is: /donate is the // first step and /donate?step= is any step, so browser back/forward // walk the flow. function DonateFlow() { const finePointer = useFinePointer(); const stepParam = useSearchParams().get("step"); const [ans, setAns] = useState(EMPTY_ANSWERS); const [restored, setRestored] = useState(false); const [pending, setPending] = useState(null); const [error, setError] = useState(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(null); // An error to show on the step the visitor is about to be sent back to. const flash = useRef(null); const stage = useRef(null); const firstStep = useRef(true); const set = (patch: Partial) => { 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; // 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("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 window.history.back()} />; } if (waiting) { return
; } if (!started) { return (

Support FRG

Ranks are cosmetic only. Your donation keeps the server running and funds new features.

Secure via Stripe · 1.5% to Stripe Climate

); } const errorLine = error && step !== "amount" ?

{error}

: null; return (

Step {current + 1}{ans.intent ? ` of ${steps.length}` : ""}

{step === "intent" && (
{errorLine}
)} {step === "rank" && (
{ set({ rank: id }); setPreview(null); }} onPreview={setPreview} /> {errorLine}
)} {step === "amount" && (
set({ customPounds })} onRecurring={(customRecurring) => set({ customRecurring })} />
)} {step === "username" && (
set({ player })} onPlatformChange={(platform) => set({ platform })} /> {errorLine}
)} {step === "gift" && (
set({ gift })} onGiftTo={(giftTo) => set({ giftTo })} onGiftPlatform={(giftPlatform) => set({ giftPlatform })} onAnonymous={(anonymous) => set({ anonymous })} /> {errorLine}
)} {step === "upgrade" && (
{ set({ upgradeTo }); setPreview(null); }} onPreview={setPreview} rank={rank} name={recipientName} /> {errorLine}
)} {step === "confirm" && (
)}
{last ? ( ) : ( )}

Secure via Stripe · Refunds 7 days · Cosmetic only · 1.5% of each donation supports Stripe Climate carbon removal

); }