'use client'; import { Suspense, useEffect, useState } from 'react'; import { useRouter, useSearchParams } from 'next/navigation'; import { STYLE_CATALOG } from '../data/styleCatalog'; import { BACKGROUND_COLORS } from '../data/backgrounds'; import { PRODUCTS, salePrice, sizeLabel, type ProductId, type Orientation } from '../lib/pricing'; import { getDraft, draftToFormData, uploadedCount, type Draft } from '../lib/draft-order'; // /checkout — the page that takes over from the inline Submit form in // the Review step. Reads the in-memory draft order (set by Builder when // the customer clicked "Continue to payment"), shows the order summary, // collects email, and kicks off the Stripe Checkout Session. // // Refresh-safety: the draft lives in module memory, so a hard refresh // loses it. In that case we route the customer back to /builder, where // their saved state would (in a future refinement) be rehydrated. For // now, refresh = restart. // // Stripe-cancel return: Stripe's hosted checkout redirects the customer // back here with ?orderId=…&canceled=1 if they hit Cancel. That's a // full-page external navigation, so the in-memory draft is gone — but // the order row already exists on the server. We detect that case and // show a resume screen with a single "Resume payment" button that // re-mints a Stripe session from the existing orderId, instead of // bouncing them all the way back to pick-a-pet. // Persisted-order shape returned by GET /api/orders/[id]/summary — // just the fields the resume screen renders. type ResumeSummary = { status: string; config: { styleId?: string; productId?: ProductId; size?: string; orientation?: Orientation; }; petPhotoUrls: string[]; customStyleUrl: string | null; priceCents: number; }; export default function LegacyCheckout() { // useSearchParams() forces a CSR bailout, which Next 15 requires us // to opt into with a Suspense boundary. The fallback is what static // prerendering emits before client-side params resolve. return (

