679 lines
30 KiB
TypeScript
679 lines
30 KiB
TypeScript
"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 (
|
|
<button
|
|
type="button"
|
|
role="radio"
|
|
aria-checked={checked}
|
|
disabled={disabled}
|
|
onClick={onClick}
|
|
className={cn(
|
|
"flex min-h-11 w-full cursor-pointer items-start gap-2.5 rounded-xl border px-3 py-2.5 text-start text-xs/relaxed transition-colors outline-none select-none hover:bg-input/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
|
|
checked ? "border-primary/40 bg-primary/10" : "border-input"
|
|
)}
|
|
>
|
|
<span
|
|
aria-hidden="true"
|
|
className={cn(
|
|
"pointer-events-none mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border",
|
|
checked ? "border-primary bg-primary" : "border-input dark:bg-input/30"
|
|
)}
|
|
>
|
|
{checked && <span className="size-2 rounded-full bg-primary-foreground" />}
|
|
</span>
|
|
<span className="flex min-w-0 flex-1 flex-col gap-0.5 leading-snug">
|
|
<span className="font-medium">{title}</span>
|
|
{description && <span className="text-muted-foreground">{description}</span>}
|
|
</span>
|
|
</button>
|
|
);
|
|
}
|
|
|
|
function Field({ className, ...props }: React.InputHTMLAttributes<HTMLInputElement>) {
|
|
return (
|
|
<input
|
|
{...props}
|
|
className={cn(
|
|
"h-11 w-full min-w-0 rounded-md border border-input bg-input/20 px-3 text-sm transition-[color,box-shadow,border-color] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 dark:bg-input/30",
|
|
className
|
|
)}
|
|
/>
|
|
);
|
|
}
|
|
|
|
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 ? <p className="text-xs text-muted-foreground">Verified current: <span className="font-medium text-foreground">{verified.label}</span> — price will be difference</p> : player.trim().length>=3 ? <p className="text-xs text-amber-600">No rank found for "{player.trim()}" — upgrade requires an existing rank.</p> : <p className="text-xs text-muted-foreground">Enter your Minecraft name in the next step to verify.</p>}
|
|
<div className="grid gap-1.5">
|
|
{(["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 <Choice key={id} checked={value===id} disabled={disabled} onClick={()=>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(" · ")} />;
|
|
})}
|
|
</div>
|
|
</>);
|
|
}
|
|
|
|
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 (
|
|
<CheckoutElementsProvider
|
|
stripe={stripePromise}
|
|
options={{ clientSecret: pending.clientSecret, elementsOptions: { appearance } }}
|
|
>
|
|
<CheckoutShell pending={pending} onBack={onBack} />
|
|
</CheckoutElementsProvider>
|
|
);
|
|
}
|
|
|
|
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't load checkout</h1>
|
|
<p className="text-sm text-muted-foreground">{state.error.message}</p>
|
|
<Button variant="outline" 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);
|
|
|
|
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 (
|
|
<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 bg-card/50 p-10">
|
|
<div className="flex items-center gap-3">
|
|
<Button
|
|
onClick={onBack}
|
|
aria-label="Back"
|
|
variant="outline"
|
|
size="icon"
|
|
className="size-8 rounded-full"
|
|
>
|
|
<ArrowLeft className="size-4" />
|
|
</Button>
|
|
<span className="font-semibold">FRG Network</span>
|
|
</div>
|
|
<div className="mt-10">
|
|
<p className="text-sm text-muted-foreground">{pending.label}</p>
|
|
<p className="text-3xl font-semibold tracking-tight mt-1">
|
|
{fmt(total)}
|
|
{pending.isSub && <span className="text-base font-normal text-muted-foreground"> /mo</span>}
|
|
</p>
|
|
</div>
|
|
<div className="flex-1" />
|
|
<Button onClick={onBack} variant="link" size="sm" className="self-start h-auto p-0 text-xs text-muted-foreground">
|
|
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.5">
|
|
<Button
|
|
onClick={onBack}
|
|
aria-label="Back"
|
|
variant="outline"
|
|
size="icon"
|
|
className="size-8 rounded-full"
|
|
>
|
|
<ArrowLeft className="size-4" />
|
|
</Button>
|
|
<span className="font-semibold text-sm">FRG Network</span>
|
|
<span className="ml-auto text-sm font-semibold">
|
|
{fmt(total)}
|
|
{pending.isSub && <span className="text-xs font-normal text-muted-foreground"> /mo</span>}
|
|
</span>
|
|
</div>
|
|
</header>
|
|
<form onSubmit={pay} className="mx-auto w-full max-w-[400px] min-w-72 px-4 py-10 lg:my-auto space-y-6">
|
|
<div className="lg:hidden">
|
|
<p className="text-sm text-muted-foreground">{pending.label}</p>
|
|
<p className="text-2xl font-semibold tracking-tight mt-1">
|
|
{fmt(total)}
|
|
{pending.isSub && <span className="text-sm font-normal text-muted-foreground"> /mo</span>}
|
|
</p>
|
|
</div>
|
|
<section className="space-y-2.5">
|
|
<h2 className="text-[15px] font-semibold tracking-tight">Contact information</h2>
|
|
<ContactDetailsElement />
|
|
</section>
|
|
<section className="space-y-2.5">
|
|
<h2 className="text-[15px] font-semibold tracking-tight">Payment method</h2>
|
|
<PaymentElement />
|
|
</section>
|
|
<Button type="submit" className="w-full h-11" disabled={submitting || !checkout.canConfirm}>
|
|
{submitting ? <Loader2 className="size-4 animate-spin" /> : "Pay"}
|
|
</Button>
|
|
<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>
|
|
);
|
|
}
|
|
|
|
function StepShell({ title, description, error, children }: {
|
|
title: string;
|
|
description?: string;
|
|
error?: string | null;
|
|
children?: React.ReactNode;
|
|
}) {
|
|
return (
|
|
<section className="flex min-w-0 flex-col gap-3">
|
|
<h2 className="text-sm font-semibold">{title}</h2>
|
|
{description && <p className="text-xs/relaxed text-pretty text-muted-foreground">{description}</p>}
|
|
{children}
|
|
{error && <p className="text-xs text-destructive" role="alert">{error}</p>}
|
|
</section>
|
|
);
|
|
}
|
|
|
|
export default function DonatePage() {
|
|
const [ans, setAns] = useState<Answers>(EMPTY_ANSWERS);
|
|
const [restored, setRestored] = useState(false);
|
|
const [pending, setPending] = useState<Pending | null>(null);
|
|
const [started, setStarted] = useState(false);
|
|
const [stepIdx, setStepIdx] = useState(0);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [submitting, setSubmitting] = useState(false);
|
|
|
|
const set = (patch: Partial<Answers>) => {
|
|
setError(null);
|
|
setAns((a) => ({ ...a, ...patch }));
|
|
};
|
|
|
|
useEffect(() => {
|
|
try {
|
|
const raw = localStorage.getItem(DRAFT_KEY);
|
|
if (raw) {
|
|
const d = JSON.parse(raw) as Partial<Answers>;
|
|
// 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 (
|
|
<main className="min-h-dvh bg-background text-foreground">
|
|
<PaymentStage pending={pending} onBack={() => setPending(null)} />
|
|
</main>
|
|
);
|
|
}
|
|
|
|
if (!started) {
|
|
return (
|
|
<main className="min-h-dvh bg-background text-foreground font-mona flex flex-col">
|
|
<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={()=>setStarted(true)} className="w-full">Donate</Button>
|
|
<p className="text-xs text-muted-foreground">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>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<main className="min-h-dvh bg-background text-foreground font-mona flex flex-col">
|
|
<TopBar />
|
|
<div className="flex-1 flex items-center justify-center px-4 py-8">
|
|
<div className="w-full max-w-md">
|
|
|
|
<p className="text-[0.625rem] font-medium text-muted-foreground tabular-nums">Step {current + 1} of {steps.length}</p>
|
|
|
|
<form onSubmit={onFormSubmit} className="mt-2 flex flex-col gap-4">
|
|
|
|
{step === "intent" && (
|
|
<StepShell title="How do you want to donate?" error={error}>
|
|
<div className="grid gap-1.5">
|
|
<Choice checked={ans.intent==="rank"} onClick={()=>set({intent:"rank"})} title="Purchase a rank" description="Iron £3 · Gold £5 · Diamond £7 — one-time" />
|
|
<Choice checked={ans.intent==="upgrade"} onClick={()=>set({intent:"upgrade"})} title="Upgrade rank" description="Already have a rank? Pay the difference" />
|
|
<Choice checked={ans.intent==="patron"} onClick={()=>set({intent:"patron"})} title="Become a patron" description="£5/mo — all cosmetics + Patron badge" />
|
|
<Choice checked={ans.intent==="custom"} onClick={()=>set({intent:"custom"})} title="Custom donation" description="Any amount — £5+ unlocks Patron" />
|
|
</div>
|
|
</StepShell>
|
|
)}
|
|
|
|
{step === "rank" && (
|
|
<StepShell title="Which rank?" error={error}>
|
|
<div className="grid gap-1.5">
|
|
{(["iron","gold","diamond"] as const).map(id=>{
|
|
const t=(TIERS as any)[id];
|
|
return <Choice key={id} checked={ans.rank===id} onClick={()=>set({rank:id})} title={`${t.label} — £${(t.price/100).toFixed(2)}`} description={t.perks.join(" · ")} />;
|
|
})}
|
|
</div>
|
|
</StepShell>
|
|
)}
|
|
|
|
{step === "username" && (
|
|
<StepShell title="Minecraft username" description="We verify your current rank from this." error={error}>
|
|
<Tabs value={ans.platform} onValueChange={(v)=>set({platform: v as any})} className="w-full">
|
|
<TabsList className="w-full"><TabsTrigger value="java" className="flex-1">Java</TabsTrigger><TabsTrigger value="bedrock" className="flex-1">Bedrock</TabsTrigger></TabsList>
|
|
</Tabs>
|
|
<Field autoFocus value={ans.player} onChange={(e)=>set({player:e.target.value})} aria-label="Minecraft name" placeholder="Your Minecraft name" />
|
|
</StepShell>
|
|
)}
|
|
|
|
{step === "upgrade" && (
|
|
<StepShell title="Upgrade your rank" description="We'll verify your current rank from your username and charge only the difference." error={error}>
|
|
<UpgradeTargetPicker value={ans.upgradeTo} onChange={(v)=>set({upgradeTo:v})} player={ans.player} />
|
|
</StepShell>
|
|
)}
|
|
|
|
{step === "gift" && (
|
|
<StepShell title="Is this a gift?" description="Optional — pick “For me” to move on." error={error}>
|
|
<div className="grid gap-1.5">
|
|
<Choice checked={ans.gift==="no"} onClick={()=>chooseGift("no")} title="For me" description="The donation goes to your account" />
|
|
<Choice checked={ans.gift==="yes"} onClick={()=>chooseGift("yes")} title="Gift to a friend" description="We'll mail it to them in-game" />
|
|
</div>
|
|
</StepShell>
|
|
)}
|
|
|
|
{step === "giftTo" && (
|
|
<StepShell title="Who is it for?" description="We'll mail the gift to them in-game." error={error}>
|
|
<Field autoFocus value={ans.giftTo} onChange={(e)=>set({giftTo:e.target.value})} aria-label="Gift recipient" placeholder="Recipient Minecraft name" />
|
|
</StepShell>
|
|
)}
|
|
|
|
{step === "amount" && (
|
|
<StepShell title="How much?" error={error}>
|
|
<Field autoFocus type="number" min={1} step="0.01" value={ans.customPounds} onChange={(e)=>set({customPounds:e.target.value})} aria-label="Custom amount in pounds" placeholder="Amount in £ e.g. 10" />
|
|
<div className="grid gap-1.5">
|
|
<Choice checked={!ans.customRecurring} onClick={()=>set({customRecurring:false})} title="One-time" />
|
|
<Choice checked={ans.customRecurring} onClick={()=>set({customRecurring:true})} title="Monthly" description="£5+/mo grants Patron" />
|
|
</div>
|
|
</StepShell>
|
|
)}
|
|
|
|
{step === "confirm" && (
|
|
<StepShell title="Confirm details">
|
|
<div className="rounded-xl border border-border bg-card/50 p-4 text-xs/relaxed">
|
|
<p className="flex justify-between gap-4">
|
|
<span className="text-muted-foreground">Recipient</span>
|
|
<span className="font-medium">{ans.gift==="yes" && ans.giftTo.trim() ? ans.giftTo.trim() : ans.player.trim() || "—"}</span>
|
|
</p>
|
|
<p className="mt-1.5 flex justify-between gap-4">
|
|
<span className="text-muted-foreground">Platform</span>
|
|
<span className="font-medium capitalize">{ans.platform}</span>
|
|
</p>
|
|
{(ans.intent === "rank" || ans.intent === "patron" || ans.intent === "upgrade") && (
|
|
<p className="mt-1.5 flex justify-between gap-4">
|
|
<span className="text-muted-foreground">Getting</span>
|
|
<span className="font-medium">
|
|
{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}
|
|
</span>
|
|
</p>
|
|
)}
|
|
{ans.intent === "custom" && (
|
|
<p className="mt-1.5 flex justify-between gap-4">
|
|
<span className="text-muted-foreground">Amount</span>
|
|
<span className="font-medium">£{ans.customPounds || "—"}{ans.customRecurring ? " /mo" : " one-time"}</span>
|
|
</p>
|
|
)}
|
|
</div>
|
|
</StepShell>
|
|
)}
|
|
|
|
<div className="flex items-center justify-between gap-2">
|
|
{current > 1 ? (
|
|
<Button type="button" variant="outline" onClick={goBack}>Back</Button>
|
|
) : <span />}
|
|
{last ? (
|
|
<Button type="submit" className="min-w-40" disabled={submitting}>
|
|
{submitting ? <Loader2 className="size-4 animate-spin" /> : "Continue to Stripe"}
|
|
</Button>
|
|
) : (
|
|
<Button type="submit">Next</Button>
|
|
)}
|
|
</div>
|
|
|
|
</form>
|
|
<p className="text-xs text-muted-foreground text-center mt-6">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>
|
|
);
|
|
}
|