'use client'; import Image from 'next/image'; import { useState, useEffect, useRef, type CSSProperties } from 'react'; import { ImageDrop } from './ImageDrop'; import { SavedPhotos } from './SavedPhotos'; import { ACCEPTED_IMAGE_LABEL } from '../lib/upload-limits'; import { STYLE_CATALOG, type StyleCatalogEntry } from '../data/styleCatalog'; import { BACKGROUND_COLORS, type BgColorId } from '../data/backgrounds'; import { getDraft, setDraft, draftToFormData, type Draft, type DraftConfig } from '../lib/draft-order'; import { urlToFile } from '../lib/url-to-file'; import { PRODUCTS, salePrice, sizeLabel, sizesForOrientation, frameAspect, type ProductId, type Orientation, } from '../lib/pricing'; // Pick which rendered variant to show for a style tile / preview slide. // There's no pet-type selector — the builder opens straight into the // style picker — so each style carries a hand-curated `display` field // (dog / cat / other) chosen to make the grid read as a varied // menagerie: mostly cats and dogs, with a few other animals (fox, // capybara, hedgehog…) sprinkled in. Falls back to the dog `example`. const exampleFor = (entry: StyleCatalogEntry) => { if (entry.display === 'cat' && entry.catExample) return entry.catExample; if (entry.display === 'other' && entry.otherExample) return entry.otherExample; return entry.example; }; // The commission builder — a multi-step wizard. // // Layout: two columns. The left column is the step-content panel (one // focused screen at a time), the right column is a persistent preview // panel showing the live framed portrait — mount + image + bg-colour + // lettering overlay — so the customer can see the state of the artwork // as they configure it. // // Steps (any inapplicable step is auto-skipped both forward and back): // 1. Style — pick the artwork style // 2. Background — pick the ground colour (skipped when the chosen // style brings its own ground, e.g. cubist, ukiyo-e) // 3. Frame — pick the frame, the size, and (if the chosen // style supports lettering) the font + on/off // 4. Photos — upload up to 4 pet photos, optionally name them. // Deferred — no point in asking for uploads until // the customer has decided what they're making. // 5. Review — order summary, optional custom-style upload, // Continue button, and the 100% Artwork Satisfaction // Guarantee trust block. // Product catalogue (sizes, prices, Prodigi mapping, and frame/matte // geometry) lives in app/lib/pricing.ts — single source of truth shared // with the orders API and the Stripe webhook. type SizeId = string; // The six finishes we offer on the box frame, matching the moulding // FRAMES + MATTES catalog lives in app/data/frames.ts so the same data // powers the Builder picker, the FramedPreview component, the admin // editor's framed mockup, and the customer approve page. import { FRAMES, MATTES, WRAPS, normalizeMatteId, normalizeWrapId, isNoMat, type FrameId, type MatteId, type WrapId } from '../data/frames'; // Background palette + per-color filename helper live in app/data/backgrounds.ts // — single source of truth shared with the Node generation script that bakes // per-color renders for watercolor / vector / named styles. // Lettering typefaces offered to the customer. `uppercase: true` forces // the name to caps (works for tracked-out modern sans + display serifs); // `uppercase: false` lets the customer's actual casing through, which // reads better in scripts, handwritten, and lowercase-friendly serifs. const FONTS = { modern: { label: 'Modern', css: '"DM Sans", sans-serif', tracking: '0.28em', weight: 500, italic: false, uppercase: true }, editorial: { label: 'Editorial', css: '"Newsreader", serif', tracking: '0.10em', weight: 500, italic: false, uppercase: true }, display: { label: 'Display', css: '"Italiana", serif', tracking: '0.18em', weight: 400, italic: false, uppercase: true }, italic: { label: 'Italic', css: '"Cormorant Garamond", serif', tracking: '0.04em', weight: 500, italic: true, uppercase: false }, serif: { label: 'Classic', css: '"Playfair Display", serif', tracking: '0.02em', weight: 500, italic: false, uppercase: false }, script: { label: 'Script', css: '"Pinyon Script", cursive', tracking: '0.01em', weight: 400, italic: false, uppercase: false }, hand: { label: 'Handwritten', css: '"Caveat", cursive', tracking: '0.01em', weight: 600, italic: false, uppercase: false }, soft: { label: 'Soft sans', css: '"Outfit", sans-serif', tracking: '0.04em', weight: 500, italic: false, uppercase: false }, } as const; type FontId = keyof typeof FONTS; const MAX_PETS = 4; type Pet = { id: number; file: File | null; name: string }; // The builder opens straight into the Style picker — there's no // "what kind of pet?" gate anymore. The style grid itself shows a // varied mix of animals (see styleCatalog `display`). const STEPS = [ { id: 'style', title: 'Style', heading: 'Choose your style' }, { id: 'background', title: 'Background', heading: 'Pick a background' }, { id: 'frame', title: 'Frame & size',heading: 'Frame, size, and lettering' }, { id: 'photos', title: 'Your pets', heading: 'Upload your pets' }, { id: 'review', title: 'Review', heading: 'Review your commission' }, ] as const; const TOTAL_STEPS = STEPS.length; const STEP_BACKGROUND = 1; const REAL = STYLE_CATALOG.length; export function Builder() { // ─── Style slideshow state (set first — used by step-skip helpers) ── // Cross-fade picker: just track the current style index. The matte / // background colour shows through between the two opacity-fading // slides during transitions. const [styleIdx, setStyleIdx] = useState(0); // ─── Product / size / frame / customization state ──────────────── const [productId, setProductId] = useState('classic'); const [size, setSize] = useState(PRODUCTS.classic.defaultSize); // Default frame is 'black' because it's available on every product // (matted limits to black/white/oak — walnut/gold/silver aren't // offered as box frames). pickProduct also snaps the current frame // to a valid one if the customer switches to a product that doesn't // carry the previously-picked finish. const [frame, setFrame] = useState('black'); // Switching product resets the size to that product's default, since // size lists don't overlap. const pickProduct = (id: ProductId) => { setProductId(id); setSize(PRODUCTS[id].defaultSize); // Snap frame to a valid finish for the new product. If the customer // was on canvas/walnut and switches to matted (which doesn't offer // walnut), fall back to the first allowed finish for matted. // Snap the frame to a valid finish — unless the product is frameless // (stretched canvas has no availableFrames), in which case leave the // current frame untouched (it's ignored for that product). const allowed = PRODUCTS[id].availableFrames as readonly FrameId[]; if (allowed.length) setFrame(curr => (allowed.includes(curr) ? curr : allowed[0])); // Snap the mount too: the box frame offers Snow white / Off-white / // Black / No matte, but the classic frame only offers Snow white / // No matte. If the current mount isn't valid for the new product, // fall back to its first allowed mount. const allowedMattes = ('availableMattes' in PRODUCTS[id] ? PRODUCTS[id].availableMattes : []) as readonly MatteId[]; if (allowedMattes.length) { setMatteId(curr => (allowedMattes.includes(curr) ? curr : allowedMattes[0])); } // Snap the edge wrap for the stretched canvas (frameless); other // products have no availableWraps and ignore it. const allowedWraps = ('availableWraps' in PRODUCTS[id] ? PRODUCTS[id].availableWraps : []) as readonly WrapId[]; if (allowedWraps.length) { setWrap(curr => (allowedWraps.includes(curr) ? curr : allowedWraps[0])); } // Both products' default sizes are rectangular, so the current // orientation stays valid; the size snap above already lands on a // size that exists for the new product. }; // Portrait (catalog default) or landscape. Landscape transposes the // chosen size's aspect everywhere downstream (preview, generation, // crop, Prodigi asset). Squares have no landscape form. const [orientation, setOrientation] = useState('portrait'); const pickOrientation = (o: Orientation) => { setOrientation(o); // Square sizes drop out of the landscape list — if the current pick // isn't valid for the new orientation, snap to the product default // (always rectangular, so valid in both orientations). const valid = sizesForOrientation(productId, o); setSize(curr => (valid.includes(curr) ? curr : PRODUCTS[productId].defaultSize)); }; const [bgColorId, setBgColorId] = useState('warmWhite'); const [bgCustom, setBgCustom] = useState('#f4ecd8'); const [fontId, setFontId] = useState('editorial'); const [includeName, setIncludeName] = useState(false); // Box-frame matted prints carry a mount in one of three colours — // Snow white (default), Off-white, or Black — fulfilled by Prodigi's // FRA-BOX-EMA-MOUNT1-ACRY line. The chosen matteId flows through to // the Prodigi order item as `mountColor` (see [prodigi-skus.ts]). // Canvas float frames ignore matteId (fixed recessed gap). const [matteId, setMatteId] = useState('snowwhite'); // Edge wrap for the frameless Stretched Canvas (Image / Mirror / White // / Black). Ignored by every other product. Flows to the Prodigi order // item as the `wrap` attribute (see prodigi-skus.ts). const [wrap, setWrap] = useState('imagewrap'); // ─── Product-photo lightbox state ───────────────────────────────── // When set, opens a full-screen gallery of the chosen product's // photos so the customer can inspect frame depth, corner finish, and // wood finishes before deciding. Closes on Esc, outside-click, or X. const [lightbox, setLightbox] = useState<{ productId: ProductId; index: number } | null>(null); // ─── Pet onboarding state ───────────────────────────────────────── const [pets, setPets] = useState([{ id: 0, file: null, name: '' }]); const nextPetId = useRef(1); // ─── Optional custom style reference (Style step) ───────────────── // Customer can drop a painting, a photo, or any look they love — the // studio attempts to recreate it instead of using a catalogued style. const [customStyle, setCustomStyle] = useState(null); // Free-text note to the studio artist, captured under the custom-style // upload. Persisted in the order config + surfaced in the admin editor. const [artistNote, setArtistNote] = useState(''); // Object URL for the uploaded custom style — rendered as the pinned // polaroid in the preview pane (see custompreview classes). createObjectURL // must be revoked on unmount / file swap to avoid memory leaks. const [customStyleUrl, setCustomStyleUrl] = useState(null); useEffect(() => { if (!customStyle) { setCustomStyleUrl(null); return; } const url = URL.createObjectURL(customStyle); setCustomStyleUrl(url); return () => URL.revokeObjectURL(url); }, [customStyle]); // The "Your own style" tile in the style grid scrolls down to this // section and flashes it — the upload otherwise sits below the fold. const customStyleRef = useRef(null); const [customStyleFlash, setCustomStyleFlash] = useState(false); const jumpToCustomStyle = () => { customStyleRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); setCustomStyleFlash(true); window.setTimeout(() => setCustomStyleFlash(false), 1400); }; // ─── Restore gate ───────────────────────────────────────────────── // The mount effect below decides where the customer belongs: redirect // to the checkout resume screen (pending order), restore an in-progress // build, apply a URL-deeplinked style, or start fresh. Until it // resolves we render a loader instead of the step content — otherwise // the builder paints step 0 ("pick a pet") for a frame and THEN jumps // or redirects, which reads as a jarring double-bounce. Starts true so // SSR + first client paint both show the loader (no hydration // mismatch); flipped to false at the end of every non-redirect branch. const [restoring, setRestoring] = useState(true); const [restorePhotoError, setRestorePhotoError] = useState(''); const [showSavedPhotos, setShowSavedPhotos] = useState(false); // ─── Submit + Stripe Checkout (inlined into the Review step) ────── // Previously this step navigated to /checkout (separate page) for // email entry and order submission. Now the email field lives on the // Review step itself and we kick off the order create + Stripe // session round-trip from here. /checkout still exists as a // legacy/fallback entry point. const [email, setEmail] = useState(''); // emailTouched flips when the customer either blurs the field after // typing, or attempts to submit. Until then we don't yell at them // with red borders — only after they've shown intent to proceed. const [emailTouched, setEmailTouched] = useState(false); const emailInputRef = useRef(null); const emailValid = /.+@.+\..+/.test(email.trim()); const emailInvalid = emailTouched && !emailValid; const [submitting, setSubmitting] = useState(false); const [submitError, setSubmitError] = useState(null); const submitAndPay = async (e: React.FormEvent) => { e.preventDefault(); setEmailTouched(true); if (!emailValid) { setSubmitError( !email.trim() ? 'Please enter your email — we need it to send you the proof.' : "That doesn't look like a valid email. Mind double-checking?", ); emailInputRef.current?.focus(); return; } setSubmitting(true); setSubmitError(null); try { const draft: Draft = { config: { styleId: STYLE_CATALOG[styleIdx].id, productId, size, orientation, frame, matteId, wrap, bgColorId, bgCustom, fontId, includeName, commissionName: commissionName ?? null, // Available on every order — trimmed so a stray whitespace // note doesn't read as intentional. artistNote: artistNote.trim(), }, pets: pets.map((pet, i) => ({ slot: i, file: pet.file, name: pet.name })), customStyle, }; // Stash for /checkout fallback (back-button safety, bookmarked tabs). setDraft(draft); // 1. Create the order — uploads photos to CF Images, creates the // user, inserts the order row. 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 }; // Persist the orderId across the Stripe round-trip. If the // customer hits browser BACK from the Stripe page (which // doesn't fire Stripe's cancel_url), the browser navigates to // /builder. Without this hint the builder mounts fresh at // step 0 ("pick a pet") and the customer loses context. With // it, the builder mount useEffect detects the pending order // and redirects to /checkout?orderId=…&canceled=1 — the same // resume screen they'd see if they'd clicked Stripe's Cancel // button. Cleared by the success page (/login/check-email) and // by the resume page's "Back to the builder" link. try { sessionStorage.setItem('lg_pending_order_id', orderId); } catch {} // 2. Mint the Stripe Checkout Session and redirect. 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) { setSubmitError(err instanceof Error ? err.message : 'Submit failed'); setSubmitting(false); } }; // Resolve the currently-selected style from the index. const styleIndex = styleIdx; const style = STYLE_CATALOG[styleIndex]; // Lettering — and the per-pet name fields + review line that hang off // it — only apply to catalog styles that support it, AND only when // there's no custom reference attached. A custom commission is // recreated from the uploaded image as-is; we don't overlay lettering // on it, so the whole Lettering control drops out for customs. Mirrors // allowsBg below. const allowsName = !customStyle && !!style.allowsName; // The Background step lets the customer pick the solid ground colour // the portrait finishes on — only meaningful for catalog styles that // render on a flat background. A custom style reference defines its // OWN background (the studio recreates the look of the uploaded // image, ground included), so a ground-colour picker would be // misleading — we hide the Background step entirely when a reference // is attached. The catalog style's hasSolidBackground governs the // normal (no-upload) case. const allowsBg = !customStyle && !!style.hasSolidBackground; // Preselect a style when the visitor arrives from an example's CTA, // e.g. /builder?style=popart. Jump (no animation) to it. Also seed // includeName from the variant's default so picking "Charcoal — named" // turns lettering on, while plain "Charcoal" leaves it off. // // If a draft order is already stashed (customer came back from // /checkout to make changes), restore every selection from it // instead — the saved draft wins over the URL-param preset, since // it's what the customer was just looking at. useEffect(() => { // Zeroth: "Make changes" on the resume screen lands here as // /builder?edit=. The order already exists server-side with // its photos on Cloudflare Images, so fetch the summary, restore every // design selection, and reconstruct the pet / style File objects from // their stored URLs — the customer keeps their uploads instead of // being asked to re-add them. Must run BEFORE the pending-order bounce // below, or we'd redirect straight back to the resume screen we came // from. Async, so `restoring` stays true (loader) until it settles. const entryParams = new URLSearchParams(window.location.search); const savedPhoto = entryParams.get('savedPhoto'); if (savedPhoto) { const [orderId, slot, extra] = savedPhoto.split(':'); (async () => { try { if (!orderId || !/^[0-3]$/.test(slot ?? '') || extra !== undefined) throw new Error('Invalid saved photo'); const file = await urlToFile(`/api/orders/photos?order=${encodeURIComponent(orderId)}&slot=${slot}`, 'saved-photo.jpg'); setPets([{ id: 0, file, name: '' }]); nextPetId.current = 1; } catch { setRestorePhotoError('Could not load the saved photo. Open Saved photos to try again.'); } finally { setStep(3); setRestoring(false); } })(); return; } const editId = entryParams.get('edit'); const replacement = entryParams.has('replace'); if (editId) { (async () => { try { const res = await fetch(`/api/orders/${encodeURIComponent(editId)}/summary${replacement ? '?replace=1' : ''}`); if (!res.ok) throw new Error(`summary ${res.status}`); const data = await res.json() as { email?: string; config?: Partial & { pets?: Array<{ slot: number; name: string | null }> }; petPhotoUrls?: string[]; customStyleUrl?: string | null; }; const cfg = data.config ?? {}; // Prefill the email they already gave us — no re-typing to re-pay. if (data.email) setEmail(data.email); const idx = STYLE_CATALOG.findIndex((s) => s.id === cfg.styleId); if (idx >= 0) setStyleIdx(idx); if (cfg.productId) setProductId(cfg.productId); if (cfg.size) setSize(cfg.size); if (cfg.orientation === 'landscape' || cfg.orientation === 'portrait') setOrientation(cfg.orientation); if (cfg.frame) setFrame(cfg.frame as FrameId); // Normalise legacy mat ids (warmwhite/cream/hayseed → offwhite, // none → snowwhite) to a current key. setMatteId(normalizeMatteId(cfg.matteId as string | undefined)); if (cfg.wrap) setWrap(normalizeWrapId(cfg.wrap as string)); if (cfg.bgColorId) setBgColorId(cfg.bgColorId as BgColorId | 'custom'); if (cfg.bgCustom) setBgCustom(cfg.bgCustom); if (cfg.fontId) setFontId(cfg.fontId as FontId); if (typeof cfg.includeName === 'boolean') setIncludeName(cfg.includeName); if (typeof cfg.artistNote === 'string') setArtistNote(cfg.artistNote); // Rebuild pet photos from their CF Images URLs (names from config). // A failed reconstruction leaves that slot empty, so the customer // only re-adds the one that couldn't be fetched — never all of them. const urls = data.petPhotoUrls ?? []; const names = (cfg.pets ?? []).map((p) => p?.name ?? ''); if (urls.length > 0) { const files = await Promise.all( urls.map((u, i) => urlToFile(u, `pet-${i + 1}.jpg`).catch(() => null)), ); const rebuilt = files.map((file, i) => ({ id: i, file, name: names[i] ?? '' })); setPets(rebuilt); nextPetId.current = rebuilt.length; if (replacement && files.some(file => !file)) setRestorePhotoError('Some saved photos could not load. Open Saved photos to try again.'); } if (data.customStyleUrl) { const cs = await urlToFile(data.customStyleUrl, 'style-reference.jpg').catch(() => null); if (cs) setCustomStyle(cs); } // Clear the pending-order hint so a later mount doesn't bounce // back to the resume screen now that we're editing in place. try { sessionStorage.removeItem('lg_pending_order_id'); } catch {} setStep(replacement ? 2 : 4); } catch { // Order gone / network failure — fall back to a fresh builder // rather than trapping the customer on the loader. if (replacement) setRestorePhotoError('Could not load the cancelled order. Your saved photos are still available.'); } finally { setRestoring(false); } })(); return; } // First: if the customer has a pending unpaid order (stashed by // submitAndPay before redirecting to Stripe), route them to the // resume screen instead of dumping them at step 0. This covers // the browser back button from Stripe (which doesn't fire // cancel_url) — the resume screen handles the case where their // order already exists server-side and they just need to re-pay. try { const pendingId = sessionStorage.getItem('lg_pending_order_id'); if (pendingId) { window.location.replace(`/checkout?orderId=${encodeURIComponent(pendingId)}&canceled=1`); return; } } catch { /* sessionStorage unavailable (SSR / private mode) — fall through */ } // A gallery "Start one like this" deeplink carries the chosen // style / frame / product / size in the URL. Treat it as an explicit // "build this exact piece" intent: it OVERRIDES any saved draft or // in-progress build, so clicking a second gallery photo replaces the // first instead of being silently ignored by the restore branches // below. (matte is read only for this presence test — we still don't // act on the value; see the note further down.) const params = new URLSearchParams(window.location.search); const hasDeeplink = ['style', 'frame', 'matte', 'product', 'size', 'orientation'].some((k) => params.has(k)); const draft = getDraft(); if (!hasDeeplink && draft) { const idx = STYLE_CATALOG.findIndex((s) => s.id === draft.config.styleId); if (idx >= 0) setStyleIdx(idx); setProductId(draft.config.productId); setSize(draft.config.size); if (draft.config.orientation === 'landscape' || draft.config.orientation === 'portrait') { setOrientation(draft.config.orientation); } setFrame(draft.config.frame as FrameId); // Normalise legacy mat ids from earlier UI revisions: // 'warmwhite' / 'cream' / 'hayseed' → 'offwhite' // 'none' → 'snowwhite' setMatteId(normalizeMatteId(draft.config.matteId as string)); setWrap(normalizeWrapId(draft.config.wrap as string)); setBgColorId(draft.config.bgColorId as BgColorId | 'custom'); setBgCustom(draft.config.bgCustom); setFontId(draft.config.fontId as FontId); setIncludeName(draft.config.includeName); // Rehydrate pets — keep slot ids stable so React keys don't churn. if (draft.pets.length > 0) { setPets(draft.pets.map((p) => ({ id: p.slot, file: p.file, name: p.name }))); nextPetId.current = Math.max(...draft.pets.map((p) => p.slot)) + 1; } setCustomStyle(draft.customStyle); if (typeof draft.config.artistNote === 'string') setArtistNote(draft.config.artistNote); // Drop the customer back where they were heading from — the // Review step — so they can fix the one thing and continue. setStep(4); setRestoring(false); return; } // Third: restore in-progress build from sessionStorage. This is the // "wandered off to the gallery and came back" path — the header's // Resume-portrait indicator routes them here. We persist the design // selections + step (see the persist effect below); File uploads // (pet photos, custom style) can't be serialized so those are NOT // restored — the customer re-adds them if they'd already uploaded. if (!hasDeeplink) try { const saved = sessionStorage.getItem('lg_build_progress'); if (saved) { const b = JSON.parse(saved) as Partial & { step?: number }; const idx = STYLE_CATALOG.findIndex((s) => s.id === b.styleId); if (idx >= 0) setStyleIdx(idx); if (b.productId) setProductId(b.productId); if (b.size) setSize(b.size); if (b.orientation === 'landscape' || b.orientation === 'portrait') setOrientation(b.orientation); if (b.frame) setFrame(b.frame as FrameId); if (b.matteId) setMatteId(normalizeMatteId(b.matteId)); if (b.wrap) setWrap(normalizeWrapId(b.wrap)); if (b.bgColorId) setBgColorId(b.bgColorId as BgColorId | 'custom'); if (b.bgCustom) setBgCustom(b.bgCustom); if (b.fontId) setFontId(b.fontId as FontId); if (typeof b.includeName === 'boolean') setIncludeName(b.includeName); if (typeof b.artistNote === 'string') setArtistNote(b.artistNote); if (typeof b.step === 'number') setStep(b.step); setRestoring(false); return; } } catch { /* ignore corrupt/unavailable storage — fall through */ } const styleParam = params.get('style'); const frameParam = params.get('frame'); const matteParam = params.get('matte'); const wrapParam = params.get('wrap'); const productParam = params.get('product'); const sizeParam = params.get('size'); const orientationParam = params.get('orientation'); // Product + size preselect from gallery "Start one like this" CTA. // Apply product first so its size list is the one we validate against, // then snap the frame to a finish the product actually offers. if (productParam && productParam in PRODUCTS) { const pid = productParam as ProductId; setProductId(pid); // Use the gallery-specified size if it exists for the product, // otherwise fall back to the product's default. const allowedSizes = PRODUCTS[pid].sizes as Record; setSize(sizeParam && sizeParam in allowedSizes ? sizeParam : PRODUCTS[pid].defaultSize); // Snap frame if the requested one isn't on this product. const allowedFrames = PRODUCTS[pid].availableFrames as readonly FrameId[]; if (frameParam && frameParam in FRAMES && allowedFrames.includes(frameParam as FrameId)) { setFrame(frameParam as FrameId); } } else if (frameParam && frameParam in FRAMES) { setFrame(frameParam as FrameId); } // Landscape deep-link (e.g. gallery "Start one like this" on a // landscape mock). Snap off any square size that isn't valid landscape. if (orientationParam === 'landscape') { setOrientation('landscape'); const pid = (productParam && productParam in PRODUCTS ? productParam : productId) as ProductId; const valid = sizesForOrientation(pid, 'landscape'); setSize((curr) => (valid.includes(curr) ? curr : PRODUCTS[pid].defaultSize)); } // Honour a deep-linked mount colour (gallery "Start one like this" // URLs carry ?matte=…). Normalised so legacy values still resolve. if (matteParam) setMatteId(normalizeMatteId(matteParam)); if (wrapParam) setWrap(normalizeWrapId(wrapParam)); // Fresh build (URL deeplink or blank) — reveal the builder now. setRestoring(false); if (!styleParam) { setIncludeName(!!STYLE_CATALOG[0].defaultIncludeName); return; } const idx = STYLE_CATALOG.findIndex((s) => s.id === styleParam); if (idx >= 0) { setStyleIdx(idx); setIncludeName(!!STYLE_CATALOG[idx].defaultIncludeName); // The style is already chosen via the deep-link (gallery / example // "Start one like this" CTA), so the Style step is a no-op for this // visitor — drop them straight on the next applicable step. That's // Background when the chosen style renders on a solid ground; // otherwise Frame & size. (allowsBg isn't reliable here — it's a // render-derived value that still reflects the pre-deeplink style — // so read hasSolidBackground off the catalog entry directly.) Style // stays in the rail, so they can still go back and change it. setStep(STYLE_CATALOG[idx].hasSolidBackground ? STEP_BACKGROUND : STEP_BACKGROUND + 1); } }, []); // ─── Step state + skip-aware navigation ─────────────────────────── const [step, setStep] = useState(0); const isStepApplicable = (i: number) => (i === STEP_BACKGROUND ? allowsBg : true); const goStepNext = () => setStep((cur) => { let n = cur + 1; while (n < TOTAL_STEPS && !isStepApplicable(n)) n++; return n >= TOTAL_STEPS ? cur : n; }); const goStepPrev = () => setStep((cur) => { let p = cur - 1; while (p >= 0 && !isStepApplicable(p)) p--; return p < 0 ? cur : p; }); const goToStep = (target: number) => { if (!isStepApplicable(target)) return; setStep(Math.max(0, Math.min(TOTAL_STEPS - 1, target))); }; // Scroll the page to the top whenever the active step changes. // Covers Next, Back, and rail-dot jumps in a single place. Smooth // scroll unless the user has prefers-reduced-motion set, in which // case we snap instantly. Skipped on the very first render so an // initial /builder load doesn't fight whatever scroll position the // browser restored. // // Desktop-only: this is the two-column layout's affordance — the // sticky preview stays in view and the step panel resets to its top. // On the stacked (<=1024) layout the preview sits ABOVE the step // content, so scrolling to the very top would yank the customer past // the preview, away from the step they just advanced to. Bail there. const isFirstRender = useRef(true); useEffect(() => { if (isFirstRender.current) { isFirstRender.current = false; return; } if (window.matchMedia?.('(max-width: 1024px)').matches) return; const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches; window.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' }); }, [step]); // Persist in-progress build to sessionStorage so the customer can // wander off (browse the gallery, read the FAQ) and return via the // header's "Resume portrait" indicator. We hold off until the mount // effect has decided where the customer belongs (`restoring` false) // so we don't clobber a draft mid-restore. File uploads aren't // serializable, so photos + custom-style images are intentionally // NOT saved; the design selections + current step are. Cleared on // successful payment (see /login/check-email). // // We only write the snapshot when the customer has DEPARTED from the // bare initial defaults (matched against the same useState() values // declared above). On default state we explicitly REMOVE the key so // the header's pre-paint resume indicator doesn't appear for users // who landed on /builder but haven't engaged. Resetting back to // defaults also clears the key — Resume only shows while there's // real progress to resume. useEffect(() => { if (restoring) return; try { const isDefault = styleIdx === 0 && productId === 'classic' && size === PRODUCTS.classic.defaultSize && orientation === 'portrait' && frame === 'black' && matteId === 'snowwhite' && wrap === 'imagewrap' && bgColorId === 'warmWhite' && bgCustom === '#f4ecd8' && fontId === 'editorial' && includeName === false && artistNote === '' && step === 0; if (isDefault) { sessionStorage.removeItem('lg_build_progress'); return; } const progress: DraftConfig & { step: number } = { styleId: STYLE_CATALOG[styleIdx].id, productId, size, orientation, frame, matteId, wrap, bgColorId, bgCustom, fontId, includeName, commissionName: null, artistNote, step, }; sessionStorage.setItem('lg_build_progress', JSON.stringify(progress)); } catch { /* storage unavailable — non-fatal */ } }, [restoring, styleIdx, productId, size, orientation, frame, matteId, wrap, bgColorId, bgCustom, fontId, includeName, artistNote, step]); // If the active step becomes inapplicable (e.g. the customer switched // from a name-bearing style to a painted one), snap forward to the // next applicable step. useEffect(() => { if (!isStepApplicable(step)) { let n = step + 1; while (n < TOTAL_STEPS && !isStepApplicable(n)) n++; setStep(n >= TOTAL_STEPS ? Math.max(0, step - 1) : n); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [allowsBg, allowsName]); // The visible step list (filters out inapplicable ones) — used for // the "Step X of Y" indicator so the count stays honest. const activeSteps = STEPS .map((s, i) => ({ ...s, i })) .filter((s) => isStepApplicable(s.i)); const visibleIdx = activeSteps.findIndex((s) => s.i === step); const isFirstStep = visibleIdx === 0; const isLastStep = visibleIdx === activeSteps.length - 1; // ─── Pricing & geometry ─────────────────────────────────────────── const product = PRODUCTS[productId]; // Size lists differ per product; the picker resets size on swap, but // be defensive in case a URL/state combination ever drifts. const sizes = product.sizes as Record; const sizeMeta = sizes[size] ?? sizes[product.defaultSize]; // Orientation-aware derived values. The size grid shows only sizes // valid for the chosen orientation (landscape drops squares); the // label + mount aspect transpose for landscape so the live preview, // review summary, and caption all read landscape. const orientedSizes = sizesForOrientation(productId, orientation); const displaySizeLabel = sizeLabel(productId, size, orientation); const mountAspect = frameAspect(productId, size, orientation) ?? sizeMeta.aspect; // Sold at cost: the portrait artwork is free, so custom style // references and extra pets don't change the price. const hasCustomStyle = !!customStyle; const saleTotal = salePrice(productId, size, matteId); // ─── Slideshow nav (style picker) ───────────────────────────────── const pickStyleByIndex = (i: number) => { const wrapped = ((i % REAL) + REAL) % REAL; setStyleIdx(wrapped); const entry = STYLE_CATALOG[wrapped]; if (entry.allowsName) setIncludeName(!!entry.defaultIncludeName); // Orientation is intentionally left alone here. The format // (portrait/landscape) is the customer's choice in the Frame step and // persists across style changes — a style names the look, not the // frame shape. }; const goPrev = () => pickStyleByIndex(styleIdx - 1); const goNext = () => pickStyleByIndex(styleIdx + 1); // ─── Pet helpers ────────────────────────────────────────────────── const addPet = () => setPets((cur) => cur.length >= MAX_PETS ? cur : [...cur, { id: nextPetId.current++, file: null, name: '' }], ); const removePet = (id: number) => setPets((cur) => (cur.length <= 1 ? cur : cur.filter((pet) => pet.id !== id))); const setPetFile = (id: number, file: File) => setPets((cur) => cur.map((pet) => (pet.id === id ? { ...pet, file } : pet))); const setPetName = (id: number, name: string) => setPets((cur) => cur.map((pet) => (pet.id === id ? { ...pet, name } : pet))); const uploaded = pets.filter((pet) => pet.file).length; // Review-step pay gate: a commission can't start without at least one // pet photo AND a valid email (that's where the proof is sent). Both // are surfaced as a checklist above the CTA and the button is disabled // until they're satisfied — see the .review__gate block. const needsPhoto = uploaded === 0; const needsEmail = !emailValid; const payBlockers = (needsPhoto ? 1 : 0) + (needsEmail ? 1 : 0); const enteredNames = pets.map((pet) => pet.name.trim()).filter(Boolean); const commissionName = allowsName && enteredNames.length ? enteredNames.join(enteredNames.length === 2 ? ' & ' : ', ') : null; // Raw, properly-cased name. The CSS `textTransform: uppercase` is // applied per font (FONTS[fontId].uppercase) so caps-friendly faces // get tracked-out caps while script / handwritten / soft sans keep // the customer's intended casing. const displayedName = commissionName ?? 'Teddy'; const bgHex = bgColorId === 'custom' ? bgCustom : BACKGROUND_COLORS[bgColorId].hex; // Products that carry a mount (box frame, classic frame) expose an // `availableMattes` list and render a real mat board; canvas has none // and renders a fixed 5 mm recess gap. "No matte" drops the mat board // to zero width. const availableMattes = ('availableMattes' in product ? product.availableMattes : []) as readonly MatteId[]; const hasMount = availableMattes.length > 0; // Frameless products (stretched canvas) hide the Frame picker and show // an Edge-wrap picker instead. const hasFrames = (product.availableFrames as readonly FrameId[]).length > 0; const availableWraps = ('availableWraps' in product ? product.availableWraps : []) as readonly WrapId[]; const hasWraps = availableWraps.length > 0; const noMat = hasMount && isNoMat(matteId); const effectiveMatteW = noMat ? 0 : product.matteW; // Mounted products read the chosen mat colour from MATTES; canvas // renders the recess as a deep shadow tone. Fall back to snow white if // an unknown legacy id slipped through. const effectiveMatteBg = hasMount ? (MATTES[matteId]?.hex ?? MATTES.snowwhite.hex) : '#0d0a08'; const mountStyle = { '--frame-w': `${product.frameW}px`, '--matte-w': `${effectiveMatteW}px`, '--frame-bg': FRAMES[frame].frame, '--matte-bg': effectiveMatteBg, '--mount-aspect': mountAspect, } as CSSProperties; // ─── Render ─────────────────────────────────────────────────────── // While the mount effect decides where the customer belongs, show a // clean loader instead of the (about-to-change) step content. Prevents // the "pick a pet" flash → bounce on resume/redirect. if (restoring) { return (
{/* Same heading as the loaded wizard, so the server-rendered HTML crawlers see has the page's h1 too. */}
Your commission