Loading your commission…

}>
); } function CheckoutInner() { const router = useRouter(); const searchParams = useSearchParams(); // The resume screen serves two entry points that both arrive without the // in-memory draft: Stripe's cancel redirect (?canceled=1) and the // abandoned-cart reminder email (?resume=1). In both cases the order row // already exists, so we re-mint a Stripe session from the orderId. const isReminderResume = searchParams.get('resume') === '1'; const pendingOrderId = searchParams.get('canceled') === '1' || isReminderResume ? searchParams.get('orderId') : null; const [draft, setDraftLocal] = useState(() => getDraft()); const [email, setEmail] = useState(''); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); const [resuming, setResuming] = useState(false); // When we land on the resume screen the in-memory draft is gone (the // Stripe redirect / reminder email is a full-page navigation), so we // fetch the persisted order to show the customer their saved photos // and design instead of a bare "Resume payment" button. const [summary, setSummary] = useState(null); const [summaryLoading, setSummaryLoading] = useState(false); useEffect(() => { if (draft || !pendingOrderId) return; let cancelled = false; setSummaryLoading(true); fetch(`/api/orders/${encodeURIComponent(pendingOrderId)}/summary`) .then((r) => (r.ok ? r.json() : null)) .then((data: ResumeSummary | null) => { if (!cancelled) setSummary(data); }) .catch(() => { /* leave summary null — the button-only screen still works */ }) .finally(() => { if (!cancelled) setSummaryLoading(false); }); return () => { cancelled = true; }; }, [draft, pendingOrderId]); // "Make changes" → reopen the builder for this exact order. The builder // reads ?edit=… and rehydrates the design + photos (see Builder.tsx), // so nothing has to be re-uploaded. Clear the pending-order hint so the // builder's own mount effect doesn't bounce us straight back here. const makeChanges = () => { try { sessionStorage.removeItem('lg_pending_order_id'); } catch {} router.push(pendingOrderId ? `/builder?edit=${encodeURIComponent(pendingOrderId)}` : '/builder'); }; // If the draft is missing (hard refresh, deep-link), bounce back to // the builder so the customer can re-enter their commission. Skip // the bounce when we're handling a Stripe cancel: the order already // exists server-side and we render a resume UI below. useEffect(() => { if (!draft && !pendingOrderId) router.replace('/builder'); }, [draft, pendingOrderId, router]); const resumePayment = async () => { if (!pendingOrderId) return; setResuming(true); setError(null); try { const sessionRes = await fetch(`/api/orders/${pendingOrderId}/checkout`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ termsAccepted: true }), }); if (!sessionRes.ok) { const data = await sessionRes.json().catch(() => null) as { error?: string } | null; throw new Error(data?.error ?? `Checkout session failed (${sessionRes.status})`); } const { url } = await sessionRes.json() as { url: string }; window.location.href = url; } catch (err) { setError(err instanceof Error ? err.message : 'Resume failed'); setResuming(false); } }; if (!draft && pendingOrderId) { const cfg = summary?.config ?? {}; const resumeStyle = STYLE_CATALOG.find((s) => s.id === cfg.styleId); const resumeProduct = cfg.productId ? PRODUCTS[cfg.productId] : null; const resumeSize = cfg.productId && cfg.size ? sizeLabel(cfg.productId, cfg.size, cfg.orientation ?? 'portrait') : null; const photos = summary?.petPhotoUrls ?? []; const priceDollars = summary ? Math.round(summary.priceCents / 100) : null; return (

{isReminderResume ? 'Your portrait is waiting' : 'Payment canceled'}

No charge was made. Your photos and design are saved — pick up where you left off, or make changes first.

{photos.length > 0 && (
{photos.map((url, i) => ( // eslint-disable-next-line @next/next/no-img-element {`Pet ))}
)} {summary && (
{resumeStyle && (
Style{resumeStyle.name}
)} {resumeProduct && resumeSize && (
Product{resumeProduct.label}, {resumeSize}
)} {photos.length > 0 && (
Photos {photos.length} {photos.length === 1 ? 'pet' : 'pets'}
)} {priceDollars != null && (
Total${priceDollars} USD
)}
)} {summaryLoading && !summary && (

Loading your commission…

)} {error &&

{error}

}

Secure payment via Stripe. By paying you agree to our{' '} commission terms and{' '} refund policy.

Change the style, size, frame, background, or photos — your uploads come with you, and nothing is charged until you complete payment.

); } if (!draft) { return (

Loading your commission…

); } const style = STYLE_CATALOG.find((s) => s.id === draft.config.styleId); const product = PRODUCTS[draft.config.productId]; // Orientation-aware label ('10 × 8 in' for landscape). No live framed // preview on this fallback page — just the text summary. const displaySizeLabel = sizeLabel(draft.config.productId, draft.config.size, draft.config.orientation ?? 'portrait'); const hasCustomStyle = !!draft.customStyle; const photoCount = uploadedCount(draft); // At cost: matches what /api/orders charges. Artwork is free, so pets // and custom style references don't change the price. const saleTotal = salePrice(draft.config.productId, draft.config.size, draft.config.matteId); const onPay = async (e: React.FormEvent) => { e.preventDefault(); if (!email.trim() || !/.+@.+\..+/.test(email)) { setError('Enter a valid email.'); return; } setSubmitting(true); setError(null); try { // 1. Create the order via the existing /api/orders endpoint — // this uploads photos to CF Images, creates the user, inserts // the order row. Returns { orderId, email }. const orderRes = await fetch('/api/orders', { method: 'POST', body: draftToFormData(draft, email), }); if (!orderRes.ok) { const data = await orderRes.json().catch(() => null) as { error?: string } | null; throw new Error(data?.error ?? `Order create failed (${orderRes.status})`); } const { orderId } = await orderRes.json() as { orderId: string }; // 2. Create the Stripe Checkout Session for this order, also // records terms acceptance on the order row. Redirects the // browser to the hosted Stripe page. const sessionRes = await fetch(`/api/orders/${orderId}/checkout`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email, termsAccepted: true }), }); if (!sessionRes.ok) { const data = await sessionRes.json().catch(() => null) as { error?: string } | null; throw new Error(data?.error ?? `Checkout session failed (${sessionRes.status})`); } const { url } = await sessionRes.json() as { url: string }; window.location.href = url; } catch (err) { setError(err instanceof Error ? err.message : 'Submit failed'); setSubmitting(false); } }; const back = () => router.push('/builder'); return (

Confirm and pay

Your commission is saved. Pay now to send it into the studio queue — we’ll email your proof within one business day. Studio hours are Monday–Friday; orders placed on a Friday arrive Monday.

Style {style?.name ?? draft.config.styleId}
Product {product.label}, {displaySizeLabel}
Photos {photoCount} {photoCount === 1 ? 'pet' : 'pets'}
{draft.config.bgColorId && draft.config.bgColorId !== 'custom' && (
Background {BACKGROUND_COLORS[draft.config.bgColorId as keyof typeof BACKGROUND_COLORS]?.label ?? draft.config.bgColorId}
)} {hasCustomStyle && (
Style reference Attached · free
)}
{/* The artwork is free and the print is at cost. */}
  • Portrait artwork Free
  • {product.label}, {displaySizeLabel}, at cost ${saleTotal}
Total
${saleTotal}USD
Ships in 10 days
Shipping included
setEmail(e.target.value)} className="auth__input" disabled={submitting} /> {error &&

{error}

}

Secure payment via Stripe. By paying you agree to our{' '} commission terms and{' '} refund policy.

); }