create-brainerce-store 1.62.0 → 1.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +71 -71
  3. package/dist/index.js +26 -3
  4. package/messages/en.json +502 -502
  5. package/messages/he.json +502 -502
  6. package/package.json +1 -1
  7. package/templates/nextjs/base/.claude/commands/design.md +60 -60
  8. package/templates/nextjs/base/.env.local.ejs +24 -24
  9. package/templates/nextjs/base/.eslintrc.json +57 -57
  10. package/templates/nextjs/base/.mcp.json +8 -8
  11. package/templates/nextjs/base/AI-GUIDE.md +174 -174
  12. package/templates/nextjs/base/TRANSLATIONS.md +200 -200
  13. package/templates/nextjs/base/package.json.ejs +52 -52
  14. package/templates/nextjs/base/src/app/agents.md/route.ts +87 -0
  15. package/templates/nextjs/base/src/app/blog/[slug]/page.tsx.ejs +308 -262
  16. package/templates/nextjs/base/src/app/blog/page.tsx.ejs +276 -276
  17. package/templates/nextjs/base/src/app/blog/rss.xml/route.ts +70 -0
  18. package/templates/nextjs/base/src/app/cart/page.tsx +7 -7
  19. package/templates/nextjs/base/src/app/category/[slug]/page.tsx +29 -3
  20. package/templates/nextjs/base/src/app/checkout/page.tsx +12 -0
  21. package/templates/nextjs/base/src/app/contact/layout.tsx.ejs +14 -0
  22. package/templates/nextjs/base/src/app/globals.css +36 -36
  23. package/templates/nextjs/base/src/app/indexnow-key.txt/route.ts +26 -26
  24. package/templates/nextjs/base/src/app/layout.tsx.ejs +30 -0
  25. package/templates/nextjs/base/src/app/llms.txt/route.ts +28 -5
  26. package/templates/nextjs/base/src/app/not-found.tsx.ejs +35 -0
  27. package/templates/nextjs/base/src/app/opengraph-image.tsx +109 -0
  28. package/templates/nextjs/base/src/app/order-confirmation/page.tsx +295 -278
  29. package/templates/nextjs/base/src/app/order-status/page.tsx +121 -121
  30. package/templates/nextjs/base/src/app/page.tsx +64 -64
  31. package/templates/nextjs/base/src/app/products/[slug]/page.tsx +14 -2
  32. package/templates/nextjs/base/src/app/products/page.tsx +19 -19
  33. package/templates/nextjs/base/src/app/robots.ts +73 -14
  34. package/templates/nextjs/base/src/app/sitemap.ts +89 -66
  35. package/templates/nextjs/base/src/components/account/order-history.tsx +385 -385
  36. package/templates/nextjs/base/src/components/brainerce-bot.tsx +70 -70
  37. package/templates/nextjs/base/src/components/checkout/checkout-form.tsx +612 -612
  38. package/templates/nextjs/base/src/components/checkout/custom-fields-step.tsx +292 -292
  39. package/templates/nextjs/base/src/components/checkout/date-picker.tsx +309 -309
  40. package/templates/nextjs/base/src/components/checkout/datetime-picker.tsx +144 -144
  41. package/templates/nextjs/base/src/components/checkout/order-bump-card.tsx +242 -242
  42. package/templates/nextjs/base/src/components/checkout/pickup-step.tsx +198 -198
  43. package/templates/nextjs/base/src/components/checkout/shipping-step.tsx +125 -125
  44. package/templates/nextjs/base/src/components/checkout/tax-display.tsx +74 -74
  45. package/templates/nextjs/base/src/components/seo/article-json-ld.tsx +59 -59
  46. package/templates/nextjs/base/src/components/seo/breadcrumbs.tsx +37 -37
  47. package/templates/nextjs/base/src/components/seo/category-json-ld.tsx +61 -61
  48. package/templates/nextjs/base/src/components/seo/organization-json-ld.tsx +97 -97
  49. package/templates/nextjs/base/src/components/seo/product-json-ld.tsx +23 -131
  50. package/templates/nextjs/base/src/components/tracking-bootstrap.tsx +62 -0
  51. package/templates/nextjs/base/src/components/ui/accordion.tsx +53 -53
  52. package/templates/nextjs/base/src/components/ui/badge.tsx +32 -32
  53. package/templates/nextjs/base/src/components/ui/button.tsx +49 -49
  54. package/templates/nextjs/base/src/components/ui/card.tsx +55 -55
  55. package/templates/nextjs/base/src/components/ui/checkbox.tsx +28 -28
  56. package/templates/nextjs/base/src/components/ui/dialog.tsx +107 -107
  57. package/templates/nextjs/base/src/components/ui/input.tsx +22 -22
  58. package/templates/nextjs/base/src/components/ui/label.tsx +21 -21
  59. package/templates/nextjs/base/src/components/ui/radio-group.tsx +38 -38
  60. package/templates/nextjs/base/src/components/ui/select.tsx +153 -153
  61. package/templates/nextjs/base/src/components/ui/separator.tsx +26 -26
  62. package/templates/nextjs/base/src/components/ui/sheet.tsx +125 -125
  63. package/templates/nextjs/base/src/components/ui/skeleton.tsx +7 -7
  64. package/templates/nextjs/base/src/components/ui/tabs.tsx +55 -55
  65. package/templates/nextjs/base/src/components/ui/textarea.tsx +21 -21
  66. package/templates/nextjs/base/src/components/ui/tooltip.tsx +32 -32
  67. package/templates/nextjs/base/src/core/hooks/use-cart-page.ts +58 -58
  68. package/templates/nextjs/base/src/core/hooks/use-home-data.ts +51 -51
  69. package/templates/nextjs/base/src/core/hooks/use-product-listing.ts +295 -295
  70. package/templates/nextjs/base/src/core/hooks/use-product-page.ts +20 -2
  71. package/templates/nextjs/base/src/core/lib/image-hosts.ts +7 -7
  72. package/templates/nextjs/base/src/core/lib/product-options.ts +121 -121
  73. package/templates/nextjs/base/src/core/lib/resolve-currency.ts +20 -20
  74. package/templates/nextjs/base/src/core/lib/safe-redirect.ts +38 -38
  75. package/templates/nextjs/base/src/core/lib/seo.ts +46 -46
  76. package/templates/nextjs/base/src/core/lib/store-info.ts +17 -0
  77. package/templates/nextjs/base/src/core/lib/tracking.ts +171 -0
  78. package/templates/nextjs/base/src/core/lib/use-currency.ts +19 -19
  79. package/templates/nextjs/base/src/core/lib/utils.ts +21 -21
  80. package/templates/nextjs/base/src/middleware.ts.ejs +54 -2
  81. package/templates/nextjs/base/src/ui/cart/cart-bundle-offer.tsx +117 -117
  82. package/templates/nextjs/base/src/ui/cart/cart-item.tsx +146 -146
  83. package/templates/nextjs/base/src/ui/cart/cart-nudges.tsx +28 -28
  84. package/templates/nextjs/base/src/ui/cart/cart-summary.tsx +110 -110
  85. package/templates/nextjs/base/src/ui/cart/cart-upgrade-banner.tsx +126 -126
  86. package/templates/nextjs/base/src/ui/cart/cart-view.tsx +140 -140
  87. package/templates/nextjs/base/src/ui/cart/coupon-input.tsx +134 -134
  88. package/templates/nextjs/base/src/ui/cart/free-shipping-bar.tsx +61 -61
  89. package/templates/nextjs/base/src/ui/cart/reservation-countdown.tsx +95 -95
  90. package/templates/nextjs/base/src/ui/home/discount-banner-strip.tsx +22 -20
  91. package/templates/nextjs/base/src/ui/home/featured-products-section.tsx +24 -24
  92. package/templates/nextjs/base/src/ui/home/hero-section.tsx +27 -27
  93. package/templates/nextjs/base/src/ui/home/home-client.tsx +29 -29
  94. package/templates/nextjs/base/src/ui/layout/announcement-bar.tsx.ejs +116 -116
  95. package/templates/nextjs/base/src/ui/layout/faq-section.tsx.ejs +90 -90
  96. package/templates/nextjs/base/src/ui/layout/header-account.tsx +40 -40
  97. package/templates/nextjs/base/src/ui/layout/language-switcher.tsx.ejs +80 -80
  98. package/templates/nextjs/base/src/ui/layout/site-footer.tsx.ejs +144 -144
  99. package/templates/nextjs/base/src/ui/layout/site-header.tsx.ejs +152 -152
  100. package/templates/nextjs/base/src/ui/product/customization-fields.tsx +457 -457
  101. package/templates/nextjs/base/src/ui/product/discount-badge.tsx +18 -18
  102. package/templates/nextjs/base/src/ui/product/frequently-bought-together.tsx +191 -191
  103. package/templates/nextjs/base/src/ui/product/modifier-group-selector.tsx +206 -206
  104. package/templates/nextjs/base/src/ui/product/price-display.tsx +62 -62
  105. package/templates/nextjs/base/src/ui/product/product-card.tsx +7 -2
  106. package/templates/nextjs/base/src/ui/product/product-client-section.tsx +455 -455
  107. package/templates/nextjs/base/src/ui/product/product-listing.tsx +446 -446
  108. package/templates/nextjs/base/src/ui/product/recommendation-section.tsx +102 -102
  109. package/templates/nextjs/base/src/ui/product/review-form.tsx +294 -294
  110. package/templates/nextjs/base/src/ui/product/reviews-section.tsx.ejs +108 -108
  111. package/templates/nextjs/base/src/ui/product/stock-badge.tsx +61 -61
  112. package/templates/nextjs/base/src/ui/product/variant-selector.tsx +291 -291
  113. package/templates/nextjs/base/src/ui/shared/cdn-image.tsx +26 -26
  114. package/templates/nextjs/base/tailwind.config.ts +69 -69
  115. package/templates/nextjs/designs/atelier/app-overlay/layout.tsx.ejs +30 -0
  116. package/templates/nextjs/designs/atelier/globals.css +402 -402
  117. package/templates/nextjs/designs/atelier/messages-patch/en.json +100 -100
  118. package/templates/nextjs/designs/atelier/messages-patch/he.json +100 -100
  119. package/templates/nextjs/designs/atelier/ui/cart/cart-bundle-offer.tsx +110 -110
  120. package/templates/nextjs/designs/atelier/ui/cart/cart-drawer.tsx +163 -163
  121. package/templates/nextjs/designs/atelier/ui/cart/cart-item.tsx +140 -140
  122. package/templates/nextjs/designs/atelier/ui/cart/cart-nudges.tsx +34 -34
  123. package/templates/nextjs/designs/atelier/ui/cart/cart-summary.tsx +107 -107
  124. package/templates/nextjs/designs/atelier/ui/cart/cart-upgrade-banner.tsx +123 -123
  125. package/templates/nextjs/designs/atelier/ui/cart/cart-view.tsx +147 -147
  126. package/templates/nextjs/designs/atelier/ui/cart/coupon-input.tsx +142 -142
  127. package/templates/nextjs/designs/atelier/ui/cart/free-shipping-bar.tsx +77 -77
  128. package/templates/nextjs/designs/atelier/ui/cart/reservation-countdown.tsx +89 -89
  129. package/templates/nextjs/designs/atelier/ui/home/benefits-band.tsx +34 -34
  130. package/templates/nextjs/designs/atelier/ui/home/category-tiles.tsx +151 -151
  131. package/templates/nextjs/designs/atelier/ui/home/discount-banner-strip.tsx +27 -27
  132. package/templates/nextjs/designs/atelier/ui/home/editorial-band.tsx +75 -75
  133. package/templates/nextjs/designs/atelier/ui/home/featured-products-section.tsx +36 -36
  134. package/templates/nextjs/designs/atelier/ui/home/hero-section.tsx +174 -174
  135. package/templates/nextjs/designs/atelier/ui/home/home-client.tsx +54 -54
  136. package/templates/nextjs/designs/atelier/ui/home/newsletter-section.tsx +78 -78
  137. package/templates/nextjs/designs/atelier/ui/home/testimonials-band.tsx +46 -46
  138. package/templates/nextjs/designs/atelier/ui/layout/announcement-bar.tsx +118 -118
  139. package/templates/nextjs/designs/atelier/ui/layout/faq-section.tsx +96 -96
  140. package/templates/nextjs/designs/atelier/ui/layout/header-account.tsx +36 -36
  141. package/templates/nextjs/designs/atelier/ui/layout/header-cart.tsx +36 -36
  142. package/templates/nextjs/designs/atelier/ui/layout/language-switcher.tsx.ejs +137 -137
  143. package/templates/nextjs/designs/atelier/ui/layout/nav-url.ts +14 -14
  144. package/templates/nextjs/designs/atelier/ui/layout/rich-text-block.tsx +34 -34
  145. package/templates/nextjs/designs/atelier/ui/layout/site-footer.tsx.ejs +141 -141
  146. package/templates/nextjs/designs/atelier/ui/layout/site-header.tsx.ejs +138 -138
  147. package/templates/nextjs/designs/atelier/ui/product/customization-fields.tsx +466 -466
  148. package/templates/nextjs/designs/atelier/ui/product/discount-badge.tsx +17 -17
  149. package/templates/nextjs/designs/atelier/ui/product/frequently-bought-together.tsx +196 -196
  150. package/templates/nextjs/designs/atelier/ui/product/modifier-group-selector.tsx +193 -193
  151. package/templates/nextjs/designs/atelier/ui/product/price-display.tsx +69 -69
  152. package/templates/nextjs/designs/atelier/ui/product/product-card.tsx +13 -11
  153. package/templates/nextjs/designs/atelier/ui/product/product-client-section.tsx +477 -477
  154. package/templates/nextjs/designs/atelier/ui/product/product-grid.tsx +42 -42
  155. package/templates/nextjs/designs/atelier/ui/product/product-listing.tsx +260 -260
  156. package/templates/nextjs/designs/atelier/ui/product/recommendation-section.tsx +95 -95
  157. package/templates/nextjs/designs/atelier/ui/product/review-form.tsx +267 -267
  158. package/templates/nextjs/designs/atelier/ui/product/reviews-section.tsx.ejs +148 -148
  159. package/templates/nextjs/designs/atelier/ui/product/stock-badge.tsx +66 -66
  160. package/templates/nextjs/designs/atelier/ui/product/variant-selector.tsx +206 -206
  161. package/templates/nextjs/designs/atelier/ui/shared/cdn-image.tsx +29 -29
  162. package/templates/nextjs/designs/atelier/ui/shared/fly-to-cart.ts +86 -86
  163. package/templates/nextjs/designs/atelier/ui/shared/icons.tsx +276 -276
  164. package/templates/nextjs/designs/atelier/ui/shared/loading-spinner.tsx +63 -63
  165. package/templates/nextjs/designs/atelier/ui/shared/reveal.tsx +71 -71
  166. package/templates/nextjs/designs/atelier/ui/shared/select-menu.tsx +125 -125
  167. package/templates/nextjs/ui-canvas/cart/cart-bundle-offer.tsx +89 -89
  168. package/templates/nextjs/ui-canvas/cart/cart-item.tsx +123 -123
  169. package/templates/nextjs/ui-canvas/cart/cart-nudges.tsx +29 -27
  170. package/templates/nextjs/ui-canvas/cart/cart-summary.tsx +99 -99
  171. package/templates/nextjs/ui-canvas/cart/cart-upgrade-banner.tsx +105 -105
  172. package/templates/nextjs/ui-canvas/cart/cart-view.tsx +106 -106
  173. package/templates/nextjs/ui-canvas/cart/coupon-input.tsx +119 -119
  174. package/templates/nextjs/ui-canvas/cart/free-shipping-bar.tsx +54 -54
  175. package/templates/nextjs/ui-canvas/cart/reservation-countdown.tsx +81 -81
  176. package/templates/nextjs/ui-canvas/home/discount-banner-strip.tsx +21 -19
  177. package/templates/nextjs/ui-canvas/home/featured-products-section.tsx +23 -23
  178. package/templates/nextjs/ui-canvas/home/hero-section.tsx +21 -21
  179. package/templates/nextjs/ui-canvas/home/home-client.tsx +26 -26
  180. package/templates/nextjs/ui-canvas/layout/announcement-bar.tsx.ejs +101 -101
  181. package/templates/nextjs/ui-canvas/layout/faq-section.tsx.ejs +71 -71
  182. package/templates/nextjs/ui-canvas/layout/header-account.tsx +31 -31
  183. package/templates/nextjs/ui-canvas/layout/language-switcher.tsx.ejs +76 -76
  184. package/templates/nextjs/ui-canvas/layout/rich-text-block.tsx.ejs +36 -36
  185. package/templates/nextjs/ui-canvas/layout/site-footer.tsx.ejs +82 -82
  186. package/templates/nextjs/ui-canvas/layout/site-header.tsx.ejs +119 -119
  187. package/templates/nextjs/ui-canvas/product/customization-fields.tsx +445 -445
  188. package/templates/nextjs/ui-canvas/product/discount-badge.tsx +19 -19
  189. package/templates/nextjs/ui-canvas/product/frequently-bought-together.tsx +168 -168
  190. package/templates/nextjs/ui-canvas/product/modifier-group-selector.tsx +165 -165
  191. package/templates/nextjs/ui-canvas/product/price-display.tsx +52 -52
  192. package/templates/nextjs/ui-canvas/product/product-card.tsx +7 -2
  193. package/templates/nextjs/ui-canvas/product/product-client-section.tsx +352 -352
  194. package/templates/nextjs/ui-canvas/product/product-grid.tsx +27 -27
  195. package/templates/nextjs/ui-canvas/product/product-listing.tsx +224 -224
  196. package/templates/nextjs/ui-canvas/product/recommendation-section.tsx +99 -99
  197. package/templates/nextjs/ui-canvas/product/review-form.tsx +266 -266
  198. package/templates/nextjs/ui-canvas/product/reviews-section.tsx.ejs +96 -96
  199. package/templates/nextjs/ui-canvas/product/stock-badge.tsx +45 -45
  200. package/templates/nextjs/ui-canvas/product/variant-selector.tsx +212 -212
  201. package/templates/nextjs/ui-canvas/shared/cdn-image.tsx +31 -31
  202. package/templates/nextjs/ui-canvas/shared/loading-spinner.tsx +27 -27
  203. package/templates/nextjs/base/tsconfig.tsbuildinfo +0 -1
