@disconetwork/shopify 0.0.7 → 0.0.8

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