Branchwell

Lumen & Gesso / website · lumengesso.com / app / components / Builder.tsx

1'use client';
2
3import Image from 'next/image';
4import { useState, useEffect, useRef, type CSSProperties } from 'react';
5import { ImageDrop } from './ImageDrop';
6import { SavedPhotos } from './SavedPhotos';
7import { ACCEPTED_IMAGE_LABEL } from '../lib/upload-limits';
8import { STYLE_CATALOG, type StyleCatalogEntry } from '../data/styleCatalog';
9import { BACKGROUND_COLORS, type BgColorId } from '../data/backgrounds';
10import { getDraft, setDraft, draftToFormData, type Draft, type DraftConfig } from '../lib/draft-order';
11import { urlToFile } from '../lib/url-to-file';
12import {
13 PRODUCTS,
14 salePrice,
15 sizeLabel,
16 sizesForOrientation,
17 frameAspect,
18 type ProductId,
19 type Orientation,
20} from '../lib/pricing';
21
22// Pick which rendered variant to show for a style tile / preview slide.
23// There's no pet-type selector — the builder opens straight into the
24// style picker — so each style carries a hand-curated `display` field
25// (dog / cat / other) chosen to make the grid read as a varied
26// menagerie: mostly cats and dogs, with a few other animals (fox,
27// capybara, hedgehog…) sprinkled in. Falls back to the dog `example`.
28const exampleFor = (entry: StyleCatalogEntry) => {
29 if (entry.display === 'cat' && entry.catExample) return entry.catExample;
30 if (entry.display === 'other' && entry.otherExample) return entry.otherExample;
31 return entry.example;
32};
33
34// The commission builder — a multi-step wizard.
35//
36// Layout: two columns. The left column is the step-content panel (one
37// focused screen at a time), the right column is a persistent preview
38// panel showing the live framed portrait — mount + image + bg-colour +
39// lettering overlay — so the customer can see the state of the artwork
40// as they configure it.
41//
42// Steps (any inapplicable step is auto-skipped both forward and back):
43// 1. Style — pick the artwork style
44// 2. Background — pick the ground colour (skipped when the chosen
45// style brings its own ground, e.g. cubist, ukiyo-e)
46// 3. Frame — pick the frame, the size, and (if the chosen
47// style supports lettering) the font + on/off
48// 4. Photos — upload up to 4 pet photos, optionally name them.
49// Deferred — no point in asking for uploads until
50// the customer has decided what they're making.
51// 5. Review — order summary, optional custom-style upload,
52// Continue button, and the 100% Artwork Satisfaction
53// Guarantee trust block.
54
55// Product catalogue (sizes, prices, Prodigi mapping, and frame/matte
56// geometry) lives in app/lib/pricing.ts — single source of truth shared
57// with the orders API and the Stripe webhook.
58type SizeId = string;
59
60// The six finishes we offer on the box frame, matching the moulding
61// FRAMES + MATTES catalog lives in app/data/frames.ts so the same data
62// powers the Builder picker, the FramedPreview component, the admin
63// editor's framed mockup, and the customer approve page.
64import { FRAMES, MATTES, WRAPS, normalizeMatteId, normalizeWrapId, isNoMat, type FrameId, type MatteId, type WrapId } from '../data/frames';
65
66// Background palette + per-color filename helper live in app/data/backgrounds.ts
67// — single source of truth shared with the Node generation script that bakes
68// per-color renders for watercolor / vector / named styles.
69
70// Lettering typefaces offered to the customer. `uppercase: true` forces
71// the name to caps (works for tracked-out modern sans + display serifs);
72// `uppercase: false` lets the customer's actual casing through, which
73// reads better in scripts, handwritten, and lowercase-friendly serifs.
74const FONTS = {
75 modern: { label: 'Modern', css: '"DM Sans", sans-serif', tracking: '0.28em', weight: 500, italic: false, uppercase: true },
76 editorial: { label: 'Editorial', css: '"Newsreader", serif', tracking: '0.10em', weight: 500, italic: false, uppercase: true },
77 display: { label: 'Display', css: '"Italiana", serif', tracking: '0.18em', weight: 400, italic: false, uppercase: true },
78 italic: { label: 'Italic', css: '"Cormorant Garamond", serif', tracking: '0.04em', weight: 500, italic: true, uppercase: false },
79 serif: { label: 'Classic', css: '"Playfair Display", serif', tracking: '0.02em', weight: 500, italic: false, uppercase: false },
80 script: { label: 'Script', css: '"Pinyon Script", cursive', tracking: '0.01em', weight: 400, italic: false, uppercase: false },
81 hand: { label: 'Handwritten', css: '"Caveat", cursive', tracking: '0.01em', weight: 600, italic: false, uppercase: false },
82 soft: { label: 'Soft sans', css: '"Outfit", sans-serif', tracking: '0.04em', weight: 500, italic: false, uppercase: false },
83} as const;
84type FontId = keyof typeof FONTS;
85
86const MAX_PETS = 4;
87type Pet = { id: number; file: File | null; name: string };
88
89// The builder opens straight into the Style picker — there's no
90// "what kind of pet?" gate anymore. The style grid itself shows a
91// varied mix of animals (see styleCatalog `display`).
92const STEPS = [
93 { id: 'style', title: 'Style', heading: 'Choose your style' },
94 { id: 'background', title: 'Background', heading: 'Pick a background' },
95 { id: 'frame', title: 'Frame & size',heading: 'Frame, size, and lettering' },
96 { id: 'photos', title: 'Your pets', heading: 'Upload your pets' },
97 { id: 'review', title: 'Review', heading: 'Review your commission' },
98] as const;
99const TOTAL_STEPS = STEPS.length;
100const STEP_BACKGROUND = 1;
101
102const REAL = STYLE_CATALOG.length;
103
104export function Builder() {
105 // ─── Style slideshow state (set first — used by step-skip helpers) ──
106 // Cross-fade picker: just track the current style index. The matte /
107 // background colour shows through between the two opacity-fading
108 // slides during transitions.
109 const [styleIdx, setStyleIdx] = useState(0);
110
111 // ─── Product / size / frame / customization state ────────────────
112 const [productId, setProductId] = useState<ProductId>('classic');
113 const [size, setSize] = useState<SizeId>(PRODUCTS.classic.defaultSize);
114 // Default frame is 'black' because it's available on every product
115 // (matted limits to black/white/oak — walnut/gold/silver aren't
116 // offered as box frames). pickProduct also snaps the current frame
117 // to a valid one if the customer switches to a product that doesn't
118 // carry the previously-picked finish.
119 const [frame, setFrame] = useState<FrameId>('black');
120 // Switching product resets the size to that product's default, since
121 // size lists don't overlap.
122 const pickProduct = (id: ProductId) => {
123 setProductId(id);
124 setSize(PRODUCTS[id].defaultSize);
125 // Snap frame to a valid finish for the new product. If the customer
126 // was on canvas/walnut and switches to matted (which doesn't offer
127 // walnut), fall back to the first allowed finish for matted.
128 // Snap the frame to a valid finish — unless the product is frameless
129 // (stretched canvas has no availableFrames), in which case leave the
130 // current frame untouched (it's ignored for that product).
131 const allowed = PRODUCTS[id].availableFrames as readonly FrameId[];
132 if (allowed.length) setFrame(curr => (allowed.includes(curr) ? curr : allowed[0]));
133 // Snap the mount too: the box frame offers Snow white / Off-white /
134 // Black / No matte, but the classic frame only offers Snow white /
135 // No matte. If the current mount isn't valid for the new product,
136 // fall back to its first allowed mount.
137 const allowedMattes = ('availableMattes' in PRODUCTS[id] ? PRODUCTS[id].availableMattes : []) as readonly MatteId[];
138 if (allowedMattes.length) {
139 setMatteId(curr => (allowedMattes.includes(curr) ? curr : allowedMattes[0]));
140 }
141 // Snap the edge wrap for the stretched canvas (frameless); other
142 // products have no availableWraps and ignore it.
143 const allowedWraps = ('availableWraps' in PRODUCTS[id] ? PRODUCTS[id].availableWraps : []) as readonly WrapId[];
144 if (allowedWraps.length) {
145 setWrap(curr => (allowedWraps.includes(curr) ? curr : allowedWraps[0]));
146 }
147 // Both products' default sizes are rectangular, so the current
148 // orientation stays valid; the size snap above already lands on a
149 // size that exists for the new product.
150 };
151 // Portrait (catalog default) or landscape. Landscape transposes the
152 // chosen size's aspect everywhere downstream (preview, generation,
153 // crop, Prodigi asset). Squares have no landscape form.
154 const [orientation, setOrientation] = useState<Orientation>('portrait');
155 const pickOrientation = (o: Orientation) => {
156 setOrientation(o);
157 // Square sizes drop out of the landscape list — if the current pick
158 // isn't valid for the new orientation, snap to the product default
159 // (always rectangular, so valid in both orientations).
160 const valid = sizesForOrientation(productId, o);
161 setSize(curr => (valid.includes(curr) ? curr : PRODUCTS[productId].defaultSize));
162 };
163 const [bgColorId, setBgColorId] = useState<BgColorId | 'custom'>('warmWhite');
164 const [bgCustom, setBgCustom] = useState('#f4ecd8');
165 const [fontId, setFontId] = useState<FontId>('editorial');
166 const [includeName, setIncludeName] = useState(false);
167 // Box-frame matted prints carry a mount in one of three colours —
168 // Snow white (default), Off-white, or Black — fulfilled by Prodigi's
169 // FRA-BOX-EMA-MOUNT1-ACRY line. The chosen matteId flows through to
170 // the Prodigi order item as `mountColor` (see [prodigi-skus.ts]).
171 // Canvas float frames ignore matteId (fixed recessed gap).
172 const [matteId, setMatteId] = useState<MatteId>('snowwhite');
173 // Edge wrap for the frameless Stretched Canvas (Image / Mirror / White
174 // / Black). Ignored by every other product. Flows to the Prodigi order
175 // item as the `wrap` attribute (see prodigi-skus.ts).
176 const [wrap, setWrap] = useState<WrapId>('imagewrap');
177
178 // ─── Product-photo lightbox state ─────────────────────────────────
179 // When set, opens a full-screen gallery of the chosen product's
180 // photos so the customer can inspect frame depth, corner finish, and
181 // wood finishes before deciding. Closes on Esc, outside-click, or X.
182 const [lightbox, setLightbox] = useState<{ productId: ProductId; index: number } | null>(null);
183
184 // ─── Pet onboarding state ─────────────────────────────────────────
185 const [pets, setPets] = useState<Pet[]>([{ id: 0, file: null, name: '' }]);
186 const nextPetId = useRef(1);
187
188 // ─── Optional custom style reference (Style step) ─────────────────
189 // Customer can drop a painting, a photo, or any look they love — the
190 // studio attempts to recreate it instead of using a catalogued style.
191 const [customStyle, setCustomStyle] = useState<File | null>(null);
192 // Free-text note to the studio artist, captured under the custom-style
193 // upload. Persisted in the order config + surfaced in the admin editor.
194 const [artistNote, setArtistNote] = useState('');
195 // Object URL for the uploaded custom style — rendered as the pinned
196 // polaroid in the preview pane (see custompreview classes). createObjectURL
197 // must be revoked on unmount / file swap to avoid memory leaks.
198 const [customStyleUrl, setCustomStyleUrl] = useState<string | null>(null);
199 useEffect(() => {
200 if (!customStyle) {
201 setCustomStyleUrl(null);
202 return;
203 }
204 const url = URL.createObjectURL(customStyle);
205 setCustomStyleUrl(url);
206 return () => URL.revokeObjectURL(url);
207 }, [customStyle]);
208 // The "Your own style" tile in the style grid scrolls down to this
209 // section and flashes it — the upload otherwise sits below the fold.
210 const customStyleRef = useRef<HTMLDivElement | null>(null);
211 const [customStyleFlash, setCustomStyleFlash] = useState(false);
212 const jumpToCustomStyle = () => {
213 customStyleRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
214 setCustomStyleFlash(true);
215 window.setTimeout(() => setCustomStyleFlash(false), 1400);
216 };
217
218 // ─── Restore gate ─────────────────────────────────────────────────
219 // The mount effect below decides where the customer belongs: redirect
220 // to the checkout resume screen (pending order), restore an in-progress
221 // build, apply a URL-deeplinked style, or start fresh. Until it
222 // resolves we render a loader instead of the step content — otherwise
223 // the builder paints step 0 ("pick a pet") for a frame and THEN jumps
224 // or redirects, which reads as a jarring double-bounce. Starts true so
225 // SSR + first client paint both show the loader (no hydration
226 // mismatch); flipped to false at the end of every non-redirect branch.
227 const [restoring, setRestoring] = useState(true);
228 const [restorePhotoError, setRestorePhotoError] = useState('');
229 const [showSavedPhotos, setShowSavedPhotos] = useState(false);
230
231 // ─── Submit + Stripe Checkout (inlined into the Review step) ──────
232 // Previously this step navigated to /checkout (separate page) for
233 // email entry and order submission. Now the email field lives on the
234 // Review step itself and we kick off the order create + Stripe
235 // session round-trip from here. /checkout still exists as a
236 // legacy/fallback entry point.
237 const [email, setEmail] = useState('');
238 // emailTouched flips when the customer either blurs the field after
239 // typing, or attempts to submit. Until then we don't yell at them
240 // with red borders — only after they've shown intent to proceed.
241 const [emailTouched, setEmailTouched] = useState(false);
242 const emailInputRef = useRef<HTMLInputElement>(null);
243 const emailValid = /.+@.+\..+/.test(email.trim());
244 const emailInvalid = emailTouched && !emailValid;
245 const [submitting, setSubmitting] = useState(false);
246 const [submitError, setSubmitError] = useState<string | null>(null);
247
248 const submitAndPay = async (e: React.FormEvent) => {
249 e.preventDefault();
250 setEmailTouched(true);
251 if (!emailValid) {
252 setSubmitError(
253 !email.trim()
254 ? 'Please enter your email — we need it to send you the proof.'
255 : "That doesn't look like a valid email. Mind double-checking?",
256 );
257 emailInputRef.current?.focus();
258 return;
259 }
260 setSubmitting(true);
261 setSubmitError(null);
262 try {
263 const draft: Draft = {
264 config: {
265 styleId: STYLE_CATALOG[styleIdx].id,
266 productId,
267 size,
268 orientation,
269 frame,
270 matteId,
271 wrap,
272 bgColorId,
273 bgCustom,
274 fontId,
275 includeName,
276 commissionName: commissionName ?? null,
277 // Available on every order — trimmed so a stray whitespace
278 // note doesn't read as intentional.
279 artistNote: artistNote.trim(),
280 },
281 pets: pets.map((pet, i) => ({ slot: i, file: pet.file, name: pet.name })),
282 customStyle,
283 };
284 // Stash for /checkout fallback (back-button safety, bookmarked tabs).
285 setDraft(draft);
286
287 // 1. Create the order — uploads photos to CF Images, creates the
288 // user, inserts the order row.
289 const orderRes = await fetch('/api/orders', {
290 method: 'POST',
291 body: draftToFormData(draft, email),
292 });
293 if (!orderRes.ok) {
294 const data = await orderRes.json().catch(() => null) as { error?: string } | null;
295 throw new Error(data?.error ?? `Order create failed (${orderRes.status})`);
296 }
297 const { orderId } = await orderRes.json() as { orderId: string };
298
299 // Persist the orderId across the Stripe round-trip. If the
300 // customer hits browser BACK from the Stripe page (which
301 // doesn't fire Stripe's cancel_url), the browser navigates to
302 // /builder. Without this hint the builder mounts fresh at
303 // step 0 ("pick a pet") and the customer loses context. With
304 // it, the builder mount useEffect detects the pending order
305 // and redirects to /checkout?orderId=…&canceled=1 — the same
306 // resume screen they'd see if they'd clicked Stripe's Cancel
307 // button. Cleared by the success page (/login/check-email) and
308 // by the resume page's "Back to the builder" link.
309 try { sessionStorage.setItem('lg_pending_order_id', orderId); } catch {}
310
311 // 2. Mint the Stripe Checkout Session and redirect.
312 const sessionRes = await fetch(`/api/orders/${orderId}/checkout`, {
313 method: 'POST',
314 headers: { 'content-type': 'application/json' },
315 body: JSON.stringify({ email, termsAccepted: true }),
316 });
317 if (!sessionRes.ok) {
318 const data = await sessionRes.json().catch(() => null) as { error?: string } | null;
319 throw new Error(data?.error ?? `Checkout session failed (${sessionRes.status})`);
320 }
321 const { url } = await sessionRes.json() as { url: string };
322 window.location.href = url;
323 } catch (err) {
324 setSubmitError(err instanceof Error ? err.message : 'Submit failed');
325 setSubmitting(false);
326 }
327 };
328
329 // Resolve the currently-selected style from the index.
330 const styleIndex = styleIdx;
331 const style = STYLE_CATALOG[styleIndex];
332 // Lettering — and the per-pet name fields + review line that hang off
333 // it — only apply to catalog styles that support it, AND only when
334 // there's no custom reference attached. A custom commission is
335 // recreated from the uploaded image as-is; we don't overlay lettering
336 // on it, so the whole Lettering control drops out for customs. Mirrors
337 // allowsBg below.
338 const allowsName = !customStyle && !!style.allowsName;
339 // The Background step lets the customer pick the solid ground colour
340 // the portrait finishes on — only meaningful for catalog styles that
341 // render on a flat background. A custom style reference defines its
342 // OWN background (the studio recreates the look of the uploaded
343 // image, ground included), so a ground-colour picker would be
344 // misleading — we hide the Background step entirely when a reference
345 // is attached. The catalog style's hasSolidBackground governs the
346 // normal (no-upload) case.
347 const allowsBg = !customStyle && !!style.hasSolidBackground;
348
349 // Preselect a style when the visitor arrives from an example's CTA,
350 // e.g. /builder?style=popart. Jump (no animation) to it. Also seed
351 // includeName from the variant's default so picking "Charcoal — named"
352 // turns lettering on, while plain "Charcoal" leaves it off.
353 //
354 // If a draft order is already stashed (customer came back from
355 // /checkout to make changes), restore every selection from it
356 // instead — the saved draft wins over the URL-param preset, since
357 // it's what the customer was just looking at.
358 useEffect(() => {
359 // Zeroth: "Make changes" on the resume screen lands here as
360 // /builder?edit=<orderId>. The order already exists server-side with
361 // its photos on Cloudflare Images, so fetch the summary, restore every
362 // design selection, and reconstruct the pet / style File objects from
363 // their stored URLs — the customer keeps their uploads instead of
364 // being asked to re-add them. Must run BEFORE the pending-order bounce
365 // below, or we'd redirect straight back to the resume screen we came
366 // from. Async, so `restoring` stays true (loader) until it settles.
367 const entryParams = new URLSearchParams(window.location.search);
368 const savedPhoto = entryParams.get('savedPhoto');
369 if (savedPhoto) {
370 const [orderId, slot, extra] = savedPhoto.split(':');
371 (async () => {
372 try {
373 if (!orderId || !/^[0-3]$/.test(slot ?? '') || extra !== undefined) throw new Error('Invalid saved photo');
374 const file = await urlToFile(`/api/orders/photos?order=${encodeURIComponent(orderId)}&slot=${slot}`, 'saved-photo.jpg');
375 setPets([{ id: 0, file, name: '' }]);
376 nextPetId.current = 1;
377 } catch {
378 setRestorePhotoError('Could not load the saved photo. Open Saved photos to try again.');
379 } finally {
380 setStep(3);
381 setRestoring(false);
382 }
383 })();
384 return;
385 }
386 const editId = entryParams.get('edit');
387 const replacement = entryParams.has('replace');
388 if (editId) {
389 (async () => {
390 try {
391 const res = await fetch(`/api/orders/${encodeURIComponent(editId)}/summary${replacement ? '?replace=1' : ''}`);
392 if (!res.ok) throw new Error(`summary ${res.status}`);
393 const data = await res.json() as {
394 email?: string;
395 config?: Partial<DraftConfig> & { pets?: Array<{ slot: number; name: string | null }> };
396 petPhotoUrls?: string[];
397 customStyleUrl?: string | null;
398 };
399 const cfg = data.config ?? {};
400 // Prefill the email they already gave us — no re-typing to re-pay.
401 if (data.email) setEmail(data.email);
402 const idx = STYLE_CATALOG.findIndex((s) => s.id === cfg.styleId);
403 if (idx >= 0) setStyleIdx(idx);
404 if (cfg.productId) setProductId(cfg.productId);
405 if (cfg.size) setSize(cfg.size);
406 if (cfg.orientation === 'landscape' || cfg.orientation === 'portrait') setOrientation(cfg.orientation);
407 if (cfg.frame) setFrame(cfg.frame as FrameId);
408 // Normalise legacy mat ids (warmwhite/cream/hayseed → offwhite,
409 // none → snowwhite) to a current key.
410 setMatteId(normalizeMatteId(cfg.matteId as string | undefined));
411 if (cfg.wrap) setWrap(normalizeWrapId(cfg.wrap as string));
412 if (cfg.bgColorId) setBgColorId(cfg.bgColorId as BgColorId | 'custom');
413 if (cfg.bgCustom) setBgCustom(cfg.bgCustom);
414 if (cfg.fontId) setFontId(cfg.fontId as FontId);
415 if (typeof cfg.includeName === 'boolean') setIncludeName(cfg.includeName);
416 if (typeof cfg.artistNote === 'string') setArtistNote(cfg.artistNote);
417
418 // Rebuild pet photos from their CF Images URLs (names from config).
419 // A failed reconstruction leaves that slot empty, so the customer
420 // only re-adds the one that couldn't be fetched — never all of them.
421 const urls = data.petPhotoUrls ?? [];
422 const names = (cfg.pets ?? []).map((p) => p?.name ?? '');
423 if (urls.length > 0) {
424 const files = await Promise.all(
425 urls.map((u, i) => urlToFile(u, `pet-${i + 1}.jpg`).catch(() => null)),
426 );
427 const rebuilt = files.map((file, i) => ({ id: i, file, name: names[i] ?? '' }));
428 setPets(rebuilt);
429 nextPetId.current = rebuilt.length;
430 if (replacement && files.some(file => !file)) setRestorePhotoError('Some saved photos could not load. Open Saved photos to try again.');
431 }
432 if (data.customStyleUrl) {
433 const cs = await urlToFile(data.customStyleUrl, 'style-reference.jpg').catch(() => null);
434 if (cs) setCustomStyle(cs);
435 }
436 // Clear the pending-order hint so a later mount doesn't bounce
437 // back to the resume screen now that we're editing in place.
438 try { sessionStorage.removeItem('lg_pending_order_id'); } catch {}
439 setStep(replacement ? 2 : 4);
440 } catch {
441 // Order gone / network failure — fall back to a fresh builder
442 // rather than trapping the customer on the loader.
443 if (replacement) setRestorePhotoError('Could not load the cancelled order. Your saved photos are still available.');
444 } finally {
445 setRestoring(false);
446 }
447 })();
448 return;
449 }
450
451 // First: if the customer has a pending unpaid order (stashed by
452 // submitAndPay before redirecting to Stripe), route them to the
453 // resume screen instead of dumping them at step 0. This covers
454 // the browser back button from Stripe (which doesn't fire
455 // cancel_url) — the resume screen handles the case where their
456 // order already exists server-side and they just need to re-pay.
457 try {
458 const pendingId = sessionStorage.getItem('lg_pending_order_id');
459 if (pendingId) {
460 window.location.replace(`/checkout?orderId=${encodeURIComponent(pendingId)}&canceled=1`);
461 return;
462 }
463 } catch { /* sessionStorage unavailable (SSR / private mode) — fall through */ }
464
465 // A gallery "Start one like this" deeplink carries the chosen
466 // style / frame / product / size in the URL. Treat it as an explicit
467 // "build this exact piece" intent: it OVERRIDES any saved draft or
468 // in-progress build, so clicking a second gallery photo replaces the
469 // first instead of being silently ignored by the restore branches
470 // below. (matte is read only for this presence test — we still don't
471 // act on the value; see the note further down.)
472 const params = new URLSearchParams(window.location.search);
473 const hasDeeplink = ['style', 'frame', 'matte', 'product', 'size', 'orientation'].some((k) => params.has(k));
474
475 const draft = getDraft();
476 if (!hasDeeplink && draft) {
477 const idx = STYLE_CATALOG.findIndex((s) => s.id === draft.config.styleId);
478 if (idx >= 0) setStyleIdx(idx);
479 setProductId(draft.config.productId);
480 setSize(draft.config.size);
481 if (draft.config.orientation === 'landscape' || draft.config.orientation === 'portrait') {
482 setOrientation(draft.config.orientation);
483 }
484 setFrame(draft.config.frame as FrameId);
485 // Normalise legacy mat ids from earlier UI revisions:
486 // 'warmwhite' / 'cream' / 'hayseed' → 'offwhite'
487 // 'none' → 'snowwhite'
488 setMatteId(normalizeMatteId(draft.config.matteId as string));
489 setWrap(normalizeWrapId(draft.config.wrap as string));
490 setBgColorId(draft.config.bgColorId as BgColorId | 'custom');
491 setBgCustom(draft.config.bgCustom);
492 setFontId(draft.config.fontId as FontId);
493 setIncludeName(draft.config.includeName);
494 // Rehydrate pets — keep slot ids stable so React keys don't churn.
495 if (draft.pets.length > 0) {
496 setPets(draft.pets.map((p) => ({ id: p.slot, file: p.file, name: p.name })));
497 nextPetId.current = Math.max(...draft.pets.map((p) => p.slot)) + 1;
498 }
499 setCustomStyle(draft.customStyle);
500 if (typeof draft.config.artistNote === 'string') setArtistNote(draft.config.artistNote);
501 // Drop the customer back where they were heading from — the
502 // Review step — so they can fix the one thing and continue.
503 setStep(4);
504 setRestoring(false);
505 return;
506 }
507
508 // Third: restore in-progress build from sessionStorage. This is the
509 // "wandered off to the gallery and came back" path — the header's
510 // Resume-portrait indicator routes them here. We persist the design
511 // selections + step (see the persist effect below); File uploads
512 // (pet photos, custom style) can't be serialized so those are NOT
513 // restored — the customer re-adds them if they'd already uploaded.
514 if (!hasDeeplink) try {
515 const saved = sessionStorage.getItem('lg_build_progress');
516 if (saved) {
517 const b = JSON.parse(saved) as Partial<DraftConfig> & { step?: number };
518 const idx = STYLE_CATALOG.findIndex((s) => s.id === b.styleId);
519 if (idx >= 0) setStyleIdx(idx);
520 if (b.productId) setProductId(b.productId);
521 if (b.size) setSize(b.size);
522 if (b.orientation === 'landscape' || b.orientation === 'portrait') setOrientation(b.orientation);
523 if (b.frame) setFrame(b.frame as FrameId);
524 if (b.matteId) setMatteId(normalizeMatteId(b.matteId));
525 if (b.wrap) setWrap(normalizeWrapId(b.wrap));
526 if (b.bgColorId) setBgColorId(b.bgColorId as BgColorId | 'custom');
527 if (b.bgCustom) setBgCustom(b.bgCustom);
528 if (b.fontId) setFontId(b.fontId as FontId);
529 if (typeof b.includeName === 'boolean') setIncludeName(b.includeName);
530 if (typeof b.artistNote === 'string') setArtistNote(b.artistNote);
531 if (typeof b.step === 'number') setStep(b.step);
532 setRestoring(false);
533 return;
534 }
535 } catch { /* ignore corrupt/unavailable storage — fall through */ }
536
537 const styleParam = params.get('style');
538 const frameParam = params.get('frame');
539 const matteParam = params.get('matte');
540 const wrapParam = params.get('wrap');
541 const productParam = params.get('product');
542 const sizeParam = params.get('size');
543 const orientationParam = params.get('orientation');
544 // Product + size preselect from gallery "Start one like this" CTA.
545 // Apply product first so its size list is the one we validate against,
546 // then snap the frame to a finish the product actually offers.
547 if (productParam && productParam in PRODUCTS) {
548 const pid = productParam as ProductId;
549 setProductId(pid);
550 // Use the gallery-specified size if it exists for the product,
551 // otherwise fall back to the product's default.
552 const allowedSizes = PRODUCTS[pid].sizes as Record<string, unknown>;
553 setSize(sizeParam && sizeParam in allowedSizes ? sizeParam : PRODUCTS[pid].defaultSize);
554 // Snap frame if the requested one isn't on this product.
555 const allowedFrames = PRODUCTS[pid].availableFrames as readonly FrameId[];
556 if (frameParam && frameParam in FRAMES && allowedFrames.includes(frameParam as FrameId)) {
557 setFrame(frameParam as FrameId);
558 }
559 } else if (frameParam && frameParam in FRAMES) {
560 setFrame(frameParam as FrameId);
561 }
562 // Landscape deep-link (e.g. gallery "Start one like this" on a
563 // landscape mock). Snap off any square size that isn't valid landscape.
564 if (orientationParam === 'landscape') {
565 setOrientation('landscape');
566 const pid = (productParam && productParam in PRODUCTS ? productParam : productId) as ProductId;
567 const valid = sizesForOrientation(pid, 'landscape');
568 setSize((curr) => (valid.includes(curr) ? curr : PRODUCTS[pid].defaultSize));
569 }
570 // Honour a deep-linked mount colour (gallery "Start one like this"
571 // URLs carry ?matte=…). Normalised so legacy values still resolve.
572 if (matteParam) setMatteId(normalizeMatteId(matteParam));
573 if (wrapParam) setWrap(normalizeWrapId(wrapParam));
574 // Fresh build (URL deeplink or blank) — reveal the builder now.
575 setRestoring(false);
576 if (!styleParam) {
577 setIncludeName(!!STYLE_CATALOG[0].defaultIncludeName);
578 return;
579 }
580 const idx = STYLE_CATALOG.findIndex((s) => s.id === styleParam);
581 if (idx >= 0) {
582 setStyleIdx(idx);
583 setIncludeName(!!STYLE_CATALOG[idx].defaultIncludeName);
584 // The style is already chosen via the deep-link (gallery / example
585 // "Start one like this" CTA), so the Style step is a no-op for this
586 // visitor — drop them straight on the next applicable step. That's
587 // Background when the chosen style renders on a solid ground;
588 // otherwise Frame & size. (allowsBg isn't reliable here — it's a
589 // render-derived value that still reflects the pre-deeplink style —
590 // so read hasSolidBackground off the catalog entry directly.) Style
591 // stays in the rail, so they can still go back and change it.
592 setStep(STYLE_CATALOG[idx].hasSolidBackground ? STEP_BACKGROUND : STEP_BACKGROUND + 1);
593 }
594 }, []);
595
596 // ─── Step state + skip-aware navigation ───────────────────────────
597 const [step, setStep] = useState(0);
598 const isStepApplicable = (i: number) => (i === STEP_BACKGROUND ? allowsBg : true);
599 const goStepNext = () =>
600 setStep((cur) => {
601 let n = cur + 1;
602 while (n < TOTAL_STEPS && !isStepApplicable(n)) n++;
603 return n >= TOTAL_STEPS ? cur : n;
604 });
605 const goStepPrev = () =>
606 setStep((cur) => {
607 let p = cur - 1;
608 while (p >= 0 && !isStepApplicable(p)) p--;
609 return p < 0 ? cur : p;
610 });
611 const goToStep = (target: number) => {
612 if (!isStepApplicable(target)) return;
613 setStep(Math.max(0, Math.min(TOTAL_STEPS - 1, target)));
614 };
615 // Scroll the page to the top whenever the active step changes.
616 // Covers Next, Back, and rail-dot jumps in a single place. Smooth
617 // scroll unless the user has prefers-reduced-motion set, in which
618 // case we snap instantly. Skipped on the very first render so an
619 // initial /builder load doesn't fight whatever scroll position the
620 // browser restored.
621 //
622 // Desktop-only: this is the two-column layout's affordance — the
623 // sticky preview stays in view and the step panel resets to its top.
624 // On the stacked (<=1024) layout the preview sits ABOVE the step
625 // content, so scrolling to the very top would yank the customer past
626 // the preview, away from the step they just advanced to. Bail there.
627 const isFirstRender = useRef(true);
628 useEffect(() => {
629 if (isFirstRender.current) {
630 isFirstRender.current = false;
631 return;
632 }
633 if (window.matchMedia?.('(max-width: 1024px)').matches) return;
634 const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
635 window.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
636 }, [step]);
637
638 // Persist in-progress build to sessionStorage so the customer can
639 // wander off (browse the gallery, read the FAQ) and return via the
640 // header's "Resume portrait" indicator. We hold off until the mount
641 // effect has decided where the customer belongs (`restoring` false)
642 // so we don't clobber a draft mid-restore. File uploads aren't
643 // serializable, so photos + custom-style images are intentionally
644 // NOT saved; the design selections + current step are. Cleared on
645 // successful payment (see /login/check-email).
646 //
647 // We only write the snapshot when the customer has DEPARTED from the
648 // bare initial defaults (matched against the same useState() values
649 // declared above). On default state we explicitly REMOVE the key so
650 // the header's pre-paint resume indicator doesn't appear for users
651 // who landed on /builder but haven't engaged. Resetting back to
652 // defaults also clears the key — Resume only shows while there's
653 // real progress to resume.
654 useEffect(() => {
655 if (restoring) return;
656 try {
657 const isDefault =
658 styleIdx === 0 &&
659 productId === 'classic' &&
660 size === PRODUCTS.classic.defaultSize &&
661 orientation === 'portrait' &&
662 frame === 'black' &&
663 matteId === 'snowwhite' &&
664 wrap === 'imagewrap' &&
665 bgColorId === 'warmWhite' &&
666 bgCustom === '#f4ecd8' &&
667 fontId === 'editorial' &&
668 includeName === false &&
669 artistNote === '' &&
670 step === 0;
671 if (isDefault) {
672 sessionStorage.removeItem('lg_build_progress');
673 return;
674 }
675 const progress: DraftConfig & { step: number } = {
676 styleId: STYLE_CATALOG[styleIdx].id,
677 productId,
678 size,
679 orientation,
680 frame,
681 matteId,
682 wrap,
683 bgColorId,
684 bgCustom,
685 fontId,
686 includeName,
687 commissionName: null,
688 artistNote,
689 step,
690 };
691 sessionStorage.setItem('lg_build_progress', JSON.stringify(progress));
692 } catch { /* storage unavailable — non-fatal */ }
693 }, [restoring, styleIdx, productId, size, orientation, frame, matteId, wrap, bgColorId, bgCustom, fontId, includeName, artistNote, step]);
694
695 // If the active step becomes inapplicable (e.g. the customer switched
696 // from a name-bearing style to a painted one), snap forward to the
697 // next applicable step.
698 useEffect(() => {
699 if (!isStepApplicable(step)) {
700 let n = step + 1;
701 while (n < TOTAL_STEPS && !isStepApplicable(n)) n++;
702 setStep(n >= TOTAL_STEPS ? Math.max(0, step - 1) : n);
703 }
704 // eslint-disable-next-line react-hooks/exhaustive-deps
705 }, [allowsBg, allowsName]);
706
707 // The visible step list (filters out inapplicable ones) — used for
708 // the "Step X of Y" indicator so the count stays honest.
709 const activeSteps = STEPS
710 .map((s, i) => ({ ...s, i }))
711 .filter((s) => isStepApplicable(s.i));
712 const visibleIdx = activeSteps.findIndex((s) => s.i === step);
713 const isFirstStep = visibleIdx === 0;
714 const isLastStep = visibleIdx === activeSteps.length - 1;
715
716 // ─── Pricing & geometry ───────────────────────────────────────────
717 const product = PRODUCTS[productId];
718 // Size lists differ per product; the picker resets size on swap, but
719 // be defensive in case a URL/state combination ever drifts.
720 const sizes = product.sizes as Record<string, { label: string; aspect: string; price: number }>;
721 const sizeMeta = sizes[size] ?? sizes[product.defaultSize];
722 // Orientation-aware derived values. The size grid shows only sizes
723 // valid for the chosen orientation (landscape drops squares); the
724 // label + mount aspect transpose for landscape so the live preview,
725 // review summary, and caption all read landscape.
726 const orientedSizes = sizesForOrientation(productId, orientation);
727 const displaySizeLabel = sizeLabel(productId, size, orientation);
728 const mountAspect = frameAspect(productId, size, orientation) ?? sizeMeta.aspect;
729 // Sold at cost: the portrait artwork is free, so custom style
730 // references and extra pets don't change the price.
731 const hasCustomStyle = !!customStyle;
732 const saleTotal = salePrice(productId, size, matteId);
733
734 // ─── Slideshow nav (style picker) ─────────────────────────────────
735 const pickStyleByIndex = (i: number) => {
736 const wrapped = ((i % REAL) + REAL) % REAL;
737 setStyleIdx(wrapped);
738 const entry = STYLE_CATALOG[wrapped];
739 if (entry.allowsName) setIncludeName(!!entry.defaultIncludeName);
740 // Orientation is intentionally left alone here. The format
741 // (portrait/landscape) is the customer's choice in the Frame step and
742 // persists across style changes — a style names the look, not the
743 // frame shape.
744 };
745 const goPrev = () => pickStyleByIndex(styleIdx - 1);
746 const goNext = () => pickStyleByIndex(styleIdx + 1);
747
748 // ─── Pet helpers ──────────────────────────────────────────────────
749 const addPet = () =>
750 setPets((cur) =>
751 cur.length >= MAX_PETS ? cur : [...cur, { id: nextPetId.current++, file: null, name: '' }],
752 );
753 const removePet = (id: number) =>
754 setPets((cur) => (cur.length <= 1 ? cur : cur.filter((pet) => pet.id !== id)));
755 const setPetFile = (id: number, file: File) =>
756 setPets((cur) => cur.map((pet) => (pet.id === id ? { ...pet, file } : pet)));
757 const setPetName = (id: number, name: string) =>
758 setPets((cur) => cur.map((pet) => (pet.id === id ? { ...pet, name } : pet)));
759
760 const uploaded = pets.filter((pet) => pet.file).length;
761 // Review-step pay gate: a commission can't start without at least one
762 // pet photo AND a valid email (that's where the proof is sent). Both
763 // are surfaced as a checklist above the CTA and the button is disabled
764 // until they're satisfied — see the .review__gate block.
765 const needsPhoto = uploaded === 0;
766 const needsEmail = !emailValid;
767 const payBlockers = (needsPhoto ? 1 : 0) + (needsEmail ? 1 : 0);
768 const enteredNames = pets.map((pet) => pet.name.trim()).filter(Boolean);
769 const commissionName =
770 allowsName && enteredNames.length
771 ? enteredNames.join(enteredNames.length === 2 ? ' & ' : ', ')
772 : null;
773 // Raw, properly-cased name. The CSS `textTransform: uppercase` is
774 // applied per font (FONTS[fontId].uppercase) so caps-friendly faces
775 // get tracked-out caps while script / handwritten / soft sans keep
776 // the customer's intended casing.
777 const displayedName = commissionName ?? 'Teddy';
778 const bgHex = bgColorId === 'custom' ? bgCustom : BACKGROUND_COLORS[bgColorId].hex;
779
780 // Products that carry a mount (box frame, classic frame) expose an
781 // `availableMattes` list and render a real mat board; canvas has none
782 // and renders a fixed 5 mm recess gap. "No matte" drops the mat board
783 // to zero width.
784 const availableMattes = ('availableMattes' in product ? product.availableMattes : []) as readonly MatteId[];
785 const hasMount = availableMattes.length > 0;
786 // Frameless products (stretched canvas) hide the Frame picker and show
787 // an Edge-wrap picker instead.
788 const hasFrames = (product.availableFrames as readonly FrameId[]).length > 0;
789 const availableWraps = ('availableWraps' in product ? product.availableWraps : []) as readonly WrapId[];
790 const hasWraps = availableWraps.length > 0;
791 const noMat = hasMount && isNoMat(matteId);
792 const effectiveMatteW = noMat ? 0 : product.matteW;
793 // Mounted products read the chosen mat colour from MATTES; canvas
794 // renders the recess as a deep shadow tone. Fall back to snow white if
795 // an unknown legacy id slipped through.
796 const effectiveMatteBg = hasMount
797 ? (MATTES[matteId]?.hex ?? MATTES.snowwhite.hex)
798 : '#0d0a08';
799
800 const mountStyle = {
801 '--frame-w': `${product.frameW}px`,
802 '--matte-w': `${effectiveMatteW}px`,
803 '--frame-bg': FRAMES[frame].frame,
804 '--matte-bg': effectiveMatteBg,
805 '--mount-aspect': mountAspect,
806 } as CSSProperties;
807
808 // ─── Render ───────────────────────────────────────────────────────
809 // While the mount effect decides where the customer belongs, show a
810 // clean loader instead of the (about-to-change) step content. Prevents
811 // the "pick a pet" flash → bounce on resume/redirect.
812 if (restoring) {
813 return (
814 <section className="wizard" id="builder">
815 {/* Same heading as the loaded wizard, so the server-rendered HTML
816 crawlers see has the page's h1 too. */}
817 <div className="wizard__intro">
818 <div className="eyebrow">Your commission</div>
819 <h1 className="wizard__title">Your pets. Your style. One portrait.</h1>
820 </div>
821 <div className="wizard__loading" role="status" aria-live="polite">
822 <span className="wizard__loading-sigil" aria-hidden="true">✦</span>
823 <p className="wizard__loading-text">Preparing your canvas…</p>
824 </div>
825 </section>
826 );
827 }
828
829 return (
830 <>
831 <section className="wizard" id="builder">
832 <div className="wizard__intro">
833 <div className="eyebrow">Your commission</div>
834 <h1 className="wizard__title">Your pets. Your style. One portrait.</h1>
835 </div>
836
837 <div className="wizard__layout">
838 {/* ── LEFT: step-content panel ─────────────────────────── */}
839 <div className="wizard__steps">
840 {/* Compact progress stepper — one connected-node row. Replaces
841 the old "Step X of Y · Title" line + chunky pill rail, which
842 together triple-stated the current step with the heading just
843 below. EVERY node is clickable to jump straight to that step
844 (back OR forward) — same free navigation the old dot-rail had;
845 the current step is the single rose focal point, done steps
846 read filled, upcoming steps read quiet but remain live. The
847 count + current title still ship to screen readers via the
848 nav label. */}
849 <nav
850 className="wizard__progress"
851 aria-label={`Step ${visibleIdx + 1} of ${activeSteps.length}: ${STEPS[step].title}`}
852 >
853 {activeSteps.map((s, i) => {
854 const isActive = s.i === step;
855 const isDone = s.i < step;
856 return (
857 <div
858 key={s.id}
859 className={`wizard__progress-step${isActive ? ' is-active' : ''}${isDone ? ' is-done' : ''}`}
860 >
861 {i > 0 && (
862 <span
863 className={`wizard__progress-line${s.i <= step ? ' is-done' : ''}`}
864 aria-hidden="true"
865 />
866 )}
867 <button
868 type="button"
869 className="wizard__progress-node"
870 onClick={() => goToStep(s.i)}
871 aria-current={isActive ? 'step' : undefined}
872 aria-label={`Go to ${s.title}${isDone ? ' — done' : isActive ? ' — current' : ''}`}
873 >
874 <span className="wizard__progress-dot">
875 {isDone ? (
876 <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
877 <path d="M2.5 6.2 5 8.6l4.6-5.2" />
878 </svg>
879 ) : (
880 <span className="wizard__progress-num">{i + 1}</span>
881 )}
882 </span>
883 <span className="wizard__progress-label">{s.title}</span>
884 </button>
885 </div>
886 );
887 })}
888 </nav>
889
890 <h2 className="wizard__heading">{STEPS[step].heading}</h2>
891
892 {/* STEP 1 — Style picker */}
893 {step === 0 && (
894 <div className="wizard__step">
895 <p className="wizard__sub">
896 Pick the look first &mdash; the preview on the right updates live.
897 Frame, size, and lettering come next.
898 </p>
899
900 <div className="config-group config-group--first">
901 <div className="config-label">
902 <span className="config-label__text">Style</span>
903 <span className="config-hint">{hasCustomStyle ? 'Your own style' : style.name}</span>
904 </div>
905 <div className="thumbstrip">
906 {STYLE_CATALOG.map((entry, i) => (
907 <button
908 key={entry.id}
909 type="button"
910 className={`thumbstrip__thumb${!hasCustomStyle && i === styleIndex ? ' is-active' : ''}`}
911 onClick={() => pickStyleByIndex(i)}
912 disabled={hasCustomStyle}
913 aria-label={hasCustomStyle ? `${entry.name} style — remove your uploaded style to pick this` : `Pick the ${entry.name} style`}
914 aria-current={!hasCustomStyle && i === styleIndex}
915 >
916 <div
917 className={`thumbstrip__frame${entry.defaultIncludeName ? ' thumbstrip__frame--named' : ''}`}
918 /* Thumbnails stay on the neutral --cream-light ground (from CSS)
919 regardless of the customer's chosen background colour — only the
920 live preview pane reflects that pick. */
921 >
922 <Image
923 src={exampleFor(entry)}
924 alt=""
925 fill
926 /* Oversample heavily — the line-art styles have
927 very fine dense strokes that alias if the
928 served image is only ~2× the display size.
929 At 512px Next ends up serving an image that's
930 roughly 5–6× the actual rendered pixel size,
931 which keeps strokes smooth at any zoom. */
932 sizes="(max-width: 768px) 35vw, 512px"
933 quality={90}
934 style={entry.multiplyBlend ? { mixBlendMode: 'multiply' } : undefined}
935 />
936 {entry.defaultIncludeName && (
937 <span
938 className="thumbstrip__lettering"
939 style={{
940 fontFamily: FONTS.editorial.css,
941 letterSpacing: FONTS.editorial.tracking,
942 fontWeight: FONTS.editorial.weight,
943 }}
944 >
945 NAME
946 </span>
947 )}
948 </div>
949 <span className="thumbstrip__label">{entry.name}</span>
950 </button>
951 ))}
952 <button
953 type="button"
954 className={`thumbstrip__thumb thumbstrip__thumb--custom${hasCustomStyle ? ' is-active' : ''}`}
955 onClick={jumpToCustomStyle}
956 aria-label="Request your own style — upload a reference photo"
957 >
958 <div className="thumbstrip__frame thumbstrip__frame--custom">
959 <span className="thumbstrip__customglyph" aria-hidden="true">✦</span>
960 </div>
961 <span className="thumbstrip__label">{hasCustomStyle ? 'Your style ✓' : 'Your own style'}</span>
962 </button>
963 </div>
964 {hasCustomStyle ? (
965 <div className="builder__substyle builder__substyle--locked" style={{ marginTop: 10 }}>
966 You’re using your own style reference, so the catalog styles are locked. Remove your reference below to pick a catalog style instead.
967 </div>
968 ) : (
969 <>
970 <div className="builder__substyle" style={{ marginTop: 10 }}>{style.blurb}</div>
971 <div className={`builder__namenote${allowsName ? ' is-on' : ''}`}>
972 {allowsName
973 ? `${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.`
974 : 'Want your pet’s name on the portrait? Try Line Drawing, Vector Outline, Charcoal, or Modern Portrait — with name.'}
975 </div>
976 </>
977 )}
978 </div>
979
980 <div
981 ref={customStyleRef}
982 className={`config-group config-group--customstyle${customStyleFlash ? ' is-flash' : ''}`}
983 >
984 <div className="config-label">
985 <span className="config-label__text">Have a style in mind?</span>
986 <span className="config-hint">Optional · free</span>
987 </div>
988 <p className="builder__custom-intro">
989 Drop a reference photo of a style you like and we&rsquo;ll attempt to recreate it for you &mdash; a painting, a photo, anything beyond our catalogued styles. Free, like all our artwork.
990 </p>
991 <ImageDrop
992 title={customStyle ? 'Style reference attached' : 'Drop a style reference'}
993 hint={ACCEPTED_IMAGE_LABEL}
994 ratio="5 / 2"
995 value={customStyle}
996 onChange={setCustomStyle}
997 onClear={() => setCustomStyle(null)}
998 />
999 </div>
1000 </div>
1001 )}
1002
1003 {/* STEP 2 — Background (only shown when style.hasSolidBackground) */}
1004 {step === STEP_BACKGROUND && (
1005 <div className="wizard__step">
1006 <p className="wizard__sub">
1007 Pick the ground colour the portrait finishes on. The preview updates live.
1008 </p>
1009
1010 <div className="config-group config-group--first">
1011 <div className="config-label">
1012 <span className="config-label__text">Background</span>
1013 </div>
1014 <div className="config-row config-row--3">
1015 {(Object.keys(BACKGROUND_COLORS) as BgColorId[]).map((id) => (
1016 <button
1017 key={id}
1018 type="button"
1019 className={`swatch${bgColorId === id ? ' is-selected' : ''}`}
1020 onClick={() => setBgColorId(id)}
1021 >
1022 <div className="swatch__chip" style={{ background: BACKGROUND_COLORS[id].hex }} />
1023 <span className="swatch__label">{BACKGROUND_COLORS[id].label}</span>
1024 </button>
1025 ))}
1026 <label className={`swatch swatch--custom${bgColorId === 'custom' ? ' is-selected' : ''}`}>
1027 <div
1028 className="swatch__chip"
1029 style={bgColorId === 'custom' ? { background: bgCustom } : undefined}
1030 />
1031 <span className="swatch__label">Custom</span>
1032 <input
1033 type="color"
1034 value={bgCustom}
1035 onChange={(e) => { setBgCustom(e.target.value); setBgColorId('custom'); }}
1036 className="swatch__color-input"
1037 aria-label="Pick a custom background colour"
1038 />
1039 </label>
1040 </div>
1041 </div>
1042 </div>
1043 )}
1044
1045 {/* STEP 3 — Frame, size, and lettering */}
1046 {step === 2 && (
1047 <div className="wizard__step">
1048 <p className="wizard__sub">
1049 Pick a wood, a size, and {allowsName ? 'how the name should look — or turn lettering off.' : 'you’re done. The preview updates live.'}
1050 </p>
1051
1052 <div className="config-group config-group--first">
1053 <div className="config-label"><span className="config-label__text">Product</span></div>
1054 <div className="config-row config-row--2">
1055 {/* Classic first — it's the bestselling lead product,
1056 the cheapest way in, and the default selection. */}
1057 {(['classic', 'matted', 'stretched', 'canvas'] as ProductId[]).map((id) => {
1058 const p = PRODUCTS[id];
1059 const selected = id === productId;
1060 return (
1061 <div key={id} className={`prodcard${selected ? ' is-selected' : ''}`}>
1062 <button
1063 type="button"
1064 className="prodcard__select"
1065 onClick={() => pickProduct(id)}
1066 aria-pressed={selected}
1067 >
1068 <div className="prodcard__media">
1069 {/* eslint-disable-next-line @next/next/no-img-element */}
1070 <img src={p.hero} alt={`${p.label} — sample`} loading="lazy" />
1071 </div>
1072 <div className="prodcard__body">
1073 <div className="prodcard__title">{p.label}</div>
1074 <div className="prodcard__sub">{p.sub}</div>
1075 <ul className="prodcard__specs">
1076 {p.specs.map((s) => (
1077 <li key={s}>{s}</li>
1078 ))}
1079 </ul>
1080 </div>
1081 </button>
1082 <button
1083 type="button"
1084 className="prodcard__more"
1085 onClick={() => setLightbox({ productId: id, index: 0 })}
1086 aria-label={`View all ${p.photos.length} photos of ${p.label}`}
1087 >
1088 View all {p.photos.length} photos
1089 <span className="prodcard__more-arrow" aria-hidden="true">→</span>
1090 </button>
1091 </div>
1092 );
1093 })}
1094 </div>
1095 </div>
1096
1097 {hasFrames && (
1098 <div className="config-group">
1099 <div className="config-label"><span className="config-label__text">Frame</span></div>
1100 <div className="config-row config-row--4">
1101 {(product.availableFrames as readonly FrameId[]).map((id) => (
1102 <button
1103 key={id}
1104 type="button"
1105 className={`swatch${id === frame ? ' is-selected' : ''}`}
1106 onClick={() => setFrame(id)}
1107 >
1108 <div className="swatch__chip" style={{ background: FRAMES[id].swatch }} />
1109 <span className="swatch__label">{FRAMES[id].label}</span>
1110 </button>
1111 ))}
1112 </div>
1113 </div>
1114 )}
1115
1116 {hasWraps && (
1117 <div className="config-group">
1118 <div className="config-label"><span className="config-label__text">Edge wrap</span></div>
1119 <div className={`config-row config-row--${availableWraps.length}`}>
1120 {availableWraps.map((id) => (
1121 <button
1122 key={id}
1123 type="button"
1124 className={`swatch${id === wrap ? ' is-selected' : ''}`}
1125 onClick={() => setWrap(id)}
1126 >
1127 <div className="swatch__chip" style={{ background: WRAPS[id].swatch }} />
1128 <span className="swatch__label">{WRAPS[id].label}</span>
1129 </button>
1130 ))}
1131 </div>
1132 </div>
1133 )}
1134
1135 {hasMount && (
1136 <div className="config-group">
1137 <div className="config-label">
1138 <span className="config-label__text">Mount</span>
1139 </div>
1140 <div className={`config-row config-row--${availableMattes.length}`}>
1141 {availableMattes.map((id) => (
1142 <button
1143 key={id}
1144 type="button"
1145 className={`swatch${id === matteId ? ' is-selected' : ''}`}
1146 onClick={() => setMatteId(id)}
1147 >
1148 <div className="swatch__chip" style={{ background: MATTES[id].swatch }} />
1149 <span className="swatch__label">{MATTES[id].label}</span>
1150 </button>
1151 ))}
1152 </div>
1153 </div>
1154 )}
1155
1156 <div className="config-group">
1157 <div className="config-label">
1158 <span className="config-label__text">Orientation</span>
1159 <span className="config-hint">{orientation === 'landscape' ? 'Wider than tall' : 'Taller than wide'}</span>
1160 </div>
1161 <div className="config-row config-row--2">
1162 {(['portrait', 'landscape'] as Orientation[]).map((o) => (
1163 <button
1164 key={o}
1165 type="button"
1166 className={`opt opt--orient${o === orientation ? ' is-selected' : ''}`}
1167 onClick={() => pickOrientation(o)}
1168 aria-pressed={o === orientation}
1169 >
1170 <span className={`opt__orientglyph opt__orientglyph--${o}`} aria-hidden="true" />
1171 {o === 'portrait' ? 'Portrait' : 'Landscape'}
1172 </button>
1173 ))}
1174 </div>
1175 </div>
1176
1177 <div className="config-group">
1178 <div className="config-label">
1179 <span className="config-label__text">Size</span>
1180 <span className="config-hint">{product.label}</span>
1181 </div>
1182 <div className="config-row config-row--3">
1183 {orientedSizes.map((id) => (
1184 <button
1185 key={id}
1186 type="button"
1187 className={`opt opt--size${id === size ? ' is-selected' : ''}`}
1188 onClick={() => setSize(id)}
1189 >
1190 {sizeLabel(productId, id, orientation)}
1191 </button>
1192 ))}
1193 </div>
1194 </div>
1195
1196 {allowsName && (
1197 <div className="config-group">
1198 <div className="config-label">
1199 <span className="config-label__text">Lettering</span>
1200 <label className="config-toggle">
1201 <input
1202 type="checkbox"
1203 checked={includeName}
1204 onChange={(e) => setIncludeName(e.target.checked)}
1205 />
1206 Include name
1207 </label>
1208 </div>
1209 {includeName && (
1210 <div className="config-row config-row--2">
1211 {(Object.keys(FONTS) as FontId[]).map((id) => (
1212 <button
1213 key={id}
1214 type="button"
1215 className={`swatch swatch--font${fontId === id ? ' is-selected' : ''}`}
1216 onClick={() => setFontId(id)}
1217 >
1218 <div
1219 className="swatch__fontpreview"
1220 style={{
1221 fontFamily: FONTS[id].css,
1222 letterSpacing: FONTS[id].tracking,
1223 fontWeight: FONTS[id].weight,
1224 fontStyle: FONTS[id].italic ? 'italic' : 'normal',
1225 textTransform: FONTS[id].uppercase ? 'uppercase' : 'none',
1226 }}
1227 >
1228 {displayedName}
1229 </div>
1230 <span className="swatch__label">{FONTS[id].label}</span>
1231 </button>
1232 ))}
1233 </div>
1234 )}
1235 </div>
1236 )}
1237
1238 </div>
1239 )}
1240
1241 {/* Live pricing was previously a standalone sticky banner
1242 above wizard__nav. Moved inline INTO the nav (between
1243 Back and Next) so there's a single pinned bottom bar
1244 instead of two stacked ones. See the wizard__nav block
1245 below. */}
1246
1247 {/* STEP 4 — Photos & names */}
1248 {step === 3 && (
1249 <div className="wizard__step">
1250 <p className="wizard__sub">
1251 Upload up to <strong>four</strong> pets &mdash; we&rsquo;ll combine them into a single composition.
1252 </p>
1253 <p className="wizard__uploadnote">
1254 <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
1255 <rect x="3" y="3" width="18" height="18" rx="2" />
1256 <circle cx="8.5" cy="8.5" r="1.5" />
1257 <path d="m21 15-5-5L5 21" />
1258 </svg>
1259 Accepted: {ACCEPTED_IMAGE_LABEL} per photo.
1260 </p>
1261 {restorePhotoError && <p role="alert">{restorePhotoError}</p>}
1262 <button type="button" className="btn btn--secondary btn--sm" aria-expanded={showSavedPhotos}
1263 onClick={() => setShowSavedPhotos(open => !open)}>
1264 {showSavedPhotos ? 'Close saved photos' : 'Choose saved photos'}
1265 </button>
1266 {showSavedPhotos && <SavedPhotos disabled={uploaded >= 4} onAdd={(file, name) => {
1267 const id = nextPetId.current++;
1268 setPets(previous => {
1269 const empty = previous.findIndex(pet => !pet.file);
1270 if (empty >= 0) return previous.map((pet, index) => index === empty ? { ...pet, file, name: name || pet.name } : pet);
1271 return previous.length < 4 ? [...previous, { id, file, name }] : previous;
1272 });
1273 }} />}
1274
1275 <div className="petgrid">
1276 {pets.map((pet, i) => (
1277 <div className="petslot" key={pet.id}>
1278 <div className="petslot__photo">
1279 <ImageDrop
1280 crop
1281 title={`Photo ${i + 1}`}
1282 hint={ACCEPTED_IMAGE_LABEL}
1283 ratio="1"
1284 value={pet.file}
1285 onChange={(file) => setPetFile(pet.id, file)}
1286 />
1287 {pets.length > 1 && (
1288 <button
1289 type="button"
1290 className="petslot__remove"
1291 onClick={(e) => { e.stopPropagation(); removePet(pet.id); }}
1292 aria-label={`Remove photo ${i + 1}`}
1293 >
1294 <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
1295 <path d="M3 3l6 6M9 3l-6 6" />
1296 </svg>
1297 </button>
1298 )}
1299 </div>
1300 {/* Only ask for the pet's name when lettering is
1301 actually going to appear on the print. If the
1302 customer is on a name-bearing variant but turned
1303 lettering off in the Frame step, or picked a
1304 no-letter style, skip the name field entirely. */}
1305 {allowsName && includeName && (
1306 <input
1307 type="text"
1308 className="petslot__name"
1309 value={pet.name}
1310 maxLength={24}
1311 placeholder={`Pet ${i + 1}’s name`}
1312 aria-label={`Name for pet ${i + 1}`}
1313 onChange={(e) => setPetName(pet.id, e.target.value)}
1314 />
1315 )}
1316 </div>
1317 ))}
1318 {pets.length < MAX_PETS && (
1319 <button type="button" className="petslot__add" onClick={addPet}>
1320 <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
1321 <path d="M12 5v14M5 12h14" />
1322 </svg>
1323 <span>
1324 Add a pet
1325 <span className="petslot__add-fee">Free</span>
1326 </span>
1327 </button>
1328 )}
1329 </div>
1330 </div>
1331 )}
1332
1333 {/* STEP 5 — Review */}
1334 {step === 4 && (
1335 <div className="wizard__step">
1336 <p className="wizard__sub">
1337 Last look before we start your portrait — your proof arrives within one business day (Mon–Fri), free.
1338 </p>
1339
1340 <div className="review">
1341 {commissionName && (
1342 <div className="review__line">
1343 <span>Commission name</span>
1344 <span>“{commissionName}”</span>
1345 </div>
1346 )}
1347 <div className="review__line">
1348 <span>Style</span>
1349 {/* With a custom reference attached, the look comes from the
1350 upload — don't surface whatever catalog style happened to
1351 be selected underneath (it reads as misleading). */}
1352 <span>{customStyle ? 'Custom' : style.name}</span>
1353 </div>
1354 {customStyle && (
1355 <div className="review__line">
1356 <span>Style reference</span>
1357 <span>Attached · free</span>
1358 </div>
1359 )}
1360 <div className={`review__line${uploaded === 0 ? ' review__line--warn' : ''}`}>
1361 <span>Pets</span>
1362 {uploaded > 0 ? (
1363 <span>
1364 {uploaded} {uploaded === 1 ? 'pet' : 'pets'}
1365 </span>
1366 ) : (
1367 <button
1368 type="button"
1369 className="review__warn-btn"
1370 onClick={() => goToStep(STEPS.findIndex((s) => s.id === 'photos'))}
1371 >
1372 No photos yet — add one
1373 </button>
1374 )}
1375 </div>
1376 <div className="review__line">
1377 <span>Product</span>
1378 <span>{product.label}, {displaySizeLabel}</span>
1379 </div>
1380 {hasFrames && (
1381 <div className="review__line">
1382 <span>Frame</span>
1383 <span>{FRAMES[frame].label}</span>
1384 </div>
1385 )}
1386 {hasMount && (
1387 <div className="review__line">
1388 <span>Mount</span>
1389 <span>{(MATTES[matteId] ?? MATTES.snowwhite).label}</span>
1390 </div>
1391 )}
1392 {hasWraps && (
1393 <div className="review__line">
1394 <span>Edge wrap</span>
1395 <span>{WRAPS[wrap].label}</span>
1396 </div>
1397 )}
1398 {allowsBg && (
1399 <div className="review__line">
1400 <span>Background</span>
1401 <span>
1402 {bgColorId === 'custom' ? bgCustom : BACKGROUND_COLORS[bgColorId].label}
1403 </span>
1404 </div>
1405 )}
1406 {allowsName && (
1407 <div className="review__line">
1408 <span>Lettering</span>
1409 <span>{includeName ? FONTS[fontId].label : 'None'}</span>
1410 </div>
1411 )}
1412 </div>
1413
1414 {/* Note for the artist — available on every order, not just
1415 custom-style ones. Deliberately non-committal copy: we
1416 don't promise to action requests, only that we try. */}
1417 <div className="builder__artistnote" style={{ marginTop: 18 }}>
1418 <label className="config-label__text" htmlFor="builder-artist-note">
1419 Note for the artist <span className="builder__artistnote-opt">optional</span>
1420 </label>
1421 <p className="builder__artistnote-hint">
1422 Anything you&rsquo;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&rsquo;t promise we&rsquo;ll act on every request, but we read each one and accommodate what we can.
1423 </p>
1424 <textarea
1425 id="builder-artist-note"
1426 className="builder__artistnote-input"
1427 rows={3}
1428 maxLength={600}
1429 placeholder="e.g. Please make sure her one floppy ear shows, and lean a little warmer if you can."
1430 value={artistNote}
1431 onChange={(e) => setArtistNote(e.target.value)}
1432 />
1433 <span className="builder__artistnote-count">{artistNote.length}/600</span>
1434 </div>
1435
1436 <div className="guarantee" style={{ marginTop: 18 }}>
1437 <div className="guarantee__head">
1438 <span className="guarantee__check" aria-hidden="true">
1439 <svg viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
1440 <path d="M3 6.4L5.2 8.6 9 4.4" />
1441 </svg>
1442 </span>
1443 100% Artwork Satisfaction Guarantee
1444 </div>
1445 <div className="guarantee__body">
1446 Free revisions until the portrait is right. Approve only when you love it &mdash; once you approve, we print.
1447 </div>
1448 </div>
1449 </div>
1450 )}
1451
1452 {/* Sticky CTA on the Review step — same sibling-of-nav trick
1453 used by the Frame pricebar so its bounding-box is the full
1454 wizard__steps panel and sticky actually engages against the
1455 viewport bottom. */}
1456 {step === 4 && (
1457 <div className="summary__total summary__total--final summary__total--sticky">
1458 {/* Breakdown: the artwork is free and the print is at cost. */}
1459 <ul className="summary__breakdown">
1460 <li className="summary__breakdown-row">
1461 <span>Portrait artwork</span>
1462 <span>Free</span>
1463 </li>
1464 <li className="summary__breakdown-row">
1465 <span>{product.label}, {displaySizeLabel}, at cost</span>
1466 <span>${saleTotal}</span>
1467 </li>
1468 </ul>
1469 <div className="summary__totalrow">
1470 <div>
1471 <div className="summary__totallabel">
1472 Total
1473 </div>
1474 <div className="summary__price">
1475 ${saleTotal}<span className="ccy">USD</span>
1476 </div>
1477 </div>
1478 <div className="summary__ships">
1479 Ships in 10 days<br />Shipping included
1480 </div>
1481 </div>
1482 <form onSubmit={submitAndPay} className="review__pay" noValidate>
1483 <label className="review__pay-label" htmlFor="builder-email">
1484 Email <span className="review__pay-required" aria-hidden="true">*</span> where we&rsquo;ll send your proof
1485 </label>
1486 <input
1487 id="builder-email"
1488 ref={emailInputRef}
1489 type="email"
1490 required
1491 aria-required="true"
1492 aria-invalid={emailInvalid || undefined}
1493 aria-describedby={emailInvalid ? 'builder-email-err' : undefined}
1494 autoComplete="email"
1495 placeholder="you@example.com"
1496 value={email}
1497 onChange={(e) => {
1498 setEmail(e.target.value);
1499 if (submitError) setSubmitError(null);
1500 }}
1501 onBlur={() => { if (email.length > 0) setEmailTouched(true); }}
1502 className={`review__pay-input${emailInvalid ? ' review__pay-input--invalid' : ''}`}
1503 disabled={submitting}
1504 />
1505 {emailInvalid && !submitError && (
1506 <p id="builder-email-err" className="review__pay-err" role="alert">
1507 {email.trim()
1508 ? "That doesn't look like a valid email."
1509 : 'Email is required.'}
1510 </p>
1511 )}
1512 {/* Pay gate — the prominent "here's why you can't continue
1513 yet" checklist. Replaces the easy-to-miss one-liner. Each
1514 unmet requirement is a warm to-do row with a jump action;
1515 satisfied ones flip to a filled check so progress is
1516 visible. The whole block disappears once both are met. */}
1517 {payBlockers > 0 && (
1518 <div className="review__gate" role="status" aria-live="polite">
1519 <div className="review__gate-head">
1520 <svg className="review__gate-headicon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
1521 <circle cx="12" cy="12" r="9.5" />
1522 <path d="M12 7.6h.01M12 11v5.2" />
1523 </svg>
1524 {payBlockers === 2
1525 ? 'Two quick things before we can start your portrait'
1526 : 'One more thing before we can start your portrait'}
1527 </div>
1528 <ul className="review__gate-list">
1529 <li className={`review__gate-item${needsPhoto ? ' is-todo' : ' is-done'}`}>
1530 <span className="review__gate-mark" aria-hidden="true">
1531 {!needsPhoto && (
1532 <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 6.2 5 8.6l4.6-5.2" /></svg>
1533 )}
1534 </span>
1535 <span className="review__gate-label">At least one pet photo</span>
1536 {needsPhoto && (
1537 <button
1538 type="button"
1539 className="review__gate-action"
1540 onClick={() => goToStep(STEPS.findIndex((s) => s.id === 'photos'))}
1541 >
1542 Add a photo <span aria-hidden="true">→</span>
1543 </button>
1544 )}
1545 </li>
1546 <li className={`review__gate-item${needsEmail ? ' is-todo' : ' is-done'}`}>
1547 <span className="review__gate-mark" aria-hidden="true">
1548 {!needsEmail && (
1549 <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 6.2 5 8.6l4.6-5.2" /></svg>
1550 )}
1551 </span>
1552 <span className="review__gate-label">Your email — where your proof goes</span>
1553 {needsEmail && (
1554 <button
1555 type="button"
1556 className="review__gate-action"
1557 onClick={() => emailInputRef.current?.focus()}
1558 >
1559 Add it above <span aria-hidden="true">↑</span>
1560 </button>
1561 )}
1562 </li>
1563 </ul>
1564 </div>
1565 )}
1566 <button
1567 className="btn btn--rose btn--lg btn--block"
1568 type="submit"
1569 style={{ marginTop: 12 }}
1570 disabled={payBlockers > 0 || submitting}
1571 aria-disabled={payBlockers > 0 || submitting}
1572 >
1573 {submitting ? 'Redirecting to payment…' : <>Continue to payment <span aria-hidden="true">→</span></>}
1574 </button>
1575 {submitError && (
1576 <p className="review__pay-err" role="alert">{submitError}</p>
1577 )}
1578 <p className="review__pay-fine">
1579 Secure payment via Stripe. Tax (if applicable) is shown at checkout. By paying you agree to our{' '}
1580 <a href="/terms" target="_blank" rel="noopener">commission terms</a> and{' '}
1581 <a href="/refund-policy" target="_blank" rel="noopener">refund policy</a>.
1582 </p>
1583 <p className="review__pay-fine review__pay-fine--international">
1584 Shipping outside the US? Your country may collect import duty or VAT at delivery — those aren&rsquo;t included in the price above.
1585 </p>
1586 </form>
1587 </div>
1588 )}
1589
1590 {/* Sticky nav strip. The builder now opens on the Style step,
1591 so the nav shows from the very first step — but Back is
1592 omitted there (nothing to go back to). A spacer keeps Next
1593 pinned to the right via the bar's space-between layout. */}
1594 <div className="wizard__nav">
1595 {isFirstStep ? (
1596 <span className="wizard__nav-spacer" aria-hidden="true" />
1597 ) : (
1598 <button
1599 type="button"
1600 className="btn btn--secondary btn--md"
1601 onClick={goStepPrev}
1602 >
1603 <span aria-hidden="true">←</span> Back
1604 </button>
1605 )}
1606
1607 {/* Inline live-pricing block — shown on the Frame step
1608 where the customer is actively picking product/size/
1609 frame. Sits between Back and Next so the bar stays
1610 pinned (via wizard__nav) without stacking a second
1611 sticky strip above the nav. Two-line layout keeps
1612 it readable in the available middle slot. */}
1613 {step === 2 && (
1614 <div className="wizard__nav-price" aria-live="polite">
1615 <div className="wizard__nav-price-label">
1616 {product.label}, {displaySizeLabel}
1617 </div>
1618 <div className="wizard__nav-price-row">
1619 <span className="wizard__nav-price-now">${saleTotal}<span className="ccy"> USD</span></span>
1620 <span className="wizard__nav-price-ships">· Ships in 10 days, shipping included</span>
1621 </div>
1622 </div>
1623 )}
1624
1625 {!isLastStep && (
1626 <button type="button" className="btn btn--rose btn--md" onClick={goStepNext}>
1627 Next <span aria-hidden="true">→</span>
1628 </button>
1629 )}
1630 </div>
1631 </div>
1632
1633 {/* ── RIGHT: persistent preview panel ──────────────────── */}
1634 {/* Always shown — the builder opens on the Style step, which
1635 needs the live preview. (Previously hidden on the removed
1636 Pet step.) */}
1637 <aside className="wizard__preview">
1638 {customStyle ? (
1639 // ── Custom commission preview — "atelier proof board" ──
1640 // Frame interior reads as an in-studio holding state (warm
1641 // matte + pulsing sigil + italic copy explaining the proof
1642 // is being rendered). The customer's actual uploaded
1643 // reference is pinned to the frame's bottom-right corner
1644 // as a tilted polaroid with washi tape — the same visual
1645 // vocabulary the gallery uses for its "atelier proof"
1646 // before/after pairs.
1647 <div className="custompreview">
1648 <div className="slideshow__mount" style={mountStyle}>
1649 <div className={`slideshow__matte${noMat ? ' is-no-matte' : ''}`}>
1650 <div className="slideshow__viewport custompreview__viewport">
1651 <div className="custompreview__atelier">
1652 <span className="custompreview__sigil" aria-hidden="true">✦</span>
1653 <span className="custompreview__atelier-eyebrow">Atelier commission</span>
1654 <p className="custompreview__atelier-body">
1655 Your custom style is in the studio.<br />Preview lands once we render.
1656 </p>
1657 </div>
1658 </div>
1659 </div>
1660 </div>
1661 {customStyleUrl && (
1662 <div className="custompreview__pin" aria-hidden="true">
1663 <div className="custompreview__tape" />
1664 <div className="custompreview__paper">
1665 <div className="custompreview__photo">
1666 {/* eslint-disable-next-line @next/next/no-img-element */}
1667 <img src={customStyleUrl} alt="" />
1668 </div>
1669 <div className="custompreview__cap">Your style reference</div>
1670 </div>
1671 </div>
1672 )}
1673 </div>
1674 ) : (
1675 <div className="slideshow">
1676 <div className="slideshow__mount" style={mountStyle}>
1677 <div className={`slideshow__matte${noMat ? ' is-no-matte' : ''}`}>
1678 <div className="slideshow__viewport">
1679 <div className="slideshow__track">
1680 {STYLE_CATALOG.map((entry, i) => {
1681 const isActive = i === styleIndex;
1682 const showsLettering = !!entry.allowsName && includeName;
1683 return (
1684 <div
1685 className={`slideshow__slide${isActive ? ' is-active' : ''}${showsLettering ? ' slideshow__slide--with-lettering' : ''}`}
1686 key={entry.id}
1687 style={entry.hasSolidBackground ? { background: bgHex } : undefined}
1688 aria-hidden={!isActive}
1689 >
1690 <Image
1691 src={exampleFor(entry)}
1692 alt={`${entry.name} — portrait example`}
1693 fill
1694 sizes="(max-width: 1024px) 90vw, 38vw"
1695 style={entry.multiplyBlend ? { mixBlendMode: 'multiply' } : undefined}
1696 {...(isActive ? { priority: true } : { loading: 'eager' as const })}
1697 />
1698 {showsLettering && (
1699 <div
1700 className="slideshow__lettering"
1701 style={{
1702 fontFamily: FONTS[fontId].css,
1703 letterSpacing: FONTS[fontId].tracking,
1704 fontWeight: FONTS[fontId].weight,
1705 fontStyle: FONTS[fontId].italic ? 'italic' : 'normal',
1706 textTransform: FONTS[fontId].uppercase ? 'uppercase' : 'none',
1707 }}
1708 >
1709 {displayedName}
1710 </div>
1711 )}
1712 </div>
1713 );
1714 })}
1715 </div>
1716 </div>
1717 </div>
1718 </div>
1719 {step === 0 && (
1720 <>
1721 <button
1722 type="button"
1723 className="slideshow__arrow slideshow__arrow--prev"
1724 onClick={goPrev}
1725 aria-label="Previous style"
1726 >
1727 <svg width="9" height="15" viewBox="0 0 9 15" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
1728 <path d="M7.5 1.5 1.5 7.5l6 6" />
1729 </svg>
1730 </button>
1731 <button
1732 type="button"
1733 className="slideshow__arrow slideshow__arrow--next"
1734 onClick={goNext}
1735 aria-label="Next style"
1736 >
1737 <svg width="9" height="15" viewBox="0 0 9 15" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
1738 <path d="M1.5 1.5 7.5 7.5l-6 6" />
1739 </svg>
1740 </button>
1741 </>
1742 )}
1743 </div>
1744 )}
1745
1746 <div className="wizard__caption">
1747 <div className="wizard__caption-name">
1748 {customStyle && <span className="custompreview__sigil-inline" aria-hidden="true">✦ </span>}
1749 {customStyle ? 'Custom commission' : 'Preview'}
1750 </div>
1751 <div className={`wizard__caption-meta${customStyle ? ' custompreview__caption-meta' : ''}`}>
1752 {customStyle ? <em>Your vision. Our hands.</em> : <>{style.name} · {displaySizeLabel} · {FRAMES[frame].label}</>}
1753 </div>
1754 <div className="wizard__caption-note">
1755 {customStyle
1756 ? <>{displaySizeLabel} · {FRAMES[frame].label}</>
1757 : 'Sample art — your pet will replace this.'}
1758 </div>
1759 </div>
1760 </aside>
1761 </div>
1762 </section>
1763
1764 {lightbox && (
1765 <ProductLightbox
1766 photos={PRODUCTS[lightbox.productId].photos}
1767 productLabel={PRODUCTS[lightbox.productId].label}
1768 index={lightbox.index}
1769 onChange={(i) => setLightbox(lb => lb && { ...lb, index: i })}
1770 onClose={() => setLightbox(null)}
1771 />
1772 )}
1773 </>
1774 );
1775}
1776
1777// Full-screen photo gallery for a single product. Keyboard nav (Esc /
1778// ← / →), click outside the stage to dismiss, click thumbnails to jump.
1779// Locks body scroll while open so the page underneath can't drift.
1780type LightboxPhoto = { src: string; label: string };
1781function ProductLightbox({
1782 photos, productLabel, index, onChange, onClose,
1783}: {
1784 photos: readonly LightboxPhoto[];
1785 productLabel: string;
1786 index: number;
1787 onChange: (i: number) => void;
1788 onClose: () => void;
1789}) {
1790 useEffect(() => {
1791 const onKey = (e: KeyboardEvent) => {
1792 if (e.key === 'Escape') onClose();
1793 else if (e.key === 'ArrowRight') onChange(Math.min(index + 1, photos.length - 1));
1794 else if (e.key === 'ArrowLeft') onChange(Math.max(index - 1, 0));
1795 };
1796 document.addEventListener('keydown', onKey);
1797 const prevOverflow = document.body.style.overflow;
1798 document.body.style.overflow = 'hidden';
1799 return () => {
1800 document.removeEventListener('keydown', onKey);
1801 document.body.style.overflow = prevOverflow;
1802 };
1803 }, [index, photos.length, onChange, onClose]);
1804
1805 const current = photos[index];
1806 return (
1807 <div className="lightbox" role="dialog" aria-modal="true" aria-label={`${productLabel} photos`} onClick={onClose}>
1808 <button type="button" className="lightbox__close" onClick={onClose} aria-label="Close gallery">×</button>
1809 <button
1810 type="button"
1811 className="lightbox__nav lightbox__nav--prev"
1812 onClick={(e) => { e.stopPropagation(); onChange(Math.max(index - 1, 0)); }}
1813 disabled={index === 0}
1814 aria-label="Previous photo"
1815 >‹</button>
1816 <button
1817 type="button"
1818 className="lightbox__nav lightbox__nav--next"
1819 onClick={(e) => { e.stopPropagation(); onChange(Math.min(index + 1, photos.length - 1)); }}
1820 disabled={index === photos.length - 1}
1821 aria-label="Next photo"
1822 >›</button>
1823
1824 <div className="lightbox__stage" onClick={(e) => e.stopPropagation()}>
1825 {/* eslint-disable-next-line @next/next/no-img-element */}
1826 <img src={current.src} alt={`${productLabel} — ${current.label}`} />
1827 <div className="lightbox__caption">
1828 <span className="lightbox__product">{productLabel}</span>
1829 <span className="lightbox__sep" aria-hidden="true">·</span>
1830 <span className="lightbox__label">{current.label}</span>
1831 <span className="lightbox__counter">{index + 1} / {photos.length}</span>
1832 </div>
1833 </div>
1834
1835 <div className="lightbox__thumbs" onClick={(e) => e.stopPropagation()}>
1836 {photos.map((p, i) => (
1837 <button
1838 key={p.src}
1839 type="button"
1840 className={`lightbox__thumb${i === index ? ' is-current' : ''}`}
1841 onClick={() => onChange(i)}
1842 aria-label={`Show ${p.label}`}
1843 aria-current={i === index}
1844 title={p.label}
1845 >
1846 {/* eslint-disable-next-line @next/next/no-img-element */}
1847 <img src={p.src} alt="" loading="lazy" />
1848 <span className="lightbox__thumb-label">{p.label}</span>
1849 </button>
1850 ))}
1851 </div>
1852 </div>
1853 );
1854}