@@ -1,612 +1,612 @@
1
- 'use client';
2
-
3
- import { useState, useEffect, useRef } from 'react';
4
- import type { SetShippingAddressDto, ShippingDestinations, AddressSuggestion } from 'brainerce';
5
- import { useTranslations } from '@/core/lib/translations';
6
- import { cn } from '@/core/lib/utils';
7
- import { isValidEmail } from '@/core/lib/validation';
8
- import { getClient } from '@/core/lib/brainerce';
9
-
10
- // Debounce address-suggestion calls rather than firing on every keystroke —
11
- // both to avoid a jumpy dropdown and to keep autocomplete-session call volume
12
- // reasonable (see `getAddressSuggestions` doc in the SDK).
13
- const ADDRESS_SEARCH_DEBOUNCE_MS = 300;
14
- const ADDRESS_SEARCH_MIN_CHARS = 3;
15
-
16
- // Editing any of these invalidates a previously picked suggestion: its
17
- // coordinates describe the address the shopper selected, not what is in the
18
- // inputs now. See `pickedPlace` below.
19
- const PLACE_INVALIDATING_FIELDS = new Set<string>([
20
- 'line1',
21
- 'line2',
22
- 'city',
23
- 'region',
24
- 'postalCode',
25
- 'country',
26
- ]);
27
-
28
- interface CheckoutConsent {
29
- acceptsMarketing: boolean;
30
- saveDetails: boolean;
31
- }
32
-
33
- interface CheckoutFormProps {
34
- onSubmit: (address: SetShippingAddressDto, consent: CheckoutConsent) => void;
35
- loading?: boolean;
36
- initialValues?: Partial<SetShippingAddressDto>;
37
- destinations?: ShippingDestinations | null;
38
- className?: string;
39
- showSaveDetails?: boolean;
40
- emailOnly?: boolean;
41
- }
42
-
43
- export function CheckoutForm({
44
- onSubmit,
45
- loading = false,
46
- initialValues,
47
- destinations,
48
- className,
49
- showSaveDetails = false,
50
- emailOnly = false,
51
- }: CheckoutFormProps) {
52
- const [formData, setFormData] = useState<SetShippingAddressDto>({
53
- email: initialValues?.email || '',
54
- firstName: initialValues?.firstName || '',
55
- lastName: initialValues?.lastName || '',
56
- line1: initialValues?.line1 || '',
57
- line2: initialValues?.line2 || '',
58
- city: initialValues?.city || '',
59
- region: initialValues?.region || '',
60
- postalCode: initialValues?.postalCode || '',
61
- country: initialValues?.country || '',
62
- phone: initialValues?.phone || '',
63
- notes: initialValues?.notes || '',
64
- });
65
- const [errors, setErrors] = useState<Record<string, string>>({});
66
- const [privacyAccepted, setPrivacyAccepted] = useState(false);
67
- const [acceptsMarketing, setAcceptsMarketing] = useState(false);
68
- const [saveDetails, setSaveDetails] = useState(true);
69
- const t = useTranslations('checkoutForm');
70
- const tc = useTranslations('common');
71
- const hasAppliedPrefill = useRef(!!initialValues);
72
-
73
- // Address-autocomplete state — groups one address-entry attempt for
74
- // session-token billing (see `getAddressSuggestions` in the SDK). A fresh
75
- // token is minted whenever a suggestion is picked, ending that session.
76
- const [addressSuggestions, setAddressSuggestions] = useState<AddressSuggestion[]>([]);
77
- const [showAddressSuggestions, setShowAddressSuggestions] = useState(false);
78
- const [isSearchingAddress, setIsSearchingAddress] = useState(false);
79
- const [outsideDeliveryZone, setOutsideDeliveryZone] = useState(false);
80
- // The suggestion the shopper actually picked, kept so it can ride along to
81
- // `setShippingAddress`. That is what lets the server match map-drawn
82
- // ("polygon") delivery zones against this address's exact coordinates
83
- // instead of geocoding the typed text — skipping it is the most common
84
- // cause of "the store says it doesn't deliver here, but it does". Null
85
- // whenever the address was typed by hand or edited after picking.
86
- const [pickedPlace, setPickedPlace] = useState<{
87
- placeId: string;
88
- sessionToken: string;
89
- } | null>(null);
90
- const addressSessionToken = useRef(
91
- typeof crypto !== 'undefined' ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`
92
- );
93
- const addressSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
94
-
95
- useEffect(() => {
96
- return () => {
97
- if (addressSearchTimer.current) clearTimeout(addressSearchTimer.current);
98
- };
99
- }, []);
100
-
101
- function handleLine1Change(value: string) {
102
- updateField('line1', value);
103
- setOutsideDeliveryZone(false);
104
-
105
- if (addressSearchTimer.current) clearTimeout(addressSearchTimer.current);
106
-
107
- const query = value.trim();
108
- if (query.length < ADDRESS_SEARCH_MIN_CHARS) {
109
- setAddressSuggestions([]);
110
- setShowAddressSuggestions(false);
111
- return;
112
- }
113
-
114
- addressSearchTimer.current = setTimeout(async () => {
115
- setIsSearchingAddress(true);
116
- try {
117
- const results = await getClient().getAddressSuggestions(query, addressSessionToken.current);
118
- setAddressSuggestions(results);
119
- setShowAddressSuggestions(results.length > 0);
120
- } catch {
121
- // Autocomplete is a soft enhancement — a failed lookup just means no
122
- // suggestions this keystroke; the shopper can keep typing manually.
123
- setAddressSuggestions([]);
124
- setShowAddressSuggestions(false);
125
- } finally {
126
- setIsSearchingAddress(false);
127
- }
128
- }, ADDRESS_SEARCH_DEBOUNCE_MS);
129
- }
130
-
131
- async function handleSelectAddressSuggestion(suggestion: AddressSuggestion) {
132
- setShowAddressSuggestions(false);
133
- // The token this resolution is billed under — hand the SAME one to
134
- // `setShippingAddress` so a server-side cache miss re-resolves within this
135
- // autocomplete session instead of opening a new (billed) one.
136
- const resolvingSessionToken = addressSessionToken.current;
137
- try {
138
- const { address, inZone } = await getClient().getAddressDetails(
139
- suggestion.placeId,
140
- resolvingSessionToken
141
- );
142
- setFormData((prev) => {
143
- const country = address.country || prev.country;
144
- // Only accept address.region if it's one of THIS store's known
145
- // region codes for the resolved country (destinations.regions —
146
- // the same list the dropdown below renders, backed by our own
147
- // geo-data, not Google's). Google's region code usually lines up
148
- // (both ultimately trace back to ISO 3166-2), but never assign a
149
- // value the dropdown wouldn't recognize — better an unselected
150
- // dropdown the shopper fills in than a silently-wrong one.
151
- const validRegions = destinations?.regions[country] ?? [];
152
- const resolvedRegionValid = validRegions.some((r) => r.code === address.region);
153
- return {
154
- ...prev,
155
- line1: address.line1 || prev.line1,
156
- city: address.city || prev.city,
157
- region: resolvedRegionValid
158
- ? address.region
159
- : country !== prev.country
160
- ? ''
161
- : prev.region,
162
- postalCode: address.postalCode || prev.postalCode,
163
- country,
164
- };
165
- });
166
- setOutsideDeliveryZone(!inZone);
167
- // Note we deliberately do NOT copy address.lat/lng into the form: no
168
- // address endpoint accepts coordinates (zone matching decides which rate
169
- // is charged, so the server resolves them from the placeId itself).
170
- // They're yours to use for a map pin and nothing else.
171
- setPickedPlace({ placeId: suggestion.placeId, sessionToken: resolvingSessionToken });
172
- } catch {
173
- // Resolution failed — keep whatever the shopper had typed/selected as
174
- // the visible text; they can still fill in the rest manually.
175
- setPickedPlace(null);
176
- } finally {
177
- // New session for the next address-entry attempt.
178
- addressSessionToken.current =
179
- typeof crypto !== 'undefined' ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`;
180
- setAddressSuggestions([]);
181
- }
182
- }
183
-
184
- // Sync prefill data when it arrives async (e.g. from getCheckoutPrefillData)
185
- useEffect(() => {
186
- if (!initialValues || hasAppliedPrefill.current) return;
187
- hasAppliedPrefill.current = true;
188
- setFormData((prev) => ({
189
- email: initialValues.email || prev.email,
190
- firstName: initialValues.firstName || prev.firstName,
191
- lastName: initialValues.lastName || prev.lastName,
192
- line1: initialValues.line1 || prev.line1,
193
- line2: initialValues.line2 || prev.line2 || '',
194
- city: initialValues.city || prev.city,
195
- region: initialValues.region || prev.region || '',
196
- postalCode: initialValues.postalCode || prev.postalCode,
197
- country: initialValues.country || prev.country,
198
- phone: initialValues.phone || prev.phone || '',
199
- notes: prev.notes || '',
200
- }));
201
- }, [initialValues]);
202
-
203
- const hasCountryOptions = destinations && destinations.countries.length > 0;
204
- const countryRegions = destinations?.regions[formData.country];
205
- const hasRegionOptions = countryRegions && countryRegions.length > 0;
206
-
207
- function validate(): boolean {
208
- const newErrors: Record<string, string> = {};
209
-
210
- if (!formData.email.trim()) {
211
- newErrors.email = t('emailRequired');
212
- } else if (!isValidEmail(formData.email.trim())) {
213
- newErrors.email = t('emailInvalid');
214
- }
215
-
216
- if (!formData.firstName.trim()) {
217
- newErrors.firstName = t('firstNameRequired');
218
- }
219
- if (!formData.lastName.trim()) {
220
- newErrors.lastName = t('lastNameRequired');
221
- }
222
- if (!emailOnly) {
223
- if (!formData.line1.trim()) {
224
- newErrors.line1 = t('addressRequired');
225
- }
226
- if (!formData.city.trim()) {
227
- newErrors.city = t('cityRequired');
228
- }
229
- if (!formData.postalCode.trim()) {
230
- newErrors.postalCode = t('postalCodeRequired');
231
- }
232
- if (!formData.country.trim()) {
233
- newErrors.country = t('countryRequired');
234
- }
235
- }
236
- if (!privacyAccepted) {
237
- newErrors.privacy = t('privacyRequired');
238
- }
239
-
240
- setErrors(newErrors);
241
- return Object.keys(newErrors).length === 0;
242
- }
243
-
244
- function handleSubmit(e: React.FormEvent) {
245
- e.preventDefault();
246
- if (validate()) {
247
- onSubmit(
248
- {
249
- ...formData,
250
- // Both undefined when the shopper typed the address by hand or
251
- // edited it after picking a suggestion — the server then geocodes
252
- // the text, which is the right behaviour once the two disagree.
253
- placeId: pickedPlace?.placeId,
254
- placeSessionToken: pickedPlace?.sessionToken,
255
- },
256
- { acceptsMarketing, saveDetails: showSaveDetails && saveDetails }
257
- );
258
- }
259
- }
260
-
261
- function updateField(field: keyof SetShippingAddressDto, value: string) {
262
- setFormData((prev) => {
263
- const next = { ...prev, [field]: value };
264
- // Reset region when country changes
265
- if (field === 'country' && value !== prev.country) {
266
- next.region = '';
267
- }
268
- return next;
269
- });
270
- // Once any address field is edited, the picked suggestion no longer
271
- // describes what is in the form — keeping its placeId would match delivery
272
- // zones against the address the shopper originally selected.
273
- if (PLACE_INVALIDATING_FIELDS.has(field)) {
274
- setPickedPlace(null);
275
- }
276
- if (errors[field]) {
277
- setErrors((prev) => {
278
- const next = { ...prev };
279
- delete next[field];
280
- return next;
281
- });
282
- }
283
- }
284
-
285
- const inputClass =
286
- 'bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary/20 focus:border-primary h-10 w-full rounded border px-3 text-sm focus:outline-none focus:ring-2';
287
- const selectClass =
288
- 'bg-background text-foreground focus:ring-primary/20 focus:border-primary h-10 w-full appearance-none rounded border px-3 text-sm focus:outline-none focus:ring-2';
289
-
290
- return (
291
- <form onSubmit={handleSubmit} className={cn('space-y-4', className)}>
292
- {/* Email */}
293
- <div>
294
- <label htmlFor="email" className="text-foreground mb-1 block text-sm font-medium">
295
- {t('email')} <span className="text-destructive">*</span>
296
- </label>
297
- <input
298
- id="email"
299
- type="email"
300
- value={formData.email}
301
- onChange={(e) => updateField('email', e.target.value)}
302
- className={cn(inputClass, errors.email ? 'border-destructive' : 'border-border')}
303
- placeholder="your@email.com"
304
- />
305
- {errors.email && <p className="text-destructive mt-1 text-xs">{errors.email}</p>}
306
- </div>
307
-
308
- {/* Name row */}
309
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
310
- <div>
311
- <label htmlFor="firstName" className="text-foreground mb-1 block text-sm font-medium">
312
- {t('firstName')} <span className="text-destructive">*</span>
313
- </label>
314
- <input
315
- id="firstName"
316
- type="text"
317
- value={formData.firstName}
318
- onChange={(e) => updateField('firstName', e.target.value)}
319
- className={cn(inputClass, errors.firstName ? 'border-destructive' : 'border-border')}
320
- />
321
- {errors.firstName && <p className="text-destructive mt-1 text-xs">{errors.firstName}</p>}
322
- </div>
323
-
324
- <div>
325
- <label htmlFor="lastName" className="text-foreground mb-1 block text-sm font-medium">
326
- {t('lastName')} <span className="text-destructive">*</span>
327
- </label>
328
- <input
329
- id="lastName"
330
- type="text"
331
- value={formData.lastName}
332
- onChange={(e) => updateField('lastName', e.target.value)}
333
- className={cn(inputClass, errors.lastName ? 'border-destructive' : 'border-border')}
334
- />
335
- {errors.lastName && <p className="text-destructive mt-1 text-xs">{errors.lastName}</p>}
336
- </div>
337
- </div>
338
-
339
- {!emailOnly && (
340
- <>
341
- {/* Country + Region row */}
342
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
343
- <div>
344
- <label htmlFor="country" className="text-foreground mb-1 block text-sm font-medium">
345
- {t('country')} <span className="text-destructive">*</span>
346
- </label>
347
- {hasCountryOptions ? (
348
- <select
349
- id="country"
350
- value={formData.country}
351
- onChange={(e) => updateField('country', e.target.value)}
352
- className={cn(
353
- selectClass,
354
- errors.country ? 'border-destructive' : 'border-border'
355
- )}
356
- >
357
- <option value="">{t('selectCountry')}</option>
358
- {destinations.countries.map((c) => (
359
- <option key={c.code} value={c.code}>
360
- {c.name}
361
- </option>
362
- ))}
363
- </select>
364
- ) : (
365
- <input
366
- id="country"
367
- type="text"
368
- value={formData.country}
369
- onChange={(e) => updateField('country', e.target.value)}
370
- className={cn(
371
- inputClass,
372
- errors.country ? 'border-destructive' : 'border-border'
373
- )}
374
- placeholder={t('countryPlaceholder')}
375
- />
376
- )}
377
- {errors.country && <p className="text-destructive mt-1 text-xs">{errors.country}</p>}
378
- </div>
379
-
380
- <div>
381
- <label htmlFor="region" className="text-foreground mb-1 block text-sm font-medium">
382
- {t('stateRegion')}
383
- </label>
384
- {hasRegionOptions ? (
385
- <select
386
- id="region"
387
- value={formData.region || ''}
388
- onChange={(e) => updateField('region', e.target.value)}
389
- className={cn(selectClass, 'border-border')}
390
- >
391
- <option value="">{t('selectRegion')}</option>
392
- {countryRegions.map((r) => (
393
- <option key={r.code} value={r.code}>
394
- {r.name}
395
- </option>
396
- ))}
397
- </select>
398
- ) : (
399
- <input
400
- id="region"
401
- type="text"
402
- value={formData.region || ''}
403
- onChange={(e) => updateField('region', e.target.value)}
404
- className={cn(inputClass, 'border-border')}
405
- />
406
- )}
407
- </div>
408
- </div>
409
-
410
- {/* Address line 1 — autocomplete typeahead */}
411
- <div className="relative">
412
- <label htmlFor="line1" className="text-foreground mb-1 block text-sm font-medium">
413
- {t('address')} <span className="text-destructive">*</span>
414
- </label>
415
- <input
416
- id="line1"
417
- type="text"
418
- autoComplete="off"
419
- value={formData.line1}
420
- onChange={(e) => handleLine1Change(e.target.value)}
421
- onFocus={() => setShowAddressSuggestions(addressSuggestions.length > 0)}
422
- onBlur={() => setTimeout(() => setShowAddressSuggestions(false), 150)}
423
- className={cn(inputClass, errors.line1 ? 'border-destructive' : 'border-border')}
424
- placeholder={t('streetAddress')}
425
- />
426
- {errors.line1 && <p className="text-destructive mt-1 text-xs">{errors.line1}</p>}
427
-
428
- {showAddressSuggestions && addressSuggestions.length > 0 && (
429
- <ul className="bg-background border-border absolute z-10 mt-1 max-h-60 w-full overflow-y-auto rounded border shadow-lg">
430
- {addressSuggestions.map((suggestion) => (
431
- <li key={suggestion.placeId}>
432
- <button
433
- type="button"
434
- // onMouseDown fires before the input's onBlur, so the
435
- // click registers before the dropdown closes.
436
- onMouseDown={() => handleSelectAddressSuggestion(suggestion)}
437
- className="hover:bg-muted w-full px-3 py-2 text-start text-sm"
438
- >
439
- {suggestion.description}
440
- </button>
441
- </li>
442
- ))}
443
- </ul>
444
- )}
445
- {isSearchingAddress && (
446
- <p className="text-muted-foreground mt-1 text-xs">{t('searchingAddress')}</p>
447
- )}
448
- {outsideDeliveryZone && (
449
- <p className="mt-2 rounded border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-200">
450
- {t('outsideDeliveryZone')}
451
- </p>
452
- )}
453
- </div>
454
-
455
- {/* Address line 2 */}
456
- <div>
457
- <label htmlFor="line2" className="text-foreground mb-1 block text-sm font-medium">
458
- {t('apartmentSuite')}
459
- </label>
460
- <input
461
- id="line2"
462
- type="text"
463
- value={formData.line2 || ''}
464
- onChange={(e) => updateField('line2', e.target.value)}
465
- className={cn(inputClass, 'border-border')}
466
- placeholder={t('aptPlaceholder')}
467
- />
468
- </div>
469
-
470
- {/* City + Postal code row */}
471
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
472
- <div>
473
- <label htmlFor="city" className="text-foreground mb-1 block text-sm font-medium">
474
- {t('city')} <span className="text-destructive">*</span>
475
- </label>
476
- <input
477
- id="city"
478
- type="text"
479
- value={formData.city}
480
- onChange={(e) => updateField('city', e.target.value)}
481
- className={cn(inputClass, errors.city ? 'border-destructive' : 'border-border')}
482
- />
483
- {errors.city && <p className="text-destructive mt-1 text-xs">{errors.city}</p>}
484
- </div>
485
-
486
- <div>
487
- <label
488
- htmlFor="postalCode"
489
- className="text-foreground mb-1 block text-sm font-medium"
490
- >
491
- {t('postalCode')} <span className="text-destructive">*</span>
492
- </label>
493
- <input
494
- id="postalCode"
495
- type="text"
496
- value={formData.postalCode}
497
- onChange={(e) => updateField('postalCode', e.target.value)}
498
- className={cn(
499
- inputClass,
500
- errors.postalCode ? 'border-destructive' : 'border-border'
501
- )}
502
- />
503
- {errors.postalCode && (
504
- <p className="text-destructive mt-1 text-xs">{errors.postalCode}</p>
505
- )}
506
- </div>
507
- </div>
508
-
509
- {/* Phone */}
510
- <div>
511
- <label htmlFor="phone" className="text-foreground mb-1 block text-sm font-medium">
512
- {t('phone')}
513
- </label>
514
- <input
515
- id="phone"
516
- type="tel"
517
- value={formData.phone || ''}
518
- onChange={(e) => updateField('phone', e.target.value)}
519
- className={cn(inputClass, 'border-border')}
520
- placeholder={t('phonePlaceholder')}
521
- />
522
- </div>
523
- </>
524
- )}
525
-
526
- {/* Order notes (optional) */}
527
- <div>
528
- <label htmlFor="orderNotes" className="text-foreground mb-1 block text-sm font-medium">
529
- {t('orderNotes')}
530
- </label>
531
- <textarea
532
- id="orderNotes"
533
- value={formData.notes || ''}
534
- onChange={(e) => updateField('notes', e.target.value)}
535
- maxLength={2000}
536
- rows={3}
537
- className={cn(
538
- inputClass,
539
- 'border-border h-auto min-h-[80px] resize-y py-2 leading-relaxed'
540
- )}
541
- placeholder={t('orderNotesPlaceholder')}
542
- />
543
- </div>
544
-
545
- {/* Privacy Policy (required) */}
546
- <div>
547
- <label className="flex cursor-pointer items-start gap-2">
548
- <input
549
- type="checkbox"
550
- checked={privacyAccepted}
551
- onChange={(e) => {
552
- setPrivacyAccepted(e.target.checked);
553
- if (e.target.checked && errors.privacy) {
554
- setErrors((prev) => {
555
- const next = { ...prev };
556
- delete next.privacy;
557
- return next;
558
- });
559
- }
560
- }}
561
- className="accent-primary mt-0.5"
562
- />
563
- <span className="text-muted-foreground text-sm">
564
- {t('privacyAcceptPrefix')}{' '}
565
- <a
566
- href="/privacy"
567
- target="_blank"
568
- rel="noopener noreferrer"
569
- className="text-primary underline underline-offset-2"
570
- >
571
- {t('privacyPolicyLink')}
572
- </a>{' '}
573
- <span className="text-destructive">*</span>
574
- </span>
575
- </label>
576
- {errors.privacy && <p className="text-destructive mt-1 text-xs">{errors.privacy}</p>}
577
- </div>
578
-
579
- {/* Marketing consent (optional) */}
580
- <label className="flex cursor-pointer items-start gap-2">
581
- <input
582
- type="checkbox"
583
- checked={acceptsMarketing}
584
- onChange={(e) => setAcceptsMarketing(e.target.checked)}
585
- className="accent-primary mt-0.5"
586
- />
587
- <span className="text-muted-foreground text-sm">{t('acceptsMarketing')}</span>
588
- </label>
589
-
590
- {/* Save details for next time (logged-in users only) */}
591
- {showSaveDetails && (
592
- <label className="flex cursor-pointer items-start gap-2">
593
- <input
594
- type="checkbox"
595
- checked={saveDetails}
596
- onChange={(e) => setSaveDetails(e.target.checked)}
597
- className="accent-primary mt-0.5"
598
- />
599
- <span className="text-muted-foreground text-sm">{t('saveDetailsForNextTime')}</span>
600
- </label>
601
- )}
602
-
603
- <button
604
- type="submit"
605
- disabled={loading}
606
- className="bg-primary text-primary-foreground w-full rounded px-6 py-3 text-sm font-medium transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
607
- >
608
- {loading ? tc('saving') : emailOnly ? t('continueToPayment') : t('continueToShipping')}
609
- </button>
610
- </form>
611
- );
612
- }
1
+ 'use client';
2
+
3
+ import { useState, useEffect, useRef } from 'react';
4
+ import type { SetShippingAddressDto, ShippingDestinations, AddressSuggestion } from 'brainerce';
5
+ import { useTranslations } from '@/core/lib/translations';
6
+ import { cn } from '@/core/lib/utils';
7
+ import { isValidEmail } from '@/core/lib/validation';
8
+ import { getClient } from '@/core/lib/brainerce';
9
+
10
+ // Debounce address-suggestion calls rather than firing on every keystroke —
11
+ // both to avoid a jumpy dropdown and to keep autocomplete-session call volume
12
+ // reasonable (see `getAddressSuggestions` doc in the SDK).
13
+ const ADDRESS_SEARCH_DEBOUNCE_MS = 300;
14
+ const ADDRESS_SEARCH_MIN_CHARS = 3;
15
+
16
+ // Editing any of these invalidates a previously picked suggestion: its
17
+ // coordinates describe the address the shopper selected, not what is in the
18
+ // inputs now. See `pickedPlace` below.
19
+ const PLACE_INVALIDATING_FIELDS = new Set<string>([
20
+ 'line1',
21
+ 'line2',
22
+ 'city',
23
+ 'region',
24
+ 'postalCode',
25
+ 'country',
26
+ ]);
27
+
28
+ interface CheckoutConsent {
29
+ acceptsMarketing: boolean;
30
+ saveDetails: boolean;
31
+ }
32
+
33
+ interface CheckoutFormProps {
34
+ onSubmit: (address: SetShippingAddressDto, consent: CheckoutConsent) => void;
35
+ loading?: boolean;
36
+ initialValues?: Partial<SetShippingAddressDto>;
37
+ destinations?: ShippingDestinations | null;
38
+ className?: string;
39
+ showSaveDetails?: boolean;
40
+ emailOnly?: boolean;
41
+ }
42
+
43
+ export function CheckoutForm({
44
+ onSubmit,
45
+ loading = false,
46
+ initialValues,
47
+ destinations,
48
+ className,
49
+ showSaveDetails = false,
50
+ emailOnly = false,
51
+ }: CheckoutFormProps) {
52
+ const [formData, setFormData] = useState<SetShippingAddressDto>({
53
+ email: initialValues?.email || '',
54
+ firstName: initialValues?.firstName || '',
55
+ lastName: initialValues?.lastName || '',
56
+ line1: initialValues?.line1 || '',
57
+ line2: initialValues?.line2 || '',
58
+ city: initialValues?.city || '',
59
+ region: initialValues?.region || '',
60
+ postalCode: initialValues?.postalCode || '',
61
+ country: initialValues?.country || '',
62
+ phone: initialValues?.phone || '',
63
+ notes: initialValues?.notes || '',
64
+ });
65
+ const [errors, setErrors] = useState<Record<string, string>>({});
66
+ const [privacyAccepted, setPrivacyAccepted] = useState(false);
67
+ const [acceptsMarketing, setAcceptsMarketing] = useState(false);
68
+ const [saveDetails, setSaveDetails] = useState(true);
69
+ const t = useTranslations('checkoutForm');
70
+ const tc = useTranslations('common');
71
+ const hasAppliedPrefill = useRef(!!initialValues);
72
+
73
+ // Address-autocomplete state — groups one address-entry attempt for
74
+ // session-token billing (see `getAddressSuggestions` in the SDK). A fresh
75
+ // token is minted whenever a suggestion is picked, ending that session.
76
+ const [addressSuggestions, setAddressSuggestions] = useState<AddressSuggestion[]>([]);
77
+ const [showAddressSuggestions, setShowAddressSuggestions] = useState(false);
78
+ const [isSearchingAddress, setIsSearchingAddress] = useState(false);
79
+ const [outsideDeliveryZone, setOutsideDeliveryZone] = useState(false);
80
+ // The suggestion the shopper actually picked, kept so it can ride along to
81
+ // `setShippingAddress`. That is what lets the server match map-drawn
82
+ // ("polygon") delivery zones against this address's exact coordinates
83
+ // instead of geocoding the typed text — skipping it is the most common
84
+ // cause of "the store says it doesn't deliver here, but it does". Null
85
+ // whenever the address was typed by hand or edited after picking.
86
+ const [pickedPlace, setPickedPlace] = useState<{
87
+ placeId: string;
88
+ sessionToken: string;
89
+ } | null>(null);
90
+ const addressSessionToken = useRef(
91
+ typeof crypto !== 'undefined' ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`
92
+ );
93
+ const addressSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
94
+
95
+ useEffect(() => {
96
+ return () => {
97
+ if (addressSearchTimer.current) clearTimeout(addressSearchTimer.current);
98
+ };
99
+ }, []);
100
+
101
+ function handleLine1Change(value: string) {
102
+ updateField('line1', value);
103
+ setOutsideDeliveryZone(false);
104
+
105
+ if (addressSearchTimer.current) clearTimeout(addressSearchTimer.current);
106
+
107
+ const query = value.trim();
108
+ if (query.length < ADDRESS_SEARCH_MIN_CHARS) {
109
+ setAddressSuggestions([]);
110
+ setShowAddressSuggestions(false);
111
+ return;
112
+ }
113
+
114
+ addressSearchTimer.current = setTimeout(async () => {
115
+ setIsSearchingAddress(true);
116
+ try {
117
+ const results = await getClient().getAddressSuggestions(query, addressSessionToken.current);
118
+ setAddressSuggestions(results);
119
+ setShowAddressSuggestions(results.length > 0);
120
+ } catch {
121
+ // Autocomplete is a soft enhancement — a failed lookup just means no
122
+ // suggestions this keystroke; the shopper can keep typing manually.
123
+ setAddressSuggestions([]);
124
+ setShowAddressSuggestions(false);
125
+ } finally {
126
+ setIsSearchingAddress(false);
127
+ }
128
+ }, ADDRESS_SEARCH_DEBOUNCE_MS);
129
+ }
130
+
131
+ async function handleSelectAddressSuggestion(suggestion: AddressSuggestion) {
132
+ setShowAddressSuggestions(false);
133
+ // The token this resolution is billed under — hand the SAME one to
134
+ // `setShippingAddress` so a server-side cache miss re-resolves within this
135
+ // autocomplete session instead of opening a new (billed) one.
136
+ const resolvingSessionToken = addressSessionToken.current;
137
+ try {
138
+ const { address, inZone } = await getClient().getAddressDetails(
139
+ suggestion.placeId,
140
+ resolvingSessionToken
141
+ );
142
+ setFormData((prev) => {
143
+ const country = address.country || prev.country;
144
+ // Only accept address.region if it's one of THIS store's known
145
+ // region codes for the resolved country (destinations.regions —
146
+ // the same list the dropdown below renders, backed by our own
147
+ // geo-data, not Google's). Google's region code usually lines up
148
+ // (both ultimately trace back to ISO 3166-2), but never assign a
149
+ // value the dropdown wouldn't recognize — better an unselected
150
+ // dropdown the shopper fills in than a silently-wrong one.
151
+ const validRegions = destinations?.regions[country] ?? [];
152
+ const resolvedRegionValid = validRegions.some((r) => r.code === address.region);
153
+ return {
154
+ ...prev,
155
+ line1: address.line1 || prev.line1,
156
+ city: address.city || prev.city,
157
+ region: resolvedRegionValid
158
+ ? address.region
159
+ : country !== prev.country
160
+ ? ''
161
+ : prev.region,
162
+ postalCode: address.postalCode || prev.postalCode,
163
+ country,
164
+ };
165
+ });
166
+ setOutsideDeliveryZone(!inZone);
167
+ // Note we deliberately do NOT copy address.lat/lng into the form: no
168
+ // address endpoint accepts coordinates (zone matching decides which rate
169
+ // is charged, so the server resolves them from the placeId itself).
170
+ // They're yours to use for a map pin and nothing else.
171
+ setPickedPlace({ placeId: suggestion.placeId, sessionToken: resolvingSessionToken });
172
+ } catch {
173
+ // Resolution failed — keep whatever the shopper had typed/selected as
174
+ // the visible text; they can still fill in the rest manually.
175
+ setPickedPlace(null);
176
+ } finally {
177
+ // New session for the next address-entry attempt.
178
+ addressSessionToken.current =
179
+ typeof crypto !== 'undefined' ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`;
180
+ setAddressSuggestions([]);
181
+ }
182
+ }
183
+
184
+ // Sync prefill data when it arrives async (e.g. from getCheckoutPrefillData)
185
+ useEffect(() => {
186
+ if (!initialValues || hasAppliedPrefill.current) return;
187
+ hasAppliedPrefill.current = true;
188
+ setFormData((prev) => ({
189
+ email: initialValues.email || prev.email,
190
+ firstName: initialValues.firstName || prev.firstName,
191
+ lastName: initialValues.lastName || prev.lastName,
192
+ line1: initialValues.line1 || prev.line1,
193
+ line2: initialValues.line2 || prev.line2 || '',
194
+ city: initialValues.city || prev.city,
195
+ region: initialValues.region || prev.region || '',
196
+ postalCode: initialValues.postalCode || prev.postalCode,
197
+ country: initialValues.country || prev.country,
198
+ phone: initialValues.phone || prev.phone || '',
199
+ notes: prev.notes || '',
200
+ }));
201
+ }, [initialValues]);
202
+
203
+ const hasCountryOptions = destinations && destinations.countries.length > 0;
204
+ const countryRegions = destinations?.regions[formData.country];
205
+ const hasRegionOptions = countryRegions && countryRegions.length > 0;
206
+
207
+ function validate(): boolean {
208
+ const newErrors: Record<string, string> = {};
209
+
210
+ if (!formData.email.trim()) {
211
+ newErrors.email = t('emailRequired');
212
+ } else if (!isValidEmail(formData.email.trim())) {
213
+ newErrors.email = t('emailInvalid');
214
+ }
215
+
216
+ if (!formData.firstName.trim()) {
217
+ newErrors.firstName = t('firstNameRequired');
218
+ }
219
+ if (!formData.lastName.trim()) {
220
+ newErrors.lastName = t('lastNameRequired');
221
+ }
222
+ if (!emailOnly) {
223
+ if (!formData.line1.trim()) {
224
+ newErrors.line1 = t('addressRequired');
225
+ }
226
+ if (!formData.city.trim()) {
227
+ newErrors.city = t('cityRequired');
228
+ }
229
+ if (!formData.postalCode.trim()) {
230
+ newErrors.postalCode = t('postalCodeRequired');
231
+ }
232
+ if (!formData.country.trim()) {
233
+ newErrors.country = t('countryRequired');
234
+ }
235
+ }
236
+ if (!privacyAccepted) {
237
+ newErrors.privacy = t('privacyRequired');
238
+ }
239
+
240
+ setErrors(newErrors);
241
+ return Object.keys(newErrors).length === 0;
242
+ }
243
+
244
+ function handleSubmit(e: React.FormEvent) {
245
+ e.preventDefault();
246
+ if (validate()) {
247
+ onSubmit(
248
+ {
249
+ ...formData,
250
+ // Both undefined when the shopper typed the address by hand or
251
+ // edited it after picking a suggestion — the server then geocodes
252
+ // the text, which is the right behaviour once the two disagree.
253
+ placeId: pickedPlace?.placeId,
254
+ placeSessionToken: pickedPlace?.sessionToken,
255
+ },
256
+ { acceptsMarketing, saveDetails: showSaveDetails && saveDetails }
257
+ );
258
+ }
259
+ }
260
+
261
+ function updateField(field: keyof SetShippingAddressDto, value: string) {
262
+ setFormData((prev) => {
263
+ const next = { ...prev, [field]: value };
264
+ // Reset region when country changes
265
+ if (field === 'country' && value !== prev.country) {
266
+ next.region = '';
267
+ }
268
+ return next;
269
+ });
270
+ // Once any address field is edited, the picked suggestion no longer
271
+ // describes what is in the form — keeping its placeId would match delivery
272
+ // zones against the address the shopper originally selected.
273
+ if (PLACE_INVALIDATING_FIELDS.has(field)) {
274
+ setPickedPlace(null);
275
+ }
276
+ if (errors[field]) {
277
+ setErrors((prev) => {
278
+ const next = { ...prev };
279
+ delete next[field];
280
+ return next;
281
+ });
282
+ }
283
+ }
284
+
285
+ const inputClass =
286
+ 'bg-background text-foreground placeholder:text-muted-foreground focus:ring-primary/20 focus:border-primary h-10 w-full rounded border px-3 text-sm focus:outline-none focus:ring-2';
287
+ const selectClass =
288
+ 'bg-background text-foreground focus:ring-primary/20 focus:border-primary h-10 w-full appearance-none rounded border px-3 text-sm focus:outline-none focus:ring-2';
289
+
290
+ return (
291
+ <form onSubmit={handleSubmit} className={cn('space-y-4', className)}>
292
+ {/* Email */}
293
+ <div>
294
+ <label htmlFor="email" className="text-foreground mb-1 block text-sm font-medium">
295
+ {t('email')} <span className="text-destructive">*</span>
296
+ </label>
297
+ <input
298
+ id="email"
299
+ type="email"
300
+ value={formData.email}
301
+ onChange={(e) => updateField('email', e.target.value)}
302
+ className={cn(inputClass, errors.email ? 'border-destructive' : 'border-border')}
303
+ placeholder="your@email.com"
304
+ />
305
+ {errors.email && <p className="text-destructive mt-1 text-xs">{errors.email}</p>}
306
+ </div>
307
+
308
+ {/* Name row */}
309
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
310
+ <div>
311
+ <label htmlFor="firstName" className="text-foreground mb-1 block text-sm font-medium">
312
+ {t('firstName')} <span className="text-destructive">*</span>
313
+ </label>
314
+ <input
315
+ id="firstName"
316
+ type="text"
317
+ value={formData.firstName}
318
+ onChange={(e) => updateField('firstName', e.target.value)}
319
+ className={cn(inputClass, errors.firstName ? 'border-destructive' : 'border-border')}
320
+ />
321
+ {errors.firstName && <p className="text-destructive mt-1 text-xs">{errors.firstName}</p>}
322
+ </div>
323
+
324
+ <div>
325
+ <label htmlFor="lastName" className="text-foreground mb-1 block text-sm font-medium">
326
+ {t('lastName')} <span className="text-destructive">*</span>
327
+ </label>
328
+ <input
329
+ id="lastName"
330
+ type="text"
331
+ value={formData.lastName}
332
+ onChange={(e) => updateField('lastName', e.target.value)}
333
+ className={cn(inputClass, errors.lastName ? 'border-destructive' : 'border-border')}
334
+ />
335
+ {errors.lastName && <p className="text-destructive mt-1 text-xs">{errors.lastName}</p>}
336
+ </div>
337
+ </div>
338
+
339
+ {!emailOnly && (
340
+ <>
341
+ {/* Country + Region row */}
342
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
343
+ <div>
344
+ <label htmlFor="country" className="text-foreground mb-1 block text-sm font-medium">
345
+ {t('country')} <span className="text-destructive">*</span>
346
+ </label>
347
+ {hasCountryOptions ? (
348
+ <select
349
+ id="country"
350
+ value={formData.country}
351
+ onChange={(e) => updateField('country', e.target.value)}
352
+ className={cn(
353
+ selectClass,
354
+ errors.country ? 'border-destructive' : 'border-border'
355
+ )}
356
+ >
357
+ <option value="">{t('selectCountry')}</option>
358
+ {destinations.countries.map((c) => (
359
+ <option key={c.code} value={c.code}>
360
+ {c.name}
361
+ </option>
362
+ ))}
363
+ </select>
364
+ ) : (
365
+ <input
366
+ id="country"
367
+ type="text"
368
+ value={formData.country}
369
+ onChange={(e) => updateField('country', e.target.value)}
370
+ className={cn(
371
+ inputClass,
372
+ errors.country ? 'border-destructive' : 'border-border'
373
+ )}
374
+ placeholder={t('countryPlaceholder')}
375
+ />
376
+ )}
377
+ {errors.country && <p className="text-destructive mt-1 text-xs">{errors.country}</p>}
378
+ </div>
379
+
380
+ <div>
381
+ <label htmlFor="region" className="text-foreground mb-1 block text-sm font-medium">
382
+ {t('stateRegion')}
383
+ </label>
384
+ {hasRegionOptions ? (
385
+ <select
386
+ id="region"
387
+ value={formData.region || ''}
388
+ onChange={(e) => updateField('region', e.target.value)}
389
+ className={cn(selectClass, 'border-border')}
390
+ >
391
+ <option value="">{t('selectRegion')}</option>
392
+ {countryRegions.map((r) => (
393
+ <option key={r.code} value={r.code}>
394
+ {r.name}
395
+ </option>
396
+ ))}
397
+ </select>
398
+ ) : (
399
+ <input
400
+ id="region"
401
+ type="text"
402
+ value={formData.region || ''}
403
+ onChange={(e) => updateField('region', e.target.value)}
404
+ className={cn(inputClass, 'border-border')}
405
+ />
406
+ )}
407
+ </div>
408
+ </div>
409
+
410
+ {/* Address line 1 — autocomplete typeahead */}
411
+ <div className="relative">
412
+ <label htmlFor="line1" className="text-foreground mb-1 block text-sm font-medium">
413
+ {t('address')} <span className="text-destructive">*</span>
414
+ </label>
415
+ <input
416
+ id="line1"
417
+ type="text"
418
+ autoComplete="off"
419
+ value={formData.line1}
420
+ onChange={(e) => handleLine1Change(e.target.value)}
421
+ onFocus={() => setShowAddressSuggestions(addressSuggestions.length > 0)}
422
+ onBlur={() => setTimeout(() => setShowAddressSuggestions(false), 150)}
423
+ className={cn(inputClass, errors.line1 ? 'border-destructive' : 'border-border')}
424
+ placeholder={t('streetAddress')}
425
+ />
426
+ {errors.line1 && <p className="text-destructive mt-1 text-xs">{errors.line1}</p>}
427
+
428
+ {showAddressSuggestions && addressSuggestions.length > 0 && (
429
+ <ul className="bg-background border-border absolute z-10 mt-1 max-h-60 w-full overflow-y-auto rounded border shadow-lg">
430
+ {addressSuggestions.map((suggestion) => (
431
+ <li key={suggestion.placeId}>
432
+ <button
433
+ type="button"
434
+ // onMouseDown fires before the input's onBlur, so the
435
+ // click registers before the dropdown closes.
436
+ onMouseDown={() => handleSelectAddressSuggestion(suggestion)}
437
+ className="hover:bg-muted w-full px-3 py-2 text-start text-sm"
438
+ >
439
+ {suggestion.description}
440
+ </button>
441
+ </li>
442
+ ))}
443
+ </ul>
444
+ )}
445
+ {isSearchingAddress && (
446
+ <p className="text-muted-foreground mt-1 text-xs">{t('searchingAddress')}</p>
447
+ )}
448
+ {outsideDeliveryZone && (
449
+ <p className="mt-2 rounded border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-200">
450
+ {t('outsideDeliveryZone')}
451
+ </p>
452
+ )}
453
+ </div>
454
+
455
+ {/* Address line 2 */}
456
+ <div>
457
+ <label htmlFor="line2" className="text-foreground mb-1 block text-sm font-medium">
458
+ {t('apartmentSuite')}
459
+ </label>
460
+ <input
461
+ id="line2"
462
+ type="text"
463
+ value={formData.line2 || ''}
464
+ onChange={(e) => updateField('line2', e.target.value)}
465
+ className={cn(inputClass, 'border-border')}
466
+ placeholder={t('aptPlaceholder')}
467
+ />
468
+ </div>
469
+
470
+ {/* City + Postal code row */}
471
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
472
+ <div>
473
+ <label htmlFor="city" className="text-foreground mb-1 block text-sm font-medium">
474
+ {t('city')} <span className="text-destructive">*</span>
475
+ </label>
476
+ <input
477
+ id="city"
478
+ type="text"
479
+ value={formData.city}
480
+ onChange={(e) => updateField('city', e.target.value)}
481
+ className={cn(inputClass, errors.city ? 'border-destructive' : 'border-border')}
482
+ />
483
+ {errors.city && <p className="text-destructive mt-1 text-xs">{errors.city}</p>}
484
+ </div>
485
+
486
+ <div>
487
+ <label
488
+ htmlFor="postalCode"
489
+ className="text-foreground mb-1 block text-sm font-medium"
490
+ >
491
+ {t('postalCode')} <span className="text-destructive">*</span>
492
+ </label>
493
+ <input
494
+ id="postalCode"
495
+ type="text"
496
+ value={formData.postalCode}
497
+ onChange={(e) => updateField('postalCode', e.target.value)}
498
+ className={cn(
499
+ inputClass,
500
+ errors.postalCode ? 'border-destructive' : 'border-border'
501
+ )}
502
+ />
503
+ {errors.postalCode && (
504
+ <p className="text-destructive mt-1 text-xs">{errors.postalCode}</p>
505
+ )}
506
+ </div>
507
+ </div>
508
+
509
+ {/* Phone */}
510
+ <div>
511
+ <label htmlFor="phone" className="text-foreground mb-1 block text-sm font-medium">
512
+ {t('phone')}
513
+ </label>
514
+ <input
515
+ id="phone"
516
+ type="tel"
517
+ value={formData.phone || ''}
518
+ onChange={(e) => updateField('phone', e.target.value)}
519
+ className={cn(inputClass, 'border-border')}
520
+ placeholder={t('phonePlaceholder')}
521
+ />
522
+ </div>
523
+ </>
524
+ )}
525
+
526
+ {/* Order notes (optional) */}
527
+ <div>
528
+ <label htmlFor="orderNotes" className="text-foreground mb-1 block text-sm font-medium">
529
+ {t('orderNotes')}
530
+ </label>
531
+ <textarea
532
+ id="orderNotes"
533
+ value={formData.notes || ''}
534
+ onChange={(e) => updateField('notes', e.target.value)}
535
+ maxLength={2000}
536
+ rows={3}
537
+ className={cn(
538
+ inputClass,
539
+ 'border-border h-auto min-h-[80px] resize-y py-2 leading-relaxed'
540
+ )}
541
+ placeholder={t('orderNotesPlaceholder')}
542
+ />
543
+ </div>
544
+
545
+ {/* Privacy Policy (required) */}
546
+ <div>
547
+ <label className="flex cursor-pointer items-start gap-2">
548
+ <input
549
+ type="checkbox"
550
+ checked={privacyAccepted}
551
+ onChange={(e) => {
552
+ setPrivacyAccepted(e.target.checked);
553
+ if (e.target.checked && errors.privacy) {
554
+ setErrors((prev) => {
555
+ const next = { ...prev };
556
+ delete next.privacy;
557
+ return next;
558
+ });
559
+ }
560
+ }}
561
+ className="accent-primary mt-0.5"
562
+ />
563
+ <span className="text-muted-foreground text-sm">
564
+ {t('privacyAcceptPrefix')}{' '}
565
+ <a
566
+ href="/privacy"
567
+ target="_blank"
568
+ rel="noopener noreferrer"
569
+ className="text-primary underline underline-offset-2"
570
+ >
571
+ {t('privacyPolicyLink')}
572
+ </a>{' '}
573
+ <span className="text-destructive">*</span>
574
+ </span>
575
+ </label>
576
+ {errors.privacy && <p className="text-destructive mt-1 text-xs">{errors.privacy}</p>}
577
+ </div>
578
+
579
+ {/* Marketing consent (optional) */}
580
+ <label className="flex cursor-pointer items-start gap-2">
581
+ <input
582
+ type="checkbox"
583
+ checked={acceptsMarketing}
584
+ onChange={(e) => setAcceptsMarketing(e.target.checked)}
585
+ className="accent-primary mt-0.5"
586
+ />
587
+ <span className="text-muted-foreground text-sm">{t('acceptsMarketing')}</span>
588
+ </label>
589
+
590
+ {/* Save details for next time (logged-in users only) */}
591
+ {showSaveDetails && (
592
+ <label className="flex cursor-pointer items-start gap-2">
593
+ <input
594
+ type="checkbox"
595
+ checked={saveDetails}
596
+ onChange={(e) => setSaveDetails(e.target.checked)}
597
+ className="accent-primary mt-0.5"
598
+ />
599
+ <span className="text-muted-foreground text-sm">{t('saveDetailsForNextTime')}</span>
600
+ </label>
601
+ )}
602
+
603
+ <button
604
+ type="submit"
605
+ disabled={loading}
606
+ className="bg-primary text-primary-foreground w-full rounded px-6 py-3 text-sm font-medium transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
607
+ >
608
+ {loading ? tc('saving') : emailOnly ? t('continueToPayment') : t('continueToShipping')}
609
+ </button>
610
+ </form>
611
+ );
612
+ }