"use client"; import React from "react"; import { TailwindSpinner } from "@/components/common/GlobalLoad"; import { useSearchParams } from "next/navigation"; import { createCheckoutSession, buyTokens } from "@/lib/stripe"; export default function PayRedirectPage() { const [status, setStatus] = React.useState("Preparing checkout..."); const [error, setError] = React.useState(""); const searchParams = useSearchParams(); React.useEffect(() => { const type = (searchParams.get("type") || "").toLowerCase(); if (!type) { setStatus(""); setError("Missing payment type."); return; } const redirectTo = async () => { try { if (type === "token") { const amountStr = searchParams.get("amount"); const pkg = searchParams.get("pkg") || "basic"; const amount = Number(amountStr); if (!amount || amount <= 0) { throw new Error("Invalid token amount"); } setStatus("Creating token purchase session..."); const resp = await buyTokens({ token_amount: amount, package_type: pkg }); if (resp?.successful && resp?.data?.checkout_url) { setStatus("Redirecting to Stripe Checkout..."); window.location.href = resp.data.checkout_url as string; return; } throw new Error(resp?.message || "Failed to create token checkout session"); } if (type === "subscription") { const plan = searchParams.get("plan"); const billing = (searchParams.get("billing") || "month") as "month" | "year"; if (!plan) { throw new Error("Missing plan name"); } const currentUser = JSON.parse(localStorage.getItem("currentUser") || "{}"); if (!currentUser?.id) { throw new Error("Not logged in. Please sign in and try again."); } setStatus("Creating subscription session..."); const result = await createCheckoutSession({ user_id: String(currentUser.id), plan_name: plan, billing_cycle: billing, }); if (result?.successful && result?.data?.checkout_url) { setStatus("Redirecting to Stripe Checkout..."); window.location.href = result.data.checkout_url as string; return; } throw new Error(result?.message || "Failed to create subscription session"); } throw new Error("Unsupported payment type"); } catch (e: unknown) { setStatus(""); setError(e instanceof Error ? e.message : "Failed to prepare checkout."); } }; redirectTo(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [searchParams]); return (

Preparing to redirect

{status &&

{status}

} {!error && (
)} {error &&

{error}

} {!error && (

If it takes too long, please return to the previous page or check your network.

)}
); }