"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useId, useState } from "react"; import { api, ApiError, errorText } from "@/lib/api"; /** Typing help: upper case, groups of four (ABCD-EFGH-JKLM). */ function format(input: string): string { const clean = input.toUpperCase().replace(/[^0-9A-Z]/g, "").slice(0, 32); return clean.match(/.{1,4}/g)?.join("-") ?? ""; } const UNITS: Record = { natal: "képletelemzés", synastry: "kapcsolati elemzés", forecast: "éves előrejelzés", person: "személyhely", question: "kérdés", }; /** "+2 képletelemzés, +3 kérdés" */ function addedText(added: Record): string { return Object.entries(added) .map(([unit, n]) => `+${n} ${UNITS[unit] ?? unit}`) .join(", "); } /** * Redeeming a promo code. It fills the units up to the package's amounts * (used ones come back, more than that stays). */ export function RedeemCode({ initial = "", compact = false }: { initial?: string; compact?: boolean }) { const router = useRouter(); const id = useId(); const [code, setCode] = useState(format(initial)); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [got, setGot] = useState<{ name: string; added: string } | null>(null); async function redeem(e: React.FormEvent) { e.preventDefault(); setBusy(true); setError(null); try { const r = await api<{ package: { name: string }; added: Record }>("/promo-codes/redeem", { body: { code }, }); setGot({ name: r.package.name, added: addedText(r.added ?? {}) }); setCode(""); router.refresh(); } catch (err) { setError( err instanceof ApiError && err.status === 429 ? "Túl sok sikertelen próbálkozás. Várj negyed órát, és próbáld újra." : errorText(err), ); } finally { setBusy(false); } } return (
setCode(format(e.target.value))} placeholder="XXXX-XXXX-XXXX" autoComplete="off" autoCapitalize="characters" spellCheck={false} inputMode="text" aria-describedby={`${id}-msg`} />
{error &&

{error}

} {got && (

Beváltva: {got.name}. Feltöltöttük az egyenlegedet: {got.added}.{" "} Tovább a képletedhez

)}
); }