"use client"; import { useState } from "react"; type PurchaseButtonProps = { gradeId: string; }; type PurchaseState = "idle" | "loading" | "error"; const minecraftNameRegex = /^[A-Za-z0-9_]{3,16}$/; export default function PurchaseButton({ gradeId }: PurchaseButtonProps) { const [isOpen, setIsOpen] = useState(false); const [username, setUsername] = useState(""); const [state, setState] = useState("idle"); const [error, setError] = useState(null); const openModal = () => { setIsOpen(true); setError(null); }; const closeModal = () => { setIsOpen(false); setState("idle"); setError(null); }; const handleCheckout = async (event: React.FormEvent) => { event.preventDefault(); const trimmed = username.trim(); if (!minecraftNameRegex.test(trimmed)) { setError("Enter a valid Minecraft username (3-16, letters, numbers, _)."); return; } setState("loading"); setError(null); try { const res = await fetch("/api/checkout", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ gradeId, minecraftUsername: trimmed }), }); const data = (await res.json().catch(() => ({}))) as { url?: string; error?: string; }; if (!res.ok || !data.url) { setState("error"); setError(data.error ?? "Checkout failed."); return; } window.location.href = data.url; } catch { setState("error"); setError("Checkout failed."); } }; return ( <> {isOpen ? (
event.stopPropagation()} >

Checkout

Enter Minecraft username

No account needed. We will send you to Stripe.

setUsername(event.target.value)} placeholder="Minecraft username" className="w-full rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 text-sm text-white" /> {error ? (

{error}

) : null}
) : null} ); }