@disconetwork/shopify 0.0.7 → 0.0.9

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.
@@ -0,0 +1,4920 @@
1
+ import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
2
+ import { createContext, createElement } from "preact";
3
+ import { cloneElement, createContext as createContext$1, createElement as createElement$1, isValidElement, useCallback as useCallback$1, useContext as useContext$1, useEffect as useEffect$1, useMemo as useMemo$1, useState as useState$1 } from "preact/compat";
4
+ import { withImpressionDedupe } from "@disconetwork/core";
5
+ import { Fragment, jsx } from "preact/jsx-runtime";
6
+ import { INTERNAL_BASE_URL, InternalDiscoClient, parseScreens } from "@disconetwork/core/internal";
7
+ import { Fragment as Fragment$1, jsx as jsx$1, jsxs } from "preact/jsx-runtime";
8
+ import { useApi, useApplyAttributeChange, useApplyCartLinesChange, useAttributeValues, useBillingAddress, useCartLines, useCheckoutToken, useCustomer, useDiscountCodes, useEmail, useExtensionEditor, useInstructions, useLocalizationCountry, usePhone, usePurchasingCompany, useShippingAddress, useShop, useSubscription, useSubtotalAmount, useTotalAmount } from "@shopify/ui-extensions/checkout/preact";
9
+ import { useApi as useApi$1, useBillingAddress as useBillingAddress$1, useCartLines as useCartLines$1, useCustomer as useCustomer$1, useDiscountCodes as useDiscountCodes$1, useEmail as useEmail$1, useOrder, usePhone as usePhone$1, usePurchasingCompany as usePurchasingCompany$1, useShippingAddress as useShippingAddress$1, useShop as useShop$1, useSubscription as useSubscription$1, useTotalAmount as useTotalAmount$1 } from "@shopify/ui-extensions/customer-account/preact";
10
+ import { QueryClient, QueryClientProvider, useMutation, useQuery } from "@tanstack/preact-query";
11
+ import { boolean, email, nullable, object, optional, string } from "zod/mini";
12
+ //#region ../react-shared/dist/createHeadlessBindings-CPuF5wZQ.js
13
+ /**
14
+ * Build a self-contained set of headless React bindings for one client type.
15
+ *
16
+ * Returns the client context (for a backing-specific `DiscoProvider` to provide
17
+ * into), the `useDiscoClient` accessor, the `Disco.Root` controller, and the
18
+ * `useDiscoRecommendations` / `useDiscoTracker` / `useFetchRecommendations`
19
+ * hooks — all concretely typed to `TRequest` / `TResponse`. Call this once per
20
+ * backing at module load; the returned components/hooks are stable references.
21
+ */
22
+ function createHeadlessBindings() {
23
+ /**
24
+ * Holds the client built by the backing's `<DiscoProvider>`. Read it with
25
+ * `useDiscoClient` to fetch recommendations or create trackers.
26
+ */
27
+ const DiscoClientContext = createContext$1(null);
28
+ /**
29
+ * Read the client configured by the surrounding `<DiscoProvider>`.
30
+ *
31
+ * Returns the single, stable, provider-configured instance — use this rather
32
+ * than constructing a client in a component (which would create a new one each
33
+ * render and risk drifting from the provider's auth/env). Throws if used
34
+ * outside a provider.
35
+ */
36
+ function useDiscoClient() {
37
+ const client = useContext$1(DiscoClientContext);
38
+ if (!client) throw new Error("useDiscoClient must be used inside a <DiscoProvider>.");
39
+ return client;
40
+ }
41
+ const LOADING = {
42
+ status: "loading",
43
+ data: void 0,
44
+ error: void 0
45
+ };
46
+ /**
47
+ * Fetch-on-mount state machine for a recommendations surface.
48
+ *
49
+ * Owns the request lifecycle — fetch on mount, refetch when the request
50
+ * changes or `refetch` is called, abort in-flight requests on unmount/change —
51
+ * and derives the session-bound tracker from each response. Renders nothing and
52
+ * knows nothing about the `Disco.*` contexts; `<Disco.Root>` adapts its result.
53
+ *
54
+ * Exported from each backing's `/headless` entry as the shared fetch
55
+ * primitive: `<Disco.Root>` builds on it. Reach for it directly only when
56
+ * building a custom surface that needs the fetch lifecycle without the
57
+ * `Disco.*` contexts.
58
+ */
59
+ function useFetchRecommendations(request) {
60
+ const client = useDiscoClient();
61
+ const [state, setState] = useState$1(LOADING);
62
+ const [tracker, setTracker] = useState$1(null);
63
+ const requestKey = useMemo$1(() => JSON.stringify(request), [request]);
64
+ const [reloadCount, setReloadCount] = useState$1(0);
65
+ const refetch = useCallback$1(() => setReloadCount((n) => n + 1), []);
66
+ useEffect$1(() => {
67
+ const controller = new AbortController();
68
+ setState(LOADING);
69
+ setTracker(null);
70
+ client.getRecommendationsWithTracker(request, { signal: controller.signal }).then(({ data, tracker }) => {
71
+ if (controller.signal.aborted) return;
72
+ setState({
73
+ status: "success",
74
+ data,
75
+ error: void 0
76
+ });
77
+ setTracker(withImpressionDedupe(tracker));
78
+ }).catch((error) => {
79
+ if (controller.signal.aborted) return;
80
+ setState({
81
+ status: "error",
82
+ data: void 0,
83
+ error
84
+ });
85
+ });
86
+ return () => controller.abort();
87
+ }, [
88
+ client,
89
+ requestKey,
90
+ reloadCount
91
+ ]);
92
+ return {
93
+ state,
94
+ tracker,
95
+ refetch
96
+ };
97
+ }
98
+ const DiscoContext = createContext$1(null);
99
+ /**
100
+ * Read the recommendations fetch state, the session-bound tracker, and
101
+ * `refetch` from the surrounding `<Disco.Root>`. The tracker is non-null only
102
+ * once `status === "success"`; for consumers that only need the tracker and
103
+ * render inside a success branch, {@link useDiscoTracker} returns a non-null
104
+ * tracker and throws if used before success. Throws if used outside a
105
+ * `<Disco.Root>`.
106
+ */
107
+ function useDiscoRecommendations() {
108
+ const ctx = useContext$1(DiscoContext);
109
+ if (!ctx) throw new Error("useDiscoRecommendations must be used inside a <Disco.Root>.");
110
+ return ctx;
111
+ }
112
+ /**
113
+ * Read the session-bound {@link EventTracker} for the surrounding
114
+ * `<Disco.Root>`.
115
+ *
116
+ * The tracker exists only once recommendations have loaded (its session comes
117
+ * from the response). Render tracking UI inside the `success` branch and this
118
+ * hook returns a ready tracker; it throws if used before `success`, surfacing
119
+ * misuse loudly rather than silently dropping events. Throws if used outside a
120
+ * `<Disco.Root>`.
121
+ */
122
+ function useDiscoTracker() {
123
+ const ctx = useContext$1(DiscoContext);
124
+ if (!ctx) throw new Error("useDiscoTracker must be used inside a <Disco.Root>.");
125
+ if (!ctx.tracker) throw new Error("useDiscoTracker is only available after recommendations have loaded — render tracking UI inside the <Disco.Root> success branch.");
126
+ return ctx.tracker;
127
+ }
128
+ /**
129
+ * Headless controller for a Disco recommendations surface — the root of the
130
+ * `Disco.*` compound. Fetches via `useFetchRecommendations` and provides the
131
+ * fetch state (read with `useDiscoRecommendations`) and the session-bound
132
+ * tracker (read with `useDiscoTracker`) to its subtree. Renders no UI of its
133
+ * own; aborts in-flight requests on unmount or request change.
134
+ */
135
+ function DiscoRoot({ request, children }) {
136
+ const { state, tracker, refetch } = useFetchRecommendations(request);
137
+ const value = useMemo$1(() => ({
138
+ ...state,
139
+ tracker,
140
+ refetch
141
+ }), [
142
+ state,
143
+ tracker,
144
+ refetch
145
+ ]);
146
+ return /* @__PURE__ */ jsx(DiscoContext.Provider, {
147
+ value,
148
+ children
149
+ });
150
+ }
151
+ return {
152
+ DiscoClientContext,
153
+ useDiscoClient,
154
+ useDiscoRecommendations,
155
+ useDiscoTracker,
156
+ useFetchRecommendations,
157
+ DiscoRoot
158
+ };
159
+ }
160
+ //#endregion
161
+ //#region ../react-shared/dist/bindings-D-XXI0bV.js
162
+ const bindings = createHeadlessBindings();
163
+ const DiscoClientContext = bindings.DiscoClientContext;
164
+ const useDiscoClient = bindings.useDiscoClient;
165
+ bindings.DiscoRoot;
166
+ const useFetchRecommendations = bindings.useFetchRecommendations;
167
+ bindings.useDiscoRecommendations;
168
+ bindings.useDiscoTracker;
169
+ //#endregion
170
+ //#region ../react-shared/dist/headless-C9iZrlrk.js
171
+ const RendererContext = createContext$1(null);
172
+ function useRendererContext() {
173
+ const ctx = useContext$1(RendererContext);
174
+ if (!ctx) throw new Error("useRendererContext must be used within a ScreensRenderer");
175
+ return ctx;
176
+ }
177
+ function generateNodes({ nodes, path, renderers }) {
178
+ return nodes.map((node, idx) => {
179
+ const generator = renderers[node.type];
180
+ if (!generator) throw new Error(`No renderer found for node type: "${node.type}"`);
181
+ const nodePath = `${path}.${node.type}.${idx}`;
182
+ const reactNode = generator({
183
+ node,
184
+ nodesToJSX: (args) => generateNodes({
185
+ nodes: args.nodes,
186
+ path: nodePath,
187
+ renderers
188
+ })
189
+ });
190
+ if (isValidElement(reactNode)) return cloneElement(reactNode, { key: nodePath });
191
+ return reactNode;
192
+ });
193
+ }
194
+ function ScreensRenderer({ jsonContent, renderers, fallback = null }) {
195
+ const screens = useMemo$1(() => parseScreens(jsonContent), [jsonContent]);
196
+ if (!screens) return fallback;
197
+ return createElement$1(ScreensNavigator, {
198
+ screens,
199
+ renderers
200
+ });
201
+ }
202
+ function ScreensNavigator({ screens, renderers }) {
203
+ const [currentScreenId, setCurrentScreenId] = useState$1(() => screens[0]?.id ?? "default");
204
+ useEffect$1(() => {
205
+ setCurrentScreenId(screens[0]?.id ?? "default");
206
+ }, [screens]);
207
+ const activeScreen = screens.find((screen) => screen.id === currentScreenId) ?? screens[0];
208
+ if (!activeScreen) return null;
209
+ return createElement$1(RendererContext.Provider, { value: {
210
+ screens,
211
+ currentScreenId: activeScreen.id,
212
+ setCurrentScreenId
213
+ } }, generateNodes({
214
+ nodes: activeScreen.children,
215
+ path: activeScreen.id,
216
+ renderers
217
+ }));
218
+ }
219
+ //#endregion
220
+ //#region src/managers/RecommendationsTrackingManager/index.tsx
221
+ const RecommendationsTrackingManagerContext = createContext(null);
222
+ function RecommendationsTrackingManager({ children, tracker }) {
223
+ return /* @__PURE__ */ jsx$1(RecommendationsTrackingManagerContext.Provider, {
224
+ value: tracker,
225
+ children
226
+ });
227
+ }
228
+ function useEventTracker$1() {
229
+ const ctx = useContext(RecommendationsTrackingManagerContext);
230
+ if (!ctx) throw new Error("useEventTracker must be used inside RecommendationsTrackingManager");
231
+ return ctx;
232
+ }
233
+ //#endregion
234
+ //#region src/hooks/usePayload.tsx
235
+ const usePayload = () => {
236
+ const data = useContext(PayloadContext);
237
+ if (!data) throw new Error("No wrapper Payload context found");
238
+ return data;
239
+ };
240
+ //#endregion
241
+ //#region src/utils/dataManagerUtils.ts
242
+ const getShopIdentifier$1 = (shopGid) => {
243
+ return shopGid.replace("gid://shopify/Shop/", "");
244
+ };
245
+ const shopifyOrderIdFormatter = (inp) => typeof inp === "string" ? inp.replace("gid://shopify/Order/", "") : inp;
246
+ const getRecommendationsRequest = ({ payload, widgetId }) => {
247
+ return {
248
+ user: {
249
+ email: payload.buyerEmail,
250
+ firstName: payload.extrapolatedFirstName,
251
+ lastName: payload.customerLastName,
252
+ phone: payload.extrapolatedPhone
253
+ },
254
+ placement: {
255
+ displayMode: "INLINE",
256
+ view: payload.target,
257
+ widgetId
258
+ },
259
+ order: {
260
+ amount: payload.totalCost,
261
+ currencyCode: payload.currencyCode,
262
+ id: shopifyOrderIdFormatter(payload.orderId) ?? void 0
263
+ },
264
+ shipping: payload.shippingAddress,
265
+ billing: payload.billingAddress,
266
+ purchases: payload.cartLines.map((cartLine) => {
267
+ return {
268
+ name: cartLine.merchandise.title,
269
+ type: cartLine.merchandise.product.productType,
270
+ variant: cartLine.merchandise.subtitle,
271
+ quantity: cartLine.quantity,
272
+ amount: cartLine.cost.totalAmount.amount,
273
+ currencyCode: cartLine.cost.totalAmount.currencyCode,
274
+ productId: cartLine.merchandise.product.id.replace("gid://shopify/Product/", "")
275
+ };
276
+ })
277
+ };
278
+ };
279
+ //#endregion
280
+ //#region src/components/CardContainer.tsx
281
+ const CardContainer = ({ children, ...rest }) => {
282
+ return /* @__PURE__ */ jsx$1("s-box", {
283
+ border: "base",
284
+ borderWidth: "base",
285
+ borderRadius: "large",
286
+ ...rest,
287
+ children
288
+ });
289
+ };
290
+ //#endregion
291
+ //#region src/components/RecommendationsWidget/RecommendationsWidgetSkeleton.tsx
292
+ const WIDE = "@container (inline-size > 450px)";
293
+ const TILE_COUNT = 4;
294
+ const Block = ({ blockSize }) => /* @__PURE__ */ jsx$1("s-box", {
295
+ blockSize,
296
+ inlineSize: "100%",
297
+ background: "subdued",
298
+ borderRadius: "base"
299
+ });
300
+ const HeroOfferSkeleton = () => /* @__PURE__ */ jsx$1("s-box", {
301
+ padding: "base",
302
+ border: "base",
303
+ borderWidth: "none none base none",
304
+ children: /* @__PURE__ */ jsxs("s-stack", {
305
+ gap: "small-400",
306
+ children: [/* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Thank you for your purchase:" }), /* @__PURE__ */ jsxs("s-stack", {
307
+ gap: "base",
308
+ children: [/* @__PURE__ */ jsxs("s-stack", {
309
+ gap: "small-200",
310
+ children: [/* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Exclusive offer from a brand you'll love" }), /* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Get a special discount on your next order" })]
311
+ }), /* @__PURE__ */ jsx$1("s-stack", {
312
+ direction: `${WIDE} inline, block`,
313
+ gap: "base",
314
+ children: [0, 1].map((index) => /* @__PURE__ */ jsx$1("s-box", {
315
+ inlineSize: `${WIDE} 160px, 100%`,
316
+ children: /* @__PURE__ */ jsx$1(Block, { blockSize: "44px" })
317
+ }, index))
318
+ })]
319
+ })]
320
+ })
321
+ });
322
+ const OfferRowSkeleton = () => /* @__PURE__ */ jsx$1("s-box", {
323
+ padding: "base",
324
+ border: "base",
325
+ borderWidth: "none none base none",
326
+ children: /* @__PURE__ */ jsx$1("s-grid", {
327
+ gridTemplateColumns: "repeat(4, minmax(0, 1fr))",
328
+ gap: "small-200",
329
+ children: Array.from({ length: TILE_COUNT }, (_, index) => /* @__PURE__ */ jsxs("s-stack", {
330
+ gap: "small-400",
331
+ children: [/* @__PURE__ */ jsx$1("s-image", {
332
+ aspectRatio: "1",
333
+ inlineSize: "fill",
334
+ border: "base",
335
+ borderRadius: "small",
336
+ accessibilityRole: "presentation"
337
+ }), /* @__PURE__ */ jsxs("s-stack", {
338
+ gap: "none",
339
+ children: [/* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Brand" }), /* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Offer" })]
340
+ })]
341
+ }, index))
342
+ })
343
+ });
344
+ const RecommendationsWidgetSkeleton = () => /* @__PURE__ */ jsx$1("s-box", {
345
+ accessibilityRole: "status",
346
+ accessibilityLabel: "Loading recommendations",
347
+ children: /* @__PURE__ */ jsx$1(CardContainer, {
348
+ background: "base",
349
+ children: /* @__PURE__ */ jsxs("s-query-container", { children: [
350
+ /* @__PURE__ */ jsx$1(HeroOfferSkeleton, {}),
351
+ /* @__PURE__ */ jsx$1(OfferRowSkeleton, {}),
352
+ /* @__PURE__ */ jsx$1("s-stack", {
353
+ padding: "small-200 base",
354
+ alignItems: "end",
355
+ children: /* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Privacy Policy" })
356
+ })
357
+ ] })
358
+ })
359
+ });
360
+ //#endregion
361
+ //#region src/sdkIdentity.ts
362
+ const SDK_IDENTITY = {
363
+ name: "@disconetwork/shopify",
364
+ version: "0.0.9"
365
+ };
366
+ //#endregion
367
+ //#region ../react-shared/dist/sdk-internals.js
368
+ /** @internal Bind SDK identity to a provider using the legacy backend proxy. */
369
+ function createProxySdkProvider(sdk) {
370
+ return function ProxySdkProvider({ children, ...auth }) {
371
+ const apiKey = "apiKey" in auth ? auth.apiKey : void 0;
372
+ const surface = "surface" in auth ? auth.surface : void 0;
373
+ const shopGid = "shopGid" in auth ? auth.shopGid : void 0;
374
+ const env = "env" in auth ? auth.env : void 0;
375
+ const client = useMemo$1(() => apiKey !== void 0 ? new InternalDiscoClient({
376
+ apiKey,
377
+ surface,
378
+ sdk
379
+ }) : new InternalDiscoClient({
380
+ shopGid,
381
+ env,
382
+ sdk
383
+ }), [
384
+ apiKey,
385
+ surface,
386
+ shopGid,
387
+ env
388
+ ]);
389
+ return /* @__PURE__ */ jsx(DiscoClientContext.Provider, {
390
+ value: client,
391
+ children
392
+ });
393
+ };
394
+ }
395
+ //#endregion
396
+ //#region src/managers/DataManager.tsx
397
+ const ShopifySdkProvider = createProxySdkProvider(SDK_IDENTITY);
398
+ const DataManager = ({ auth, widgetId, request, children }) => {
399
+ const payload = usePayload();
400
+ return /* @__PURE__ */ jsx$1(ShopifySdkProvider, {
401
+ ..."apiKey" in auth ? {
402
+ apiKey: auth.apiKey,
403
+ surface: "shopify"
404
+ } : {
405
+ shopGid: payload.shopGid,
406
+ env: auth.env
407
+ },
408
+ children: /* @__PURE__ */ jsx$1(RecommendationsContent, {
409
+ request: request ?? getRecommendationsRequest({
410
+ payload,
411
+ widgetId
412
+ }),
413
+ children
414
+ })
415
+ });
416
+ };
417
+ const RecommendationsContent = ({ children, request }) => {
418
+ const { state: recommendations, tracker } = useFetchRecommendations(request);
419
+ if (recommendations.status === "error") return null;
420
+ if (recommendations.status === "loading" || !tracker) return /* @__PURE__ */ jsx$1(RecommendationsWidgetSkeleton, {});
421
+ return /* @__PURE__ */ jsx$1(RecommendationsDataContext.Provider, {
422
+ value: recommendations.data,
423
+ children: /* @__PURE__ */ jsx$1(RecommendationsTrackingManager, {
424
+ tracker,
425
+ children
426
+ })
427
+ });
428
+ };
429
+ //#endregion
430
+ //#region src/utils/address.ts
431
+ /**
432
+ * Map a Shopify `MailingAddress` onto the recommendations `Address`, dropping
433
+ * empty fields. `undefined` when Shopify gives no address (e.g. no protected
434
+ * customer data access) or the address has none of the fields we forward.
435
+ */
436
+ const toRecommendationsAddress = (address) => {
437
+ if (!address) return void 0;
438
+ const mapped = {
439
+ addressLine1: address.address1 || void 0,
440
+ addressLine2: address.address2 || void 0,
441
+ city: address.city || void 0,
442
+ state: address.provinceCode || void 0,
443
+ zip: address.zip || void 0,
444
+ phone: address.phone || void 0,
445
+ countryCode: address.countryCode || void 0
446
+ };
447
+ return Object.values(mapped).some(Boolean) ? mapped : void 0;
448
+ };
449
+ //#endregion
450
+ //#region src/managers/PayloadManager.tsx
451
+ const GenericPayloadProvider = ({ target, children, payload, additionalPayload, isB2BPurchase }) => {
452
+ useEffect(() => {
453
+ if (!isB2BPurchase) return;
454
+ throw new Error("[Disco]: Disabling for B2B purchase");
455
+ }, [isB2BPurchase]);
456
+ if (isB2BPurchase) return null;
457
+ return /* @__PURE__ */ jsx$1(PayloadContext.Provider, {
458
+ value: {
459
+ ...payload,
460
+ ...additionalPayload || {},
461
+ target
462
+ },
463
+ children
464
+ });
465
+ };
466
+ function createGenericPayload({ buyerPhone, buyerEmail, customer, shippingAddress, billingAddress, totalAmount, cartLines, checkoutToken, discountCodes, shopGid, extensionTarget }) {
467
+ const derivedFirstName = billingAddress?.firstName || shippingAddress?.firstName;
468
+ return {
469
+ buyerPhone,
470
+ buyerEmail,
471
+ customerId: customer?.id,
472
+ customerFirstName: customer?.firstName,
473
+ customerLastName: customer?.lastName,
474
+ customerFullName: customer?.fullName,
475
+ derivedFirstName,
476
+ billingFirstName: billingAddress?.firstName,
477
+ billingLastName: billingAddress?.lastName,
478
+ billingZipCode: billingAddress?.zip,
479
+ shippingZipCode: shippingAddress?.zip,
480
+ shippingAddress: toRecommendationsAddress(shippingAddress),
481
+ billingAddress: toRecommendationsAddress(billingAddress),
482
+ extrapolatedFirstName: customer?.firstName || derivedFirstName,
483
+ extrapolatedPhone: buyerPhone || shippingAddress?.phone || billingAddress?.phone || "",
484
+ totalCost: totalAmount.amount,
485
+ currencyCode: totalAmount.currencyCode,
486
+ cartLines,
487
+ checkoutToken,
488
+ discountCodes,
489
+ shopGid,
490
+ target: PAYLOAD_MANAGER_TARGET.GENERIC,
491
+ extensionTarget
492
+ };
493
+ }
494
+ const ThankYouPayloadManager = ({ children }) => {
495
+ const target = PAYLOAD_MANAGER_TARGET.THANK_YOU;
496
+ const customer = useCustomer();
497
+ const buyerEmail = useEmail();
498
+ const buyerPhone = usePhone();
499
+ const purchasingCompany = usePurchasingCompany();
500
+ const shippingAddress = useShippingAddress();
501
+ const billingAddress = useBillingAddress();
502
+ const totalAmount = useTotalAmount();
503
+ const cartLines = useCartLines();
504
+ const checkoutToken = useCheckoutToken();
505
+ const discountCodes = useDiscountCodes();
506
+ const shop = useShop();
507
+ const api = useApi();
508
+ const orderId = useSubscription(api.orderConfirmation).order.id.split("/").pop();
509
+ if (!orderId) console.warn("[Disco]: Order ID not found in thank you page");
510
+ return /* @__PURE__ */ jsx$1(GenericPayloadProvider, {
511
+ target,
512
+ payload: createGenericPayload({
513
+ buyerPhone,
514
+ buyerEmail,
515
+ customer,
516
+ shippingAddress,
517
+ billingAddress,
518
+ totalAmount,
519
+ cartLines,
520
+ checkoutToken,
521
+ discountCodes,
522
+ shopGid: shop.id,
523
+ extensionTarget: api.extension.target
524
+ }),
525
+ additionalPayload: {
526
+ orderId,
527
+ target
528
+ },
529
+ isB2BPurchase: Boolean(purchasingCompany?.company),
530
+ children
531
+ });
532
+ };
533
+ const OrderStatusPayloadManager = ({ children }) => {
534
+ const target = PAYLOAD_MANAGER_TARGET.ORDER_STATUS;
535
+ const customer = useCustomer$1();
536
+ const buyerEmail = useEmail$1();
537
+ const buyerPhone = usePhone$1();
538
+ const purchasingCompany = usePurchasingCompany$1();
539
+ const shippingAddress = useShippingAddress$1();
540
+ const billingAddress = useBillingAddress$1();
541
+ const totalAmount = useTotalAmount$1();
542
+ const cartLines = useCartLines$1();
543
+ const discountCodes = useDiscountCodes$1();
544
+ const shop = useShop$1();
545
+ const order = useOrder();
546
+ const api = useApi$1();
547
+ return /* @__PURE__ */ jsx$1(GenericPayloadProvider, {
548
+ target,
549
+ payload: createGenericPayload({
550
+ buyerPhone,
551
+ buyerEmail,
552
+ customer,
553
+ shippingAddress,
554
+ billingAddress,
555
+ totalAmount,
556
+ cartLines,
557
+ checkoutToken: useSubscription$1(api.checkoutToken),
558
+ discountCodes,
559
+ shopGid: shop.id,
560
+ extensionTarget: api.extension.target
561
+ }),
562
+ additionalPayload: {
563
+ orderId: order?.id,
564
+ orderName: order?.name,
565
+ target
566
+ },
567
+ isB2BPurchase: Boolean(purchasingCompany?.company),
568
+ children
569
+ });
570
+ };
571
+ const PAYLOAD_MANAGER_TARGET = {
572
+ GENERIC: "GENERIC",
573
+ ORDER_STATUS: "ORDER_STATUS",
574
+ THANK_YOU: "THANK_YOU"
575
+ };
576
+ const EXTENSION_TARGETS = {
577
+ "purchase.thank-you.block.render": PAYLOAD_MANAGER_TARGET.THANK_YOU,
578
+ "customer-account.order-status.block.render": PAYLOAD_MANAGER_TARGET.ORDER_STATUS
579
+ };
580
+ const getExtensionTarget = () => globalThis.shopify?.extension?.target;
581
+ const PayloadManager = ({ children }) => {
582
+ const extensionTarget = getExtensionTarget();
583
+ const target = extensionTarget && EXTENSION_TARGETS[extensionTarget];
584
+ if (target === PAYLOAD_MANAGER_TARGET.THANK_YOU) return /* @__PURE__ */ jsx$1(ThankYouPayloadManager, { children });
585
+ if (target === PAYLOAD_MANAGER_TARGET.ORDER_STATUS) return /* @__PURE__ */ jsx$1(OrderStatusPayloadManager, { children });
586
+ throw new Error(`[Disco]: Unsupported extension target ${extensionTarget ?? "(none)"}`);
587
+ };
588
+ //#endregion
589
+ //#region src/managers/UserManager.tsx
590
+ const UserManager = ({ children }) => {
591
+ const { buyerEmail, customerFirstName, customerLastName, customerFullName, derivedFirstName, extrapolatedFirstName } = usePayload();
592
+ const [user, setUser] = useState({
593
+ email: buyerEmail,
594
+ firstName: customerFirstName,
595
+ lastName: customerLastName,
596
+ fullName: customerFullName,
597
+ derivedFirstName,
598
+ extrapolatedFirstName
599
+ });
600
+ const hasIdentity = useMemo(() => !!user?.email, [user]);
601
+ return /* @__PURE__ */ jsx$1(UserContext.Provider, {
602
+ value: {
603
+ user,
604
+ setUser,
605
+ hasIdentity
606
+ },
607
+ children
608
+ });
609
+ };
610
+ //#endregion
611
+ //#region src/managers/index.ts
612
+ const RecommendationsDataContext = createContext(null);
613
+ const PayloadContext = createContext(null);
614
+ const UserContext = createContext(null);
615
+ //#endregion
616
+ //#region src/hooks/useRecommendationsData.tsx
617
+ function useRecommendationsData() {
618
+ const ctx = useContext(RecommendationsDataContext);
619
+ if (!ctx) throw new Error("useRecommendationsData must be used inside RecommendationsDataContext");
620
+ return ctx;
621
+ }
622
+ //#endregion
623
+ //#region src/hooks/useCounter.tsx
624
+ const useCounter = ({ start = 0, min = 0, max = Infinity, resetOnMax = false, disabled = false } = {}) => {
625
+ const [counter, setCounter] = useState(start);
626
+ const incrementCounter = useCallback((counter) => Math.min(max, counter + 1) % (resetOnMax ? max : Infinity), [max, resetOnMax]);
627
+ const increment = useCallback(() => disabled ? null : setCounter(incrementCounter), [incrementCounter, disabled]);
628
+ const decrementCounter = useCallback((counter) => Math.max(min, counter - 1), [min]);
629
+ const decrement = useCallback(() => disabled ? null : setCounter(decrementCounter), [decrementCounter, disabled]);
630
+ const nextCounter = useMemo(() => incrementCounter(counter), [incrementCounter, counter]);
631
+ const prevCounter = useMemo(() => decrementCounter(counter), [decrementCounter, counter]);
632
+ const isMin = useMemo(() => counter === min, [min, counter]);
633
+ const isMax = useMemo(() => counter === max, [max, counter]);
634
+ const procValue = useCallback((value) => Math.max(min, Math.min(max, value)), [max, min]);
635
+ return {
636
+ counter,
637
+ setCounter: useCallback((cb) => {
638
+ if (disabled) return;
639
+ setCounter((counter) => procValue(typeof cb === "function" ? cb(counter) : cb));
640
+ }, [procValue, disabled]),
641
+ increment,
642
+ decrement,
643
+ nextCounter,
644
+ prevCounter,
645
+ isMin,
646
+ isMax
647
+ };
648
+ };
649
+ //#endregion
650
+ //#region src/components/RecommendationsWidget/HeroOfferProvider.tsx
651
+ const HeroContext = createContext(null);
652
+ const HeroOfferProvider = ({ children, recommendationGroup, loop }) => {
653
+ const [claimedOffers, setClaimedOffers] = useState([]);
654
+ const { recommendations } = recommendationGroup;
655
+ const { counter: activeRecommendationIdx, increment: nextOffer, decrement: prevOffer, isMin: isFirstOffer, isMax: isLastOffer } = useCounter(loop ? {
656
+ start: 0,
657
+ min: 0,
658
+ max: recommendations.length,
659
+ resetOnMax: true
660
+ } : {
661
+ start: 0,
662
+ min: 0,
663
+ max: recommendations.length - 1
664
+ });
665
+ const activeRecommendation = recommendations[activeRecommendationIdx];
666
+ const handleOfferClaim = () => {
667
+ setClaimedOffers((claimedOffers) => [...claimedOffers, activeRecommendation.id]);
668
+ };
669
+ const value = {
670
+ activeRecommendation,
671
+ activeOfferIndex: activeRecommendationIdx,
672
+ nextOffer,
673
+ prevOffer,
674
+ isOfferClaimed: claimedOffers.includes(activeRecommendation.id),
675
+ handleOfferClaim,
676
+ TOTAL_NUM_OFFERS: recommendations.length,
677
+ isFirstOffer,
678
+ isLastOffer,
679
+ claimedOffers,
680
+ recommendations
681
+ };
682
+ return /* @__PURE__ */ jsx$1(HeroContext.Provider, {
683
+ value,
684
+ children
685
+ });
686
+ };
687
+ const useHeroOffer = () => {
688
+ const context = useContext(HeroContext);
689
+ if (!context) throw new Error("useHeroOffer must be used within a HeroOfferProvider");
690
+ return context;
691
+ };
692
+ //#endregion
693
+ //#region src/components/RecommendationsWidget/ScrollableSlotProvider.tsx
694
+ const ScrollableSlotContext = createContext(null);
695
+ const ScrollableSlotProvider = ({ children, scrollableRecommendationGroup }) => {
696
+ const value = { hasScrollableSlot: !!scrollableRecommendationGroup };
697
+ return /* @__PURE__ */ jsx$1(ScrollableSlotContext.Provider, {
698
+ value,
699
+ children
700
+ });
701
+ };
702
+ const useScrollableSlot = () => {
703
+ const context = useContext(ScrollableSlotContext);
704
+ if (!context) throw new Error("useScrollableSlot must be used within a ScrollableSlotProvider");
705
+ return context;
706
+ };
707
+ //#endregion
708
+ //#region src/hooks/useIdentity.tsx
709
+ const useIdentity = () => {
710
+ const data = useContext(UserContext);
711
+ if (!data) throw new Error("No wrapper User manager found");
712
+ return data;
713
+ };
714
+ //#endregion
715
+ //#region src/hooks/useCustomization.ts
716
+ const CUSTOMIZATION_TYPE = {
717
+ CHECKOUT: "checkout",
718
+ UPFRONT: "upfront"
719
+ };
720
+ //#endregion
721
+ //#region src/hooks/useRecommendationsCustomization.tsx
722
+ const useRecommendationsCustomization = ({ type = CUSTOMIZATION_TYPE.CHECKOUT } = {}) => {
723
+ const customization = useRecommendationsData()?.publisherCustomization?.[type] || null;
724
+ const hasCustomization = (detail) => {
725
+ if (!customization || typeof customization !== "object" || !detail) return false;
726
+ return !!customization[detail];
727
+ };
728
+ const getCustomization = (detail) => {
729
+ if (!hasCustomization(detail) || !customization) return null;
730
+ return customization[detail];
731
+ };
732
+ const applyCustomizationOrFallback = (detail, fallback = null) => {
733
+ if (!hasCustomization(detail)) return fallback;
734
+ return getCustomization(detail);
735
+ };
736
+ return { applyCustomizationOrFallback };
737
+ };
738
+ //#endregion
739
+ //#region src/components/RecommendationsWidget/useFirstOfferHeading.ts
740
+ const useFirstOfferHeading = () => {
741
+ const { user } = useIdentity();
742
+ const { applyCustomizationOrFallback } = useRecommendationsCustomization();
743
+ const firstName = user?.extrapolatedFirstName;
744
+ return applyCustomizationOrFallback("widget_heading", `${firstName ? `${firstName}, thank you` : "Thank you"} for your purchase:`);
745
+ };
746
+ //#endregion
747
+ //#region src/conf/env_conf.ts
748
+ const BUCKET_NAME = {
749
+ production: "coopcommerce",
750
+ staging: "coopcommerce-staging"
751
+ };
752
+ const IMAGE_HANDLING_CLOUDFRONT_DOMAIN = {
753
+ production: "https://d1t86rpuyqggut.cloudfront.net/",
754
+ staging: "https://dn9o42i1jy6mo.cloudfront.net/"
755
+ };
756
+ //#endregion
757
+ //#region src/utils/getImgUrl.ts
758
+ /**
759
+ * Parses a cloudfront image URL and extracts the key from its BASE64-encoded payload.
760
+ * Returns the key if the URL is a valid cloudfront URL, otherwise returns null.
761
+ */
762
+ function parseKeyFromCloudfrontUrl(url, env) {
763
+ const domain = IMAGE_HANDLING_CLOUDFRONT_DOMAIN[env];
764
+ if (!url.startsWith(domain)) return null;
765
+ try {
766
+ const base64Path = url.slice(domain.length).split("?")[0];
767
+ if (!base64Path) return null;
768
+ const decodedPayload = atob(base64Path);
769
+ return JSON.parse(decodedPayload).key ?? null;
770
+ } catch {
771
+ return null;
772
+ }
773
+ }
774
+ const getCloudfrontImageSources = ({ env, key, edits, width, height }) => {
775
+ const imgPayload = JSON.stringify({
776
+ bucket: BUCKET_NAME[env],
777
+ key,
778
+ edits: {
779
+ ...edits,
780
+ resize: {
781
+ fit: "fill",
782
+ withoutEnlargement: true
783
+ }
784
+ }
785
+ });
786
+ return getImageVariants(`${IMAGE_HANDLING_CLOUDFRONT_DOMAIN[env]}${btoa(imgPayload)}`, {
787
+ width: width || 350,
788
+ height: height || 350
789
+ });
790
+ };
791
+ /**
792
+ * Square image sources for `url`. A cloudfront image-handler URL is re-encoded
793
+ * at `size` with 1x-4x variants; any other URL is used as-is.
794
+ */
795
+ function getImageSources(url, { env, size }) {
796
+ const key = parseKeyFromCloudfrontUrl(url, env);
797
+ return key ? getCloudfrontImageSources({
798
+ env,
799
+ key,
800
+ width: size,
801
+ height: size
802
+ }) : { src: url };
803
+ }
804
+ function getImageVariants(imgUrl, dimensions) {
805
+ const { width: cssWidth, height: cssHeight } = dimensions;
806
+ const getTransformedDimension = (resolution, dimension) => {
807
+ const STEP = 32;
808
+ return Math.ceil(dimension * resolution / STEP) * STEP;
809
+ };
810
+ const getTransformedImageUrl = (resolution) => {
811
+ return `${imgUrl}?width=${getTransformedDimension(resolution, cssWidth)}&height=${getTransformedDimension(resolution, cssHeight)}`;
812
+ };
813
+ const variants = [
814
+ 1,
815
+ 2,
816
+ 3,
817
+ 4
818
+ ].map((resolution) => ({
819
+ resolution,
820
+ url: getTransformedImageUrl(resolution)
821
+ }));
822
+ return {
823
+ src: getTransformedImageUrl(1),
824
+ srcSet: variants.map(({ resolution, url }) => `${url} ${resolution}x`).join(", ")
825
+ };
826
+ }
827
+ //#endregion
828
+ //#region src/hooks/useDiscoEnv.ts
829
+ const useDiscoEnv = () => useDiscoClient().env;
830
+ //#endregion
831
+ //#region src/components/Essential/generation/LinkGenerator.tsx
832
+ function InternalLink({ targetScreenId, children }) {
833
+ const ctx = useRendererContext();
834
+ return /* @__PURE__ */ jsx$1("s-link", {
835
+ tone: "neutral",
836
+ onClick: () => ctx.setCurrentScreenId(targetScreenId),
837
+ children
838
+ });
839
+ }
840
+ const LinkGenerator = { link: ({ node, nodesToJSX }) => {
841
+ const children = nodesToJSX({ nodes: node.children });
842
+ if ("targetScreenId" in node.attributes) return /* @__PURE__ */ jsx$1(InternalLink, {
843
+ targetScreenId: node.attributes.targetScreenId,
844
+ children
845
+ });
846
+ const href = node.attributes.to;
847
+ const external = node.attributes.external;
848
+ return /* @__PURE__ */ jsx$1("s-link", {
849
+ tone: "neutral",
850
+ href,
851
+ target: external ? "_blank" : "auto",
852
+ children
853
+ });
854
+ } };
855
+ //#endregion
856
+ //#region src/components/Essential/generation/ParagraphGenerator.tsx
857
+ const ParagraphGenerator = { paragraph: ({ node, nodesToJSX }) => {
858
+ return /* @__PURE__ */ jsx$1("s-paragraph", {
859
+ color: "subdued",
860
+ children: /* @__PURE__ */ jsx$1("s-text", {
861
+ type: "strong",
862
+ children: nodesToJSX({ nodes: node.children })
863
+ })
864
+ });
865
+ } };
866
+ //#endregion
867
+ //#region src/components/Essential/generation/ScrollViewGenerator.tsx
868
+ const DEFAULT_MAX_BLOCK_SIZE = 300;
869
+ const ScrollViewGenerator = { scrollview: ({ node, nodesToJSX }) => {
870
+ const children = nodesToJSX({ nodes: node.children });
871
+ return /* @__PURE__ */ jsx$1("s-scroll-box", {
872
+ maxBlockSize: `${node.attributes?.maxBlockSize ?? DEFAULT_MAX_BLOCK_SIZE}px`,
873
+ children
874
+ });
875
+ } };
876
+ //#endregion
877
+ //#region src/components/Essential/EssentialOfferContent.tsx
878
+ const renderers = {
879
+ text: ({ node }) => {
880
+ return node.text;
881
+ },
882
+ ...LinkGenerator,
883
+ ...ParagraphGenerator,
884
+ ...ScrollViewGenerator
885
+ };
886
+ const EssentialOfferContent = ({ heading: offerHeading, subheading: offerSubheading, jsonContent: incentiveJson }) => {
887
+ return /* @__PURE__ */ jsxs("s-stack", {
888
+ gap: "small-200",
889
+ children: [/* @__PURE__ */ jsx$1("s-heading", { children: offerHeading }), /* @__PURE__ */ jsx$1(ScreensRenderer, {
890
+ jsonContent: incentiveJson,
891
+ renderers,
892
+ fallback: /* @__PURE__ */ jsx$1("s-paragraph", {
893
+ color: "subdued",
894
+ children: /* @__PURE__ */ jsx$1("s-text", {
895
+ type: "strong",
896
+ children: offerSubheading || ""
897
+ })
898
+ })
899
+ })]
900
+ });
901
+ };
902
+ //#endregion
903
+ //#region src/components/RecommendationsWidget/Essential/EssentialLayoutType.tsx
904
+ const EssentialLayoutType = ({ onLastOffer, compact }) => {
905
+ const { isFirstOffer, activeRecommendation: recommendation } = useHeroOffer();
906
+ const renderBrandLogo = recommendation.offer.metadata.layoutType === "FEATURED_IMAGE";
907
+ return /* @__PURE__ */ jsx$1("s-query-container", { children: /* @__PURE__ */ jsx$1("s-box", {
908
+ padding: compact ? "none" : "base",
909
+ children: /* @__PURE__ */ jsxs("s-stack", {
910
+ gap: "small-400",
911
+ children: [
912
+ renderBrandLogo && /* @__PURE__ */ jsx$1("s-box", {
913
+ display: "@container (inline-size > 450px) none, auto",
914
+ children: /* @__PURE__ */ jsx$1("s-stack", {
915
+ alignItems: "center",
916
+ children: /* @__PURE__ */ jsx$1(AdvertiserLogo, { recommendation })
917
+ })
918
+ }),
919
+ isFirstOffer && !compact && /* @__PURE__ */ jsx$1(FirstOfferHeading, {}),
920
+ /* @__PURE__ */ jsxs("s-grid", {
921
+ gridTemplateColumns: renderBrandLogo ? "@container (inline-size > 450px) 1fr auto, 1fr" : "1fr",
922
+ gap: "base",
923
+ alignItems: "center",
924
+ children: [/* @__PURE__ */ jsxs("s-stack", {
925
+ gap: "base",
926
+ children: [/* @__PURE__ */ jsx$1(EssentialOfferContent, {
927
+ heading: recommendation.offer.heading || "",
928
+ subheading: recommendation.offer.subheading || "",
929
+ jsonContent: recommendation.offer.jsonContent
930
+ }), /* @__PURE__ */ jsxs("s-stack", {
931
+ direction: "@container (inline-size > 450px) inline, block",
932
+ gap: "base",
933
+ children: [/* @__PURE__ */ jsx$1("s-box", {
934
+ inlineSize: "@container (inline-size > 450px) auto, 100%",
935
+ children: /* @__PURE__ */ jsx$1(PrimaryButton, {})
936
+ }), /* @__PURE__ */ jsx$1("s-box", {
937
+ inlineSize: "@container (inline-size > 450px) auto, 100%",
938
+ children: /* @__PURE__ */ jsx$1(SecondaryButton, { onLastOffer })
939
+ })]
940
+ })]
941
+ }), renderBrandLogo && /* @__PURE__ */ jsx$1("s-box", {
942
+ display: "@container (inline-size > 450px) auto, none",
943
+ children: /* @__PURE__ */ jsx$1(AdvertiserLogo, { recommendation })
944
+ })]
945
+ })
946
+ ]
947
+ })
948
+ }) });
949
+ };
950
+ function AdvertiserLogo({ recommendation }) {
951
+ const { advertiser } = recommendation;
952
+ const env = useDiscoEnv();
953
+ const imageSize = 140;
954
+ const image = getImageSources(advertiser.logoUrl, {
955
+ env,
956
+ size: imageSize
957
+ });
958
+ return /* @__PURE__ */ jsx$1("s-box", {
959
+ blockSize: `${imageSize}px`,
960
+ inlineSize: `${imageSize}px`,
961
+ children: /* @__PURE__ */ jsx$1("s-image", {
962
+ aspectRatio: "1",
963
+ src: image.src,
964
+ srcSet: image.srcSet,
965
+ alt: `${advertiser.name} Logo`,
966
+ inlineSize: "fill"
967
+ })
968
+ });
969
+ }
970
+ function PrimaryButton() {
971
+ const { track } = useEventTracker$1();
972
+ const { handleOfferClaim, isOfferClaimed, activeRecommendation: recommendation } = useHeroOffer();
973
+ const handleClick = () => {
974
+ track({
975
+ type: "BRAND_CLICK",
976
+ target: "INLINE_ACTION_BUTTON",
977
+ brand: {
978
+ offerId: recommendation.offer.id,
979
+ advertiserId: recommendation.advertiser.id,
980
+ insertionId: recommendation.insertionId
981
+ }
982
+ });
983
+ handleOfferClaim();
984
+ };
985
+ return /* @__PURE__ */ jsx$1("s-button", {
986
+ href: recommendation.offer.targetUrl,
987
+ target: "_blank",
988
+ inlineSize: "fill",
989
+ variant: isOfferClaimed ? "secondary" : "primary",
990
+ onClick: handleClick,
991
+ children: recommendation.offer.ctaDetails.acceptCopy
992
+ });
993
+ }
994
+ function SecondaryButton({ onLastOffer }) {
995
+ const { track } = useEventTracker$1();
996
+ const { hasScrollableSlot } = useScrollableSlot();
997
+ const { isOfferClaimed, nextOffer, isLastOffer, activeRecommendation: recommendation } = useHeroOffer();
998
+ const handleClick = () => {
999
+ track({
1000
+ type: "ELEMENT_CLICK",
1001
+ target: "INLINE_NAV_FORWARD",
1002
+ brand: {
1003
+ offerId: recommendation.offer.id,
1004
+ advertiserId: recommendation.advertiser.id,
1005
+ insertionId: recommendation.insertionId
1006
+ }
1007
+ });
1008
+ if (isLastOffer) {
1009
+ onLastOffer();
1010
+ return;
1011
+ }
1012
+ nextOffer();
1013
+ };
1014
+ const buttonText = isOfferClaimed ? isLastOffer ? hasScrollableSlot ? "See more" : "Close" : "Next offer" : recommendation.offer.ctaDetails.declineCopy || "No thanks";
1015
+ return /* @__PURE__ */ jsx$1("s-button", {
1016
+ inlineSize: "fill",
1017
+ variant: isOfferClaimed ? "primary" : "secondary",
1018
+ onClick: handleClick,
1019
+ children: buttonText
1020
+ });
1021
+ }
1022
+ function FirstOfferHeading() {
1023
+ return /* @__PURE__ */ jsx$1("s-text", {
1024
+ tone: "info",
1025
+ children: useFirstOfferHeading()
1026
+ });
1027
+ }
1028
+ //#endregion
1029
+ //#region src/components/RecommendationsWidget/DotIndicators.tsx
1030
+ const DotIndicators = ({ totalCount, activeIndex }) => {
1031
+ if (totalCount <= 1) return null;
1032
+ return /* @__PURE__ */ jsx$1("s-stack", {
1033
+ padding: "small-200 none",
1034
+ alignItems: "center",
1035
+ children: /* @__PURE__ */ jsx$1("s-stack", {
1036
+ direction: "inline",
1037
+ gap: "small-200",
1038
+ children: Array.from({ length: totalCount }, (_, i) => /* @__PURE__ */ jsx$1("s-badge", {
1039
+ size: "small",
1040
+ color: i === activeIndex ? "base" : "subdued",
1041
+ children: `${i + 1}`
1042
+ }, i))
1043
+ })
1044
+ });
1045
+ };
1046
+ //#endregion
1047
+ //#region src/conf/index.ts
1048
+ const getLeadGenRegisterUrl = (env) => `${INTERNAL_BASE_URL[env]}/lead_gen/register_lead/`;
1049
+ const PRIVACY_POLICY_URL = "https://www.disconetwork.com/privacy-policy";
1050
+ //#endregion
1051
+ //#region src/components/PrivacyLink.tsx
1052
+ const PrivacyLink = ({ onPress }) => {
1053
+ return /* @__PURE__ */ jsx$1("s-text", {
1054
+ color: "subdued",
1055
+ children: /* @__PURE__ */ jsx$1("s-link", {
1056
+ href: PRIVACY_POLICY_URL,
1057
+ target: "_blank",
1058
+ tone: "neutral",
1059
+ onClick: onPress,
1060
+ children: "Privacy Policy"
1061
+ })
1062
+ });
1063
+ };
1064
+ //#endregion
1065
+ //#region src/components/RecommendationsWidget/Footer.tsx
1066
+ function Footer() {
1067
+ const { track } = useEventTracker$1();
1068
+ const handlePrivacyClick = () => {
1069
+ track({
1070
+ type: "ELEMENT_CLICK",
1071
+ target: "INLINE_FOOTER_PRIVACY"
1072
+ });
1073
+ };
1074
+ return /* @__PURE__ */ jsx$1("s-stack", {
1075
+ padding: "small-200 base",
1076
+ alignItems: "end",
1077
+ children: /* @__PURE__ */ jsx$1(PrivacyLink, { onPress: handlePrivacyClick })
1078
+ });
1079
+ }
1080
+ //#endregion
1081
+ //#region src/components/RecommendationsWidget/Cover/index.tsx
1082
+ const CoverRecommendationsWidget = ({ heroRecommendationGroup }) => {
1083
+ const { track } = useEventTracker$1();
1084
+ useEffect(() => {
1085
+ track({ type: "WIDGET_LOAD" });
1086
+ }, [track]);
1087
+ return /* @__PURE__ */ jsx$1(HeroOfferProvider, {
1088
+ recommendationGroup: heroRecommendationGroup,
1089
+ loop: true,
1090
+ children: /* @__PURE__ */ jsx$1(CoverRecommendationsWidgetContent, {})
1091
+ });
1092
+ };
1093
+ const CoverRecommendationsWidgetContent = () => {
1094
+ const { track } = useEventTracker$1();
1095
+ const firstOfferHeading = useFirstOfferHeading();
1096
+ const modalHeading = typeof firstOfferHeading === "string" ? firstOfferHeading : "Your rewards";
1097
+ const { TOTAL_NUM_OFFERS, activeOfferIndex, nextOffer, activeRecommendation } = useHeroOffer();
1098
+ const [modalOpen, setModalOpen] = useState(false);
1099
+ const { insertionId, offer, advertiser } = activeRecommendation;
1100
+ useEffect(() => {
1101
+ if (!modalOpen) return;
1102
+ track({
1103
+ type: "BRAND_DISPLAY",
1104
+ target: "INLINE_SLOT",
1105
+ brand: {
1106
+ offerId: offer.id,
1107
+ advertiserId: advertiser.id,
1108
+ insertionId
1109
+ }
1110
+ });
1111
+ }, [
1112
+ modalOpen,
1113
+ track,
1114
+ insertionId,
1115
+ offer.id,
1116
+ advertiser.id
1117
+ ]);
1118
+ const subtitle = `You've unlocked ${TOTAL_NUM_OFFERS} exclusive offer${TOTAL_NUM_OFFERS !== 1 ? "s" : ""} with your purchase — don't let them go to waste!`;
1119
+ return /* @__PURE__ */ jsx$1(CardContainer, {
1120
+ background: "transparent",
1121
+ children: /* @__PURE__ */ jsx$1("s-box", {
1122
+ padding: "base",
1123
+ children: /* @__PURE__ */ jsxs("s-stack", {
1124
+ gap: "base",
1125
+ children: [
1126
+ /* @__PURE__ */ jsx$1("s-heading", { children: "Your purchase comes with rewards!" }),
1127
+ /* @__PURE__ */ jsx$1("s-text", {
1128
+ color: "subdued",
1129
+ children: subtitle
1130
+ }),
1131
+ /* @__PURE__ */ jsx$1("s-button", {
1132
+ variant: "primary",
1133
+ command: "--show",
1134
+ commandFor: "cover-modal",
1135
+ onClick: () => track({
1136
+ type: "ELEMENT_CLICK",
1137
+ target: "OPEN_OVERLAY"
1138
+ }),
1139
+ children: "View my rewards"
1140
+ }),
1141
+ /* @__PURE__ */ jsxs("s-modal", {
1142
+ id: "cover-modal",
1143
+ padding: "base",
1144
+ heading: modalHeading,
1145
+ size: "large",
1146
+ onShow: () => {
1147
+ setModalOpen(true);
1148
+ track({ type: "WIDGET_DISPLAY" });
1149
+ },
1150
+ onHide: () => {
1151
+ setModalOpen(false);
1152
+ track({
1153
+ type: "ELEMENT_CLICK",
1154
+ target: "CLOSE_BUTTON"
1155
+ });
1156
+ },
1157
+ children: [
1158
+ /* @__PURE__ */ jsx$1(ScrollableSlotProvider, { children: /* @__PURE__ */ jsx$1(EssentialLayoutType, {
1159
+ onLastOffer: nextOffer,
1160
+ compact: true
1161
+ }) }),
1162
+ /* @__PURE__ */ jsx$1(DotIndicators, {
1163
+ totalCount: TOTAL_NUM_OFFERS,
1164
+ activeIndex: activeOfferIndex
1165
+ }),
1166
+ /* @__PURE__ */ jsx$1("s-divider", {}),
1167
+ /* @__PURE__ */ jsx$1(Footer, {})
1168
+ ]
1169
+ })
1170
+ ]
1171
+ })
1172
+ })
1173
+ });
1174
+ };
1175
+ //#endregion
1176
+ //#region src/components/DiscoFeed/DiscoFeedProduct.tsx
1177
+ function ProductTile({ targetUrl, trackClick, image, productName }) {
1178
+ return /* @__PURE__ */ jsx$1("s-box", {
1179
+ inlineSize: "100%",
1180
+ children: /* @__PURE__ */ jsxs("s-stack", {
1181
+ alignItems: "stretch",
1182
+ gap: "none",
1183
+ children: [/* @__PURE__ */ jsx$1("s-link", {
1184
+ target: "_blank",
1185
+ tone: "neutral",
1186
+ href: targetUrl,
1187
+ onClick: trackClick,
1188
+ children: /* @__PURE__ */ jsx$1("s-box", {
1189
+ inlineSize: "100%",
1190
+ children: /* @__PURE__ */ jsx$1("s-image", {
1191
+ aspectRatio: "1",
1192
+ src: image.src,
1193
+ srcSet: image.srcSet,
1194
+ alt: productName,
1195
+ inlineSize: "fill",
1196
+ border: "base",
1197
+ borderRadius: "small"
1198
+ })
1199
+ })
1200
+ }), /* @__PURE__ */ jsx$1("s-stack", {
1201
+ maxBlockSize: "50px",
1202
+ maxInlineSize: "100%",
1203
+ padding: "small-400 none none none",
1204
+ overflow: "hidden",
1205
+ children: /* @__PURE__ */ jsx$1("s-text", {
1206
+ type: "strong",
1207
+ color: "subdued",
1208
+ children: /* @__PURE__ */ jsx$1("s-link", {
1209
+ target: "_blank",
1210
+ tone: "neutral",
1211
+ href: targetUrl,
1212
+ onClick: trackClick,
1213
+ children: productName
1214
+ })
1215
+ })
1216
+ })]
1217
+ })
1218
+ });
1219
+ }
1220
+ //#endregion
1221
+ //#region src/components/RecommendationsWidget/RecommendationsOfferRow.tsx
1222
+ const PAGE_SIZE = 4;
1223
+ const PRODUCT_IMAGE_SOURCE_SIZE = 256;
1224
+ const RecommendationsOfferRow = ({ recommendations, padding }) => {
1225
+ return /* @__PURE__ */ jsx$1(RecommendationsPager, {
1226
+ recommendations: recommendations.filter((recommendation) => recommendation.offer.assets.length > 0),
1227
+ padding
1228
+ });
1229
+ };
1230
+ function RecommendationsPager({ recommendations, padding }) {
1231
+ const [page, setPage] = useState(0);
1232
+ const pageCount = Math.ceil(recommendations.length / PAGE_SIZE);
1233
+ const currentPage = Math.min(page, Math.max(pageCount - 1, 0));
1234
+ const pageRecommendations = recommendations.slice(currentPage * PAGE_SIZE, (currentPage + 1) * PAGE_SIZE);
1235
+ useEffect(() => {
1236
+ if (page !== currentPage) setPage(currentPage);
1237
+ }, [page, currentPage]);
1238
+ if (pageRecommendations.length === 0) return null;
1239
+ return /* @__PURE__ */ jsx$1("s-box", {
1240
+ padding,
1241
+ children: /* @__PURE__ */ jsxs("s-stack", {
1242
+ gap: "base",
1243
+ children: [/* @__PURE__ */ jsx$1("s-grid", {
1244
+ gridTemplateColumns: "repeat(4, minmax(0, 1fr))",
1245
+ gap: "small-200",
1246
+ children: pageRecommendations.map((recommendation) => /* @__PURE__ */ jsx$1("s-box", {
1247
+ inlineSize: "100%",
1248
+ children: /* @__PURE__ */ jsx$1(RecommendationsOfferRowTile, { recommendation })
1249
+ }, recommendation.id))
1250
+ }), pageCount > 1 && /* @__PURE__ */ jsxs("s-stack", {
1251
+ direction: "inline",
1252
+ justifyContent: "center",
1253
+ alignItems: "center",
1254
+ gap: "small-200",
1255
+ children: [
1256
+ /* @__PURE__ */ jsx$1("s-clickable", {
1257
+ accessibilityLabel: "Previous recommendations page",
1258
+ disabled: currentPage === 0,
1259
+ inlineSize: "32px",
1260
+ blockSize: "32px",
1261
+ border: "base",
1262
+ borderRadius: "base",
1263
+ onClick: () => setPage(currentPage - 1),
1264
+ children: /* @__PURE__ */ jsx$1("s-stack", {
1265
+ blockSize: "100%",
1266
+ alignItems: "center",
1267
+ justifyContent: "center",
1268
+ children: /* @__PURE__ */ jsx$1("s-icon", {
1269
+ type: "chevron-left",
1270
+ size: "small",
1271
+ tone: currentPage === 0 ? "neutral" : "auto"
1272
+ })
1273
+ })
1274
+ }),
1275
+ /* @__PURE__ */ jsxs("s-text", {
1276
+ type: "small",
1277
+ tone: "neutral",
1278
+ color: "base",
1279
+ children: [
1280
+ currentPage + 1,
1281
+ " / ",
1282
+ pageCount
1283
+ ]
1284
+ }),
1285
+ /* @__PURE__ */ jsx$1("s-clickable", {
1286
+ accessibilityLabel: "Next recommendations page",
1287
+ disabled: currentPage === pageCount - 1,
1288
+ inlineSize: "32px",
1289
+ blockSize: "32px",
1290
+ border: "base",
1291
+ borderRadius: "base",
1292
+ onClick: () => setPage(currentPage + 1),
1293
+ children: /* @__PURE__ */ jsx$1("s-stack", {
1294
+ blockSize: "100%",
1295
+ alignItems: "center",
1296
+ justifyContent: "center",
1297
+ children: /* @__PURE__ */ jsx$1("s-icon", {
1298
+ type: "chevron-right",
1299
+ size: "small",
1300
+ tone: currentPage === pageCount - 1 ? "neutral" : "auto"
1301
+ })
1302
+ })
1303
+ })
1304
+ ]
1305
+ })]
1306
+ })
1307
+ });
1308
+ }
1309
+ function RecommendationsOfferRowTile({ recommendation }) {
1310
+ const { track } = useEventTracker$1();
1311
+ const env = useDiscoEnv();
1312
+ const offerId = recommendation.offer.id;
1313
+ const advertiserId = recommendation.advertiser.id;
1314
+ const insertionId = recommendation.insertionId;
1315
+ useEffect(() => {
1316
+ track({
1317
+ type: "BRAND_DISPLAY",
1318
+ target: "SCROLLABLE_SLOT",
1319
+ brand: {
1320
+ offerId,
1321
+ advertiserId,
1322
+ insertionId
1323
+ }
1324
+ });
1325
+ }, [
1326
+ track,
1327
+ offerId,
1328
+ advertiserId,
1329
+ insertionId
1330
+ ]);
1331
+ const trackClick = () => {
1332
+ track({
1333
+ type: "BRAND_CLICK",
1334
+ target: "SCROLLABLE_SLOT_TILE",
1335
+ brand: {
1336
+ offerId,
1337
+ advertiserId,
1338
+ insertionId
1339
+ }
1340
+ });
1341
+ };
1342
+ const targetUrl = recommendation.offer.targetUrl;
1343
+ const productName = `${recommendation.offer.heading} ${recommendation.offer.subheading}`;
1344
+ const offerImageAsset = recommendation.offer.assets[0];
1345
+ if (!offerImageAsset) return null;
1346
+ return /* @__PURE__ */ jsx$1(ProductTile, {
1347
+ targetUrl,
1348
+ trackClick,
1349
+ image: getImageSources(offerImageAsset.imageUrl, {
1350
+ env,
1351
+ size: PRODUCT_IMAGE_SOURCE_SIZE
1352
+ }),
1353
+ productName
1354
+ });
1355
+ }
1356
+ //#endregion
1357
+ //#region src/components/RecommendationsWidget/Essential/index.tsx
1358
+ const EssentialRecommendationsWidget = ({ heroRecommendationGroup, scrollableRecommendationGroup }) => {
1359
+ const [showOfferSlot, setShowOfferSlot] = useState(!!heroRecommendationGroup);
1360
+ const { track } = useEventTracker$1();
1361
+ const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1362
+ useEffect(() => {
1363
+ track({ type: "WIDGET_LOAD" });
1364
+ track({ type: "WIDGET_DISPLAY" });
1365
+ }, [track]);
1366
+ const hideOfferSlot = () => setShowOfferSlot(false);
1367
+ const heading = applyCustomizationOrFallback("widget_bottom_slot_heading", "Trending brands we think you'll love");
1368
+ if (!showOfferSlot && !scrollableRecommendationGroup) return null;
1369
+ return /* @__PURE__ */ jsx$1(ScrollableSlotProvider, {
1370
+ scrollableRecommendationGroup,
1371
+ children: /* @__PURE__ */ jsxs(CardContainer, {
1372
+ background: "base",
1373
+ children: [
1374
+ showOfferSlot && heroRecommendationGroup ? /* @__PURE__ */ jsx$1("s-box", {
1375
+ border: "base",
1376
+ borderWidth: "none none base none",
1377
+ children: /* @__PURE__ */ jsx$1(HeroOfferProvider, {
1378
+ recommendationGroup: heroRecommendationGroup,
1379
+ children: /* @__PURE__ */ jsx$1(TrackedEssentialLayout, { onLastOffer: hideOfferSlot })
1380
+ })
1381
+ }) : /* @__PURE__ */ jsx$1("s-box", {
1382
+ padding: "base base none base",
1383
+ children: /* @__PURE__ */ jsx$1("s-heading", { children: heading })
1384
+ }),
1385
+ scrollableRecommendationGroup && /* @__PURE__ */ jsx$1("s-box", {
1386
+ padding: "base none",
1387
+ border: "base",
1388
+ borderWidth: "none none base none",
1389
+ children: /* @__PURE__ */ jsx$1(RecommendationsOfferRow, {
1390
+ recommendations: scrollableRecommendationGroup.recommendations,
1391
+ padding: "none base"
1392
+ })
1393
+ }),
1394
+ /* @__PURE__ */ jsx$1(Footer, {})
1395
+ ]
1396
+ })
1397
+ });
1398
+ };
1399
+ const TrackedEssentialLayout = ({ onLastOffer }) => {
1400
+ const { track } = useEventTracker$1();
1401
+ const { activeRecommendation } = useHeroOffer();
1402
+ const { insertionId, offer, advertiser } = activeRecommendation;
1403
+ useEffect(() => {
1404
+ track({
1405
+ type: "BRAND_DISPLAY",
1406
+ target: "INLINE_SLOT",
1407
+ brand: {
1408
+ offerId: offer.id,
1409
+ advertiserId: advertiser.id,
1410
+ insertionId
1411
+ }
1412
+ });
1413
+ }, [
1414
+ track,
1415
+ insertionId,
1416
+ offer.id,
1417
+ advertiser.id
1418
+ ]);
1419
+ return /* @__PURE__ */ jsx$1(EssentialLayoutType, { onLastOffer });
1420
+ };
1421
+ //#endregion
1422
+ //#region src/components/RecommendationsWidget/LeadGen/LeadGenHeader.tsx
1423
+ const LeadGenHeader = () => {
1424
+ const { claimedOffers } = useHeroOffer();
1425
+ const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1426
+ const hasClaimedAnOffer = claimedOffers.length > 0;
1427
+ const heading = applyCustomizationOrFallback("widget_heading", !hasClaimedAnOffer ? `Special offers just for you` : `Your special offer is claimed!`);
1428
+ const subheading = applyCustomizationOrFallback("widget_subheading", !hasClaimedAnOffer ? `As a thank you for your recent purchase` : "Discover more deals to save on top brands");
1429
+ return /* @__PURE__ */ jsxs("s-stack", {
1430
+ gap: "none",
1431
+ padding: "large-200",
1432
+ children: [/* @__PURE__ */ jsx$1("s-heading", { children: heading }), /* @__PURE__ */ jsx$1("s-text", {
1433
+ color: "subdued",
1434
+ children: subheading
1435
+ })]
1436
+ });
1437
+ };
1438
+ //#endregion
1439
+ //#region src/components/RecommendationsWidget/LeadGen/LeadGenBrand.tsx
1440
+ const LeadGenAssetTile = ({ asset }) => {
1441
+ const env = useDiscoEnv();
1442
+ const image = getImageSources(asset.imageUrl, {
1443
+ env,
1444
+ size: 400
1445
+ });
1446
+ return /* @__PURE__ */ jsx$1("s-image", {
1447
+ aspectRatio: "1",
1448
+ src: image.src,
1449
+ srcSet: image.srcSet,
1450
+ alt: "Offer product",
1451
+ inlineSize: "fill",
1452
+ border: "base",
1453
+ borderRadius: "base",
1454
+ loading: "lazy"
1455
+ });
1456
+ };
1457
+ const LeadGenBrandProducts = () => {
1458
+ const { activeRecommendation } = useHeroOffer();
1459
+ const assets = activeRecommendation.offer.assets.slice(0, 4);
1460
+ if (assets.length === 0) return null;
1461
+ return /* @__PURE__ */ jsx$1("s-query-container", { children: /* @__PURE__ */ jsx$1("s-grid", {
1462
+ gridTemplateColumns: "@container (inline-size > 450px) repeat(4, 1fr), repeat(3, 1fr)",
1463
+ gap: "small-200",
1464
+ children: assets.map((asset) => /* @__PURE__ */ jsx$1(LeadGenAssetTile, { asset }, asset.id))
1465
+ }) });
1466
+ };
1467
+ const LeadGenBrand = () => {
1468
+ const { activeRecommendation } = useHeroOffer();
1469
+ const { advertiser } = activeRecommendation;
1470
+ const env = useDiscoEnv();
1471
+ const logoSize = 56;
1472
+ const logo = getImageSources(advertiser.logoUrl, {
1473
+ env,
1474
+ size: logoSize
1475
+ });
1476
+ return /* @__PURE__ */ jsxs("s-stack", {
1477
+ gap: "small-200",
1478
+ padding: "base large-200",
1479
+ children: [/* @__PURE__ */ jsxs("s-grid", {
1480
+ gridTemplateColumns: `1fr ${logoSize}px`,
1481
+ gap: "small-200",
1482
+ alignItems: "start",
1483
+ children: [/* @__PURE__ */ jsxs("s-stack", {
1484
+ gap: "none",
1485
+ children: [/* @__PURE__ */ jsx$1("s-text", {
1486
+ type: "strong",
1487
+ children: advertiser.name
1488
+ }), /* @__PURE__ */ jsx$1("s-paragraph", { children: advertiser.description })]
1489
+ }), /* @__PURE__ */ jsx$1("s-box", {
1490
+ inlineSize: `${logoSize}px`,
1491
+ blockSize: `${logoSize}px`,
1492
+ children: /* @__PURE__ */ jsx$1("s-image", {
1493
+ aspectRatio: "1",
1494
+ src: logo.src,
1495
+ srcSet: logo.srcSet,
1496
+ alt: `${advertiser.name} logo`,
1497
+ inlineSize: "fill",
1498
+ border: "base",
1499
+ borderRadius: "max"
1500
+ })
1501
+ })]
1502
+ }), /* @__PURE__ */ jsx$1(LeadGenBrandProducts, {})]
1503
+ });
1504
+ };
1505
+ //#endregion
1506
+ //#region src/hooks/useResource.tsx
1507
+ const initialResource = {
1508
+ loading: false,
1509
+ error: false,
1510
+ data: null,
1511
+ headers: null
1512
+ };
1513
+ const useResource = (options, autoLoad = true, debug = false) => {
1514
+ const [shouldLoad, setShouldLoad] = useState(autoLoad);
1515
+ const [resource, setResource] = useState(initialResource);
1516
+ const reset = useCallback(() => {
1517
+ setResource(initialResource);
1518
+ setShouldLoad(false);
1519
+ }, []);
1520
+ const log = useCallback((...msg) => {
1521
+ if (debug) console.log(...msg);
1522
+ }, [debug]);
1523
+ const mounted = useRef(true);
1524
+ useEffect(() => {
1525
+ mounted.current = true;
1526
+ return () => {
1527
+ mounted.current = false;
1528
+ };
1529
+ }, []);
1530
+ const startLoad = useCallback(() => setShouldLoad(true), []);
1531
+ const load = useCallback(async () => {
1532
+ log("[uR]: Load called ");
1533
+ if (resource.loading || !shouldLoad || !options?.url) {
1534
+ log("[uR]: Load stopped ");
1535
+ return;
1536
+ }
1537
+ log("[uR]: Load started ");
1538
+ setShouldLoad(false);
1539
+ let resp;
1540
+ setResource({
1541
+ loading: true,
1542
+ error: false,
1543
+ data: null,
1544
+ headers: null
1545
+ });
1546
+ try {
1547
+ let reqOptions = {
1548
+ headers: { "Content-Type": "application/json" },
1549
+ method: "GET",
1550
+ ...options
1551
+ };
1552
+ if ((options?.method === "POST" || options?.method === "PUT") && options.data) reqOptions = {
1553
+ ...reqOptions,
1554
+ body: JSON.stringify(options.data)
1555
+ };
1556
+ resp = await fetch(options.url, reqOptions);
1557
+ if (resp.status !== 200 && resp.status !== 201) throw new Error("RESP_ERR");
1558
+ try {
1559
+ resp = await resp.json();
1560
+ } catch {
1561
+ throw new Error("JSON_ERR");
1562
+ }
1563
+ } catch (e) {
1564
+ if (typeof e === "string") {
1565
+ log(`[uR]: Load error! String => ${e}`);
1566
+ return;
1567
+ } else if (!(e instanceof Error)) {
1568
+ log(`[uR]: Load error! Unknown error =>`, e);
1569
+ return;
1570
+ }
1571
+ const { message: errMessage } = e;
1572
+ log(`[uR]: Load error! ${errMessage}`);
1573
+ if (mounted.current) return setResource({
1574
+ loading: false,
1575
+ error: errMessage === "RESP_ERR" || errMessage === "JSON_ERR" ? "An unknown error occured" : "Could not connect to the server",
1576
+ data: null
1577
+ });
1578
+ else return log("[uR]: Load error but NOT MOUNTED ");
1579
+ }
1580
+ if (mounted.current) {
1581
+ log("[uR]: Load complete:", resp);
1582
+ setResource({
1583
+ loading: false,
1584
+ error: false,
1585
+ data: resp,
1586
+ headers: null
1587
+ });
1588
+ } else log("[uR]: Load complete but NOT MOUNTED ");
1589
+ }, [
1590
+ options,
1591
+ resource.loading,
1592
+ shouldLoad,
1593
+ log
1594
+ ]);
1595
+ useEffect(() => {
1596
+ if (!resource.loading && shouldLoad) load();
1597
+ }, [
1598
+ resource.loading,
1599
+ shouldLoad,
1600
+ load
1601
+ ]);
1602
+ return [
1603
+ resource,
1604
+ startLoad,
1605
+ reset
1606
+ ];
1607
+ };
1608
+ //#endregion
1609
+ //#region src/hooks/useSendOfferEmail.ts
1610
+ const useSendOfferEmail = ({ shopGid, offerRemoteId, displayedOfferRemoteIds, sessionId }) => {
1611
+ const payload = usePayload();
1612
+ return useResource({
1613
+ url: getLeadGenRegisterUrl(useDiscoEnv()),
1614
+ method: "POST",
1615
+ data: {
1616
+ email: payload.buyerEmail,
1617
+ first_name: payload.billingFirstName || "",
1618
+ last_name: payload.billingLastName || "",
1619
+ shop_gid: shopGid,
1620
+ offer_id: offerRemoteId,
1621
+ displayed_offer_ids: displayedOfferRemoteIds,
1622
+ session_id: sessionId,
1623
+ shopify_order_id: shopifyOrderIdFormatter(payload.orderId || null)
1624
+ }
1625
+ }, false);
1626
+ };
1627
+ //#endregion
1628
+ //#region src/components/RecommendationsWidget/LeadGen/LeadGenActionButton.tsx
1629
+ function LeadGenActionButton() {
1630
+ const { activeRecommendation, isOfferClaimed, handleOfferClaim, recommendations } = useHeroOffer();
1631
+ const { track } = useEventTracker$1();
1632
+ const buttonText = useGetButtonText();
1633
+ const data = useRecommendationsData();
1634
+ const payload = usePayload();
1635
+ const [, sendOfferEmail] = useSendOfferEmail({
1636
+ shopGid: getShopIdentifier$1(payload.shopGid),
1637
+ displayedOfferRemoteIds: recommendations.map((recommendation) => recommendation.offer.id),
1638
+ offerRemoteId: activeRecommendation.offer.id,
1639
+ sessionId: data.sessionId
1640
+ });
1641
+ const handleClick = () => {
1642
+ track({
1643
+ type: "BRAND_CLICK",
1644
+ target: "INLINE_ACTION_BUTTON",
1645
+ brand: {
1646
+ offerId: activeRecommendation.offer.id,
1647
+ advertiserId: activeRecommendation.advertiser.id,
1648
+ insertionId: activeRecommendation.insertionId
1649
+ }
1650
+ });
1651
+ if (isOfferClaimed) return;
1652
+ if (payload.buyerEmail) sendOfferEmail();
1653
+ handleOfferClaim();
1654
+ };
1655
+ return /* @__PURE__ */ jsx$1("s-button", {
1656
+ href: activeRecommendation.offer.targetUrl,
1657
+ target: "_blank",
1658
+ inlineSize: "fill",
1659
+ variant: isOfferClaimed ? "secondary" : "primary",
1660
+ onClick: handleClick,
1661
+ children: buttonText
1662
+ }, "lead-action-button");
1663
+ }
1664
+ function useGetButtonText() {
1665
+ const { activeRecommendation, isOfferClaimed } = useHeroOffer();
1666
+ const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1667
+ if (activeRecommendation.offer.metadata.type === "NO_PROMO_CODE") {
1668
+ if (isOfferClaimed) return applyCustomizationOrFallback("widget_claimed_no_promo_cta_text", "Redeem onsite");
1669
+ return applyCustomizationOrFallback("widget_unclaimed_no_promo_cta_text", "Redeem onsite");
1670
+ }
1671
+ if (isOfferClaimed) return applyCustomizationOrFallback("widget_claimed_promo_cta_text", "Visit shop");
1672
+ return applyCustomizationOrFallback("widget_unclaimed_promo_cta_text", "Claim offer");
1673
+ }
1674
+ //#endregion
1675
+ //#region src/components/RecommendationsWidget/LeadGen/LeadGenOfferRow.tsx
1676
+ const LeadGenOfferRow = ({ recommendations }) => {
1677
+ const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1678
+ return /* @__PURE__ */ jsxs("s-stack", {
1679
+ gap: "small-200",
1680
+ padding: "base none",
1681
+ children: [/* @__PURE__ */ jsx$1("s-box", {
1682
+ padding: "none large-200",
1683
+ children: /* @__PURE__ */ jsx$1("s-text", {
1684
+ type: "strong",
1685
+ children: applyCustomizationOrFallback("widget_bottom_slot_heading", "Trending brands we think you'll love")
1686
+ })
1687
+ }), /* @__PURE__ */ jsx$1(RecommendationsOfferRow, {
1688
+ recommendations,
1689
+ padding: "small-400 large-200"
1690
+ })]
1691
+ });
1692
+ };
1693
+ //#endregion
1694
+ //#region src/components/RecommendationsWidget/LeadGen/index.tsx
1695
+ const LeadGen = ({ heroRecommendationGroup, scrollableRecommendationGroup }) => {
1696
+ const { track } = useEventTracker$1();
1697
+ useEffect(() => {
1698
+ track({ type: "WIDGET_LOAD" });
1699
+ track({ type: "WIDGET_DISPLAY" });
1700
+ }, [track]);
1701
+ return /* @__PURE__ */ jsxs(CardContainer, {
1702
+ background: "base",
1703
+ padding: "none none large-200 none",
1704
+ children: [
1705
+ heroRecommendationGroup && /* @__PURE__ */ jsxs(HeroOfferProvider, {
1706
+ recommendationGroup: heroRecommendationGroup,
1707
+ children: [
1708
+ /* @__PURE__ */ jsx$1(LeadGenHeader, {}),
1709
+ /* @__PURE__ */ jsx$1("s-divider", {}),
1710
+ /* @__PURE__ */ jsx$1("s-box", {
1711
+ minBlockSize: "230px",
1712
+ children: /* @__PURE__ */ jsx$1(LeadGenBrand, {})
1713
+ }),
1714
+ /* @__PURE__ */ jsxs("s-stack", {
1715
+ padding: "none large-200 large-200 large-200",
1716
+ gap: "base",
1717
+ children: [/* @__PURE__ */ jsx$1(LeadGenActionOffer, {}), /* @__PURE__ */ jsx$1(LeadGenActionNav, {})]
1718
+ }),
1719
+ /* @__PURE__ */ jsx$1("s-divider", {})
1720
+ ]
1721
+ }),
1722
+ scrollableRecommendationGroup && /* @__PURE__ */ jsx$1(LeadGenOfferRow, { recommendations: scrollableRecommendationGroup.recommendations }),
1723
+ /* @__PURE__ */ jsx$1(Footer, {})
1724
+ ]
1725
+ });
1726
+ };
1727
+ function LeadGenActionOffer() {
1728
+ const { activeRecommendation, isOfferClaimed } = useHeroOffer();
1729
+ const { heading, subheading, metadata } = activeRecommendation.offer;
1730
+ const primaryHeading = isOfferClaimed ? `You've got ${heading}` : heading;
1731
+ const secondaryHeading = isOfferClaimed && metadata.type === "PROMO_CODE" ? /* @__PURE__ */ jsxs(Fragment$1, { children: ["Use code: ", /* @__PURE__ */ jsx$1("s-text", {
1732
+ type: "strong",
1733
+ children: metadata.code
1734
+ })] }) : subheading || "On your next purchase";
1735
+ return /* @__PURE__ */ jsxs("s-stack", {
1736
+ padding: "base",
1737
+ background: "subdued",
1738
+ border: "base base dashed",
1739
+ borderRadius: "base",
1740
+ gap: "base",
1741
+ children: [/* @__PURE__ */ jsxs("s-stack", {
1742
+ gap: "none",
1743
+ children: [/* @__PURE__ */ jsx$1("s-heading", { children: primaryHeading }), /* @__PURE__ */ jsx$1("s-text", { children: secondaryHeading })]
1744
+ }), /* @__PURE__ */ jsx$1(LeadGenActionButton, {})]
1745
+ });
1746
+ }
1747
+ function LeadGenActionNav() {
1748
+ const { activeRecommendation, nextOffer, prevOffer, isFirstOffer, isLastOffer, isOfferClaimed, TOTAL_NUM_OFFERS } = useHeroOffer();
1749
+ const { track } = useEventTracker$1();
1750
+ const { applyCustomizationOrFallback } = useRecommendationsCustomization();
1751
+ if (TOTAL_NUM_OFFERS <= 1) return null;
1752
+ const showPrevious = !isFirstOffer;
1753
+ const showNext = !isLastOffer;
1754
+ const hasSingleButton = !showNext || !showPrevious;
1755
+ const trackNavigation = () => ({
1756
+ offerId: activeRecommendation.offer.id,
1757
+ advertiserId: activeRecommendation.advertiser.id,
1758
+ insertionId: activeRecommendation.insertionId
1759
+ });
1760
+ const handleNext = () => {
1761
+ track({
1762
+ type: "ELEMENT_CLICK",
1763
+ target: "INLINE_NAV_FORWARD",
1764
+ brand: trackNavigation()
1765
+ });
1766
+ nextOffer();
1767
+ };
1768
+ const handlePrevious = () => {
1769
+ track({
1770
+ type: "ELEMENT_CLICK",
1771
+ target: "INLINE_NAV_BACKWARD",
1772
+ brand: trackNavigation()
1773
+ });
1774
+ prevOffer();
1775
+ };
1776
+ return /* @__PURE__ */ jsxs("s-grid", {
1777
+ gridTemplateColumns: hasSingleButton ? "1fr" : "1fr 11px 1fr",
1778
+ gap: "base",
1779
+ children: [
1780
+ showPrevious && /* @__PURE__ */ jsx$1("s-button", {
1781
+ variant: !isOfferClaimed || showNext ? "secondary" : "primary",
1782
+ onClick: handlePrevious,
1783
+ children: applyCustomizationOrFallback("widget_nav_backward_cta_text", "Previous offer")
1784
+ }),
1785
+ !hasSingleButton && /* @__PURE__ */ jsx$1("s-box", {}),
1786
+ showNext && /* @__PURE__ */ jsx$1("s-button", {
1787
+ variant: isOfferClaimed ? "primary" : "secondary",
1788
+ onClick: handleNext,
1789
+ children: applyCustomizationOrFallback("widget_nav_forward_cta_text", showPrevious ? "Next offer" : "No thanks")
1790
+ })
1791
+ ]
1792
+ });
1793
+ }
1794
+ //#endregion
1795
+ //#region src/components/RecommendationsWidget/index.tsx
1796
+ const ESSENTIAL_LAYOUT_IDS = ["SHOPIFY_NATIVE_ESSENTIAL", "SHOPIFY_NATIVE_ESSENTIAL_0.22"];
1797
+ const Widget = () => {
1798
+ const recommendationsData = useRecommendationsData();
1799
+ const heroRecommendationGroup = recommendationsData.recommendationGroups.find((group) => group.slotContext === "HERO");
1800
+ const scrollableRecommendationGroup = recommendationsData.recommendationGroups.find((group) => group.slotContext === "SCROLLABLE");
1801
+ if (!heroRecommendationGroup && !scrollableRecommendationGroup) return null;
1802
+ const layoutId = recommendationsData.layoutId;
1803
+ if (ESSENTIAL_LAYOUT_IDS.includes(layoutId)) return /* @__PURE__ */ jsx$1(EssentialRecommendationsWidget, {
1804
+ heroRecommendationGroup,
1805
+ scrollableRecommendationGroup
1806
+ });
1807
+ if (layoutId === "SHOPIFY_NATIVE_COVER") {
1808
+ if (!heroRecommendationGroup) return null;
1809
+ return /* @__PURE__ */ jsx$1(CoverRecommendationsWidget, { heroRecommendationGroup });
1810
+ }
1811
+ return /* @__PURE__ */ jsx$1(LeadGen, {
1812
+ heroRecommendationGroup,
1813
+ scrollableRecommendationGroup
1814
+ });
1815
+ };
1816
+ //#endregion
1817
+ //#region src/DiscoRecommendations.tsx
1818
+ /**
1819
+ * Disco post-purchase recommendations for a Shopify UI extension.
1820
+ *
1821
+ * Render it from a `purchase.thank-you.block.render` or
1822
+ * `customer-account.order-status.block.render` target; the order and buyer
1823
+ * details are read from that target's API.
1824
+ */
1825
+ function DiscoRecommendations({ apiKey, ...source }) {
1826
+ return /* @__PURE__ */ jsx$1(Recommendations, {
1827
+ auth: { apiKey },
1828
+ ...source
1829
+ });
1830
+ }
1831
+ /**
1832
+ * The widget tree shared by the public (`apiKey`) and internal (`shop_gid`)
1833
+ * entry points.
1834
+ */
1835
+ function Recommendations({ auth, ...source }) {
1836
+ return /* @__PURE__ */ jsx$1(PayloadManager, { children: /* @__PURE__ */ jsx$1(DataManager, {
1837
+ auth,
1838
+ ...source,
1839
+ children: /* @__PURE__ */ jsx$1(UserManager, { children: /* @__PURE__ */ jsx$1(Widget, {}) })
1840
+ }) });
1841
+ }
1842
+ //#endregion
1843
+ //#region src/prepurchase/conf.ts
1844
+ /** Headers for every prepurchase request, identifying this SDK to the backend. */
1845
+ const PREPURCHASE_REQUEST_HEADERS = {
1846
+ "Content-Type": "application/json",
1847
+ "Disco-SDK-Name": SDK_IDENTITY.name,
1848
+ "Disco-SDK-Version": SDK_IDENTITY.version
1849
+ };
1850
+ function getPrepurchaseEndpoints(auth) {
1851
+ if ("apiKey" in auth) {
1852
+ const base = INTERNAL_BASE_URL.production;
1853
+ return {
1854
+ incentiveUrl: () => `${base}/api/prepurchase/incentive/`,
1855
+ orderUrl: () => `${base}/api/prepurchase/order/`,
1856
+ orderIntentUrl: () => `${base}/api/prepurchase/order-intent/`,
1857
+ eventUrl: `${base}/track/partners_event/prepurchase/`,
1858
+ headers: {
1859
+ ...PREPURCHASE_REQUEST_HEADERS,
1860
+ "x-api-key": auth.apiKey
1861
+ }
1862
+ };
1863
+ }
1864
+ const base = INTERNAL_BASE_URL[auth.env];
1865
+ return {
1866
+ incentiveUrl: (shopId) => `${base}/api/prepurchase/incentive/shop_gid/${shopId}/`,
1867
+ orderUrl: (shopId) => `${base}/api/prepurchase/order/shop_gid/${shopId}/`,
1868
+ orderIntentUrl: (shopId) => `${base}/api/prepurchase/order-intent/shop_gid/${shopId}/`,
1869
+ eventUrl: `${base}/track/partners_event/prepurchase/`,
1870
+ headers: { ...PREPURCHASE_REQUEST_HEADERS }
1871
+ };
1872
+ }
1873
+ //#endregion
1874
+ //#region src/prepurchase/context.ts
1875
+ const PrepurchaseEndpointsContext = createContext(null);
1876
+ /** Where every prepurchase request in this tree is sent, and how it authenticates. */
1877
+ function usePrepurchaseEndpoints() {
1878
+ const endpoints = useContext(PrepurchaseEndpointsContext);
1879
+ if (!endpoints) throw new Error("usePrepurchaseEndpoints must be used inside PrepurchaseProvider");
1880
+ return endpoints;
1881
+ }
1882
+ //#endregion
1883
+ //#region src/prepurchase/PrepurchaseProvider.tsx
1884
+ /**
1885
+ * Everything the prepurchase widgets read from above: where to send requests
1886
+ * and how to authenticate them, and the query client their requests are cached
1887
+ * in. One client per mounted widget, since each extension target runs in its
1888
+ * own worker anyway.
1889
+ */
1890
+ function PrepurchaseProvider({ auth, children }) {
1891
+ const [queryClient] = useState(() => new QueryClient());
1892
+ const endpoints = useMemo(() => getPrepurchaseEndpoints(auth), [auth]);
1893
+ return /* @__PURE__ */ jsx$1(PrepurchaseEndpointsContext.Provider, {
1894
+ value: endpoints,
1895
+ children: /* @__PURE__ */ jsx$1(QueryClientProvider, {
1896
+ client: queryClient,
1897
+ children
1898
+ })
1899
+ });
1900
+ }
1901
+ //#endregion
1902
+ //#region src/prepurchase/tracking/tracking-manager.tsx
1903
+ const TrackingManagerContext = createContext(null);
1904
+ function TrackingManager({ children, enabled = true, sessionId, trackingTicketId }) {
1905
+ const { eventUrl } = usePrepurchaseEndpoints();
1906
+ const dedupeRef = useRef(/* @__PURE__ */ new Set());
1907
+ const tracker = useMemo(() => ({ track(event) {
1908
+ if (!enabled || !sessionId) return;
1909
+ if (isDeduped(event, dedupeRef.current)) return;
1910
+ fetch(eventUrl, {
1911
+ method: "POST",
1912
+ headers: PREPURCHASE_REQUEST_HEADERS,
1913
+ keepalive: true,
1914
+ body: JSON.stringify(toBody(sessionId, trackingTicketId, event))
1915
+ }).catch((error) => {
1916
+ console.error("Event tracking failed:", error);
1917
+ });
1918
+ } }), [
1919
+ enabled,
1920
+ eventUrl,
1921
+ sessionId,
1922
+ trackingTicketId
1923
+ ]);
1924
+ return /* @__PURE__ */ jsx$1(TrackingManagerContext.Provider, {
1925
+ value: tracker,
1926
+ children
1927
+ });
1928
+ }
1929
+ function useEventTracker() {
1930
+ const ctx = useContext(TrackingManagerContext);
1931
+ if (!ctx) throw new Error("useEventTracker must be used inside TrackingManager");
1932
+ return ctx;
1933
+ }
1934
+ function isDeduped(event, dedupe) {
1935
+ if (event.type === "WIDGET_DISPLAY" || event.type === "WIDGET_VIEW" || event.type === "BRAND_DISPLAY" || event.type === "BRAND_VIEW") {
1936
+ const key = event.type + ("brand" in event ? event.brand.insertionId : "widget");
1937
+ if (dedupe.has(key)) return true;
1938
+ dedupe.add(key);
1939
+ }
1940
+ return false;
1941
+ }
1942
+ function toBody(sessionId, trackingTicketId, event) {
1943
+ const getBrandProperties = (brand) => {
1944
+ return {
1945
+ offer_id: brand.offerId,
1946
+ advertiser_id: brand.advertiserId,
1947
+ insertion_id: brand.insertionId
1948
+ };
1949
+ };
1950
+ const eventDatetime = /* @__PURE__ */ new Date();
1951
+ eventDatetime.setMilliseconds(0);
1952
+ const commonEventFields = {
1953
+ session_id: sessionId,
1954
+ tracking_ticket_id: trackingTicketId,
1955
+ event_name: event.type,
1956
+ event_datetime: eventDatetime.toISOString()
1957
+ };
1958
+ switch (event.type) {
1959
+ case "BRAND_CLICK": return {
1960
+ ...commonEventFields,
1961
+ brand_properties: getBrandProperties(event.brand),
1962
+ initiating_target: event.target
1963
+ };
1964
+ case "BRAND_DISPLAY":
1965
+ case "BRAND_VIEW": return {
1966
+ ...commonEventFields,
1967
+ brand_properties: getBrandProperties(event.brand),
1968
+ initiating_target: event.target
1969
+ };
1970
+ case "ELEMENT_CLICK": return {
1971
+ ...commonEventFields,
1972
+ brand_properties: event.brand ? getBrandProperties(event.brand) : void 0,
1973
+ initiating_target: event.target
1974
+ };
1975
+ default: return commonEventFields;
1976
+ }
1977
+ }
1978
+ //#endregion
1979
+ //#region ../../node_modules/.pnpm/@portabletext+toolkit@5.0.2/node_modules/@portabletext/toolkit/dist/index.js
1980
+ function isPortableTextSpan(node) {
1981
+ return node._type === "span" && "text" in node && typeof node.text == "string" && (node.marks === void 0 || Array.isArray(node.marks) && node.marks.every((mark) => typeof mark == "string"));
1982
+ }
1983
+ function isPortableTextBlock(node) {
1984
+ return typeof node._type == "string" && node._type[0] !== "@" && (!("markDefs" in node) || !node.markDefs || Array.isArray(node.markDefs) && node.markDefs.every((def) => typeof def._key == "string")) && "children" in node && Array.isArray(node.children) && node.children.every((child) => typeof child == "object" && "_type" in child);
1985
+ }
1986
+ function isPortableTextListItemBlock(block) {
1987
+ return isPortableTextBlock(block) && "listItem" in block && typeof block.listItem == "string" && (block.level === void 0 || typeof block.level == "number");
1988
+ }
1989
+ function isPortableTextToolkitList(block) {
1990
+ return block._type === "@list";
1991
+ }
1992
+ function isPortableTextToolkitSpan(span) {
1993
+ return span._type === "@span";
1994
+ }
1995
+ function isPortableTextToolkitTextNode(node) {
1996
+ return node._type === "@text";
1997
+ }
1998
+ const knownDecorators = [
1999
+ "strong",
2000
+ "em",
2001
+ "code",
2002
+ "underline",
2003
+ "strike-through"
2004
+ ];
2005
+ function sortMarksByOccurences(span, index, blockChildren) {
2006
+ if (!isPortableTextSpan(span) || !span.marks || !span.marks.length) return [];
2007
+ let marks = span.marks.slice(), occurences = {};
2008
+ return marks.forEach((mark) => {
2009
+ occurences[mark] = 1;
2010
+ for (let siblingIndex = index + 1; siblingIndex < blockChildren.length; siblingIndex++) {
2011
+ let sibling = blockChildren[siblingIndex];
2012
+ if (sibling && isPortableTextSpan(sibling) && Array.isArray(sibling.marks) && sibling.marks.indexOf(mark) !== -1) occurences[mark]++;
2013
+ else break;
2014
+ }
2015
+ }), marks.sort((markA, markB) => sortMarks(occurences, markA, markB));
2016
+ }
2017
+ function sortMarks(occurences, markA, markB) {
2018
+ let aOccurences = occurences[markA], bOccurences = occurences[markB];
2019
+ if (aOccurences !== bOccurences) return bOccurences - aOccurences;
2020
+ let aKnownPos = knownDecorators.indexOf(markA), bKnownPos = knownDecorators.indexOf(markB);
2021
+ return aKnownPos === bKnownPos ? markA.localeCompare(markB) : aKnownPos - bKnownPos;
2022
+ }
2023
+ function buildMarksTree(block) {
2024
+ let { children } = block, markDefs = block.markDefs ?? [];
2025
+ if (!children || !children.length) return [];
2026
+ let sortedMarks = children.map(sortMarksByOccurences), rootNode = {
2027
+ _type: "@span",
2028
+ children: [],
2029
+ markType: "<unknown>"
2030
+ }, nodeStack = [rootNode];
2031
+ for (let i = 0; i < children.length; i++) {
2032
+ let span = children[i];
2033
+ if (!span) continue;
2034
+ let marksNeeded = sortedMarks[i] || [], pos = 1;
2035
+ if (nodeStack.length > 1) for (; pos < nodeStack.length; pos++) {
2036
+ let mark = nodeStack[pos]?.markKey || "", index = marksNeeded.indexOf(mark);
2037
+ if (index === -1) break;
2038
+ marksNeeded.splice(index, 1);
2039
+ }
2040
+ nodeStack = nodeStack.slice(0, pos);
2041
+ let currentNode = nodeStack[nodeStack.length - 1];
2042
+ if (currentNode) {
2043
+ for (let markKey of marksNeeded) {
2044
+ let markDef = markDefs?.find((def) => def._key === markKey), node = {
2045
+ _type: "@span",
2046
+ _key: span._key,
2047
+ children: [],
2048
+ markDef,
2049
+ markType: markDef ? markDef._type : markKey,
2050
+ markKey
2051
+ };
2052
+ currentNode.children.push(node), nodeStack.push(node), currentNode = node;
2053
+ }
2054
+ if (isPortableTextSpan(span)) {
2055
+ let lines = span.text.split("\n");
2056
+ for (let line = lines.length; line-- > 1;) lines.splice(line, 0, "\n");
2057
+ currentNode.children = currentNode.children.concat(lines.map((text) => ({
2058
+ _type: "@text",
2059
+ text
2060
+ })));
2061
+ } else currentNode.children = currentNode.children.concat(span);
2062
+ }
2063
+ }
2064
+ return rootNode.children;
2065
+ }
2066
+ function nestLists(blocks, mode) {
2067
+ let tree = [], currentList;
2068
+ for (let i = 0; i < blocks.length; i++) {
2069
+ let block = blocks[i];
2070
+ if (block) {
2071
+ if (!isPortableTextListItemBlock(block)) {
2072
+ tree.push(block), currentList = void 0;
2073
+ continue;
2074
+ }
2075
+ if (!currentList) {
2076
+ currentList = listFromBlock(block, i, mode), tree.push(currentList);
2077
+ continue;
2078
+ }
2079
+ if (blockMatchesList(block, currentList)) {
2080
+ currentList.children.push(block);
2081
+ continue;
2082
+ }
2083
+ if ((block.level || 1) > currentList.level) {
2084
+ let newList = listFromBlock(block, i, mode);
2085
+ if (mode === "html") {
2086
+ let lastListItem = currentList.children[currentList.children.length - 1], newLastChild = {
2087
+ ...lastListItem,
2088
+ children: [...lastListItem.children, newList]
2089
+ };
2090
+ currentList.children[currentList.children.length - 1] = newLastChild;
2091
+ } else currentList.children.push(newList);
2092
+ currentList = newList;
2093
+ continue;
2094
+ }
2095
+ if ((block.level || 1) < currentList.level) {
2096
+ let matchingBranch = tree[tree.length - 1], match = matchingBranch && findListMatching(matchingBranch, block);
2097
+ if (match) {
2098
+ currentList = match, currentList.children.push(block);
2099
+ continue;
2100
+ }
2101
+ currentList = listFromBlock(block, i, mode), tree.push(currentList);
2102
+ continue;
2103
+ }
2104
+ if (block.listItem !== currentList.listItem) {
2105
+ let matchingBranch = tree[tree.length - 1], match = matchingBranch && findListMatching(matchingBranch, { level: block.level || 1 });
2106
+ if (match && match.listItem === block.listItem) {
2107
+ currentList = match, currentList.children.push(block);
2108
+ continue;
2109
+ } else {
2110
+ currentList = listFromBlock(block, i, mode), tree.push(currentList);
2111
+ continue;
2112
+ }
2113
+ }
2114
+ console.warn("Unknown state encountered for block", block), tree.push(block);
2115
+ }
2116
+ }
2117
+ return tree;
2118
+ }
2119
+ function blockMatchesList(block, list) {
2120
+ return (block.level || 1) === list.level && block.listItem === list.listItem;
2121
+ }
2122
+ function listFromBlock(block, index, mode) {
2123
+ return {
2124
+ _type: "@list",
2125
+ _key: `${block._key || `${index}`}-parent`,
2126
+ mode,
2127
+ level: block.level || 1,
2128
+ listItem: block.listItem,
2129
+ children: [block]
2130
+ };
2131
+ }
2132
+ function findListMatching(rootNode, matching) {
2133
+ let level = matching.level || 1, style = matching.listItem || "normal", filterOnType = typeof matching.listItem == "string";
2134
+ if (isPortableTextToolkitList(rootNode) && (rootNode.level || 1) === level && filterOnType && (rootNode.listItem || "normal") === style) return rootNode;
2135
+ if (!("children" in rootNode)) return;
2136
+ let node = rootNode.children[rootNode.children.length - 1];
2137
+ return node && !isPortableTextSpan(node) ? findListMatching(node, matching) : void 0;
2138
+ }
2139
+ function spanToPlainText(span) {
2140
+ let text = "";
2141
+ return span.children.forEach((current) => {
2142
+ isPortableTextToolkitTextNode(current) ? text += current.text : isPortableTextToolkitSpan(current) && (text += spanToPlainText(current));
2143
+ }), text;
2144
+ }
2145
+ //#endregion
2146
+ //#region ../../node_modules/.pnpm/@portabletext+react@6.2.0_@preact+compat@18.3.2_preact@10.29.8_/node_modules/@portabletext/react/dist/index.js
2147
+ const defaultLists = {
2148
+ number: ({ children }) => /* @__PURE__ */ jsx("ol", { children }),
2149
+ bullet: ({ children }) => /* @__PURE__ */ jsx("ul", { children })
2150
+ }, DefaultListItem = ({ children }) => /* @__PURE__ */ jsx("li", { children }), link = ({ children, value }) => /* @__PURE__ */ jsx("a", {
2151
+ href: value?.href,
2152
+ children
2153
+ }), underlineStyle = { textDecoration: "underline" }, defaultMarks = {
2154
+ em: ({ children }) => /* @__PURE__ */ jsx("em", { children }),
2155
+ strong: ({ children }) => /* @__PURE__ */ jsx("strong", { children }),
2156
+ code: ({ children }) => /* @__PURE__ */ jsx("code", { children }),
2157
+ underline: ({ children }) => /* @__PURE__ */ jsx("span", {
2158
+ style: underlineStyle,
2159
+ children
2160
+ }),
2161
+ "strike-through": ({ children }) => /* @__PURE__ */ jsx("del", { children }),
2162
+ link
2163
+ }, getTemplate = (type, prop) => `[@portabletext/react] Unknown ${type}, specify a component for it in the \`components.${prop}\` prop`, unknownTypeWarning = (typeName) => getTemplate(`block type "${typeName}"`, "types"), unknownMarkWarning = (markType) => getTemplate(`mark type "${markType}"`, "marks"), unknownBlockStyleWarning = (blockStyle) => getTemplate(`block style "${blockStyle}"`, "block"), unknownListStyleWarning = (listStyle) => getTemplate(`list style "${listStyle}"`, "list"), unknownListItemStyleWarning = (listStyle) => getTemplate(`list item style "${listStyle}"`, "listItem");
2164
+ function printWarning(message) {
2165
+ console.warn(message);
2166
+ }
2167
+ const hidden = { display: "none" }, defaultComponents = {
2168
+ types: {},
2169
+ block: {
2170
+ normal: ({ children }) => /* @__PURE__ */ jsx("p", { children }),
2171
+ blockquote: ({ children }) => /* @__PURE__ */ jsx("blockquote", { children }),
2172
+ h1: ({ children }) => /* @__PURE__ */ jsx("h1", { children }),
2173
+ h2: ({ children }) => /* @__PURE__ */ jsx("h2", { children }),
2174
+ h3: ({ children }) => /* @__PURE__ */ jsx("h3", { children }),
2175
+ h4: ({ children }) => /* @__PURE__ */ jsx("h4", { children }),
2176
+ h5: ({ children }) => /* @__PURE__ */ jsx("h5", { children }),
2177
+ h6: ({ children }) => /* @__PURE__ */ jsx("h6", { children })
2178
+ },
2179
+ marks: defaultMarks,
2180
+ list: defaultLists,
2181
+ listItem: DefaultListItem,
2182
+ hardBreak: () => /* @__PURE__ */ jsx("br", {}),
2183
+ unknownType: ({ value, isInline }) => {
2184
+ let warning = unknownTypeWarning(value._type);
2185
+ return jsx(isInline ? "span" : "div", {
2186
+ style: hidden,
2187
+ children: warning
2188
+ });
2189
+ },
2190
+ unknownMark: ({ markType, children }) => /* @__PURE__ */ jsx("span", {
2191
+ className: `unknown__pt__mark__${markType}`,
2192
+ children
2193
+ }),
2194
+ unknownList: ({ children }) => /* @__PURE__ */ jsx("ul", { children }),
2195
+ unknownListItem: ({ children }) => /* @__PURE__ */ jsx("li", { children }),
2196
+ unknownBlockStyle: ({ children }) => /* @__PURE__ */ jsx("p", { children })
2197
+ };
2198
+ function mergeComponents(parent, overrides) {
2199
+ let { block: _block, list: _list, listItem: _listItem, marks: _marks, types: _types, ...rest } = overrides;
2200
+ return {
2201
+ ...parent,
2202
+ block: mergeDeeply(parent, overrides, "block"),
2203
+ list: mergeDeeply(parent, overrides, "list"),
2204
+ listItem: mergeDeeply(parent, overrides, "listItem"),
2205
+ marks: mergeDeeply(parent, overrides, "marks"),
2206
+ types: mergeDeeply(parent, overrides, "types"),
2207
+ ...rest
2208
+ };
2209
+ }
2210
+ function mergeDeeply(parent, overrides, key) {
2211
+ let override = overrides[key], parentVal = parent[key];
2212
+ return typeof override == "function" || override && typeof parentVal == "function" ? override : override ? {
2213
+ ...parentVal,
2214
+ ...override
2215
+ } : parentVal;
2216
+ }
2217
+ function PortableText({ value: input, components: componentOverrides, listNestingMode, onMissingComponent: missingComponentHandler = printWarning }) {
2218
+ let handleMissingComponent = missingComponentHandler || noop, blocks;
2219
+ blocks = Array.isArray(input) ? input : input == null ? [] : [input];
2220
+ let nested = nestLists(blocks, listNestingMode || "html"), components = useMemo$1(() => componentOverrides ? mergeComponents(defaultComponents, componentOverrides) : defaultComponents, [componentOverrides]), renderNode = useMemo$1(() => getNodeRenderer(components, handleMissingComponent), [components, handleMissingComponent]);
2221
+ return /* @__PURE__ */ jsx(Fragment, { children: nested.map((node, index) => renderNode({
2222
+ node,
2223
+ index,
2224
+ isInline: !1,
2225
+ renderNode
2226
+ })) });
2227
+ }
2228
+ const getNodeRenderer = (components, handleMissingComponent) => {
2229
+ function renderNode(options) {
2230
+ let { node, index, isInline } = options, key = node._key || `node-${index}`;
2231
+ return isPortableTextToolkitList(node) ? renderList(node, index, key) : isPortableTextListItemBlock(node) ? renderListItem(node, index, key) : isPortableTextToolkitSpan(node) ? renderSpan(node, index, key) : hasCustomComponentForNode(node) ? renderCustomBlock(node, index, key, isInline) : isPortableTextBlock(node) ? renderBlock(node, index, key, isInline) : isPortableTextToolkitTextNode(node) ? renderText(node, key) : renderUnknownType(node, index, key, isInline);
2232
+ }
2233
+ function hasCustomComponentForNode(node) {
2234
+ return node._type in components.types;
2235
+ }
2236
+ function renderListItem(node, index, key) {
2237
+ let tree = serializeBlock({
2238
+ node,
2239
+ index,
2240
+ isInline: !1,
2241
+ renderNode
2242
+ }), renderer = components.listItem, Li = (typeof renderer == "function" ? renderer : renderer[node.listItem]) || components.unknownListItem;
2243
+ if (Li === components.unknownListItem) {
2244
+ let style = node.listItem || "bullet";
2245
+ handleMissingComponent(unknownListItemStyleWarning(style), {
2246
+ type: style,
2247
+ nodeType: "listItemStyle"
2248
+ });
2249
+ }
2250
+ let children = tree.children;
2251
+ if (node.style && node.style !== "normal") {
2252
+ let { listItem: _listItem, ...blockNode } = node;
2253
+ children = renderNode({
2254
+ node: blockNode,
2255
+ index,
2256
+ isInline: !1,
2257
+ renderNode
2258
+ });
2259
+ }
2260
+ return /* @__PURE__ */ jsx(Li, {
2261
+ value: node,
2262
+ index,
2263
+ isInline: !1,
2264
+ renderNode,
2265
+ children
2266
+ }, key);
2267
+ }
2268
+ function renderList(node, index, key) {
2269
+ let children = node.children.map((child, childIndex) => renderNode({
2270
+ node: child._key ? child : {
2271
+ ...child,
2272
+ _key: `li-${index}-${childIndex}`
2273
+ },
2274
+ index: childIndex,
2275
+ isInline: !1,
2276
+ renderNode
2277
+ })), component = components.list, List = (typeof component == "function" ? component : component[node.listItem]) || components.unknownList;
2278
+ if (List === components.unknownList) {
2279
+ let style = node.listItem || "bullet";
2280
+ handleMissingComponent(unknownListStyleWarning(style), {
2281
+ nodeType: "listStyle",
2282
+ type: style
2283
+ });
2284
+ }
2285
+ return /* @__PURE__ */ jsx(List, {
2286
+ value: node,
2287
+ index,
2288
+ isInline: !1,
2289
+ renderNode,
2290
+ children
2291
+ }, key);
2292
+ }
2293
+ function renderSpan(node, _index, key) {
2294
+ let { markDef, markType, markKey } = node, Span = components.marks[markType] || components.unknownMark, children = node.children.map((child, childIndex) => renderNode({
2295
+ node: child,
2296
+ index: childIndex,
2297
+ isInline: !0,
2298
+ renderNode
2299
+ }));
2300
+ return Span === components.unknownMark && handleMissingComponent(unknownMarkWarning(markType), {
2301
+ nodeType: "mark",
2302
+ type: markType
2303
+ }), /* @__PURE__ */ jsx(Span, {
2304
+ text: spanToPlainText(node),
2305
+ value: markDef,
2306
+ markType,
2307
+ markKey,
2308
+ renderNode,
2309
+ children
2310
+ }, key);
2311
+ }
2312
+ function renderBlock(node, index, key, isInline) {
2313
+ let { _key, ...props } = serializeBlock({
2314
+ node,
2315
+ index,
2316
+ isInline,
2317
+ renderNode
2318
+ }), style = props.node.style || "normal", Block = (typeof components.block == "function" ? components.block : components.block[style]) || components.unknownBlockStyle;
2319
+ return Block === components.unknownBlockStyle && handleMissingComponent(unknownBlockStyleWarning(style), {
2320
+ nodeType: "blockStyle",
2321
+ type: style
2322
+ }), /* @__PURE__ */ jsx(Block, {
2323
+ ...props,
2324
+ value: props.node,
2325
+ renderNode
2326
+ }, key);
2327
+ }
2328
+ function renderText(node, key) {
2329
+ if (node.text === "\n") {
2330
+ let HardBreak = components.hardBreak;
2331
+ return HardBreak ? /* @__PURE__ */ jsx(HardBreak, {}, key) : "\n";
2332
+ }
2333
+ return node.text;
2334
+ }
2335
+ function renderUnknownType(node, index, key, isInline) {
2336
+ let nodeOptions = {
2337
+ value: node,
2338
+ isInline,
2339
+ index,
2340
+ renderNode
2341
+ };
2342
+ handleMissingComponent(unknownTypeWarning(node._type), {
2343
+ nodeType: "block",
2344
+ type: node._type
2345
+ });
2346
+ let UnknownType = components.unknownType;
2347
+ return /* @__PURE__ */ jsx(UnknownType, { ...nodeOptions }, key);
2348
+ }
2349
+ function renderCustomBlock(node, index, key, isInline) {
2350
+ let nodeOptions = {
2351
+ value: node,
2352
+ isInline,
2353
+ index,
2354
+ renderNode
2355
+ }, Node = components.types[node._type];
2356
+ return Node ? /* @__PURE__ */ jsx(Node, { ...nodeOptions }, key) : null;
2357
+ }
2358
+ return renderNode;
2359
+ };
2360
+ function serializeBlock(options) {
2361
+ let { node, index, isInline, renderNode } = options, children = buildMarksTree(node).map((child, i) => renderNode({
2362
+ node: child,
2363
+ isInline: !0,
2364
+ index: i,
2365
+ renderNode
2366
+ }));
2367
+ return {
2368
+ _key: node._key || `block-${index}`,
2369
+ children,
2370
+ index,
2371
+ isInline,
2372
+ node
2373
+ };
2374
+ }
2375
+ function noop() {}
2376
+ //#endregion
2377
+ //#region src/prepurchase/portable-text-renderer.tsx
2378
+ /**
2379
+ * Bridges the caller's handlers to the interactive block components. This is the only
2380
+ * shared surface — per-node interaction state lives inside each component instance.
2381
+ */
2382
+ const PortableTextContext = createContext({});
2383
+ function appearanceProps(appearance) {
2384
+ return appearance === "subdued" ? { color: "subdued" } : { tone: appearance };
2385
+ }
2386
+ function NormalBlock({ children }) {
2387
+ const { appearance, paragraphType } = useContext(PortableTextContext);
2388
+ return /* @__PURE__ */ jsx$1("s-paragraph", {
2389
+ type: paragraphType,
2390
+ ...appearanceProps(appearance),
2391
+ children
2392
+ });
2393
+ }
2394
+ function BlockquoteBlock({ children }) {
2395
+ const { appearance, paragraphType } = useContext(PortableTextContext);
2396
+ return /* @__PURE__ */ jsx$1("s-paragraph", {
2397
+ type: paragraphType,
2398
+ ...appearanceProps(appearance),
2399
+ children: /* @__PURE__ */ jsx$1("s-text", {
2400
+ type: "emphasis",
2401
+ children
2402
+ })
2403
+ });
2404
+ }
2405
+ function StrongMark({ children }) {
2406
+ const { appearance } = useContext(PortableTextContext);
2407
+ return /* @__PURE__ */ jsx$1("s-text", {
2408
+ type: "strong",
2409
+ ...appearanceProps(appearance),
2410
+ children
2411
+ });
2412
+ }
2413
+ function EmphasisMark({ children }) {
2414
+ const { appearance } = useContext(PortableTextContext);
2415
+ return /* @__PURE__ */ jsx$1("s-text", {
2416
+ type: "emphasis",
2417
+ ...appearanceProps(appearance),
2418
+ children
2419
+ });
2420
+ }
2421
+ function LinkMark({ children, value }) {
2422
+ const { appearance } = useContext(PortableTextContext);
2423
+ return /* @__PURE__ */ jsx$1("s-link", {
2424
+ href: value?.href,
2425
+ target: "_blank",
2426
+ tone: appearance ? "neutral" : void 0,
2427
+ children
2428
+ });
2429
+ }
2430
+ function UnknownMark({ children }) {
2431
+ const { appearance } = useContext(PortableTextContext);
2432
+ return /* @__PURE__ */ jsx$1("s-text", {
2433
+ ...appearanceProps(appearance),
2434
+ children
2435
+ });
2436
+ }
2437
+ /**
2438
+ * Renders a `checkboxBlock` node as a <Checkbox>. The component owns its own
2439
+ * checked/error state; toggles are reported to the caller's `onChange` optimistically —
2440
+ * a rejected handler rolls the checkbox back and shows an error.
2441
+ */
2442
+ function CheckboxBlock({ value, index, renderNode }) {
2443
+ const { checkedByKey, onChange } = useContext(PortableTextContext).checkboxBlock ?? {};
2444
+ const externalChecked = checkedByKey?.[value._key];
2445
+ const [checked, setChecked] = useState(externalChecked ?? false);
2446
+ const [error, setError] = useState(void 0);
2447
+ useEffect(() => {
2448
+ if (externalChecked !== void 0) setChecked(externalChecked);
2449
+ }, [externalChecked]);
2450
+ async function handleChange(next) {
2451
+ const previousChecked = checked;
2452
+ setChecked(next);
2453
+ if (!onChange) return;
2454
+ setError(void 0);
2455
+ try {
2456
+ await onChange({
2457
+ key: value._key,
2458
+ checked: next
2459
+ });
2460
+ } catch {
2461
+ setChecked(previousChecked);
2462
+ setError("Something went wrong. Please try again.");
2463
+ }
2464
+ }
2465
+ const label = renderNode({
2466
+ node: {
2467
+ ...value,
2468
+ _type: "block"
2469
+ },
2470
+ index,
2471
+ isInline: false,
2472
+ renderNode
2473
+ });
2474
+ return createElement("s-checkbox", {
2475
+ checked,
2476
+ error,
2477
+ onChange: (event) => handleChange(event.currentTarget.checked ?? false)
2478
+ }, /* @__PURE__ */ jsx$1("s-text", {
2479
+ slot: "label",
2480
+ children: label
2481
+ }));
2482
+ }
2483
+ /**
2484
+ * The complete `_type` -> UI mapping. Static and module-level: interactive components
2485
+ * pull the caller's inputs from context and hold their own state, so this map is never
2486
+ * rebuilt. Includes safe fallbacks: the library's defaults for unknown marks/types/hard
2487
+ * breaks emit raw DOM (`<span>`, `<div>`, `<br>`), which would break the remote UI
2488
+ * reconciler.
2489
+ */
2490
+ const uiComponents = {
2491
+ block: {
2492
+ normal: NormalBlock,
2493
+ h1: ({ children }) => /* @__PURE__ */ jsx$1("s-heading", { children }),
2494
+ blockquote: BlockquoteBlock
2495
+ },
2496
+ marks: {
2497
+ strong: StrongMark,
2498
+ em: EmphasisMark,
2499
+ link: LinkMark
2500
+ },
2501
+ types: { checkboxBlock: CheckboxBlock },
2502
+ unknownMark: UnknownMark,
2503
+ unknownType: () => null,
2504
+ hardBreak: false
2505
+ };
2506
+ const gapBySpacing = {
2507
+ none: "none",
2508
+ extraTight: "small-400",
2509
+ tight: "small-200",
2510
+ base: "base",
2511
+ loose: "large-200",
2512
+ extraLoose: "large-500"
2513
+ };
2514
+ function PortableTextRenderer({ value, handlers, spacing = "base", appearance, type }) {
2515
+ const contextValue = useMemo(() => ({
2516
+ ...handlers ?? {},
2517
+ appearance,
2518
+ paragraphType: type
2519
+ }), [
2520
+ handlers,
2521
+ appearance,
2522
+ type
2523
+ ]);
2524
+ return /* @__PURE__ */ jsx$1(PortableTextContext.Provider, {
2525
+ value: contextValue,
2526
+ children: /* @__PURE__ */ jsx$1("s-stack", {
2527
+ gap: gapBySpacing[spacing],
2528
+ children: /* @__PURE__ */ jsx$1(PortableText, {
2529
+ value,
2530
+ components: uiComponents,
2531
+ onMissingComponent: false
2532
+ })
2533
+ })
2534
+ });
2535
+ }
2536
+ //#endregion
2537
+ //#region src/prepurchase/attribute.ts
2538
+ const ATTRIBUTE_KEY = "prepurchase_incentive_opted_in";
2539
+ const prepurchaseAttributeSchema = object({
2540
+ optedIn: boolean(),
2541
+ trackingTicketId: nullable(string()),
2542
+ idempotencyKey: nullable(string()),
2543
+ insertionId: nullable(string()),
2544
+ sessionId: optional(nullable(string()))
2545
+ });
2546
+ const DEFAULT_ATTRIBUTE = {
2547
+ optedIn: false,
2548
+ trackingTicketId: null,
2549
+ idempotencyKey: null,
2550
+ insertionId: null,
2551
+ sessionId: null
2552
+ };
2553
+ const encodePrepurchaseAttribute = (value) => JSON.stringify(value);
2554
+ const decodePrepurchaseAttribute = (raw) => {
2555
+ if (!raw) return DEFAULT_ATTRIBUTE;
2556
+ try {
2557
+ const parsed = prepurchaseAttributeSchema.safeParse(JSON.parse(raw));
2558
+ if (!parsed.success) return DEFAULT_ATTRIBUTE;
2559
+ return {
2560
+ optedIn: parsed.data.optedIn,
2561
+ trackingTicketId: parsed.data.trackingTicketId ?? null,
2562
+ idempotencyKey: parsed.data.idempotencyKey ?? null,
2563
+ insertionId: parsed.data.insertionId ?? null,
2564
+ sessionId: parsed.data.sessionId ?? null
2565
+ };
2566
+ } catch {
2567
+ return DEFAULT_ATTRIBUTE;
2568
+ }
2569
+ };
2570
+ //#endregion
2571
+ //#region src/prepurchase/hooks/usePrepurchaseOptIn.ts
2572
+ /** `_type` of the opt-in node in the partner's Portable Text content. */
2573
+ const CHECKBOX_BLOCK_TYPE = "checkboxBlock";
2574
+ function usePrepurchaseOptIn({ incentive, tracking_ticket_id, idempotency_key, session_id }) {
2575
+ const applyAttributeChange = useApplyAttributeChange();
2576
+ const { i18n } = useApi();
2577
+ const { track } = useEventTracker();
2578
+ const [rawAttribute] = useAttributeValues([ATTRIBUTE_KEY]);
2579
+ const stored = decodePrepurchaseAttribute(rawAttribute);
2580
+ const optedIn = stored.optedIn && stored.trackingTicketId === tracking_ticket_id;
2581
+ const [checked, setChecked] = useState(optedIn);
2582
+ const [error, setError] = useState(void 0);
2583
+ useEffect(() => {
2584
+ setChecked(optedIn);
2585
+ }, [optedIn]);
2586
+ const rewardAmount = incentive.reward.amount / 10 ** incentive.reward.scale;
2587
+ const rewardText = i18n.formatCurrency(rewardAmount, {
2588
+ currency: incentive.reward.currency,
2589
+ minimumFractionDigits: Number.isInteger(rewardAmount) ? 0 : 2
2590
+ });
2591
+ const rewardLabel = `${rewardText} Cash Back from this order`;
2592
+ const addedLabel = `${rewardText} Cash Back added`;
2593
+ const ctaLabel = `Get ${rewardText} cash back`;
2594
+ const yesCtaLabel = `Yes, get ${rewardText}`;
2595
+ const optInChoiceLabel = `Yes, get my ${rewardText} cash back`;
2596
+ const totalLabel = i18n.formatCurrency(checked ? rewardAmount : 0, { currency: incentive.reward.currency });
2597
+ const contentBlocks = useMemo(() => {
2598
+ const blocks = incentive.display.blocks;
2599
+ return Array.isArray(blocks) ? blocks.filter((block) => block._type !== CHECKBOX_BLOCK_TYPE) : blocks;
2600
+ }, [incentive.display.blocks]);
2601
+ const brandProperties = useMemo(() => ({
2602
+ offerId: crypto.randomUUID(),
2603
+ advertiserId: incentive.advertiser_id,
2604
+ insertionId: incentive.insertion_id
2605
+ }), [incentive.advertiser_id, incentive.insertion_id]);
2606
+ useEffect(() => {
2607
+ track({
2608
+ type: "BRAND_DISPLAY",
2609
+ target: "INLINE_SLOT",
2610
+ brand: brandProperties
2611
+ });
2612
+ }, [track, brandProperties]);
2613
+ const inFlightRef = useRef(null);
2614
+ const writeAttribute = useCallback(async (nextOptedIn) => {
2615
+ const value = encodePrepurchaseAttribute({
2616
+ optedIn: nextOptedIn,
2617
+ trackingTicketId: tracking_ticket_id,
2618
+ idempotencyKey: idempotency_key,
2619
+ insertionId: incentive.insertion_id,
2620
+ sessionId: session_id
2621
+ });
2622
+ if (value === rawAttribute || value === inFlightRef.current) return;
2623
+ inFlightRef.current = value;
2624
+ try {
2625
+ const result = await applyAttributeChange({
2626
+ type: "updateAttribute",
2627
+ key: ATTRIBUTE_KEY,
2628
+ value
2629
+ });
2630
+ if (result.type !== "success") {
2631
+ console.error(result.message);
2632
+ throw new Error(result.message);
2633
+ }
2634
+ } finally {
2635
+ inFlightRef.current = null;
2636
+ }
2637
+ }, [
2638
+ applyAttributeChange,
2639
+ tracking_ticket_id,
2640
+ idempotency_key,
2641
+ session_id,
2642
+ incentive.insertion_id,
2643
+ rawAttribute
2644
+ ]);
2645
+ return {
2646
+ checked,
2647
+ error,
2648
+ onToggle: useCallback(async (nextChecked) => {
2649
+ const previousChecked = checked;
2650
+ setChecked(nextChecked);
2651
+ setError(void 0);
2652
+ track({
2653
+ type: "ELEMENT_CLICK",
2654
+ target: nextChecked ? "OPT_IN" : "OPT_OUT",
2655
+ brand: brandProperties
2656
+ });
2657
+ try {
2658
+ await writeAttribute(nextChecked);
2659
+ } catch {
2660
+ setChecked(previousChecked);
2661
+ setError("Something went wrong. Please try again.");
2662
+ }
2663
+ }, [
2664
+ checked,
2665
+ track,
2666
+ brandProperties,
2667
+ writeAttribute
2668
+ ]),
2669
+ rewardText,
2670
+ rewardLabel,
2671
+ addedLabel,
2672
+ ctaLabel,
2673
+ yesCtaLabel,
2674
+ optInChoiceLabel,
2675
+ totalLabel,
2676
+ contentBlocks,
2677
+ logoUrl: incentive.display.logo_url
2678
+ };
2679
+ }
2680
+ //#endregion
2681
+ //#region src/prepurchase/components/checkout/shared.tsx
2682
+ /**
2683
+ * The pieces every prepurchase widget variant is built from. A variant composes these
2684
+ * and decides what to show when; none of them holds state, so behavior stays in
2685
+ * `usePrepurchaseOptIn` and layout differences stay in the variant.
2686
+ */
2687
+ /**
2688
+ * The opt-in control: a checkbox with the reward beside it.
2689
+ *
2690
+ * The default row lets the Polaris checkbox own its visible label. The emphasized form
2691
+ * gives the checkbox an accessible label and renders matching strong, clickable text
2692
+ * beside it, while the checked state still comes from the persisted checkout attribute.
2693
+ */
2694
+ function OptInCheckboxRow({ label, checked, onToggle, emphasized = false }) {
2695
+ if (emphasized) return /* @__PURE__ */ jsxs("s-stack", {
2696
+ direction: "inline",
2697
+ gap: "small-400",
2698
+ alignItems: "center",
2699
+ children: [/* @__PURE__ */ jsx$1("s-checkbox", {
2700
+ checked,
2701
+ accessibilityLabel: label,
2702
+ onChange: (event) => onToggle(event.currentTarget.checked ?? false)
2703
+ }), /* @__PURE__ */ jsx$1("s-clickable", {
2704
+ type: "button",
2705
+ onClick: () => onToggle(!checked),
2706
+ children: /* @__PURE__ */ jsx$1("s-text", {
2707
+ type: "strong",
2708
+ children: label
2709
+ })
2710
+ })]
2711
+ });
2712
+ return /* @__PURE__ */ jsx$1("s-checkbox", {
2713
+ checked,
2714
+ label,
2715
+ onChange: (event) => onToggle(event.currentTarget.checked ?? false)
2716
+ });
2717
+ }
2718
+ /** The ids of the two choices, which are also what `ChoiceList`'s values are compared against. */
2719
+ const OPT_IN_CHOICE = "yes";
2720
+ const OPT_OUT_CHOICE = "no";
2721
+ /**
2722
+ * The pair of radios the yes/no variants are built from, selected and answered by
2723
+ * whichever of them renders it.
2724
+ *
2725
+ * `ChoiceList` renders radios unless `multiple` is enabled. Its `values` prop keeps the
2726
+ * current radio synchronized with the persisted checkout attribute, including after a
2727
+ * failed write rolls the buyer back, while each choice's `defaultSelected` initializes
2728
+ * the selection before the custom element has finished upgrading.
2729
+ *
2730
+ * "No thanks" carries no reward text of its own — it answers a question posed above it — so a
2731
+ * variant using either wrapper below must name the offer itself, the way the button
2732
+ * variants do with `RewardHeading`. `optInLabel` restates the reward on the affirmative
2733
+ * choice, which is the one whose wording a buyer has to be sure of before selecting it.
2734
+ */
2735
+ function YesNoChoiceList({ label, optInLabel, value, onChange }) {
2736
+ const { target } = shopify.extension;
2737
+ return /* @__PURE__ */ jsxs("s-choice-list", {
2738
+ name: `prepurchase-opt-in-${target}`,
2739
+ values: [value],
2740
+ onChange: (event) => onChange(event.currentTarget.values?.[0] ?? ""),
2741
+ children: [/* @__PURE__ */ jsx$1("s-choice", {
2742
+ value: OPT_IN_CHOICE,
2743
+ defaultSelected: value === OPT_IN_CHOICE,
2744
+ children: optInLabel
2745
+ }), /* @__PURE__ */ jsx$1("s-choice", {
2746
+ value: OPT_OUT_CHOICE,
2747
+ defaultSelected: value === OPT_OUT_CHOICE,
2748
+ accessibilityLabel: `No thanks — ${label}`,
2749
+ children: "No thanks"
2750
+ })]
2751
+ });
2752
+ }
2753
+ /**
2754
+ * The opt-in control as a yes/no question, for the variants where taking the offer is
2755
+ * one-way: a pair of radios pinned to "No thanks".
2756
+ *
2757
+ * The value is hardcoded to the declining choice because the control only renders while
2758
+ * the buyer has not opted in — the one selection that changes that unmounts the whole
2759
+ * control, and a write that fails rolls the buyer back to exactly this state, so there
2760
+ * is no third state for a selection to hold.
2761
+ *
2762
+ * Selecting "No thanks" runs nothing. It is already the state on screen, so opting out here
2763
+ * would write an attribute saying the buyer declined where previously there was no
2764
+ * attribute at all, and would report an `OPT_OUT` click for a choice that changed
2765
+ * nothing — neither of which the buyer's tap actually did.
2766
+ */
2767
+ function OptInYesNoChoice({ label, optInLabel, onOptIn }) {
2768
+ return /* @__PURE__ */ jsx$1(YesNoChoiceList, {
2769
+ label,
2770
+ optInLabel,
2771
+ value: OPT_OUT_CHOICE,
2772
+ onChange: (value) => {
2773
+ if (value === OPT_IN_CHOICE) onOptIn();
2774
+ }
2775
+ });
2776
+ }
2777
+ /**
2778
+ * The same yes/no question as radios that behave like radios: the selection tracks the
2779
+ * opt-in and either choice writes it, so the buyer can move between them as often as
2780
+ * they like.
2781
+ *
2782
+ * Both directions go through the one toggle — the same call `OptInCheckboxRow` makes —
2783
+ * so declining after opting in writes the attribute the thank-you page reads and tracks
2784
+ * its `OPT_OUT`, rather than only clearing the radio on screen. Unlike
2785
+ * `OptInYesNoChoice` there is no state the control is already sitting in for the
2786
+ * decline to be a no-op against: while the buyer is opted in, "No thanks" is a real
2787
+ * change.
2788
+ */
2789
+ function OptInYesNoRadios({ label, optInLabel, checked, onToggle }) {
2790
+ return /* @__PURE__ */ jsx$1(YesNoChoiceList, {
2791
+ label,
2792
+ optInLabel,
2793
+ value: checked ? OPT_IN_CHOICE : OPT_OUT_CHOICE,
2794
+ onChange: (value) => onToggle(value === OPT_IN_CHOICE)
2795
+ });
2796
+ }
2797
+ /**
2798
+ * Sets the partner's logo beside the content it belongs to, as a trailing column of its own.
2799
+ *
2800
+ * Wraps rather than sits above so the logo marks everything it encloses — offer and terms
2801
+ * together read as the partner's — instead of only the row it adjoins. What a variant
2802
+ * leaves outside the wrapper stays full width beneath it, which is where a closing total
2803
+ * row belongs: inside, it would stop short of the right margin and leave its divider cut
2804
+ * off at the logo's edge.
2805
+ *
2806
+ * The logo trails the copy, so the buyer reads the offer first and the brand second, and
2807
+ * the checkbox keeps the left margin it has in every other variant — the column order is
2808
+ * the only thing separating this from a leading-logo layout.
2809
+ *
2810
+ * The column fixes the logo's size, since `Image` fills the space it's given. Square
2811
+ * logos keep the original compact treatment; wordmarks get a wider column and matching
2812
+ * aspect ratio so their lettering remains legible.
2813
+ *
2814
+ * The rounding is the `View`'s, not the image's: `Image` takes no `cornerRadius`, so the
2815
+ * corners have to be clipped by a wrapper that does — which is why it carries
2816
+ * `overflow="hidden"`, without which the radius is set but nothing is cut to it.
2817
+ *
2818
+ * `blockAlignment` must stay set to something — the value is a design choice, but the
2819
+ * default is not one of the options. A column left to default stretches to the row's full
2820
+ * height, so the wrapper's rounded bottom corners land at the foot of the terms copy, far
2821
+ * below the image, leaving the image's own square bottom edge on show while only its top
2822
+ * corners get clipped. Any explicit alignment shrinks the wrapper back onto the logo;
2823
+ * `center` then sets it against the middle of the offer and terms beside it.
2824
+ *
2825
+ * Renders the widget alone when there is no logo to show: the field is typed as always
2826
+ * present, but an `Image` with an empty source is a broken image in the checkout, which
2827
+ * is worse than the layout this variant is measured against.
2828
+ */
2829
+ function WithPartnerLogo({ source, children, format = "square", logoWidth }) {
2830
+ if (!source) return /* @__PURE__ */ jsx$1(Fragment$1, { children });
2831
+ const aspectRatio = format === "wordmark" ? "5/2" : "1";
2832
+ return /* @__PURE__ */ jsxs("s-grid", {
2833
+ gridTemplateColumns: typeof logoWidth === "object" ? `@container (inline-size > ${logoWidth.containerAbove}) 1fr ${logoWidth.wide}, 1fr ${logoWidth.narrow}` : `minmax(0, 1fr) ${logoWidth ?? (format === "wordmark" ? "128px" : "48px")}`,
2834
+ gap: "base",
2835
+ alignItems: "center",
2836
+ children: [children, /* @__PURE__ */ jsx$1("s-box", {
2837
+ borderRadius: "small",
2838
+ overflow: "hidden",
2839
+ children: /* @__PURE__ */ jsx$1("s-image", {
2840
+ src: source,
2841
+ alt: "Cash Back partner logo",
2842
+ aspectRatio,
2843
+ objectFit: "contain"
2844
+ })
2845
+ })]
2846
+ });
2847
+ }
2848
+ /**
2849
+ * A `logoWidth` for `wordmark` logos: full size in the desktop main column, smaller on a
2850
+ * phone. Checkout exposes no viewport, so this keys off the widget's own width, which
2851
+ * runs ~44px under the viewport: at most ~386px on a phone (430px viewport). The
2852
+ * two-column desktop main column measured under 500px, so the threshold sits just above
2853
+ * the widest phone. Only takes effect inside an `s-query-container` spanning the widget.
2854
+ */
2855
+ const RESPONSIVE_WORDMARK_WIDTH = {
2856
+ containerAbove: "400px",
2857
+ wide: "112px",
2858
+ narrow: "96px"
2859
+ };
2860
+ const RAKUTEN_WORDMARK_URL = "https://static.rakuten.com/static/svg/rakuten/rak-logo-brand-v1.svg";
2861
+ /**
2862
+ * The logo for a `wordmark`-format `WithPartnerLogo`. Rakuten's incentive logo is its
2863
+ * square mark, which reads poorly at wordmark width, so it's swapped for the full
2864
+ * wordmark; any other partner's logo is used as served.
2865
+ */
2866
+ function partnerWordmarkSource(logoUrl) {
2867
+ return logoUrl.includes("static.rakuten.com") ? RAKUTEN_WORDMARK_URL : logoUrl;
2868
+ }
2869
+ /**
2870
+ * The reward, stated as a heading. For variants whose control carries no label of its
2871
+ * own — a button says what it does, not what's on offer — this is what names the offer.
2872
+ */
2873
+ function RewardHeading({ label }) {
2874
+ return /* @__PURE__ */ jsx$1("s-text", {
2875
+ type: "strong",
2876
+ children: label
2877
+ });
2878
+ }
2879
+ /**
2880
+ * The opt-in, once taken. Replaces the control in the variants where opting in is
2881
+ * one-way, so it only ever renders for a buyer who is already opted in — which is why
2882
+ * `success` is hardcoded rather than derived from the opt-in state.
2883
+ */
2884
+ function OptInConfirmation({ label }) {
2885
+ return /* @__PURE__ */ jsxs("s-stack", {
2886
+ direction: "inline",
2887
+ gap: "small-400",
2888
+ alignItems: "center",
2889
+ children: [/* @__PURE__ */ jsx$1("s-icon", {
2890
+ type: "check-circle",
2891
+ tone: "success"
2892
+ }), /* @__PURE__ */ jsx$1("s-text", {
2893
+ type: "strong",
2894
+ tone: "success",
2895
+ children: label
2896
+ })]
2897
+ });
2898
+ }
2899
+ /**
2900
+ * Takes the opt-in back, for the variants that let the buyer reverse it.
2901
+ *
2902
+ * Sits below the copy rather than beside the confirmation, so the buyer reads what the
2903
+ * offer is worth before the way out is in reach — the variant places it, including
2904
+ * which margin it sits on. Small and quiet on purpose: the confirmation is the outcome
2905
+ * the buyer wanted, and this is only the way back.
2906
+ *
2907
+ * A `Link` rather than a `Button`, so it can't compete with a variant's call to action
2908
+ * for the same tap.
2909
+ *
2910
+ * The variant supplies the wording, and how quiet the link is, where the defaults read
2911
+ * wrong against the control above it — nothing smaller than `extraSmall`, which is the
2912
+ * floor for a tap target this text still has to be legible as. The accessibility label
2913
+ * stays fixed on the action instead of the wording, so what the link does is stated the
2914
+ * same way whatever it is captioned or sized.
2915
+ */
2916
+ function OptInUndoLink({ label = "No thanks", onPress }) {
2917
+ return /* @__PURE__ */ jsx$1("s-link", {
2918
+ onClick: onPress,
2919
+ accessibilityLabel: "Remove Cash Back from this order",
2920
+ children: /* @__PURE__ */ jsx$1("s-text", {
2921
+ type: "small",
2922
+ children: label
2923
+ })
2924
+ });
2925
+ }
2926
+ /**
2927
+ * A failed attribute write. `Checkbox`'s own `error` would render inside the narrow
2928
+ * first column of the row above, so it's surfaced as its own line instead.
2929
+ */
2930
+ function OptInError({ message }) {
2931
+ return /* @__PURE__ */ jsx$1("s-text", {
2932
+ tone: "critical",
2933
+ type: "small",
2934
+ children: message
2935
+ });
2936
+ }
2937
+ /**
2938
+ * The running total for this order, closing out the widget.
2939
+ *
2940
+ * Owns its divider so a variant can't render the section without the rule that
2941
+ * separates it from the copy above. The icon and both labels turn green once the buyer
2942
+ * has opted in, so the row reads as earned rather than as a static footer — `success`
2943
+ * is the theme's positive color, the only green available here since these primitives
2944
+ * don't accept raw colors.
2945
+ */
2946
+ function TotalCashBack({ total, earned }) {
2947
+ const tone = earned ? "success" : void 0;
2948
+ const color = earned ? void 0 : "subdued";
2949
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx$1("s-divider", {}), /* @__PURE__ */ jsxs("s-grid", {
2950
+ gridTemplateColumns: "1fr auto",
2951
+ alignItems: "center",
2952
+ children: [/* @__PURE__ */ jsxs("s-stack", {
2953
+ direction: "inline",
2954
+ gap: "small-400",
2955
+ alignItems: "center",
2956
+ children: [/* @__PURE__ */ jsx$1("s-icon", {
2957
+ type: "cash-dollar",
2958
+ tone: earned ? "success" : "neutral"
2959
+ }), /* @__PURE__ */ jsx$1("s-text", {
2960
+ type: "strong",
2961
+ tone,
2962
+ color,
2963
+ children: "TOTAL CASH BACK"
2964
+ })]
2965
+ }), /* @__PURE__ */ jsx$1("s-text", {
2966
+ type: "strong",
2967
+ tone,
2968
+ color,
2969
+ children: total
2970
+ })]
2971
+ })] });
2972
+ }
2973
+ //#endregion
2974
+ //#region src/prepurchase/components/checkout/inline-checkbox.tsx
2975
+ /**
2976
+ * The `inline_checkbox` variant — the shipping widget.
2977
+ *
2978
+ * The checkbox is always on screen: after opting in it stays, checked, and the buyer
2979
+ * can uncheck it to opt back out. Contrast `inline_checkbox_confirmation`, where
2980
+ * opting in replaces the control outright.
2981
+ */
2982
+ function InlineCheckboxWidget(props) {
2983
+ const { checked, error, onToggle, rewardLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
2984
+ return /* @__PURE__ */ jsxs("s-stack", {
2985
+ gap: "small-200",
2986
+ children: [
2987
+ /* @__PURE__ */ jsx$1(OptInCheckboxRow, {
2988
+ label: rewardLabel,
2989
+ checked,
2990
+ onToggle
2991
+ }),
2992
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
2993
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
2994
+ value: contentBlocks,
2995
+ spacing: "tight"
2996
+ }),
2997
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
2998
+ total: totalLabel,
2999
+ earned: checked
3000
+ })
3001
+ ]
3002
+ });
3003
+ }
3004
+ //#endregion
3005
+ //#region src/prepurchase/components/checkout/inline-checkbox-with-logo.tsx
3006
+ /**
3007
+ * The `inline_checkbox_with_logo` variant.
3008
+ *
3009
+ * `inline_checkbox` — the same always-on checkbox the buyer can toggle back off — with
3010
+ * the partner's logo leading the widget as a column of its own. The logo is the only
3011
+ * difference between the two, so the pair isolates what showing a brand the buyer
3012
+ * already recognizes does to opt-in, uncrossed with any change to the control itself.
3013
+ */
3014
+ function InlineCheckboxWithLogoWidget(props) {
3015
+ const { checked, error, onToggle, rewardLabel, totalLabel, contentBlocks, logoUrl } = usePrepurchaseOptIn(props);
3016
+ return /* @__PURE__ */ jsxs("s-stack", {
3017
+ gap: "small-200",
3018
+ children: [/* @__PURE__ */ jsx$1(WithPartnerLogo, {
3019
+ source: logoUrl,
3020
+ children: /* @__PURE__ */ jsxs("s-stack", {
3021
+ gap: "small-200",
3022
+ children: [
3023
+ /* @__PURE__ */ jsx$1(OptInCheckboxRow, {
3024
+ label: rewardLabel,
3025
+ checked,
3026
+ onToggle,
3027
+ emphasized: true
3028
+ }),
3029
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3030
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3031
+ value: contentBlocks,
3032
+ spacing: "tight",
3033
+ appearance: "subdued"
3034
+ })
3035
+ ]
3036
+ })
3037
+ }), /* @__PURE__ */ jsx$1(TotalCashBack, {
3038
+ total: totalLabel,
3039
+ earned: checked
3040
+ })]
3041
+ });
3042
+ }
3043
+ //#endregion
3044
+ //#region src/prepurchase/components/checkout/inline-checkbox-logo-card.tsx
3045
+ /**
3046
+ * The screenshot-inspired, standalone checkbox offer card. It intentionally omits
3047
+ * tiers, recommendations and the separate total row; the amount and legal copy still
3048
+ * come from the eligible incentive response rather than from the reference image.
3049
+ * Opt-in, rollback and tracking remain shared with the other checkout variants.
3050
+ */
3051
+ function InlineCheckboxLogoCardWidget(props) {
3052
+ const { checked, error, onToggle, rewardText, contentBlocks } = usePrepurchaseOptIn(props);
3053
+ const offerLabel = `Get ${rewardText} Cash Back with`;
3054
+ return /* @__PURE__ */ jsx$1("s-box", {
3055
+ border: "base",
3056
+ borderRadius: "large",
3057
+ padding: "base",
3058
+ children: /* @__PURE__ */ jsxs("s-stack", {
3059
+ gap: "small-400",
3060
+ children: [/* @__PURE__ */ jsxs("s-stack", {
3061
+ direction: "inline",
3062
+ columnGap: "none",
3063
+ rowGap: "small-200",
3064
+ alignItems: "center",
3065
+ justifyContent: "start",
3066
+ children: [/* @__PURE__ */ jsx$1("s-checkbox", {
3067
+ checked,
3068
+ label: offerLabel,
3069
+ accessibilityLabel: `${offerLabel} Rakuten`,
3070
+ onChange: (event) => onToggle(event.currentTarget.checked ?? false)
3071
+ }), /* @__PURE__ */ jsx$1("s-box", {
3072
+ inlineSize: "80px",
3073
+ children: /* @__PURE__ */ jsx$1("s-image", {
3074
+ src: RAKUTEN_WORDMARK_URL,
3075
+ alt: "",
3076
+ aspectRatio: "4/1",
3077
+ objectFit: "contain",
3078
+ inlineSize: "fill"
3079
+ })
3080
+ })]
3081
+ }), /* @__PURE__ */ jsxs("s-stack", {
3082
+ gap: "small-200",
3083
+ children: [error && /* @__PURE__ */ jsx$1(OptInError, { message: error }), /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3084
+ value: contentBlocks,
3085
+ spacing: "tight",
3086
+ appearance: "subdued",
3087
+ type: "small"
3088
+ })]
3089
+ })]
3090
+ })
3091
+ });
3092
+ }
3093
+ //#endregion
3094
+ //#region src/prepurchase/components/checkout/inline-checkbox-confirmation.tsx
3095
+ /**
3096
+ * The `inline_checkbox_confirmation` variant.
3097
+ *
3098
+ * Opting in swaps the checkbox out for a green confirmation, and the swap is one-way:
3099
+ * the control unmounts and nothing takes its place that can write the attribute back,
3100
+ * so within this checkout the opt-in is final. Contrast `inline_checkbox`, where the
3101
+ * control persists and stays togglable.
3102
+ */
3103
+ function InlineCheckboxConfirmationWidget(props) {
3104
+ const { checked, error, onToggle, rewardLabel, addedLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3105
+ return /* @__PURE__ */ jsxs("s-stack", {
3106
+ gap: "small-200",
3107
+ children: [
3108
+ checked ? /* @__PURE__ */ jsx$1(OptInConfirmation, { label: addedLabel }) : /* @__PURE__ */ jsx$1(OptInCheckboxRow, {
3109
+ label: rewardLabel,
3110
+ checked,
3111
+ onToggle
3112
+ }),
3113
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3114
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3115
+ value: contentBlocks,
3116
+ spacing: "tight"
3117
+ }),
3118
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3119
+ total: totalLabel,
3120
+ earned: checked
3121
+ })
3122
+ ]
3123
+ });
3124
+ }
3125
+ //#endregion
3126
+ //#region src/prepurchase/components/checkout/inline-button-confirmation.tsx
3127
+ /**
3128
+ * The `inline_button_confirmation` variant.
3129
+ *
3130
+ * Same one-way opt-in as `inline_checkbox_confirmation`, and the same swap: the
3131
+ * heading turns into the confirmation. What differs is the control — a button below
3132
+ * the partner's copy rather than a checkbox above it, so the buyer reads the offer and
3133
+ * the terms before acting — and that the button simply goes away once used, leaving
3134
+ * the confirmed offer and its total.
3135
+ *
3136
+ * The reward is a heading of its own here rather than the control's label: a checkbox
3137
+ * is labelled with what's on offer, but a button is labelled with the action, so
3138
+ * without the heading nothing would name the offer above the copy.
3139
+ */
3140
+ function InlineButtonConfirmationWidget(props) {
3141
+ const { checked, error, onToggle, rewardLabel, addedLabel, ctaLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3142
+ return /* @__PURE__ */ jsxs("s-stack", {
3143
+ gap: "small-200",
3144
+ children: [
3145
+ checked ? /* @__PURE__ */ jsx$1(OptInConfirmation, { label: addedLabel }) : /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3146
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3147
+ value: contentBlocks,
3148
+ spacing: "tight"
3149
+ }),
3150
+ !checked && /* @__PURE__ */ jsx$1("s-button", {
3151
+ tone: "neutral",
3152
+ onClick: () => onToggle(true),
3153
+ children: ctaLabel
3154
+ }),
3155
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3156
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3157
+ total: totalLabel,
3158
+ earned: checked
3159
+ })
3160
+ ]
3161
+ });
3162
+ }
3163
+ //#endregion
3164
+ //#region src/prepurchase/components/checkout/inline-radio-confirmation.tsx
3165
+ /**
3166
+ * The `inline_radio_confirmation` variant.
3167
+ *
3168
+ * The same one-way opt-in as the other confirmation variants, asked as a question: the
3169
+ * offer is stated as a heading and answered with a pair of radios that starts on "No
3170
+ * thanks". Taking the offer sends both radios with it — there is no control left to
3171
+ * answer the question a second time — leaving the confirmation in their place.
3172
+ *
3173
+ * What this isolates against `inline_checkbox_confirmation` is the cost of declining: an
3174
+ * unchecked box is the buyer doing nothing, while "No thanks" is a choice they have to
3175
+ * make on the record before the checkout will look settled.
3176
+ *
3177
+ * "No thanks" is inert, not an opt-out — see `OptInYesNoChoice`. It is where the control
3178
+ * already sits, including after a failed write rolls the buyer back.
3179
+ */
3180
+ function InlineRadioConfirmationWidget(props) {
3181
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, addedLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3182
+ return /* @__PURE__ */ jsxs("s-stack", {
3183
+ gap: "small-200",
3184
+ children: [
3185
+ checked ? /* @__PURE__ */ jsx$1(OptInConfirmation, { label: addedLabel }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }), /* @__PURE__ */ jsx$1(OptInYesNoChoice, {
3186
+ label: rewardLabel,
3187
+ optInLabel: optInChoiceLabel,
3188
+ onOptIn: () => onToggle(true)
3189
+ })] }),
3190
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3191
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3192
+ value: contentBlocks,
3193
+ spacing: "tight"
3194
+ }),
3195
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3196
+ total: totalLabel,
3197
+ earned: checked
3198
+ })
3199
+ ]
3200
+ });
3201
+ }
3202
+ //#endregion
3203
+ //#region src/prepurchase/components/checkout/inline-checkbox-confirmation-undo.tsx
3204
+ /**
3205
+ * The `inline_checkbox_confirmation_undo` variant.
3206
+ *
3207
+ * `inline_checkbox_confirmation` — the checkbox swapped out for a green confirmation —
3208
+ * with the swap no longer one-way: a "No thanks" link below the copy brings the
3209
+ * checkbox back, unchecked, and writes the opt-out. It pairs against that variant to
3210
+ * measure what an unmistakable way out is worth on a control the buyer otherwise can't
3211
+ * take back, and against `inline_checkbox`, where the way out is the same box they
3212
+ * checked and nothing announces it.
3213
+ *
3214
+ * Undoing is not a dead end either: the checkbox that returns opts back in, so the
3215
+ * buyer can cross between the two states as often as they like.
3216
+ */
3217
+ function InlineCheckboxConfirmationUndoWidget(props) {
3218
+ const { checked, error, onToggle, rewardLabel, addedLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3219
+ return /* @__PURE__ */ jsxs("s-stack", {
3220
+ gap: "small-200",
3221
+ children: [
3222
+ checked ? /* @__PURE__ */ jsx$1(OptInConfirmation, { label: addedLabel }) : /* @__PURE__ */ jsx$1(OptInCheckboxRow, {
3223
+ label: rewardLabel,
3224
+ checked,
3225
+ onToggle
3226
+ }),
3227
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3228
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3229
+ value: contentBlocks,
3230
+ spacing: "tight"
3231
+ }),
3232
+ checked && /* @__PURE__ */ jsx$1("s-stack", {
3233
+ alignItems: "end",
3234
+ children: /* @__PURE__ */ jsx$1(OptInUndoLink, { onPress: () => onToggle(false) })
3235
+ }),
3236
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3237
+ total: totalLabel,
3238
+ earned: checked
3239
+ })
3240
+ ]
3241
+ });
3242
+ }
3243
+ //#endregion
3244
+ //#region src/prepurchase/components/checkout/inline-button-confirmation-decline.tsx
3245
+ /**
3246
+ * The `inline_button_confirmation_decline` variant.
3247
+ *
3248
+ * `inline_button_confirmation` with a "No thanks" button set beside the call to action.
3249
+ * The opt-in path is unchanged — the same one-way toggle, the same confirmation in the
3250
+ * heading's place, the same pair of buttons unmounting once it is taken — so the pair
3251
+ * isolates what putting a way to decline next to the offer does to the offer's uptake.
3252
+ *
3253
+ * Declining is deliberately inert: it writes nothing, opts nobody out, and leaves the
3254
+ * widget exactly as it is. A buyer who means it simply moves on with the checkout, and
3255
+ * the exposure row for this variant plus an absent opt-in already says so. Should the
3256
+ * decline need to be recorded, it wants a real `OPT_OUT` toggle rather than an `onPress`
3257
+ * added here for the tracking alone — the attribute and the event are written together
3258
+ * in `usePrepurchaseOptIn`, and splitting them is how the two start disagreeing.
3259
+ */
3260
+ function InlineButtonConfirmationDeclineWidget(props) {
3261
+ const { checked, error, onToggle, rewardLabel, addedLabel, yesCtaLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3262
+ return /* @__PURE__ */ jsxs("s-stack", {
3263
+ gap: "small-200",
3264
+ children: [
3265
+ checked ? /* @__PURE__ */ jsx$1(OptInConfirmation, { label: addedLabel }) : /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3266
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3267
+ value: contentBlocks,
3268
+ spacing: "tight"
3269
+ }),
3270
+ !checked && /* @__PURE__ */ jsxs("s-grid", {
3271
+ gridTemplateColumns: "1fr auto",
3272
+ gap: "base",
3273
+ alignItems: "center",
3274
+ children: [/* @__PURE__ */ jsx$1("s-button", {
3275
+ tone: "neutral",
3276
+ onClick: () => onToggle(true),
3277
+ children: yesCtaLabel
3278
+ }), /* @__PURE__ */ jsx$1("s-button", {
3279
+ variant: "secondary",
3280
+ tone: "neutral",
3281
+ children: "No thanks"
3282
+ })]
3283
+ }),
3284
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3285
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3286
+ total: totalLabel,
3287
+ earned: checked
3288
+ })
3289
+ ]
3290
+ });
3291
+ }
3292
+ //#endregion
3293
+ //#region src/prepurchase/components/checkout/inline-radio-confirmation-undo.tsx
3294
+ /**
3295
+ * The `inline_radio_confirmation_undo` variant.
3296
+ *
3297
+ * `inline_radio_confirmation` — the offer posed as a question, answered by a pair of
3298
+ * radios sitting on "No thanks", with the confirmation replacing heading and radios
3299
+ * together — with the swap no longer one-way: a "No cash back" link below the copy
3300
+ * brings the question back and writes the opt-out. It pairs against that variant to
3301
+ * measure what an unmistakable way out is worth once the buyer has answered, the same
3302
+ * thing `inline_checkbox_confirmation_undo` measures against its checkbox.
3303
+ *
3304
+ * Undoing is not a dead end: the radios that return opt back in, so the buyer can cross
3305
+ * between the two states as often as they like. They return sitting on "No thanks" —
3306
+ * `OptInYesNoChoice` hardcodes that value, and the remount after an undo is one more
3307
+ * state it holds nothing local for — which is also the state the undo just put the
3308
+ * buyer in, so the control agrees with the attribute behind it.
3309
+ */
3310
+ function InlineRadioConfirmationUndoWidget(props) {
3311
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, addedLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3312
+ return /* @__PURE__ */ jsxs("s-stack", {
3313
+ gap: "small-200",
3314
+ children: [
3315
+ checked ? /* @__PURE__ */ jsx$1(OptInConfirmation, { label: addedLabel }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }), /* @__PURE__ */ jsx$1(OptInYesNoChoice, {
3316
+ label: rewardLabel,
3317
+ optInLabel: optInChoiceLabel,
3318
+ onOptIn: () => onToggle(true)
3319
+ })] }),
3320
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3321
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3322
+ value: contentBlocks,
3323
+ spacing: "tight"
3324
+ }),
3325
+ checked && /* @__PURE__ */ jsx$1("s-stack", {
3326
+ alignItems: "end",
3327
+ children: /* @__PURE__ */ jsx$1(OptInUndoLink, {
3328
+ label: "No cash back",
3329
+ onPress: () => onToggle(false)
3330
+ })
3331
+ }),
3332
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3333
+ total: totalLabel,
3334
+ earned: checked
3335
+ })
3336
+ ]
3337
+ });
3338
+ }
3339
+ //#endregion
3340
+ //#region src/prepurchase/components/checkout/inline-radio.tsx
3341
+ /**
3342
+ * The `inline_radio` variant.
3343
+ *
3344
+ * `inline_radio_confirmation`'s layout — the offer stated as a heading, answered by a
3345
+ * pair of radios — with the radios behaving as radios ordinarily do: they stay on
3346
+ * screen, the selection sits on whichever answer the buyer has given, and moving it to
3347
+ * "No thanks" opts back out. Nothing is swapped out and nothing is final, so the
3348
+ * question the widget poses stays answerable for as long as the checkout is open.
3349
+ *
3350
+ * It is to `inline_radio_confirmation` what `inline_checkbox` is to
3351
+ * `inline_checkbox_confirmation`, and pairs against it to measure what the one-way
3352
+ * confirmation is worth on its own — the same opt-in, minus the swap.
3353
+ *
3354
+ * The heading stays put rather than giving way to `OptInConfirmation`: the radios never
3355
+ * leave, so a confirmation line would sit above a control still asking the question it
3356
+ * claims to have settled. What marks the opt-in as taken is the affirmative radio
3357
+ * holding the selection, plus the total below turning green.
3358
+ */
3359
+ function InlineRadioWidget(props) {
3360
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3361
+ return /* @__PURE__ */ jsxs("s-stack", {
3362
+ gap: "small-200",
3363
+ children: [
3364
+ /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3365
+ /* @__PURE__ */ jsx$1(OptInYesNoRadios, {
3366
+ label: rewardLabel,
3367
+ optInLabel: optInChoiceLabel,
3368
+ checked,
3369
+ onToggle
3370
+ }),
3371
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3372
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3373
+ value: contentBlocks,
3374
+ spacing: "tight"
3375
+ }),
3376
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3377
+ total: totalLabel,
3378
+ earned: checked
3379
+ })
3380
+ ]
3381
+ });
3382
+ }
3383
+ //#endregion
3384
+ //#region src/prepurchase/components/checkout/inline-radio-with-large-logo.tsx
3385
+ /**
3386
+ * The `inline_radio_with_large_logo` variant.
3387
+ *
3388
+ * Keeps `inline_radio`'s reversible yes/no control and places the partner wordmark beside
3389
+ * the radio choices. The terms and total stay outside that two-column layout so both span
3390
+ * the full widget width beneath it.
3391
+ */
3392
+ function InlineRadioWithLargeLogoWidget(props) {
3393
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, totalLabel, contentBlocks, logoUrl } = usePrepurchaseOptIn(props);
3394
+ return /* @__PURE__ */ jsx$1("s-query-container", { children: /* @__PURE__ */ jsxs("s-stack", {
3395
+ gap: "small-200",
3396
+ children: [
3397
+ /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3398
+ /* @__PURE__ */ jsx$1(WithPartnerLogo, {
3399
+ source: partnerWordmarkSource(logoUrl),
3400
+ format: "wordmark",
3401
+ logoWidth: RESPONSIVE_WORDMARK_WIDTH,
3402
+ children: /* @__PURE__ */ jsx$1(OptInYesNoRadios, {
3403
+ label: rewardLabel,
3404
+ optInLabel: optInChoiceLabel,
3405
+ checked,
3406
+ onToggle
3407
+ })
3408
+ }),
3409
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3410
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3411
+ value: contentBlocks,
3412
+ spacing: "tight"
3413
+ }),
3414
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3415
+ total: totalLabel,
3416
+ earned: checked
3417
+ })
3418
+ ]
3419
+ }) });
3420
+ }
3421
+ //#endregion
3422
+ //#region src/prepurchase/components/checkout/cash-back-tiers.ts
3423
+ const CASH_BACK_TIERS = [
3424
+ {
3425
+ minimumSubtotalCents: 0,
3426
+ cashBack: 5
3427
+ },
3428
+ {
3429
+ minimumSubtotalCents: 2500,
3430
+ cashBack: 10
3431
+ },
3432
+ {
3433
+ minimumSubtotalCents: 7e3,
3434
+ cashBack: 15
3435
+ },
3436
+ {
3437
+ minimumSubtotalCents: 1e4,
3438
+ cashBack: 20
3439
+ },
3440
+ {
3441
+ minimumSubtotalCents: 14e3,
3442
+ cashBack: 25
3443
+ },
3444
+ {
3445
+ minimumSubtotalCents: 17500,
3446
+ cashBack: 30
3447
+ }
3448
+ ];
3449
+ /**
3450
+ * Calculates progress within the buyer's current tier using integer cents, avoiding
3451
+ * floating-point errors at exact boundaries such as $35 and $70.
3452
+ */
3453
+ function getCashBackTierProgress(subtotalCents) {
3454
+ const safeSubtotalCents = Math.max(0, Math.round(subtotalCents));
3455
+ let currentTierIndex = 0;
3456
+ for (let index = 1; index < CASH_BACK_TIERS.length; index += 1) {
3457
+ if (safeSubtotalCents < CASH_BACK_TIERS[index].minimumSubtotalCents) break;
3458
+ currentTierIndex = index;
3459
+ }
3460
+ const currentTier = CASH_BACK_TIERS[currentTierIndex];
3461
+ const nextTier = CASH_BACK_TIERS[currentTierIndex + 1];
3462
+ if (!nextTier) return {
3463
+ currentCashBack: currentTier.cashBack,
3464
+ currentMinimumCents: currentTier.minimumSubtotalCents,
3465
+ remainingCents: 0,
3466
+ progressCents: 1,
3467
+ progressMaximumCents: 1
3468
+ };
3469
+ return {
3470
+ currentCashBack: currentTier.cashBack,
3471
+ currentMinimumCents: currentTier.minimumSubtotalCents,
3472
+ nextCashBack: nextTier.cashBack,
3473
+ nextMinimumCents: nextTier.minimumSubtotalCents,
3474
+ remainingCents: nextTier.minimumSubtotalCents - safeSubtotalCents,
3475
+ progressCents: safeSubtotalCents - currentTier.minimumSubtotalCents,
3476
+ progressMaximumCents: nextTier.minimumSubtotalCents - currentTier.minimumSubtotalCents
3477
+ };
3478
+ }
3479
+ //#endregion
3480
+ //#region src/prepurchase/components/checkout/tier-progress.tsx
3481
+ /** The spend-to-next-tier summary and progress bar used by the tier radio variant. */
3482
+ function TierProgress() {
3483
+ const { i18n } = shopify;
3484
+ const subtotal = shopify.cost.subtotalAmount.value;
3485
+ const subtotalCents = Math.round(subtotal.amount * 100);
3486
+ const tier = getCashBackTierProgress(subtotalCents);
3487
+ const formatMoney = (amount, keepCents = false) => i18n.formatCurrency(amount, {
3488
+ currency: subtotal.currencyCode,
3489
+ minimumFractionDigits: keepCents ? 2 : Number.isInteger(amount) ? 0 : 2
3490
+ });
3491
+ if (tier.nextCashBack === void 0 || tier.nextMinimumCents === void 0) {
3492
+ const topCashBack = formatMoney(tier.currentCashBack);
3493
+ return /* @__PURE__ */ jsxs("s-stack", {
3494
+ gap: "small-200",
3495
+ children: [
3496
+ /* @__PURE__ */ jsxs("s-text", {
3497
+ type: "strong",
3498
+ children: [
3499
+ "Top tier unlocked: ",
3500
+ topCashBack,
3501
+ " cash back"
3502
+ ]
3503
+ }),
3504
+ /* @__PURE__ */ jsx$1("s-progress", {
3505
+ value: tier.progressCents,
3506
+ max: tier.progressMaximumCents,
3507
+ accessibilityLabel: `${topCashBack} top cash back tier unlocked`
3508
+ }),
3509
+ /* @__PURE__ */ jsxs("s-text", {
3510
+ color: "subdued",
3511
+ type: "small",
3512
+ children: [
3513
+ topCashBack,
3514
+ " back at ",
3515
+ formatMoney(175),
3516
+ "+"
3517
+ ]
3518
+ })
3519
+ ]
3520
+ });
3521
+ }
3522
+ const currentCashBack = formatMoney(tier.currentCashBack);
3523
+ const nextCashBack = formatMoney(tier.nextCashBack);
3524
+ const remaining = formatMoney(tier.remainingCents / 100, true);
3525
+ const currentSubtotal = formatMoney(subtotalCents / 100, true);
3526
+ const nextMinimum = formatMoney(tier.nextMinimumCents / 100);
3527
+ return /* @__PURE__ */ jsxs("s-stack", {
3528
+ gap: "small-200",
3529
+ children: [
3530
+ /* @__PURE__ */ jsxs("s-text", {
3531
+ type: "strong",
3532
+ children: [
3533
+ "Add ",
3534
+ remaining,
3535
+ " more to unlock ",
3536
+ nextCashBack,
3537
+ " cash back"
3538
+ ]
3539
+ }),
3540
+ /* @__PURE__ */ jsx$1("s-progress", {
3541
+ value: Math.max(tier.progressCents, .01),
3542
+ max: tier.progressMaximumCents,
3543
+ accessibilityLabel: `${currentSubtotal} spent; ${remaining} more to unlock ${nextCashBack} cash back`
3544
+ }),
3545
+ /* @__PURE__ */ jsxs("s-grid", {
3546
+ gridTemplateColumns: "1fr auto",
3547
+ gap: "base",
3548
+ children: [/* @__PURE__ */ jsxs("s-text", {
3549
+ color: "subdued",
3550
+ type: "small",
3551
+ children: [
3552
+ currentCashBack,
3553
+ " back at ",
3554
+ currentSubtotal
3555
+ ]
3556
+ }), /* @__PURE__ */ jsxs("s-text", {
3557
+ color: "subdued",
3558
+ type: "small",
3559
+ children: [
3560
+ nextCashBack,
3561
+ " back at ",
3562
+ nextMinimum
3563
+ ]
3564
+ })]
3565
+ })
3566
+ ]
3567
+ });
3568
+ }
3569
+ //#endregion
3570
+ //#region src/prepurchase/components/checkout/inline-radio-with-tier-progress.tsx
3571
+ /**
3572
+ * The `inline_radio_with_tier_progress` variant.
3573
+ *
3574
+ * Keeps `inline_radio`'s reversible yes/no control and adds the buyer's progress from
3575
+ * their current cash-back tier to the next one before the offer terms.
3576
+ */
3577
+ function InlineRadioWithTierProgressWidget(props) {
3578
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3579
+ return /* @__PURE__ */ jsxs("s-stack", {
3580
+ gap: "small-200",
3581
+ children: [
3582
+ /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3583
+ /* @__PURE__ */ jsx$1(OptInYesNoRadios, {
3584
+ label: rewardLabel,
3585
+ optInLabel: optInChoiceLabel,
3586
+ checked,
3587
+ onToggle
3588
+ }),
3589
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3590
+ /* @__PURE__ */ jsx$1(TierProgress, {}),
3591
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3592
+ value: contentBlocks,
3593
+ spacing: "tight"
3594
+ }),
3595
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3596
+ total: totalLabel,
3597
+ earned: checked
3598
+ })
3599
+ ]
3600
+ });
3601
+ }
3602
+ //#endregion
3603
+ //#region src/prepurchase/components/checkout/inline-radio-with-tier-progress-with-large-logo.tsx
3604
+ /**
3605
+ * The `inline_radio_with_tier_progress_large_logo` variant.
3606
+ *
3607
+ * `inline_radio_with_tier_progress` with the partner wordmark beside the radio choices,
3608
+ * as in `inline_radio_with_large_logo`. Tier progress, the terms and the total stay
3609
+ * outside that two-column layout at full widget width.
3610
+ */
3611
+ function InlineRadioWithTierProgressWithLargeLogoWidget(props) {
3612
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, totalLabel, contentBlocks, logoUrl } = usePrepurchaseOptIn(props);
3613
+ return /* @__PURE__ */ jsx$1("s-query-container", { children: /* @__PURE__ */ jsxs("s-stack", {
3614
+ gap: "small-200",
3615
+ children: [
3616
+ /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3617
+ /* @__PURE__ */ jsx$1(WithPartnerLogo, {
3618
+ source: partnerWordmarkSource(logoUrl),
3619
+ format: "wordmark",
3620
+ logoWidth: RESPONSIVE_WORDMARK_WIDTH,
3621
+ children: /* @__PURE__ */ jsx$1(OptInYesNoRadios, {
3622
+ label: rewardLabel,
3623
+ optInLabel: optInChoiceLabel,
3624
+ checked,
3625
+ onToggle
3626
+ })
3627
+ }),
3628
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3629
+ /* @__PURE__ */ jsx$1(TierProgress, {}),
3630
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3631
+ value: contentBlocks,
3632
+ spacing: "tight"
3633
+ }),
3634
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3635
+ total: totalLabel,
3636
+ earned: checked
3637
+ })
3638
+ ]
3639
+ }) });
3640
+ }
3641
+ //#endregion
3642
+ //#region src/prepurchase/quick-add-cart.ts
3643
+ async function addQuickAddProduct(applyCartLinesChange, merchandiseId) {
3644
+ if ((await applyCartLinesChange({
3645
+ type: "addCartLine",
3646
+ merchandiseId,
3647
+ quantity: 1
3648
+ })).type === "error") throw new Error("Product couldn't be added to the cart.");
3649
+ }
3650
+ //#endregion
3651
+ //#region src/prepurchase/hooks/useAddCartProduct.ts
3652
+ function useAddCartProduct() {
3653
+ const applyCartLinesChange = useApplyCartLinesChange();
3654
+ const [addingVariantId, setAddingVariantId] = useState();
3655
+ const [error, setError] = useState();
3656
+ return {
3657
+ addProduct: useCallback(async (variantId) => {
3658
+ if (addingVariantId) return;
3659
+ setAddingVariantId(variantId);
3660
+ setError(void 0);
3661
+ try {
3662
+ await addQuickAddProduct(applyCartLinesChange, variantId);
3663
+ } catch (caught) {
3664
+ console.error(caught);
3665
+ setError("This product couldn't be added. Please try again.");
3666
+ } finally {
3667
+ setAddingVariantId(void 0);
3668
+ }
3669
+ }, [addingVariantId, applyCartLinesChange]),
3670
+ addingVariantId,
3671
+ error
3672
+ };
3673
+ }
3674
+ //#endregion
3675
+ //#region src/prepurchase/quick-add-products.ts
3676
+ function parseQuickAddProducts(data) {
3677
+ return (data.products?.nodes ?? []).flatMap((product) => {
3678
+ const variant = product.variants?.nodes?.find((candidate) => candidate.availableForSale && !candidate.currentlyNotInStock);
3679
+ const price = Number(variant?.price?.amount);
3680
+ if (!variant?.id || !variant.title || !product.title || !variant.price?.currencyCode || !Number.isFinite(price)) return [];
3681
+ const image = variant.image ?? product.featuredImage;
3682
+ return [{
3683
+ id: variant.id,
3684
+ title: variant.title,
3685
+ productTitle: product.title,
3686
+ priceCents: Math.round(price * 100),
3687
+ currencyCode: variant.price.currencyCode,
3688
+ availableForSale: true,
3689
+ ...image?.url ? { imageUrl: image.url } : {},
3690
+ ...image?.altText ? { imageAlt: image.altText } : {}
3691
+ }];
3692
+ });
3693
+ }
3694
+ function getQuickAddHeading(progress) {
3695
+ if (progress.nextCashBack === void 0 || progress.remainingCents <= 0) return;
3696
+ return "Recommended products";
3697
+ }
3698
+ function getQuickAddVariantLabel(productTitle, variantTitle) {
3699
+ if (variantTitle === "Default Title") return void 0;
3700
+ const normalize = (value) => value.toLocaleLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
3701
+ const normalizedProductTitle = normalize(productTitle);
3702
+ const normalizedVariantTitle = normalize(variantTitle);
3703
+ if (normalizedVariantTitle === normalizedProductTitle || normalizedVariantTitle.includes(normalizedProductTitle)) return;
3704
+ return variantTitle;
3705
+ }
3706
+ const QUICK_ADD_PRODUCTS_QUERY = `#graphql
3707
+ query QuickAddProducts {
3708
+ products(first: 20, sortKey: BEST_SELLING) {
3709
+ nodes {
3710
+ title
3711
+ featuredImage {
3712
+ url
3713
+ altText
3714
+ }
3715
+ variants(first: 10) {
3716
+ nodes {
3717
+ id
3718
+ title
3719
+ availableForSale
3720
+ currentlyNotInStock
3721
+ price {
3722
+ amount
3723
+ currencyCode
3724
+ }
3725
+ image {
3726
+ url
3727
+ altText
3728
+ }
3729
+ }
3730
+ }
3731
+ }
3732
+ }
3733
+ }
3734
+ `;
3735
+ async function loadQuickAddProducts(query, options) {
3736
+ const result = await query(QUICK_ADD_PRODUCTS_QUERY, { version: "2026-07" });
3737
+ if (result.errors?.length || !result.data) throw new Error("Products couldn't be loaded.");
3738
+ return rankQuickAddProducts(parseQuickAddProducts(result.data), options.remainingCents, options);
3739
+ }
3740
+ /** Products may exceed the next-tier gap by at most $20. */
3741
+ const MAX_QUICK_ADD_OVERSHOOT_CENTS = 2e3;
3742
+ /**
3743
+ * Ranks products against the amount needed for the next tier. Products that
3744
+ * reach the tier come first with the least overshoot, followed by products
3745
+ * below the gap with the closest price first. Products that overshoot the gap
3746
+ * by more than $20 are excluded as economically irrelevant.
3747
+ */
3748
+ function rankQuickAddProducts(products, remainingCents, options = {}) {
3749
+ const gapCents = Math.max(0, Math.round(remainingCents));
3750
+ const { excludedVariantIds = /* @__PURE__ */ new Set(), maxProducts } = options;
3751
+ const ranked = products.filter((product) => product.availableForSale && !excludedVariantIds.has(product.id) && product.priceCents <= gapCents + MAX_QUICK_ADD_OVERSHOOT_CENTS).sort((left, right) => {
3752
+ const leftReachesTier = left.priceCents >= gapCents;
3753
+ if (leftReachesTier !== right.priceCents >= gapCents) return leftReachesTier ? -1 : 1;
3754
+ if (leftReachesTier) return left.priceCents - right.priceCents;
3755
+ return right.priceCents - left.priceCents;
3756
+ });
3757
+ return maxProducts === void 0 ? ranked : ranked.slice(0, maxProducts);
3758
+ }
3759
+ //#endregion
3760
+ //#region src/prepurchase/hooks/useQuickAddProducts.ts
3761
+ const MAX_QUICK_ADD_PRODUCTS = 8;
3762
+ function useQuickAddProducts(remainingCents, enabled) {
3763
+ const { query } = useApi();
3764
+ const cartLines = useCartLines();
3765
+ const cartVariantIds = useMemo(() => new Set(cartLines.map((line) => line.merchandise.id)), [cartLines]);
3766
+ return useQuery({
3767
+ queryKey: [
3768
+ "quick-add-products",
3769
+ remainingCents,
3770
+ ...Array.from(cartVariantIds).sort()
3771
+ ],
3772
+ queryFn: () => loadQuickAddProducts((source, options) => query(source, options), {
3773
+ remainingCents,
3774
+ excludedVariantIds: cartVariantIds,
3775
+ maxProducts: MAX_QUICK_ADD_PRODUCTS
3776
+ }),
3777
+ enabled: enabled && remainingCents > 0,
3778
+ staleTime: 300 * 1e3
3779
+ });
3780
+ }
3781
+ //#endregion
3782
+ //#region src/prepurchase/components/checkout/quick-add-products.tsx
3783
+ function QuickAddProducts({ remainingCents, nextCashBack }) {
3784
+ const { i18n } = useApi();
3785
+ const { canAddCartLine } = useInstructions().lines;
3786
+ const productsQuery = useQuickAddProducts(remainingCents, canAddCartLine);
3787
+ const { addProduct, addingVariantId, error } = useAddCartProduct();
3788
+ const heading = getQuickAddHeading({
3789
+ remainingCents,
3790
+ nextCashBack
3791
+ });
3792
+ if (!canAddCartLine || !heading || productsQuery.isError || !productsQuery.isPending && !productsQuery.data?.length) return null;
3793
+ return /* @__PURE__ */ jsx$1("s-box", {
3794
+ paddingBlock: "base",
3795
+ children: /* @__PURE__ */ jsxs("s-stack", {
3796
+ gap: "base",
3797
+ children: [
3798
+ /* @__PURE__ */ jsx$1("s-text", {
3799
+ type: "strong",
3800
+ children: heading
3801
+ }),
3802
+ productsQuery.isPending ? /* @__PURE__ */ jsx$1("s-skeleton-paragraph", { content: "Loading product suggestions" }) : productsQuery.data.length > 0 ? /* @__PURE__ */ jsx$1("s-scroll-box", {
3803
+ overflow: "hidden auto",
3804
+ children: /* @__PURE__ */ jsx$1("s-grid", {
3805
+ gridTemplateColumns: `repeat(${productsQuery.data.length}, 304px)`,
3806
+ gap: "small-400",
3807
+ alignItems: "stretch",
3808
+ children: productsQuery.data.map((product) => /* @__PURE__ */ jsx$1(QuickAddProductItem, {
3809
+ product,
3810
+ isAdding: addingVariantId === product.id,
3811
+ isDisabled: addingVariantId !== void 0,
3812
+ onAdd: () => addProduct(product.id),
3813
+ formatCurrency: (amount, currency) => i18n.formatCurrency(amount, { currency })
3814
+ }, product.id))
3815
+ })
3816
+ }) : null,
3817
+ error ? /* @__PURE__ */ jsx$1("s-text", {
3818
+ tone: "critical",
3819
+ type: "small",
3820
+ children: error
3821
+ }) : null
3822
+ ]
3823
+ })
3824
+ });
3825
+ }
3826
+ function QuickAddProductItem({ product, isAdding, isDisabled, onAdd, formatCurrency }) {
3827
+ const price = formatCurrency(product.priceCents / 100, product.currencyCode);
3828
+ const variantTitle = getQuickAddVariantLabel(product.productTitle, product.title);
3829
+ return /* @__PURE__ */ jsx$1("s-box", {
3830
+ background: "base",
3831
+ border: "base",
3832
+ borderRadius: "base",
3833
+ padding: "small-200",
3834
+ blockSize: "100%",
3835
+ children: /* @__PURE__ */ jsxs("s-grid", {
3836
+ gridTemplateColumns: "88px minmax(0, 1fr)",
3837
+ gap: "base",
3838
+ alignItems: "stretch",
3839
+ blockSize: "100%",
3840
+ children: [/* @__PURE__ */ jsx$1("s-stack", {
3841
+ blockSize: "100%",
3842
+ justifyContent: "center",
3843
+ children: /* @__PURE__ */ jsx$1(ProductImage, { product })
3844
+ }), /* @__PURE__ */ jsxs("s-grid", {
3845
+ blockSize: "100%",
3846
+ gridTemplateRows: "auto minmax(0, 1fr) auto",
3847
+ children: [
3848
+ /* @__PURE__ */ jsxs("s-stack", {
3849
+ gap: "small-100",
3850
+ children: [/* @__PURE__ */ jsx$1("s-text", {
3851
+ type: "strong",
3852
+ children: product.productTitle
3853
+ }), variantTitle ? /* @__PURE__ */ jsx$1("s-text", {
3854
+ color: "subdued",
3855
+ children: variantTitle
3856
+ }) : null]
3857
+ }),
3858
+ /* @__PURE__ */ jsx$1("s-box", {}),
3859
+ /* @__PURE__ */ jsxs("s-stack", {
3860
+ gap: "small-300",
3861
+ children: [/* @__PURE__ */ jsx$1("s-text", { children: price }), /* @__PURE__ */ jsx$1("s-button", {
3862
+ accessibilityLabel: `Add ${product.productTitle} to cart`,
3863
+ disabled: isDisabled,
3864
+ loading: isAdding,
3865
+ onClick: onAdd,
3866
+ children: "Add to cart"
3867
+ })]
3868
+ })
3869
+ ]
3870
+ })]
3871
+ })
3872
+ });
3873
+ }
3874
+ function ProductImage({ product }) {
3875
+ return /* @__PURE__ */ jsx$1("s-box", {
3876
+ background: "subdued",
3877
+ borderRadius: "small",
3878
+ blockSize: "88px",
3879
+ inlineSize: "88px",
3880
+ overflow: "hidden",
3881
+ children: /* @__PURE__ */ jsx$1("s-image", {
3882
+ src: product.imageUrl ?? "",
3883
+ alt: product.imageAlt ?? product.productTitle,
3884
+ aspectRatio: "1",
3885
+ objectFit: "contain",
3886
+ inlineSize: "fill",
3887
+ loading: "lazy"
3888
+ })
3889
+ });
3890
+ }
3891
+ //#endregion
3892
+ //#region src/prepurchase/components/checkout/inline-radio-with-tier-progress-and-quick-add.tsx
3893
+ function InlineRadioWithTierProgressAndQuickAddWidget(props) {
3894
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, totalLabel, contentBlocks } = usePrepurchaseOptIn(props);
3895
+ const subtotal = useSubtotalAmount();
3896
+ const tier = getCashBackTierProgress(Math.round(subtotal.amount * 100));
3897
+ return /* @__PURE__ */ jsxs("s-stack", {
3898
+ gap: "small-200",
3899
+ children: [
3900
+ /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3901
+ /* @__PURE__ */ jsx$1(OptInYesNoRadios, {
3902
+ label: rewardLabel,
3903
+ optInLabel: optInChoiceLabel,
3904
+ checked,
3905
+ onToggle
3906
+ }),
3907
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3908
+ /* @__PURE__ */ jsx$1(TierProgress, {}),
3909
+ /* @__PURE__ */ jsx$1(QuickAddProducts, {
3910
+ remainingCents: tier.remainingCents,
3911
+ nextCashBack: tier.nextCashBack
3912
+ }),
3913
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3914
+ value: contentBlocks,
3915
+ spacing: "tight"
3916
+ }),
3917
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3918
+ total: totalLabel,
3919
+ earned: checked
3920
+ })
3921
+ ]
3922
+ });
3923
+ }
3924
+ //#endregion
3925
+ //#region src/prepurchase/components/checkout/inline-radio-with-tier-progress-and-quick-add-with-large-logo.tsx
3926
+ /**
3927
+ * The `inline_radio_with_tier_progress_quick_add_compact_large_logo` variant.
3928
+ *
3929
+ * `inline_radio_with_tier_progress_quick_add_compact` with the partner wordmark beside
3930
+ * the radio choices, as in `inline_radio_with_large_logo`. Tier progress, quick add, the
3931
+ * terms and the total stay outside that two-column layout at full widget width.
3932
+ */
3933
+ function InlineRadioWithTierProgressAndQuickAddWithLargeLogoWidget(props) {
3934
+ const { checked, error, onToggle, rewardLabel, optInChoiceLabel, totalLabel, contentBlocks, logoUrl } = usePrepurchaseOptIn(props);
3935
+ const subtotal = useSubtotalAmount();
3936
+ const tier = getCashBackTierProgress(Math.round(subtotal.amount * 100));
3937
+ return /* @__PURE__ */ jsx$1("s-query-container", { children: /* @__PURE__ */ jsxs("s-stack", {
3938
+ gap: "small-200",
3939
+ children: [
3940
+ /* @__PURE__ */ jsx$1(RewardHeading, { label: rewardLabel }),
3941
+ /* @__PURE__ */ jsx$1(WithPartnerLogo, {
3942
+ source: partnerWordmarkSource(logoUrl),
3943
+ format: "wordmark",
3944
+ logoWidth: RESPONSIVE_WORDMARK_WIDTH,
3945
+ children: /* @__PURE__ */ jsx$1(OptInYesNoRadios, {
3946
+ label: rewardLabel,
3947
+ optInLabel: optInChoiceLabel,
3948
+ checked,
3949
+ onToggle
3950
+ })
3951
+ }),
3952
+ error && /* @__PURE__ */ jsx$1(OptInError, { message: error }),
3953
+ /* @__PURE__ */ jsx$1(TierProgress, {}),
3954
+ /* @__PURE__ */ jsx$1(QuickAddProducts, {
3955
+ remainingCents: tier.remainingCents,
3956
+ nextCashBack: tier.nextCashBack
3957
+ }),
3958
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
3959
+ value: contentBlocks,
3960
+ spacing: "tight"
3961
+ }),
3962
+ /* @__PURE__ */ jsx$1(TotalCashBack, {
3963
+ total: totalLabel,
3964
+ earned: checked
3965
+ })
3966
+ ]
3967
+ }) });
3968
+ }
3969
+ //#endregion
3970
+ //#region src/prepurchase/components/prepurchase-widget.tsx
3971
+ /**
3972
+ * Maps the API's `widget_variant` onto a widget this bundle knows how to render.
3973
+ *
3974
+ * These cases are the only list of widget ids anywhere: the backend deliberately holds
3975
+ * none, passing the `prepurchase_widget_variant` flag value straight through — ids it
3976
+ * has never heard of included — so that shipping a new widget doesn't need a backend
3977
+ * deploy. The ids are append-only and name the widget's form rather than its position
3978
+ * in a test, because every value served is permanent in the warehouse's exposure rows;
3979
+ * redesigning a widget mints a new id (`inline_checkbox_v2`) instead of reusing one.
3980
+ */
3981
+ function resolveWidget$1(raw) {
3982
+ switch (raw) {
3983
+ case "inline_checkbox_with_logo": return InlineCheckboxWithLogoWidget;
3984
+ case "inline_checkbox_rakuten_card": return InlineCheckboxLogoCardWidget;
3985
+ case "inline_checkbox_confirmation": return InlineCheckboxConfirmationWidget;
3986
+ case "inline_button_confirmation": return InlineButtonConfirmationWidget;
3987
+ case "inline_radio_confirmation": return InlineRadioConfirmationWidget;
3988
+ case "inline_checkbox_confirmation_undo": return InlineCheckboxConfirmationUndoWidget;
3989
+ case "inline_button_confirmation_decline": return InlineButtonConfirmationDeclineWidget;
3990
+ case "inline_radio_confirmation_undo": return InlineRadioConfirmationUndoWidget;
3991
+ case "inline_radio": return InlineRadioWidget;
3992
+ case "inline_radio_with_large_logo": return InlineRadioWithLargeLogoWidget;
3993
+ case "inline_radio_with_tier_progress": return InlineRadioWithTierProgressWidget;
3994
+ case "inline_radio_with_tier_progress_large_logo": return InlineRadioWithTierProgressWithLargeLogoWidget;
3995
+ case "inline_radio_with_tier_progress_quick_add_compact": return InlineRadioWithTierProgressAndQuickAddWidget;
3996
+ case "inline_radio_with_tier_progress_quick_add_compact_large_logo": return InlineRadioWithTierProgressAndQuickAddWithLargeLogoWidget;
3997
+ default: return InlineCheckboxWidget;
3998
+ }
3999
+ }
4000
+ function PrepurchaseWidget({ incentiveResponse }) {
4001
+ const { track } = useEventTracker();
4002
+ useEffect(() => {
4003
+ track({ type: "WIDGET_LOAD" });
4004
+ track({ type: "WIDGET_DISPLAY" });
4005
+ }, [track]);
4006
+ if (!("tracking_ticket_id" in incentiveResponse)) return null;
4007
+ return /* @__PURE__ */ jsx$1(resolveWidget$1(incentiveResponse.widget_variant), {
4008
+ incentive: incentiveResponse.incentive,
4009
+ tracking_ticket_id: incentiveResponse.tracking_ticket_id,
4010
+ idempotency_key: incentiveResponse.idempotency_key,
4011
+ session_id: incentiveResponse.session_id
4012
+ });
4013
+ }
4014
+ //#endregion
4015
+ //#region src/prepurchase/utils.ts
4016
+ const getShopIdentifier = (shopGid) => {
4017
+ return shopGid.replace("gid://shopify/Shop/", "");
4018
+ };
4019
+ //#endregion
4020
+ //#region src/prepurchase/hooks/useGetIncentive.ts
4021
+ const SUPPORTED_COUNTRY_CODE = "US";
4022
+ const useGetIncentive = (widgetPlacement) => {
4023
+ const endpoints = usePrepurchaseEndpoints();
4024
+ const { id: shopGid } = useShop();
4025
+ const incentiveUrl = endpoints.incentiveUrl(getShopIdentifier(shopGid));
4026
+ const customer = useCustomer();
4027
+ const contactEmail = useEmail();
4028
+ const subtotalAmount = useSubtotalAmount();
4029
+ const checkoutToken = useCheckoutToken();
4030
+ const country = useLocalizationCountry();
4031
+ const isEligibleCountry = country === void 0 || country.isoCode === SUPPORTED_COUNTRY_CODE;
4032
+ const email$2 = customer?.email ?? contactEmail;
4033
+ const validatedEmail = email().safeParse(email$2?.trim().toLowerCase());
4034
+ const validEmail = validatedEmail.success ? validatedEmail.data : null;
4035
+ const cartSubtotalAmount = Math.round(subtotalAmount.amount * 100);
4036
+ const cartSubtotalCurrency = subtotalAmount.currencyCode;
4037
+ return useQuery({
4038
+ queryKey: [
4039
+ "prepurchase-incentive",
4040
+ incentiveUrl,
4041
+ endpoints.headers["x-api-key"],
4042
+ shopGid,
4043
+ validEmail,
4044
+ cartSubtotalAmount,
4045
+ cartSubtotalCurrency,
4046
+ checkoutToken,
4047
+ isEligibleCountry,
4048
+ widgetPlacement
4049
+ ],
4050
+ queryFn: async ({ signal }) => {
4051
+ const response = await fetch(incentiveUrl, {
4052
+ method: "POST",
4053
+ headers: endpoints.headers,
4054
+ body: JSON.stringify({
4055
+ email: validEmail,
4056
+ cart_subtotal: {
4057
+ amount: cartSubtotalAmount,
4058
+ currency: cartSubtotalCurrency
4059
+ },
4060
+ checkout_token: checkoutToken,
4061
+ widget_placement: widgetPlacement
4062
+ }),
4063
+ signal
4064
+ });
4065
+ if (!response.ok) throw new Error(`Incentive request failed: ${response.status}`);
4066
+ return await response.json();
4067
+ },
4068
+ enabled: !!validEmail && isEligibleCountry,
4069
+ gcTime: 0,
4070
+ staleTime: 0,
4071
+ refetchOnWindowFocus: false
4072
+ });
4073
+ };
4074
+ const getTrackingIdentifiers = (data) => ({
4075
+ sessionId: data && "session_id" in data ? data.session_id : void 0,
4076
+ trackingTicketId: data && "tracking_ticket_id" in data ? data.tracking_ticket_id : void 0
4077
+ });
4078
+ //#endregion
4079
+ //#region src/prepurchase/DiscoPrepurchaseIncentive.tsx
4080
+ /**
4081
+ * Disco's prepurchase cash-back opt-in, shown in checkout.
4082
+ *
4083
+ * Render it from a `purchase.checkout.reductions.render-before` or
4084
+ * `purchase.checkout.actions.render-before` target. The opt-in is persisted to
4085
+ * a checkout attribute that `DiscoPrepurchaseThankYou` reads after purchase, so
4086
+ * render that too: it is what submits the order.
4087
+ *
4088
+ * Renders nothing when there is no incentive for this checkout, including when
4089
+ * the key is rejected.
4090
+ */
4091
+ function DiscoPrepurchaseIncentive({ apiKey }) {
4092
+ return /* @__PURE__ */ jsx$1(PrepurchaseIncentive, { auth: useMemo(() => ({ apiKey }), [apiKey]) });
4093
+ }
4094
+ /**
4095
+ * The checkout widget shared by the public (`apiKey`) and internal (`env`)
4096
+ * entry points.
4097
+ */
4098
+ function PrepurchaseIncentive({ auth }) {
4099
+ return /* @__PURE__ */ jsx$1(PrepurchaseProvider, {
4100
+ auth,
4101
+ children: /* @__PURE__ */ jsx$1(Incentive, {})
4102
+ });
4103
+ }
4104
+ function Incentive() {
4105
+ const editor = useExtensionEditor();
4106
+ const { data } = useGetIncentive("CHECKOUT");
4107
+ const { sessionId, trackingTicketId } = getTrackingIdentifiers(data);
4108
+ if (!data || !sessionId) return null;
4109
+ return /* @__PURE__ */ jsx$1(TrackingManager, {
4110
+ enabled: !editor,
4111
+ sessionId,
4112
+ trackingTicketId,
4113
+ children: /* @__PURE__ */ jsx$1(PrepurchaseWidget, { incentiveResponse: data })
4114
+ });
4115
+ }
4116
+ //#endregion
4117
+ //#region src/prepurchase/hooks/useSubmitOrder.ts
4118
+ const toMinorUnits = (majorUnits) => Math.round(majorUnits * 100);
4119
+ const withOptional = (item, key, value) => {
4120
+ if (value && value.trim()) return {
4121
+ ...item,
4122
+ [key]: value
4123
+ };
4124
+ return item;
4125
+ };
4126
+ const toOrderItem = (line) => {
4127
+ const lineTotal = line.cost.totalAmount;
4128
+ let item = {
4129
+ line_item_id: line.id.split("/").pop() ?? line.id,
4130
+ quantity: line.quantity,
4131
+ unit_price: {
4132
+ amount: toMinorUnits(lineTotal.amount / line.quantity),
4133
+ currency: lineTotal.currencyCode
4134
+ }
4135
+ };
4136
+ if (line.merchandise.type === "variant") {
4137
+ const { sku, title, product } = line.merchandise;
4138
+ item = withOptional(item, "sku", sku);
4139
+ item = withOptional(item, "description", title);
4140
+ item = withOptional(item, "category", product.productType);
4141
+ item = withOptional(item, "brand", product.vendor);
4142
+ }
4143
+ return item;
4144
+ };
4145
+ const useOrderRequest = (trackingTicketId, idempotencyKey, insertionId) => {
4146
+ const endpoints = usePrepurchaseEndpoints();
4147
+ const { id: shopGid } = useShop();
4148
+ const customer = useCustomer();
4149
+ const contactEmail = useEmail();
4150
+ const subtotalAmount = useSubtotalAmount();
4151
+ const cartLines = useCartLines();
4152
+ const checkoutToken = useCheckoutToken();
4153
+ const { orderConfirmation } = useApi();
4154
+ const orderId = useSubscription(orderConfirmation).order.id.split("/").pop();
4155
+ const email$1 = customer?.email ?? contactEmail;
4156
+ const validatedEmail = email().safeParse(email$1?.trim().toLowerCase());
4157
+ const validEmail = validatedEmail.success ? validatedEmail.data : null;
4158
+ const ready = Boolean(trackingTicketId && idempotencyKey && insertionId && checkoutToken && validEmail && orderId && cartLines.length > 0);
4159
+ return {
4160
+ buildPayload: useCallback(() => {
4161
+ if (!trackingTicketId || !idempotencyKey || !insertionId || !checkoutToken || !validEmail || !orderId) throw new Error("Missing data required to submit the prepurchase order");
4162
+ return {
4163
+ email: validEmail,
4164
+ order_id: orderId,
4165
+ order_subtotal: {
4166
+ amount: toMinorUnits(subtotalAmount.amount),
4167
+ currency: subtotalAmount.currencyCode
4168
+ },
4169
+ order_timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4170
+ tracking_ticket_id: trackingTicketId,
4171
+ order_items: cartLines.map(toOrderItem),
4172
+ idempotency_key: idempotencyKey,
4173
+ checkout_token: checkoutToken,
4174
+ insertion_id: insertionId
4175
+ };
4176
+ }, [
4177
+ cartLines,
4178
+ checkoutToken,
4179
+ idempotencyKey,
4180
+ insertionId,
4181
+ orderId,
4182
+ subtotalAmount.amount,
4183
+ subtotalAmount.currencyCode,
4184
+ trackingTicketId,
4185
+ validEmail
4186
+ ]),
4187
+ orderId,
4188
+ ready,
4189
+ endpoints,
4190
+ shopIdentifier: getShopIdentifier(shopGid)
4191
+ };
4192
+ };
4193
+ /**
4194
+ * Submits the completed order to the backend `OrderView` when the buyer opted
4195
+ * into the prepurchase incentive. Fires exactly once, as soon as the required
4196
+ * post-checkout data (order id + a valid email) is available.
4197
+ *
4198
+ * `useMutation` (not `useQuery`) because this is a one-shot, non-idempotent POST
4199
+ * that creates the order upstream — React Query must never retry or refetch it.
4200
+ */
4201
+ const useSubmitOrder = (trackingTicketId, idempotencyKey, insertionId) => {
4202
+ const { buildPayload, endpoints, orderId, ready, shopIdentifier } = useOrderRequest(trackingTicketId, idempotencyKey, insertionId);
4203
+ const mutation = useMutation({
4204
+ mutationKey: [
4205
+ "prepurchase-order",
4206
+ orderId,
4207
+ trackingTicketId
4208
+ ],
4209
+ retry: false,
4210
+ mutationFn: async () => {
4211
+ const response = await fetch(endpoints.orderUrl(shopIdentifier), {
4212
+ method: "POST",
4213
+ headers: endpoints.headers,
4214
+ body: JSON.stringify(buildPayload())
4215
+ });
4216
+ if (!response.ok) throw new Error(`Order submit failed: ${response.status}`);
4217
+ return await response.json();
4218
+ }
4219
+ });
4220
+ const { mutate } = mutation;
4221
+ const firedRef = useRef(false);
4222
+ useEffect(() => {
4223
+ if (firedRef.current || !ready) return;
4224
+ firedRef.current = true;
4225
+ mutate();
4226
+ }, [ready, mutate]);
4227
+ return mutation;
4228
+ };
4229
+ //#endregion
4230
+ //#region src/prepurchase/hooks/useCreateOrderIntent.ts
4231
+ /**
4232
+ * Stages the final order behind an opaque, short-lived URL. This never calls
4233
+ * the affiliate provider; that only happens after the buyer follows the URL.
4234
+ */
4235
+ const useCreateOrderIntent = (trackingTicketId, idempotencyKey, insertionId, enabled) => {
4236
+ const { buildPayload, endpoints, orderId, ready, shopIdentifier } = useOrderRequest(trackingTicketId, idempotencyKey, insertionId);
4237
+ const mutation = useMutation({
4238
+ mutationKey: [
4239
+ "prepurchase-order-intent",
4240
+ orderId,
4241
+ trackingTicketId
4242
+ ],
4243
+ retry: false,
4244
+ mutationFn: async () => {
4245
+ const response = await fetch(endpoints.orderIntentUrl(shopIdentifier), {
4246
+ method: "POST",
4247
+ headers: endpoints.headers,
4248
+ body: JSON.stringify(buildPayload())
4249
+ });
4250
+ if (!response.ok) throw new Error(`Order intent creation failed: ${response.status}`);
4251
+ return await response.json();
4252
+ }
4253
+ });
4254
+ const { mutate } = mutation;
4255
+ const firedRef = useRef(false);
4256
+ useEffect(() => {
4257
+ if (firedRef.current || !enabled || !ready) return;
4258
+ firedRef.current = true;
4259
+ mutate();
4260
+ }, [
4261
+ enabled,
4262
+ mutate,
4263
+ ready
4264
+ ]);
4265
+ return mutation;
4266
+ };
4267
+ //#endregion
4268
+ //#region src/prepurchase/components/thank-you/check-icons.tsx
4269
+ /** The check-icon checklist layout, with a redeem/forfeit decision. */
4270
+ function CheckIconsThankYouWidget({ rewardWithCents, compactReward, contentBlocks, launchUrl, claimed, onClaim, onDecline }) {
4271
+ const { i18n } = useApi();
4272
+ const { name: merchantName } = useShop();
4273
+ const total = useTotalAmount();
4274
+ const customer = useCustomer();
4275
+ const billingAddress = useBillingAddress();
4276
+ const shippingAddress = useShippingAddress();
4277
+ const firstName = customer?.firstName ?? billingAddress?.firstName ?? shippingAddress?.firstName;
4278
+ const orderTotal = i18n.formatCurrency(total.amount, { currency: total.currencyCode });
4279
+ return /* @__PURE__ */ jsxs("s-stack", {
4280
+ gap: "base",
4281
+ children: [
4282
+ /* @__PURE__ */ jsx$1("s-heading", { children: firstName ? `${firstName}, thank you for your ${merchantName} purchase` : `Thank you for your ${merchantName} purchase` }),
4283
+ /* @__PURE__ */ jsxs("s-text", { children: [
4284
+ "You unlocked ",
4285
+ rewardWithCents,
4286
+ " cash back on the order you just placed."
4287
+ ] }),
4288
+ /* @__PURE__ */ jsxs("s-stack", {
4289
+ gap: "small-200",
4290
+ children: [/* @__PURE__ */ jsxs("s-stack", {
4291
+ direction: "inline",
4292
+ gap: "small-200",
4293
+ alignItems: "center",
4294
+ children: [/* @__PURE__ */ jsx$1("s-icon", {
4295
+ type: "check-circle",
4296
+ tone: "success"
4297
+ }), /* @__PURE__ */ jsxs("s-text", { children: [orderTotal, " order total"] })]
4298
+ }), /* @__PURE__ */ jsxs("s-stack", {
4299
+ direction: "inline",
4300
+ gap: "small-200",
4301
+ alignItems: "center",
4302
+ children: [/* @__PURE__ */ jsx$1("s-icon", {
4303
+ type: "check-circle",
4304
+ tone: "success"
4305
+ }), /* @__PURE__ */ jsxs("s-text", { children: [rewardWithCents, " cash back"] })]
4306
+ })]
4307
+ }),
4308
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
4309
+ value: contentBlocks,
4310
+ spacing: "extraTight",
4311
+ appearance: "subdued"
4312
+ }),
4313
+ claimed ? /* @__PURE__ */ jsxs("s-text", {
4314
+ tone: "success",
4315
+ type: "strong",
4316
+ children: [
4317
+ "Congratulations! You claimed your ",
4318
+ compactReward,
4319
+ " cash back."
4320
+ ]
4321
+ }) : /* @__PURE__ */ jsxs("s-grid", {
4322
+ gridTemplateColumns: "1fr 1fr",
4323
+ gap: "base",
4324
+ alignItems: "center",
4325
+ children: [/* @__PURE__ */ jsxs("s-button", {
4326
+ tone: "neutral",
4327
+ variant: "primary",
4328
+ inlineSize: "fill",
4329
+ href: launchUrl,
4330
+ onClick: onClaim,
4331
+ children: ["Redeem my ", compactReward]
4332
+ }), /* @__PURE__ */ jsx$1("s-stack", {
4333
+ direction: "inline",
4334
+ justifyContent: "center",
4335
+ inlineSize: "100%",
4336
+ children: /* @__PURE__ */ jsxs("s-link", {
4337
+ tone: "neutral",
4338
+ onClick: onDecline,
4339
+ children: ["Forfeit my ", compactReward]
4340
+ })
4341
+ })]
4342
+ })
4343
+ ]
4344
+ });
4345
+ }
4346
+ //#endregion
4347
+ //#region src/prepurchase/components/thank-you/cash-back-cost.tsx
4348
+ /** The order-cost comparison layout. */
4349
+ function CashBackCostThankYouWidget({ rewardWithCents, compactReward, rewardAmount, contentBlocks, launchUrl, claimed, onClaim }) {
4350
+ const { i18n } = useApi();
4351
+ const total = useTotalAmount();
4352
+ const orderTotal = i18n.formatCurrency(total.amount, { currency: total.currencyCode });
4353
+ const cashBackAdjustedTotal = i18n.formatCurrency(Math.max(total.amount - rewardAmount, 0), { currency: total.currencyCode });
4354
+ return /* @__PURE__ */ jsx$1("s-box", {
4355
+ padding: "large-200",
4356
+ children: /* @__PURE__ */ jsxs("s-stack", {
4357
+ gap: "base",
4358
+ children: [
4359
+ /* @__PURE__ */ jsxs("s-grid", {
4360
+ gridTemplateColumns: "1fr auto",
4361
+ alignItems: "center",
4362
+ children: [/* @__PURE__ */ jsx$1("s-text", { children: "Order total" }), /* @__PURE__ */ jsx$1("s-text", {
4363
+ type: "strong",
4364
+ children: orderTotal
4365
+ })]
4366
+ }),
4367
+ /* @__PURE__ */ jsxs("s-grid", {
4368
+ gridTemplateColumns: "1fr auto",
4369
+ alignItems: "center",
4370
+ children: [/* @__PURE__ */ jsxs("s-text", {
4371
+ type: "strong",
4372
+ color: "subdued",
4373
+ children: [
4374
+ "Your cost with ",
4375
+ rewardWithCents,
4376
+ " cash back"
4377
+ ]
4378
+ }), /* @__PURE__ */ jsx$1("s-heading", { children: /* @__PURE__ */ jsx$1("s-text", {
4379
+ color: "subdued",
4380
+ children: cashBackAdjustedTotal
4381
+ }) })]
4382
+ }),
4383
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
4384
+ value: contentBlocks,
4385
+ spacing: "extraTight",
4386
+ appearance: "subdued"
4387
+ }),
4388
+ claimed ? /* @__PURE__ */ jsxs("s-text", {
4389
+ tone: "success",
4390
+ type: "strong",
4391
+ children: [
4392
+ "Congratulations! You claimed your ",
4393
+ compactReward,
4394
+ " cash back."
4395
+ ]
4396
+ }) : /* @__PURE__ */ jsxs("s-button", {
4397
+ tone: "neutral",
4398
+ variant: "primary",
4399
+ inlineSize: "fill",
4400
+ href: launchUrl,
4401
+ onClick: onClaim,
4402
+ children: [
4403
+ "Get ",
4404
+ compactReward,
4405
+ " cash back"
4406
+ ]
4407
+ })
4408
+ ]
4409
+ })
4410
+ });
4411
+ }
4412
+ //#endregion
4413
+ //#region src/prepurchase/components/thank-you/countdown.ts
4414
+ /** Returns a drift-resistant countdown that stops when it reaches zero. */
4415
+ function useCountdown(durationSeconds) {
4416
+ const [secondsRemaining, setSecondsRemaining] = useState(durationSeconds);
4417
+ useEffect(() => {
4418
+ const deadline = Date.now() + durationSeconds * 1e3;
4419
+ const updateCountdown = () => {
4420
+ const nextSeconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1e3));
4421
+ setSecondsRemaining(nextSeconds);
4422
+ if (nextSeconds === 0) clearInterval(interval);
4423
+ };
4424
+ const interval = setInterval(updateCountdown, 1e3);
4425
+ return () => clearInterval(interval);
4426
+ }, [durationSeconds]);
4427
+ return secondsRemaining;
4428
+ }
4429
+ function formatCountdown(seconds) {
4430
+ return `${Math.floor(seconds / 60)}:${(seconds % 60).toString().padStart(2, "0")}`;
4431
+ }
4432
+ //#endregion
4433
+ //#region src/prepurchase/components/thank-you/countdown-10-minute.tsx
4434
+ const COUNTDOWN_SECONDS = 600;
4435
+ /** The order-confirmation layout with a ten-minute claim countdown. */
4436
+ function TenMinuteCountdownThankYouWidget({ rewardWithCents, compactReward, contentBlocks, launchUrl, claimed, onClaim }) {
4437
+ const { name: merchantName } = useShop();
4438
+ const customer = useCustomer();
4439
+ const billingAddress = useBillingAddress();
4440
+ const shippingAddress = useShippingAddress();
4441
+ const firstName = customer?.firstName ?? billingAddress?.firstName ?? shippingAddress?.firstName;
4442
+ const secondsRemaining = useCountdown(COUNTDOWN_SECONDS);
4443
+ if (secondsRemaining === 0) return null;
4444
+ const timer = formatCountdown(secondsRemaining);
4445
+ return /* @__PURE__ */ jsx$1("s-box", {
4446
+ padding: "large-200",
4447
+ children: /* @__PURE__ */ jsxs("s-stack", {
4448
+ gap: "base",
4449
+ children: [
4450
+ /* @__PURE__ */ jsx$1("s-heading", { children: firstName ? `${firstName}, thank you for your ${merchantName} purchase` : `Thank you for your ${merchantName} purchase` }),
4451
+ /* @__PURE__ */ jsxs("s-text", { children: [
4452
+ "You earned ",
4453
+ /* @__PURE__ */ jsxs("s-text", {
4454
+ type: "strong",
4455
+ children: [rewardWithCents, " cash back"]
4456
+ }),
4457
+ " ",
4458
+ "on the order you just placed."
4459
+ ] }),
4460
+ /* @__PURE__ */ jsxs("s-stack", {
4461
+ gap: "small-200",
4462
+ children: [/* @__PURE__ */ jsxs("s-paragraph", {
4463
+ accessibilityVisibility: "hidden",
4464
+ children: [
4465
+ /* @__PURE__ */ jsx$1("s-text", {
4466
+ type: "strong",
4467
+ tone: "critical",
4468
+ children: timer
4469
+ }),
4470
+ " ",
4471
+ /* @__PURE__ */ jsx$1("s-text", {
4472
+ color: "base",
4473
+ children: "left to claim your offer."
4474
+ })
4475
+ ]
4476
+ }), /* @__PURE__ */ jsxs("s-text", {
4477
+ accessibilityVisibility: "exclusive",
4478
+ children: [
4479
+ timer,
4480
+ " left to claim your ",
4481
+ rewardWithCents,
4482
+ " cash back on the order you just placed."
4483
+ ]
4484
+ })]
4485
+ }),
4486
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
4487
+ value: contentBlocks,
4488
+ spacing: "extraTight",
4489
+ appearance: "subdued"
4490
+ }),
4491
+ claimed ? /* @__PURE__ */ jsxs("s-text", {
4492
+ tone: "success",
4493
+ type: "strong",
4494
+ children: [
4495
+ "Congratulations! You claimed your ",
4496
+ compactReward,
4497
+ " cash back."
4498
+ ]
4499
+ }) : /* @__PURE__ */ jsxs("s-button", {
4500
+ tone: "neutral",
4501
+ variant: "primary",
4502
+ inlineSize: "fill",
4503
+ href: launchUrl,
4504
+ onClick: onClaim,
4505
+ children: ["Claim my ", compactReward]
4506
+ })
4507
+ ]
4508
+ })
4509
+ });
4510
+ }
4511
+ //#endregion
4512
+ //#region src/prepurchase/components/thank-you/earned-progress.tsx
4513
+ /** The two-step earned-to-collect reward progress layout. */
4514
+ function EarnedProgressThankYouWidget({ rewardWithCents, compactReward, contentBlocks, launchUrl, claimed, onClaim }) {
4515
+ const { i18n } = useApi();
4516
+ const { name: merchantName } = useShop();
4517
+ const total = useTotalAmount();
4518
+ const customer = useCustomer();
4519
+ const billingAddress = useBillingAddress();
4520
+ const shippingAddress = useShippingAddress();
4521
+ const firstName = customer?.firstName ?? billingAddress?.firstName ?? shippingAddress?.firstName;
4522
+ const orderTotal = i18n.formatCurrency(total.amount, { currency: total.currencyCode });
4523
+ return /* @__PURE__ */ jsxs("s-stack", {
4524
+ gap: "base",
4525
+ children: [
4526
+ /* @__PURE__ */ jsx$1("s-heading", { children: firstName ? `${firstName}, your ${orderTotal} order at ${merchantName} earned you` : `Your ${orderTotal} order at ${merchantName} earned you` }),
4527
+ /* @__PURE__ */ jsxs("s-stack", {
4528
+ gap: "small-200",
4529
+ children: [
4530
+ /* @__PURE__ */ jsx$1("s-heading", { children: /* @__PURE__ */ jsxs("s-text", { children: [rewardWithCents, " cash back"] }) }),
4531
+ /* @__PURE__ */ jsx$1("s-progress", {
4532
+ value: 1,
4533
+ max: 2,
4534
+ accessibilityLabel: `${rewardWithCents} earned; next step is to collect it`
4535
+ }),
4536
+ /* @__PURE__ */ jsxs("s-grid", {
4537
+ gridTemplateColumns: "1fr auto",
4538
+ gap: "base",
4539
+ alignItems: "center",
4540
+ children: [/* @__PURE__ */ jsxs("s-stack", {
4541
+ direction: "inline",
4542
+ gap: "small-200",
4543
+ alignItems: "center",
4544
+ children: [/* @__PURE__ */ jsx$1("s-icon", {
4545
+ type: "check-circle",
4546
+ size: "small",
4547
+ tone: "info"
4548
+ }), /* @__PURE__ */ jsx$1("s-text", {
4549
+ type: "strong",
4550
+ children: "Earned"
4551
+ })]
4552
+ }), /* @__PURE__ */ jsx$1("s-text", {
4553
+ color: "subdued",
4554
+ children: "Next: collect it"
4555
+ })]
4556
+ })
4557
+ ]
4558
+ }),
4559
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
4560
+ value: contentBlocks,
4561
+ spacing: "extraTight",
4562
+ appearance: "subdued"
4563
+ }),
4564
+ claimed ? /* @__PURE__ */ jsxs("s-text", {
4565
+ tone: "success",
4566
+ type: "strong",
4567
+ children: [
4568
+ "Congratulations! You claimed your ",
4569
+ compactReward,
4570
+ " cash back."
4571
+ ]
4572
+ }) : /* @__PURE__ */ jsxs("s-button", {
4573
+ tone: "neutral",
4574
+ variant: "primary",
4575
+ inlineSize: "fill",
4576
+ href: launchUrl,
4577
+ onClick: onClaim,
4578
+ children: ["Collect my ", compactReward]
4579
+ })
4580
+ ]
4581
+ });
4582
+ }
4583
+ //#endregion
4584
+ //#region src/prepurchase/components/thank-you/order-earned.tsx
4585
+ /** The order-number layout that leads with the earned reward. */
4586
+ function OrderEarnedThankYouWidget({ rewardWithCents, compactReward, contentBlocks, launchUrl, claimed, onClaim }) {
4587
+ const { orderConfirmation } = useApi();
4588
+ const { number: orderNumber } = useSubscription(orderConfirmation);
4589
+ const customer = useCustomer();
4590
+ const billingAddress = useBillingAddress();
4591
+ const shippingAddress = useShippingAddress();
4592
+ const firstName = customer?.firstName ?? billingAddress?.firstName ?? shippingAddress?.firstName;
4593
+ const heading = firstName ? `${firstName}, this order earned you` : "This order earned you";
4594
+ return /* @__PURE__ */ jsx$1("s-box", {
4595
+ padding: "large-200",
4596
+ children: /* @__PURE__ */ jsxs("s-stack", {
4597
+ gap: "base",
4598
+ children: [
4599
+ orderNumber && /* @__PURE__ */ jsxs("s-text", {
4600
+ color: "subdued",
4601
+ children: ["ORDER #", orderNumber.replace(/^#/, "")]
4602
+ }),
4603
+ /* @__PURE__ */ jsxs("s-grid", {
4604
+ gridTemplateColumns: "1fr auto",
4605
+ gap: "base",
4606
+ alignItems: "center",
4607
+ children: [/* @__PURE__ */ jsx$1("s-text", {
4608
+ type: "strong",
4609
+ children: heading
4610
+ }), /* @__PURE__ */ jsx$1("s-heading", { children: /* @__PURE__ */ jsx$1("s-text", {
4611
+ tone: "success",
4612
+ children: rewardWithCents
4613
+ }) })]
4614
+ }),
4615
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
4616
+ value: contentBlocks,
4617
+ spacing: "extraTight",
4618
+ appearance: "subdued"
4619
+ }),
4620
+ claimed ? /* @__PURE__ */ jsxs("s-text", {
4621
+ tone: "success",
4622
+ type: "strong",
4623
+ children: [
4624
+ "Congratulations! You claimed your ",
4625
+ compactReward,
4626
+ " cash back."
4627
+ ]
4628
+ }) : /* @__PURE__ */ jsxs("s-button", {
4629
+ tone: "neutral",
4630
+ variant: "primary",
4631
+ inlineSize: "fill",
4632
+ href: launchUrl,
4633
+ onClick: onClaim,
4634
+ children: [
4635
+ "Claim the ",
4636
+ compactReward,
4637
+ " from this order"
4638
+ ]
4639
+ })
4640
+ ]
4641
+ })
4642
+ });
4643
+ }
4644
+ //#endregion
4645
+ //#region src/prepurchase/components/thank-you/social-proof.tsx
4646
+ const TEN_MINUTES_MS = 600 * 1e3;
4647
+ const WEEK_MS = 10080 * 60 * 1e3;
4648
+ const MONDAY_EPOCH_MS = Date.UTC(1970, 0, 5);
4649
+ const MIN_WEEKLY_CLAIM_COUNT = 850;
4650
+ function getWeeklyClaimCount(timestamp) {
4651
+ const millisecondsSinceEpoch = timestamp - MONDAY_EPOCH_MS;
4652
+ const weekIndex = Math.floor(millisecondsSinceEpoch / WEEK_MS);
4653
+ const weekStart = MONDAY_EPOCH_MS + weekIndex * WEEK_MS;
4654
+ const tenMinuteBuckets = Math.floor((timestamp - weekStart) / TEN_MINUTES_MS);
4655
+ return MIN_WEEKLY_CLAIM_COUNT + (weekIndex * 47 % 101 + 101) % 101 + tenMinuteBuckets;
4656
+ }
4657
+ /** The order-confirmation layout that reinforces the offer with social proof. */
4658
+ function SocialProofThankYouWidget({ rewardWithCents, compactReward, contentBlocks, launchUrl, claimed, onClaim }) {
4659
+ const { i18n } = useApi();
4660
+ const { name: merchantName } = useShop();
4661
+ const customer = useCustomer();
4662
+ const billingAddress = useBillingAddress();
4663
+ const shippingAddress = useShippingAddress();
4664
+ const firstName = customer?.firstName ?? billingAddress?.firstName ?? shippingAddress?.firstName;
4665
+ const claimCount = useMemo(() => getWeeklyClaimCount(Date.now()), []);
4666
+ const formattedClaimCount = i18n.formatNumber(claimCount);
4667
+ return /* @__PURE__ */ jsxs("s-stack", {
4668
+ gap: "base",
4669
+ children: [
4670
+ /* @__PURE__ */ jsx$1("s-heading", { children: firstName ? `${firstName}, thank you for your ${merchantName} purchase` : `Thank you for your ${merchantName} purchase` }),
4671
+ /* @__PURE__ */ jsxs("s-grid", {
4672
+ gridTemplateColumns: "auto 1fr",
4673
+ gap: "small-200",
4674
+ alignItems: "center",
4675
+ children: [/* @__PURE__ */ jsx$1("s-icon", {
4676
+ type: "check-circle",
4677
+ tone: "success"
4678
+ }), /* @__PURE__ */ jsxs("s-text", { children: [
4679
+ "You earned ",
4680
+ /* @__PURE__ */ jsxs("s-text", {
4681
+ type: "strong",
4682
+ children: [rewardWithCents, " cash back"]
4683
+ }),
4684
+ " ",
4685
+ "on the order you just placed."
4686
+ ] })]
4687
+ }),
4688
+ /* @__PURE__ */ jsx$1("s-stack", {
4689
+ gap: "small-200",
4690
+ children: /* @__PURE__ */ jsxs("s-grid", {
4691
+ gridTemplateColumns: "auto 1fr",
4692
+ gap: "small-200",
4693
+ alignItems: "center",
4694
+ children: [/* @__PURE__ */ jsx$1("s-icon", {
4695
+ type: "check-circle",
4696
+ tone: "success"
4697
+ }), /* @__PURE__ */ jsxs("s-text", { children: [
4698
+ formattedClaimCount,
4699
+ " shoppers claimed theirs at ",
4700
+ merchantName,
4701
+ " this week"
4702
+ ] })]
4703
+ })
4704
+ }),
4705
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
4706
+ value: contentBlocks,
4707
+ spacing: "extraTight",
4708
+ appearance: "subdued"
4709
+ }),
4710
+ claimed ? /* @__PURE__ */ jsxs("s-text", {
4711
+ tone: "success",
4712
+ type: "strong",
4713
+ children: [
4714
+ "Congratulations! You claimed your ",
4715
+ compactReward,
4716
+ " cash back."
4717
+ ]
4718
+ }) : /* @__PURE__ */ jsxs("s-button", {
4719
+ tone: "neutral",
4720
+ variant: "primary",
4721
+ inlineSize: "fill",
4722
+ href: launchUrl,
4723
+ onClick: onClaim,
4724
+ children: ["Claim my ", compactReward]
4725
+ })
4726
+ ]
4727
+ });
4728
+ }
4729
+ //#endregion
4730
+ //#region src/prepurchase/components/thank-you-widget.tsx
4731
+ /**
4732
+ * Maps the API's `widget_variant` onto a thank-you layout this bundle can render.
4733
+ *
4734
+ * The thank-you page's counterpart to `resolveWidget` in prepurchase-widget.tsx, and
4735
+ * it follows that file's contract exactly: these cases are the only list of valid ids
4736
+ * anywhere, because the backend holds none and passes whatever
4737
+ * `prepurchase_thank_you_widget_variant` serves straight through -- ids it has never
4738
+ * heard of included -- so a new layout ships without a backend deploy. The ids are
4739
+ * append-only and name the layout's FORM rather than its position in a test, since
4740
+ * every value served is permanent in the warehouse's exposure rows; redesigning a
4741
+ * layout mints a new id (`check-icons-v2`) instead of reusing one.
4742
+ *
4743
+ * Note this is a DIFFERENT flag from the checkout surface's `prepurchase_widget_variant`
4744
+ * and a different id space: the backend picks the flag off `widget_placement`, so a
4745
+ * checkout id (`inline_radio`) can never arrive here, nor a thank-you id there.
4746
+ */
4747
+ function resolveWidget(raw) {
4748
+ switch (raw) {
4749
+ case "cash-back-cost": return CashBackCostThankYouWidget;
4750
+ case "countdown-10-minute": return TenMinuteCountdownThankYouWidget;
4751
+ case "earned-progress": return EarnedProgressThankYouWidget;
4752
+ case "order-earned": return OrderEarnedThankYouWidget;
4753
+ case "social-proof": return SocialProofThankYouWidget;
4754
+ default: return CheckIconsThankYouWidget;
4755
+ }
4756
+ }
4757
+ function ThankYouClaimWidget({ incentive, launchUrl }) {
4758
+ const { track } = useEventTracker();
4759
+ const { i18n } = useApi();
4760
+ const [status, setStatus] = useState("idle");
4761
+ const display = incentive.incentive.display;
4762
+ const reward = incentive.incentive.reward;
4763
+ const rewardAmount = reward.amount / 10 ** reward.scale;
4764
+ const rewardWithCents = i18n.formatCurrency(rewardAmount, { currency: reward.currency });
4765
+ const compactReward = i18n.formatCurrency(rewardAmount, {
4766
+ currency: reward.currency,
4767
+ minimumFractionDigits: Number.isInteger(rewardAmount) ? 0 : 2
4768
+ });
4769
+ const brandProperties = useMemo(() => ({
4770
+ offerId: crypto.randomUUID(),
4771
+ advertiserId: incentive.incentive.advertiser_id,
4772
+ insertionId: incentive.incentive.insertion_id
4773
+ }), [incentive.incentive.advertiser_id, incentive.incentive.insertion_id]);
4774
+ const contentBlocks = Array.isArray(display.blocks) ? display.blocks.filter((block) => block._type !== "checkboxBlock") : display.blocks;
4775
+ useEffect(() => {
4776
+ track({
4777
+ type: "BRAND_DISPLAY",
4778
+ target: "INLINE_SLOT",
4779
+ brand: brandProperties
4780
+ });
4781
+ }, [track, brandProperties]);
4782
+ if (status === "declined") return null;
4783
+ return /* @__PURE__ */ jsx$1(resolveWidget(incentive.widget_variant), {
4784
+ rewardWithCents,
4785
+ compactReward,
4786
+ rewardAmount,
4787
+ contentBlocks,
4788
+ launchUrl,
4789
+ claimed: status === "claimed",
4790
+ onClaim: () => {
4791
+ track({
4792
+ type: "ELEMENT_CLICK",
4793
+ target: "OPT_IN",
4794
+ brand: brandProperties
4795
+ });
4796
+ setStatus("claimed");
4797
+ },
4798
+ onDecline: () => {
4799
+ track({
4800
+ type: "ELEMENT_CLICK",
4801
+ target: "INLINE_NAV_FORWARD",
4802
+ brand: brandProperties
4803
+ });
4804
+ setStatus("declined");
4805
+ }
4806
+ });
4807
+ }
4808
+ //#endregion
4809
+ //#region src/prepurchase/DiscoPrepurchaseThankYou.tsx
4810
+ /**
4811
+ * Disco's prepurchase incentive on the thank-you page.
4812
+ *
4813
+ * Render it from a `purchase.thank-you.block.render` target. A buyer who opted
4814
+ * in at checkout (via `DiscoPrepurchaseIncentive`) has their order submitted
4815
+ * and sees the partner's confirmation; anyone else is offered the incentive
4816
+ * post-purchase instead.
4817
+ *
4818
+ * Renders nothing when there is nothing to show, including when the key is
4819
+ * rejected.
4820
+ */
4821
+ function DiscoPrepurchaseThankYou({ apiKey }) {
4822
+ return /* @__PURE__ */ jsx$1(PrepurchaseThankYou, { auth: useMemo(() => ({ apiKey }), [apiKey]) });
4823
+ }
4824
+ /**
4825
+ * The thank-you widget shared by the public (`apiKey`) and internal (`env`)
4826
+ * entry points.
4827
+ */
4828
+ function PrepurchaseThankYou({ auth }) {
4829
+ return /* @__PURE__ */ jsx$1(PrepurchaseProvider, {
4830
+ auth,
4831
+ children: /* @__PURE__ */ jsx$1(ThankYou, {})
4832
+ });
4833
+ }
4834
+ function ThankYou() {
4835
+ const editor = useExtensionEditor();
4836
+ const [rawAttribute] = useAttributeValues([ATTRIBUTE_KEY]);
4837
+ const { optedIn, trackingTicketId, idempotencyKey, insertionId, sessionId } = decodePrepurchaseAttribute(rawAttribute);
4838
+ if (!optedIn) return /* @__PURE__ */ jsx$1(ThankYouIncentive, { enabled: !editor });
4839
+ if (!trackingTicketId || !idempotencyKey || !insertionId) return null;
4840
+ return /* @__PURE__ */ jsx$1(TrackingManager, {
4841
+ enabled: !editor,
4842
+ sessionId: sessionId ?? void 0,
4843
+ trackingTicketId,
4844
+ children: /* @__PURE__ */ jsx$1(OrderSubmitter, {
4845
+ trackingTicketId,
4846
+ idempotencyKey,
4847
+ insertionId
4848
+ })
4849
+ });
4850
+ }
4851
+ function ThankYouIncentive({ enabled }) {
4852
+ const { data } = useGetIncentive("THANK_YOU");
4853
+ const { sessionId, trackingTicketId } = getTrackingIdentifiers(data);
4854
+ if (!data || !sessionId) return null;
4855
+ return /* @__PURE__ */ jsx$1(TrackingManager, {
4856
+ enabled,
4857
+ sessionId,
4858
+ trackingTicketId,
4859
+ children: /* @__PURE__ */ jsx$1(ThankYouWidget, {
4860
+ incentiveResponse: data,
4861
+ enabled
4862
+ })
4863
+ });
4864
+ }
4865
+ function ThankYouWidget({ incentiveResponse, enabled }) {
4866
+ const { track } = useEventTracker();
4867
+ const incentive = "tracking_ticket_id" in incentiveResponse ? incentiveResponse : void 0;
4868
+ const { data: intent } = useCreateOrderIntent(incentive?.tracking_ticket_id ?? null, incentive?.idempotency_key ?? null, incentive?.incentive.insertion_id ?? null, enabled && Boolean(incentive));
4869
+ useEffect(() => {
4870
+ track({ type: "WIDGET_LOAD" });
4871
+ track({ type: "WIDGET_DISPLAY" });
4872
+ }, [track]);
4873
+ if (!incentive || !intent?.launch_url) return null;
4874
+ return /* @__PURE__ */ jsx$1(ThankYouClaimWidget, {
4875
+ incentive,
4876
+ launchUrl: intent.launch_url
4877
+ });
4878
+ }
4879
+ function OrderSubmitter({ trackingTicketId, idempotencyKey, insertionId }) {
4880
+ const { data } = useSubmitOrder(trackingTicketId, idempotencyKey, insertionId);
4881
+ const { track } = useEventTracker();
4882
+ const display = data?.display;
4883
+ if (!display) return null;
4884
+ return /* @__PURE__ */ jsx$1("s-box", {
4885
+ borderRadius: "large",
4886
+ background: "subdued",
4887
+ padding: "large-200",
4888
+ children: /* @__PURE__ */ jsxs("s-grid", {
4889
+ gridTemplateColumns: "36px 1fr auto",
4890
+ gap: "base",
4891
+ alignItems: "center",
4892
+ children: [
4893
+ /* @__PURE__ */ jsx$1("s-image", {
4894
+ src: display.logo_url,
4895
+ alt: "Rakuten Logo",
4896
+ aspectRatio: "1"
4897
+ }),
4898
+ /* @__PURE__ */ jsx$1(PortableTextRenderer, {
4899
+ value: display.blocks,
4900
+ spacing: "extraTight"
4901
+ }),
4902
+ /* @__PURE__ */ jsx$1("s-button", {
4903
+ href: display.action.href,
4904
+ target: "_blank",
4905
+ tone: "neutral",
4906
+ variant: "primary",
4907
+ onClick: () => track({
4908
+ type: "ELEMENT_CLICK",
4909
+ target: "CONSUMER_REDIRECT"
4910
+ }),
4911
+ children: display.action.label
4912
+ })
4913
+ ]
4914
+ })
4915
+ });
4916
+ }
4917
+ //#endregion
4918
+ export { DiscoRecommendations as a, PrepurchaseIncentive as i, PrepurchaseThankYou as n, Recommendations as o, DiscoPrepurchaseIncentive as r, DiscoPrepurchaseThankYou as t };
4919
+
4920
+ //# sourceMappingURL=DiscoPrepurchaseThankYou-COYkyyEU.js.map