"use client"; import { useEffect, useMemo, useState } from "react"; import Link from "next/link"; 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 { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { TIERS, tierForAmount, upgradePrice } from "@/lib/donations"; import { TopBar } from "@/components/top-bar"; const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ""); const DRAFT_KEY = "frg-donate-draft-v1"; type Answers = { intent: string; rank: string; upgradeTo: string; gift: string; platform: "java" | "bedrock"; player: string; giftTo: string; customPounds: string; customRecurring: boolean; }; const EMPTY_ANSWERS: Answers = { intent: "", rank: "", upgradeTo: "", gift: "", platform: "java", player: "", giftTo: "", customPounds: "", customRecurring: false, }; function Choice({ title, description, checked, disabled, onClick }: { title: React.ReactNode; description?: React.ReactNode; checked: boolean; disabled?: boolean; onClick: () => void; }) { return ( ); } function Field({ className, ...props }: React.InputHTMLAttributes) { return ( ); } function UpgradeTargetPicker({ value, onChange, player }: { value: string; onChange: (v: string)=>void; player: string }) { const [verified, setVerified] = useState<{current:string|null;label?:string}|null>(null); useEffect(()=>{ const name=(player||"").trim(); if(name.length<3){setVerified(null);return;} let cancelled=false; const t=setTimeout(async()=>{ try{ const r=await fetch(`/api/donations/verify?username=${encodeURIComponent(name)}`); const j=await r.json(); if(!cancelled) setVerified(j.error?null:j); }catch{ if(!cancelled) setVerified(null); } },500); return()=>{cancelled=true;clearTimeout(t);}; },[player]); return (<> {verified?.current ?

Verified current: {verified.label} — price will be difference

: player.trim().length>=3 ?

No rank found for "{player.trim()}" — upgrade requires an existing rank.

:

Enter your Minecraft name in the next step to verify.

}
{(["gold","diamond"] as const).map(id=>{ const t=(TIERS as any)[id]; const disabled = !!verified?.current && !upgradePrice(verified.current as any, id as any); const price = verified?.current ? upgradePrice(verified.current as any, id as any) : null; return onChange(id)} title={`${t.label}${price ? ` — £${(price/100).toFixed(2)} upgrade` : ` — £${(t.price/100).toFixed(2)}`}`} description={disabled ? `Already have ${verified?.label} or higher` : t.perks.join(" · ")} />; })}
); } type Pending = { clientSecret: string; label: string; perks: string[]; isSub: boolean; forUser: string; gift: boolean; }; function useStripeAppearance() { return useMemo(() => { const cs = getComputedStyle(document.documentElement); const v = (n: string) => cs.getPropertyValue(n).trim(); const primary = v("--primary"); const fg = v("--foreground"); const bg = v("--background"); const border = v("--border"); const input = v("--input"); const mutedFg = v("--muted-foreground"); const destructive = v("--destructive"); const accent = v("--accent"); const radius = v("--radius") || "0.75rem"; const appearance: Appearance = { theme: "night", labels: "above", variables: { fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Ubuntu, sans-serif", colorPrimary: primary, colorPrimaryText: v("--primary-foreground"), colorBackground: bg, colorText: fg, colorTextSecondary: mutedFg, colorTextPlaceholder: mutedFg, colorIcon: mutedFg, colorDanger: destructive, colorSuccess: primary, borderRadius: radius, }, rules: { ".Input": { border: `1px solid ${input}`, backgroundColor: "transparent", boxShadow: "none" }, ".Input:focus": { border: `1px solid ${primary}`, boxShadow: "none" }, ".Input--invalid": { border: `1px solid ${destructive}`, boxShadow: "none" }, ".Label": { color: mutedFg, fontWeight: "500", marginBottom: "6px" }, ".Tab": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" }, ".Tab:hover": { backgroundColor: accent, boxShadow: "none" }, ".Tab--selected": { borderColor: primary, boxShadow: "none" }, ".AccordionItem": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" }, ".AccordionItem--selected": { borderColor: primary, boxShadow: "none" }, ".Block": { border: `1px solid ${border}`, backgroundColor: "transparent", boxShadow: "none" }, ".Divider": { backgroundColor: border }, ".Error": { color: destructive }, ".TermsText": { color: mutedFg }, }, }; return { appearance }; }, []); } function PaymentStage({ pending, onBack }: { pending: Pending; onBack: () => void }) { const { appearance } = useStripeAppearance(); return ( ); } 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); 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); } } return (
FRG Network {fmt(total)} {pending.isSub && /mo}

{pending.label}

{fmt(total)} {pending.isSub && /mo}

Contact information

Payment method

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

Powered by Terms Privacy
); } function StepShell({ title, description, error, children }: { title: string; description?: string; error?: string | null; children?: React.ReactNode; }) { return (

{title}

{description &&

{description}

} {children} {error &&

{error}

}
); } export default function DonatePage() { const [ans, setAns] = useState(EMPTY_ANSWERS); const [restored, setRestored] = useState(false); const [pending, setPending] = useState(null); const [started, setStarted] = useState(false); const [stepIdx, setStepIdx] = useState(0); const [error, setError] = useState(null); const [submitting, setSubmitting] = useState(false); const set = (patch: Partial) => { setError(null); setAns((a) => ({ ...a, ...patch })); }; useEffect(() => { try { const raw = localStorage.getItem(DRAFT_KEY); if (raw) { const d = JSON.parse(raw) as Partial; // autofill fields from storage but always start at the first step // eslint-disable-next-line react-hooks/set-state-in-effect setAns((a) => ({ ...a, 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, platform: d.platform === "bedrock" ? "bedrock" : d.platform === "java" ? "java" : a.platform, player: d.player ?? a.player, giftTo: d.giftTo ?? a.giftTo, 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. const steps = useMemo(() => { const s: string[] = ["intent"]; if (ans.intent === "rank") s.push("rank"); s.push("username"); if (ans.intent === "upgrade") s.push("upgrade"); s.push("gift"); if (ans.gift === "yes") s.push("giftTo"); if (ans.intent === "custom") s.push("amount"); s.push("confirm"); return s; }, [ans.intent, ans.gift]); const current = Math.min(stepIdx, steps.length - 1); const step = steps[current]; const last = step === "confirm"; function validateStep(name: string): string | null { switch (name) { case "intent": return ans.intent ? null : "Choose an answer to continue."; case "rank": return ans.rank ? null : "Choose a rank to continue."; case "upgrade": return ans.upgradeTo ? null : "Choose a target rank to continue."; case "username": return ans.player.trim().length >= 3 ? null : "Enter your Minecraft name (3+ characters)."; case "gift": return ans.gift === "yes" || ans.gift === "no" ? null : "Choose an answer to continue."; case "giftTo": return ans.giftTo.trim().length >= 3 ? null : "Enter the recipient's Minecraft name (3+ characters)."; case "amount": { const p = parseFloat(ans.customPounds.trim()); return !isNaN(p) && p >= 1 ? null : "Enter an amount of at least £1."; } default: return null; } } function goNext() { const err = validateStep(step); if (err) { setError(err); return; } setError(null); setStepIdx((i) => Math.min(i + 1, steps.length - 1)); } function goBack() { setError(null); setStepIdx((i) => Math.max(i - 1, 0)); } // Gift step: pick yes -> "who to?" step, pick no -> move straight on function chooseGift(choice: "yes" | "no") { set({ gift: choice }); const s: string[] = ["intent"]; if (ans.intent === "rank") s.push("rank"); s.push("username"); if (ans.intent === "upgrade") s.push("upgrade"); s.push("gift"); if (choice === "yes") s.push("giftTo"); if (ans.intent === "custom") s.push("amount"); s.push("confirm"); setStepIdx(s.indexOf("gift") + 1); } async function handleSubmit() { if (submitting) return; const playerVal = ans.player.trim(); const giftToVal = ans.giftTo.trim(); const customPoundsVal = ans.customPounds.trim(); if (!playerVal || playerVal.length < 3) { toast.error("Enter your Minecraft name"); return; } if (ans.gift === "yes" && (!giftToVal || giftToVal.length < 3)) { toast.error("Enter gift recipient name"); return; } let tier: string; let customAmount: number | undefined; let isUpgrade = false; if (ans.intent === "patron") tier = "patron"; else if (ans.intent === "rank") { if (!ans.rank) { toast.error("Pick a rank"); return; } tier = ans.rank; } else if (ans.intent === "upgrade") { if (!ans.upgradeTo) { toast.error("Pick target rank"); return; } tier = ans.upgradeTo; isUpgrade = true; } else if (ans.intent === "custom") { const pounds = parseFloat(customPoundsVal); if (isNaN(pounds) || pounds < 1) { toast.error("Min £1 for custom"); return; } customAmount = Math.round(pounds * 100); tier = "custom"; } else { toast.error("Choose how you want to donate"); return; } let label: string; let perks: string[] = []; let isSub = false; if (tier === "patron") { label = TIERS.patron.label; perks = [...TIERS.patron.perks]; isSub = true; } else if (isUpgrade) { const to = (TIERS as any)[tier]; label = `Upgrade → ${to.label}`; perks = [...to.perks]; } else if (tier === "custom") { isSub = ans.customRecurring; const unlocked = isSub && customAmount! >= TIERS.patron.price ? "patron" : tierForAmount(customAmount!); label = unlocked ? `Custom — unlocks ${unlocked}` : "Custom donation"; perks = unlocked ? [...(TIERS as any)[unlocked].perks] : []; if (isSub && customAmount! >= TIERS.patron.price) perks = [...TIERS.patron.perks]; } else { const t = (TIERS as any)[tier]; label = t.label; perks = [...t.perks]; } setSubmitting(true); try { const res = await fetch("/api/donations/checkout", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ platform: ans.platform, username: playerVal, tier, customAmount, customRecurring: ans.customRecurring || undefined, giftTo: ans.gift==="yes" ? giftToVal || undefined : undefined, upgrade: isUpgrade || undefined }) }); const text = await res.text(); let j: any = {}; try { j = JSON.parse(text); } catch { toast.error(text || "Checkout failed"); return; } if (j.clientSecret) { setPending({ clientSecret: j.clientSecret, label, perks, isSub, forUser: ans.gift === "yes" ? giftToVal : playerVal, gift: ans.gift === "yes", }); } else toast.error(j.error || "Checkout failed"); } catch { toast.error("Checkout failed"); } finally { setSubmitting(false); } } function onFormSubmit(e: React.FormEvent) { e.preventDefault(); if (last) handleSubmit(); else goNext(); } if (pending) { return (
setPending(null)} />
); } 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

); } return (

Step {current + 1} of {steps.length}

{step === "intent" && (
set({intent:"rank"})} title="Purchase a rank" description="Iron £3 · Gold £5 · Diamond £7 — one-time" /> set({intent:"upgrade"})} title="Upgrade rank" description="Already have a rank? Pay the difference" /> set({intent:"patron"})} title="Become a patron" description="£5/mo — all cosmetics + Patron badge" /> set({intent:"custom"})} title="Custom donation" description="Any amount — £5+ unlocks Patron" />
)} {step === "rank" && (
{(["iron","gold","diamond"] as const).map(id=>{ const t=(TIERS as any)[id]; return set({rank:id})} title={`${t.label} — £${(t.price/100).toFixed(2)}`} description={t.perks.join(" · ")} />; })}
)} {step === "username" && ( set({platform: v as any})} className="w-full"> JavaBedrock set({player:e.target.value})} aria-label="Minecraft name" placeholder="Your Minecraft name" /> )} {step === "upgrade" && ( set({upgradeTo:v})} player={ans.player} /> )} {step === "gift" && (
chooseGift("no")} title="For me" description="The donation goes to your account" /> chooseGift("yes")} title="Gift to a friend" description="We'll mail it to them in-game" />
)} {step === "giftTo" && ( set({giftTo:e.target.value})} aria-label="Gift recipient" placeholder="Recipient Minecraft name" /> )} {step === "amount" && ( set({customPounds:e.target.value})} aria-label="Custom amount in pounds" placeholder="Amount in £ e.g. 10" />
set({customRecurring:false})} title="One-time" /> set({customRecurring:true})} title="Monthly" description="£5+/mo grants Patron" />
)} {step === "confirm" && (

Recipient {ans.gift==="yes" && ans.giftTo.trim() ? ans.giftTo.trim() : ans.player.trim() || "—"}

Platform {ans.platform}

{(ans.intent === "rank" || ans.intent === "patron" || ans.intent === "upgrade") && (

Getting {ans.intent === "rank" && ans.rank ? (TIERS as any)[ans.rank]?.label : null} {ans.intent === "patron" ? TIERS.patron.label : null} {ans.intent === "upgrade" && ans.upgradeTo ? `Upgrade → ${(TIERS as any)[ans.upgradeTo]?.label}` : null}

)} {ans.intent === "custom" && (

Amount £{ans.customPounds || "—"}{ans.customRecurring ? " /mo" : " one-time"}

)}
)}
{current > 1 ? ( ) : } {last ? ( ) : ( )}

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

); }