Your pets. Your style. One portrait.

Preparing your canvas…

); } return ( <>
Your commission

Your pets. Your style. One portrait.

{/* ── LEFT: step-content panel ─────────────────────────── */}
{/* Compact progress stepper — one connected-node row. Replaces the old "Step X of Y · Title" line + chunky pill rail, which together triple-stated the current step with the heading just below. EVERY node is clickable to jump straight to that step (back OR forward) — same free navigation the old dot-rail had; the current step is the single rose focal point, done steps read filled, upcoming steps read quiet but remain live. The count + current title still ship to screen readers via the nav label. */}

{STEPS[step].heading}

{/* STEP 1 — Style picker */} {step === 0 && (

Pick the look first — the preview on the right updates live. Frame, size, and lettering come next.

Style {hasCustomStyle ? 'Your own style' : style.name}
{STYLE_CATALOG.map((entry, i) => ( ))}
{hasCustomStyle ? (
You’re using your own style reference, so the catalog styles are locked. Remove your reference below to pick a catalog style instead.
) : ( <>
{style.blurb}
{allowsName ? `${style.name} can letter each pet’s name onto the artwork. You can pick the typeface (or turn lettering off) when you choose your frame.` : 'Want your pet’s name on the portrait? Try Line Drawing, Vector Outline, Charcoal, or Modern Portrait — with name.'}
)}
Have a style in mind? Optional · free

Drop a reference photo of a style you like and we’ll attempt to recreate it for you — a painting, a photo, anything beyond our catalogued styles. Free, like all our artwork.

setCustomStyle(null)} />
)} {/* STEP 2 — Background (only shown when style.hasSolidBackground) */} {step === STEP_BACKGROUND && (

Pick the ground colour the portrait finishes on. The preview updates live.

Background
{(Object.keys(BACKGROUND_COLORS) as BgColorId[]).map((id) => ( ))}
)} {/* STEP 3 — Frame, size, and lettering */} {step === 2 && (

Pick a wood, a size, and {allowsName ? 'how the name should look — or turn lettering off.' : 'you’re done. The preview updates live.'}

Product
{/* Classic first — it's the bestselling lead product, the cheapest way in, and the default selection. */} {(['classic', 'matted', 'stretched', 'canvas'] as ProductId[]).map((id) => { const p = PRODUCTS[id]; const selected = id === productId; return (
); })}
{hasFrames && (
Frame
{(product.availableFrames as readonly FrameId[]).map((id) => ( ))}
)} {hasWraps && (
Edge wrap
{availableWraps.map((id) => ( ))}
)} {hasMount && (
Mount
{availableMattes.map((id) => ( ))}
)}
Orientation {orientation === 'landscape' ? 'Wider than tall' : 'Taller than wide'}
{(['portrait', 'landscape'] as Orientation[]).map((o) => ( ))}
Size {product.label}
{orientedSizes.map((id) => ( ))}
{allowsName && (
Lettering
{includeName && (
{(Object.keys(FONTS) as FontId[]).map((id) => ( ))}
)}
)}
)} {/* Live pricing was previously a standalone sticky banner above wizard__nav. Moved inline INTO the nav (between Back and Next) so there's a single pinned bottom bar instead of two stacked ones. See the wizard__nav block below. */} {/* STEP 4 — Photos & names */} {step === 3 && (

Upload up to four pets — we’ll combine them into a single composition.

Accepted: {ACCEPTED_IMAGE_LABEL} per photo.

{restorePhotoError &&

{restorePhotoError}

} {showSavedPhotos && = 4} onAdd={(file, name) => { const id = nextPetId.current++; setPets(previous => { const empty = previous.findIndex(pet => !pet.file); if (empty >= 0) return previous.map((pet, index) => index === empty ? { ...pet, file, name: name || pet.name } : pet); return previous.length < 4 ? [...previous, { id, file, name }] : previous; }); }} />}
{pets.map((pet, i) => (
setPetFile(pet.id, file)} /> {pets.length > 1 && ( )}
{/* Only ask for the pet's name when lettering is actually going to appear on the print. If the customer is on a name-bearing variant but turned lettering off in the Frame step, or picked a no-letter style, skip the name field entirely. */} {allowsName && includeName && ( setPetName(pet.id, e.target.value)} /> )}
))} {pets.length < MAX_PETS && ( )}
)} {/* STEP 5 — Review */} {step === 4 && (

Last look before we start your portrait — your proof arrives within one business day (Mon–Fri), free.

{commissionName && (
Commission name “{commissionName}”
)}
Style {/* With a custom reference attached, the look comes from the upload — don't surface whatever catalog style happened to be selected underneath (it reads as misleading). */} {customStyle ? 'Custom' : style.name}
{customStyle && (
Style reference Attached · free
)}
Pets {uploaded > 0 ? ( {uploaded} {uploaded === 1 ? 'pet' : 'pets'} ) : ( )}
Product {product.label}, {displaySizeLabel}
{hasFrames && (
Frame {FRAMES[frame].label}
)} {hasMount && (
Mount {(MATTES[matteId] ?? MATTES.snowwhite).label}
)} {hasWraps && (
Edge wrap {WRAPS[wrap].label}
)} {allowsBg && (
Background {bgColorId === 'custom' ? bgCustom : BACKGROUND_COLORS[bgColorId].label}
)} {allowsName && (
Lettering {includeName ? FONTS[fontId].label : 'None'}
)}
{/* Note for the artist — available on every order, not just custom-style ones. Deliberately non-committal copy: we don't promise to action requests, only that we try. */}

Anything you’d like us to keep in mind for your portrait{customStyle ? ' or your uploaded reference' : ''} — a detail to emphasise, a mood, something about your pet. We can’t promise we’ll act on every request, but we read each one and accommodate what we can.