@quantaroute/checkout 1.3.2 → 1.4.1

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.
@@ -1,12 +1,34 @@
1
- import React, { useState } from 'react';
1
+ import React, { useState, useMemo, useEffect, useRef, useCallback } from 'react';
2
+ import type { CSSProperties } from 'react';
2
3
  import MapPinSelector from './MapPinSelector';
3
4
  import AddressForm from './AddressForm';
4
- import type { CheckoutWidgetProps, CompleteAddress } from '../core/types';
5
+ import PhoneStep from './PhoneStep';
6
+ import OtpStep from './OtpStep';
7
+ import SavedAddressStep from './SavedAddressStep';
8
+ import {
9
+ createAddress,
10
+ notifyAddressCompleted,
11
+ logFunnelEvent,
12
+ notifySessionAbandoned,
13
+ fetchSessionOffer,
14
+ type SessionOffer,
15
+ } from '../core/checkout-api';
16
+ import type { CheckoutEvent, CheckoutWidgetProps, CompleteAddress } from '../core/types';
17
+ import type { SavedAddress } from '../core/checkout-api';
18
+ import type { SessionContextPayload } from '../core/checkout-api';
19
+ import CodAvailabilityBanner from './CodAvailabilityBanner';
20
+ import PrepaidNudge from './PrepaidNudge';
21
+ import PaymentStep from './PaymentStep';
22
+ import EmailStep from './EmailStep';
23
+ import EmailOtpStep from './EmailOtpStep';
24
+ import { getWebDeviceContext } from '../core/device';
25
+ import { captureUtmFromUrl } from '../core/utm';
5
26
  import '../styles/checkout.css';
6
27
 
7
28
  // ─── Types ────────────────────────────────────────────────────────────────────
8
29
 
9
- type Step = 'map' | 'form' | 'done';
30
+ /** Full step machine — auth gate is phone, email, or none */
31
+ type Step = 'phone' | 'otp' | 'email' | 'email-otp' | 'saved' | 'map' | 'form' | 'payment' | 'done';
10
32
 
11
33
  interface ConfirmedLocation {
12
34
  lat: number;
@@ -14,6 +36,13 @@ interface ConfirmedLocation {
14
36
  digipin: string;
15
37
  }
16
38
 
39
+ interface AuthState {
40
+ mobile: string;
41
+ sessionToken: string;
42
+ sessionId: string;
43
+ buyerId: string;
44
+ }
45
+
17
46
  // ─── Success screen ───────────────────────────────────────────────────────────
18
47
 
19
48
  interface SuccessScreenProps {
@@ -50,17 +79,63 @@ const SuccessScreen: React.FC<SuccessScreenProps> = ({ address, onEditAddress })
50
79
  </div>
51
80
  );
52
81
 
82
+ // ─── Step indicator ───────────────────────────────────────────────────────────
83
+
84
+ type AuthMode = 'phone' | 'email' | 'none';
85
+
86
+ function stepToIndex(step: Step, mode: AuthMode, withPayment: boolean): number {
87
+ if (mode === 'none') {
88
+ if (withPayment) {
89
+ const order: Step[] = ['map', 'form', 'payment', 'done'];
90
+ const idx = order.indexOf(step);
91
+ return idx === -1 ? 0 : idx;
92
+ }
93
+ return step === 'map' ? 0 : step === 'form' ? 1 : 2;
94
+ }
95
+ const order: Step[] =
96
+ mode === 'email'
97
+ ? withPayment
98
+ ? ['email', 'email-otp', 'saved', 'map', 'form', 'payment', 'done']
99
+ : ['email', 'email-otp', 'saved', 'map', 'form', 'done']
100
+ : withPayment
101
+ ? ['phone', 'otp', 'saved', 'map', 'form', 'payment', 'done']
102
+ : ['phone', 'otp', 'saved', 'map', 'form', 'done'];
103
+ const idx = order.indexOf(step);
104
+ return idx === -1 ? 0 : idx;
105
+ }
106
+
107
+ function totalSteps(mode: AuthMode, withPayment: boolean): number {
108
+ if (mode === 'none') return withPayment ? 3 : 2;
109
+ return withPayment ? 6 : 5;
110
+ }
111
+
112
+ /** Merge merchant `brandColor` into CSS variables consumed by checkout.css */
113
+ function mergeBrandRootStyle(
114
+ base: CSSProperties | undefined,
115
+ brandColor: string | undefined
116
+ ): CSSProperties | undefined {
117
+ const trimmed = brandColor?.trim();
118
+ if (!trimmed) return base;
119
+ const vars: CSSProperties = {
120
+ ['--qr-primary' as string]: trimmed,
121
+ ['--qr-primary-dark' as string]: trimmed,
122
+ ['--qr-border-focus' as string]: trimmed,
123
+ ['--qr-primary-light' as string]: `color-mix(in srgb, ${trimmed} 18%, white)`,
124
+ };
125
+ return base ? { ...base, ...vars } : vars;
126
+ }
127
+
53
128
  // ─── Main Widget ──────────────────────────────────────────────────────────────
54
129
 
55
130
  /**
56
131
  * QuantaRoute Checkout Widget
57
132
  *
58
- * A two-step, mobile-first address collection component:
59
- * Step 1 – Map: user pins their exact location (DigiPin shown offline, real-time)
60
- * Step 2 – Form: auto-filled address + manual flat/building details
133
+ * Default (enablePhoneAuth = false):
134
+ * map → form → done
61
135
  *
62
- * Works in React, Next.js, Nuxt (via nuxt-module), Vite, etc.
63
- * Embed as a script tag (vanilla JS) via the UMD build.
136
+ * With phone auth (enablePhoneAuth = true):
137
+ * phone → otp → saved → map → form → done
138
+ * (buyer can skip phone auth to go straight to map)
64
139
  */
65
140
  const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
66
141
  apiKey,
@@ -76,76 +151,491 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
76
151
  title = 'Add Delivery Address',
77
152
  indiaBoundaryUrl,
78
153
  enableSearch = true,
154
+ enablePhoneAuth = false,
155
+ merchantId = '',
156
+ supabaseFunctionBaseUrl = '',
157
+ brandColor,
158
+ logoUrl,
159
+ headerBanner,
160
+ onCheckoutEvent,
161
+ enableCod = false,
162
+ codCartTotalPaise,
163
+ codSessionToken = '',
164
+ enableEmailAuth = false,
165
+ variant,
166
+ utmParams: utmParamsProp,
167
+ enablePayment = false,
168
+ paymentAmountPaise,
169
+ onPaymentComplete,
170
+ enablePrepaidNudge = false,
171
+ prepaidNudgeCopy,
172
+ prepaidNudgeCtaUrl,
79
173
  }) => {
80
- const [step, setStep] = useState<Step>('map');
174
+ const authMode: AuthMode = enablePhoneAuth ? 'phone' : enableEmailAuth ? 'email' : 'none';
175
+ const initialStep: Step = authMode === 'phone' ? 'phone' : authMode === 'email' ? 'email' : 'map';
176
+ const withPayment = Boolean(enablePayment && paymentAmountPaise && supabaseFunctionBaseUrl);
177
+
178
+ const [step, setStep] = useState<Step>(initialStep);
81
179
  const [confirmedLocation, setConfirmedLocation] = useState<ConfirmedLocation | null>(null);
82
180
  const [completedAddress, setCompletedAddress] = useState<CompleteAddress | null>(null);
181
+ const [auth, setAuth] = useState<AuthState | null>(null);
182
+ const [emailPending, setEmailPending] = useState('');
183
+ const [emailCodeReused, setEmailCodeReused] = useState(false);
184
+ const [codAllowed, setCodAllowed] = useState(false);
185
+ const [sessionOffer, setSessionOffer] = useState<SessionOffer | null>(null);
186
+ const [paymentMethod, setPaymentMethod] = useState<string | null>(null);
187
+ const stepRef = useRef(step);
188
+
189
+ const utmParams = useMemo(
190
+ () => utmParamsProp ?? captureUtmFromUrl(),
191
+ [utmParamsProp]
192
+ );
193
+
194
+ const deviceCtx = useMemo(() => getWebDeviceContext(), []);
195
+
196
+ const sessionContext: SessionContextPayload = useMemo(
197
+ () => ({
198
+ utm_source: utmParams.utm_source,
199
+ utm_medium: utmParams.utm_medium,
200
+ utm_campaign: utmParams.utm_campaign,
201
+ device_type: deviceCtx.deviceType,
202
+ platform: deviceCtx.platform,
203
+ user_agent: deviceCtx.userAgent,
204
+ experiment_variant: variant,
205
+ }),
206
+ [utmParams, deviceCtx, variant]
207
+ );
208
+
209
+ const checkoutConfig = {
210
+ functionBaseUrl: supabaseFunctionBaseUrl,
211
+ merchantId,
212
+ };
213
+
214
+ const codSession = auth?.sessionToken || codSessionToken;
215
+
216
+ useEffect(() => {
217
+ stepRef.current = step;
218
+ }, [step]);
219
+
220
+ const authChannel = (): CheckoutEvent['authChannel'] => {
221
+ if (authMode === 'phone') return 'phone';
222
+ if (authMode === 'email') return 'email';
223
+ return 'none';
224
+ };
225
+
226
+ /** Fire client + server analytics without blocking the UI. */
227
+ const emit = useCallback(
228
+ (partial: Omit<CheckoutEvent, 'timestamp'>) => {
229
+ const event: CheckoutEvent = {
230
+ ...partial,
231
+ sessionId: partial.sessionId ?? auth?.sessionId,
232
+ buyerId: partial.buyerId ?? auth?.buyerId,
233
+ authChannel: partial.authChannel ?? authChannel(),
234
+ deviceType: partial.deviceType ?? deviceCtx.deviceType,
235
+ platform: partial.platform ?? deviceCtx.platform,
236
+ userAgent: partial.userAgent ?? deviceCtx.userAgent,
237
+ experimentVariant: partial.experimentVariant ?? variant,
238
+ timestamp: new Date().toISOString(),
239
+ };
240
+
241
+ if (onCheckoutEvent) {
242
+ try {
243
+ onCheckoutEvent(event);
244
+ } catch {
245
+ // Never let analytics crash the checkout
246
+ }
247
+ }
248
+
249
+ if (merchantId && supabaseFunctionBaseUrl) {
250
+ logFunnelEvent(
251
+ checkoutConfig,
252
+ {
253
+ event_type: event.type,
254
+ step: event.step,
255
+ buyer_id: event.buyerId,
256
+ auth_channel: event.authChannel,
257
+ device_type: event.deviceType,
258
+ platform: event.platform,
259
+ user_agent: event.userAgent,
260
+ payment_method: event.paymentMethod,
261
+ experiment_variant: event.experimentVariant,
262
+ },
263
+ auth?.sessionToken
264
+ ).catch(() => {/* silent */});
265
+ }
266
+ },
267
+ [
268
+ auth,
269
+ authMode,
270
+ deviceCtx,
271
+ variant,
272
+ onCheckoutEvent,
273
+ merchantId,
274
+ supabaseFunctionBaseUrl,
275
+ checkoutConfig,
276
+ ]
277
+ );
278
+
279
+ // Explicit abandon on tab close / navigate away
280
+ useEffect(() => {
281
+ if (!merchantId || !supabaseFunctionBaseUrl) return;
282
+
283
+ const onLeave = () => {
284
+ if (stepRef.current === 'done' || !auth?.sessionToken) return;
285
+ notifySessionAbandoned(checkoutConfig, auth.sessionToken, stepRef.current).catch(() => {});
286
+ emit({ type: 'session_abandoned', step: stepRef.current });
287
+ };
288
+
289
+ window.addEventListener('pagehide', onLeave);
290
+ return () => window.removeEventListener('pagehide', onLeave);
291
+ }, [auth?.sessionToken, merchantId, supabaseFunctionBaseUrl, checkoutConfig, emit]);
292
+
293
+ // Fetch UTM-matched offer after auth
294
+ useEffect(() => {
295
+ if (!auth?.sessionToken || !merchantId || !supabaseFunctionBaseUrl) return;
296
+ fetchSessionOffer(checkoutConfig, auth.sessionToken)
297
+ .then(setSessionOffer)
298
+ .catch(() => setSessionOffer(null));
299
+ }, [auth?.sessionToken, merchantId, supabaseFunctionBaseUrl, checkoutConfig]);
300
+
301
+ const rootStyle = useMemo(
302
+ () => mergeBrandRootStyle(style as CSSProperties | undefined, brandColor),
303
+ [style, brandColor]
304
+ );
83
305
 
84
- // ── Handlers ──────────────────────────────────────────────────────────────
306
+ // ── Phone step callbacks ──────────────────────────────────────────────────
307
+
308
+ const handleOtpSent = (mobile: string) => {
309
+ setAuth((prev) => ({ mobile, sessionToken: '', sessionId: '', buyerId: prev?.buyerId ?? '' }));
310
+ emit({ type: 'otp_sent', step: 'otp', mobile });
311
+ setStep('otp');
312
+ };
313
+
314
+ const handleVerified = (sessionToken: string, buyerId: string, sessionId?: string) => {
315
+ setAuth({ mobile: auth?.mobile ?? '', sessionToken, sessionId: sessionId ?? '', buyerId });
316
+ emit({ type: 'phone_verified', step: 'saved', buyerId, sessionId });
317
+ setStep('saved');
318
+ };
319
+
320
+ const handleSkipAuth = () => {
321
+ emit({ type: 'auth_skipped', step: 'map' });
322
+ setStep('map');
323
+ };
324
+
325
+ // ── Email step callbacks ──────────────────────────────────────────────────
326
+
327
+ const handleEmailOtpSent = (sentEmail: string, info?: { reused?: boolean }) => {
328
+ setEmailPending(sentEmail);
329
+ setEmailCodeReused(Boolean(info?.reused));
330
+ emit({ type: 'email_otp_sent', step: 'email-otp', mobile: sentEmail });
331
+ setStep('email-otp');
332
+ };
333
+
334
+ const handleEmailVerified = (sessionToken: string, buyerId: string, sessionId?: string) => {
335
+ setAuth({ mobile: emailPending, sessionToken, sessionId: sessionId ?? '', buyerId });
336
+ emit({ type: 'email_verified', step: 'saved', buyerId, sessionId });
337
+ setStep('saved');
338
+ };
339
+
340
+ // ── Saved addresses callbacks ─────────────────────────────────────────────
341
+
342
+ const handleSelectSavedAddress = (saved: SavedAddress) => {
343
+ emit({ type: 'saved_address_selected', step: withPayment ? 'payment' : 'done', buyerId: auth?.buyerId, digipin: saved.digipin });
344
+ if (auth?.sessionToken) {
345
+ notifyAddressCompleted(checkoutConfig, auth.sessionToken, {
346
+ pincode: saved.pincode,
347
+ digipin: saved.digipin,
348
+ state: saved.state,
349
+ district: saved.district,
350
+ locality: saved.locality,
351
+ }).catch(() => {/* silent */});
352
+ }
353
+ const complete: CompleteAddress = {
354
+ digipin: saved.digipin,
355
+ lat: saved.lat,
356
+ lng: saved.lng,
357
+ state: saved.state,
358
+ district: saved.district,
359
+ division: '',
360
+ locality: saved.locality,
361
+ pincode: saved.pincode,
362
+ delivery: saved.delivery_status,
363
+ country: 'India',
364
+ flatNumber: saved.flat_number,
365
+ floorNumber: saved.floor_number,
366
+ buildingName: saved.building_name,
367
+ streetName: saved.street_name,
368
+ formattedAddress: [
369
+ saved.flat_number,
370
+ saved.building_name,
371
+ saved.street_name,
372
+ saved.locality,
373
+ saved.district,
374
+ saved.state,
375
+ saved.pincode,
376
+ ]
377
+ .filter(Boolean)
378
+ .join(', '),
379
+ };
380
+ void finishAddress(complete);
381
+ };
382
+
383
+ const handlePaymentComplete = (method: string) => {
384
+ setPaymentMethod(method);
385
+ emit({ type: 'payment_method_selected', step: 'done', paymentMethod: method });
386
+ setStep('done');
387
+ if (completedAddress) onComplete(completedAddress);
388
+ onPaymentComplete?.({ paymentMethod: method, sessionId: auth?.sessionId });
389
+ };
390
+
391
+ // ── Map step callbacks ────────────────────────────────────────────────────
85
392
 
86
393
  const handleLocationConfirm = (lat: number, lng: number, digipin: string) => {
87
394
  setConfirmedLocation({ lat, lng, digipin });
395
+ emit({ type: 'location_confirmed', step: 'form', digipin, buyerId: auth?.buyerId });
88
396
  setStep('form');
89
397
  };
90
398
 
91
- const handleAddressComplete = (address: CompleteAddress) => {
399
+ // ── Form step callbacks ───────────────────────────────────────────────────
400
+
401
+ const finishAddress = async (address: CompleteAddress) => {
92
402
  setCompletedAddress(address);
93
- setStep('done');
94
- onComplete(address);
403
+ emit({ type: 'address_completed', step: withPayment ? 'payment' : 'done', digipin: address.digipin, buyerId: auth?.buyerId });
404
+
405
+ if (auth?.sessionToken) {
406
+ notifyAddressCompleted(checkoutConfig, auth.sessionToken, {
407
+ pincode: address.pincode,
408
+ digipin: address.digipin,
409
+ state: address.state,
410
+ district: address.district,
411
+ locality: address.locality,
412
+ }).catch(() => {/* silent */});
413
+
414
+ try {
415
+ await createAddress(checkoutConfig, auth.sessionToken, {
416
+ digipin: address.digipin,
417
+ lat: address.lat,
418
+ lng: address.lng,
419
+ state: address.state,
420
+ district: address.district,
421
+ locality: address.locality,
422
+ pincode: address.pincode,
423
+ delivery_status: address.delivery,
424
+ flat_number: address.flatNumber,
425
+ floor_number: address.floorNumber,
426
+ building_name: address.buildingName,
427
+ street_name: address.streetName,
428
+ full_address_json: address as unknown as Record<string, unknown>,
429
+ label: 'home',
430
+ is_default: true,
431
+ });
432
+ } catch {
433
+ // Silent
434
+ }
435
+ }
436
+
437
+ if (withPayment && codSession) {
438
+ setStep('payment');
439
+ } else {
440
+ setStep('done');
441
+ onComplete(address);
442
+ }
443
+ };
444
+
445
+ const handleAddressComplete = async (address: CompleteAddress) => {
446
+ await finishAddress(address);
95
447
  };
96
448
 
97
449
  const handleBack = () => {
98
- setStep('map');
450
+ if (step === 'form') {
451
+ setStep('map');
452
+ } else if (step === 'map' && auth?.sessionToken) {
453
+ setStep('saved');
454
+ } else if (step === 'email-otp') {
455
+ setStep('email');
456
+ }
99
457
  };
100
458
 
101
459
  const handleEditAddress = () => {
102
- setStep('map');
460
+ emit({ type: 'widget_reset', step: initialStep });
461
+ setStep(initialStep);
103
462
  setConfirmedLocation(null);
104
463
  setCompletedAddress(null);
105
464
  };
106
465
 
107
- // ── Step indicator ─────────────────────────────────────────────────────────
466
+ // ── Emit "step viewed" event on every step change ────────────────────────
108
467
 
109
- const renderStepDots = () => (
110
- <div className="qr-progress" aria-label="Progress: step ${ step === 'map' ? 1 : 2 } of 2" role="progressbar">
111
- <div className={`qr-progress__dot ${step === 'map' || step === 'form' || step === 'done' ? 'qr-progress__dot--active' : ''}`} />
112
- <div className={`qr-progress__line ${step === 'form' || step === 'done' ? 'qr-progress__line--active' : ''}`} />
113
- <div className={`qr-progress__dot ${step === 'form' || step === 'done' ? 'qr-progress__dot--active' : ''}`} />
114
- </div>
115
- );
468
+ useEffect(() => {
469
+ // OTP steps fire send events in handlers; only emit step-viewed here.
470
+ const viewedMap: Partial<Record<Step, CheckoutEvent['type']>> = {
471
+ phone: 'phone_step_viewed',
472
+ email: 'email_step_viewed',
473
+ saved: 'saved_addresses_viewed',
474
+ map: 'map_step_viewed',
475
+ form: 'form_step_viewed',
476
+ payment: 'payment_step_viewed',
477
+ };
478
+ const eventType = viewedMap[step];
479
+ if (!eventType) return;
480
+ emit({ type: eventType, step, buyerId: auth?.buyerId });
481
+ // eslint-disable-next-line react-hooks/exhaustive-deps
482
+ }, [step]);
483
+
484
+ useEffect(() => {
485
+ if (!enableEmailAuth || authMode !== 'email') return;
486
+ if (merchantId && supabaseFunctionBaseUrl) return;
487
+ onError?.(
488
+ new Error(
489
+ 'enableEmailAuth requires merchantId and supabaseFunctionBaseUrl on CheckoutWidget.'
490
+ )
491
+ );
492
+ }, [enableEmailAuth, authMode, merchantId, supabaseFunctionBaseUrl, onError]);
116
493
 
117
- // ── Render ─────────────────────────────────────────────────────────────────
494
+ const currentIndex = stepToIndex(step, authMode, withPayment);
495
+ const total = totalSteps(authMode, withPayment);
496
+
497
+ const renderProgress = () => {
498
+ const dots = Array.from({ length: total + 1 }, (_, i) => i);
499
+ return (
500
+ <div
501
+ className="qr-progress"
502
+ role="progressbar"
503
+ aria-valuenow={currentIndex + 1}
504
+ aria-valuemin={1}
505
+ aria-valuemax={total + 1}
506
+ aria-label={`Step ${currentIndex + 1} of ${total + 1}`}
507
+ >
508
+ {dots.map((i) => (
509
+ <React.Fragment key={i}>
510
+ <div className={`qr-progress__dot${currentIndex >= i ? ' qr-progress__dot--active' : ''}`} />
511
+ {i < total && (
512
+ <div className={`qr-progress__line${currentIndex > i ? ' qr-progress__line--active' : ''}`} />
513
+ )}
514
+ </React.Fragment>
515
+ ))}
516
+ </div>
517
+ );
518
+ };
519
+
520
+ // ── Render ────────────────────────────────────────────────────────────────
118
521
 
119
522
  return (
120
523
  <div
121
524
  className={`qr-checkout qr-checkout--${theme} ${className}`}
122
- style={style}
525
+ style={rootStyle}
123
526
  data-testid="quantaroute-checkout"
124
527
  >
125
528
  {/* Widget header */}
126
529
  {step !== 'done' && (
127
- <div className="qr-header">
128
- <div className="qr-header__brand">
129
- <svg
130
- className="qr-header__logo"
131
- aria-hidden="true"
132
- viewBox="0 0 24 24"
133
- fill="none"
134
- stroke="currentColor"
135
- strokeWidth="2"
136
- strokeLinecap="round"
137
- strokeLinejoin="round"
138
- >
139
- <path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z" />
140
- <circle cx="12" cy="10" r="3" />
141
- </svg>
142
- <span className="qr-header__title">{title}</span>
530
+ <>
531
+ <div className="qr-header">
532
+ <div className="qr-header__brand">
533
+ {logoUrl ? (
534
+ <img
535
+ src={logoUrl}
536
+ alt=""
537
+ className="qr-header__logo-img"
538
+ width={28}
539
+ height={28}
540
+ decoding="async"
541
+ />
542
+ ) : (
543
+ <svg
544
+ className="qr-header__logo"
545
+ aria-hidden="true"
546
+ viewBox="0 0 24 24"
547
+ fill="none"
548
+ stroke="currentColor"
549
+ strokeWidth="2"
550
+ strokeLinecap="round"
551
+ strokeLinejoin="round"
552
+ >
553
+ <path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z" />
554
+ <circle cx="12" cy="10" r="3" />
555
+ </svg>
556
+ )}
557
+ <span className="qr-header__title">{title}</span>
558
+ </div>
559
+ {renderProgress()}
143
560
  </div>
144
- {renderStepDots()}
145
- </div>
561
+ {headerBanner ? (
562
+ <div className="qr-header-banner" role="region" aria-label="Merchant message">
563
+ {headerBanner}
564
+ </div>
565
+ ) : null}
566
+ {sessionOffer ? (
567
+ <div className="qr-offer-banner" role="region" aria-label="Special offer">
568
+ {sessionOffer.banner_copy}
569
+ {sessionOffer.banner_cta_url ? (
570
+ <>
571
+ {' '}
572
+ <a href={sessionOffer.banner_cta_url} target="_blank" rel="noopener noreferrer">
573
+ Learn more
574
+ </a>
575
+ </>
576
+ ) : null}
577
+ </div>
578
+ ) : null}
579
+ </>
580
+ )}
581
+
582
+ {/* ── Email step ── */}
583
+ {step === 'email' && enableEmailAuth && (
584
+ <EmailStep
585
+ onOtpSent={handleEmailOtpSent}
586
+ onSkip={handleSkipAuth}
587
+ functionBaseUrl={supabaseFunctionBaseUrl}
588
+ merchantId={merchantId}
589
+ />
590
+ )}
591
+
592
+ {/* ── Email OTP step ── */}
593
+ {step === 'email-otp' && enableEmailAuth && emailPending && (
594
+ <EmailOtpStep
595
+ email={emailPending}
596
+ codeReused={emailCodeReused}
597
+ onVerified={handleEmailVerified}
598
+ onBack={() => setStep('email')}
599
+ functionBaseUrl={supabaseFunctionBaseUrl}
600
+ merchantId={merchantId}
601
+ sessionContext={sessionContext}
602
+ />
603
+ )}
604
+
605
+ {/* ── Phone step ── */}
606
+ {step === 'phone' && enablePhoneAuth && (
607
+ <PhoneStep
608
+ onOtpSent={handleOtpSent}
609
+ onSkip={handleSkipAuth}
610
+ functionBaseUrl={supabaseFunctionBaseUrl}
611
+ merchantId={merchantId}
612
+ />
146
613
  )}
147
614
 
148
- {/* ── Step 1: Map ── */}
615
+ {/* ── OTP step ── */}
616
+ {step === 'otp' && auth && (
617
+ <OtpStep
618
+ mobile={auth.mobile}
619
+ onVerified={handleVerified}
620
+ onBack={() => setStep('phone')}
621
+ functionBaseUrl={supabaseFunctionBaseUrl}
622
+ merchantId={merchantId}
623
+ sessionContext={sessionContext}
624
+ />
625
+ )}
626
+
627
+ {/* ── Saved addresses step ── */}
628
+ {step === 'saved' && auth?.sessionToken && (
629
+ <SavedAddressStep
630
+ sessionToken={auth.sessionToken}
631
+ functionBaseUrl={supabaseFunctionBaseUrl}
632
+ merchantId={merchantId}
633
+ onSelectAddress={handleSelectSavedAddress}
634
+ onAddNew={() => setStep('map')}
635
+ />
636
+ )}
637
+
638
+ {/* ── Map step ── */}
149
639
  {step === 'map' && (
150
640
  <MapPinSelector
151
641
  onLocationConfirm={handleLocationConfirm}
@@ -157,10 +647,11 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
157
647
  enableSearch={enableSearch}
158
648
  apiKey={apiKey}
159
649
  apiBaseUrl={apiBaseUrl}
650
+ brandColor={brandColor}
160
651
  />
161
652
  )}
162
653
 
163
- {/* ── Step 2: Form ── */}
654
+ {/* ── Form step ── */}
164
655
  {step === 'form' && confirmedLocation && (
165
656
  <AddressForm
166
657
  digipin={confirmedLocation.digipin}
@@ -175,9 +666,53 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
175
666
  />
176
667
  )}
177
668
 
178
- {/* ── Step 3: Done ── */}
669
+ {/* ── Payment step ── */}
670
+ {step === 'payment' && withPayment && codSession && paymentAmountPaise && (
671
+ <PaymentStep
672
+ checkoutConfig={checkoutConfig}
673
+ sessionToken={codSession}
674
+ sessionId={auth?.sessionId}
675
+ amountPaise={paymentAmountPaise}
676
+ enableCod={enableCod}
677
+ codAllowed={codAllowed}
678
+ theme={theme}
679
+ onComplete={handlePaymentComplete}
680
+ onBack={() => setStep('form')}
681
+ onEvent={(type, paymentMethod) =>
682
+ emit({ type, step: 'payment', paymentMethod, buyerId: auth?.buyerId })
683
+ }
684
+ />
685
+ )}
686
+
687
+ {/* ── Done ── */}
179
688
  {step === 'done' && completedAddress && (
180
- <SuccessScreen address={completedAddress} onEditAddress={handleEditAddress} />
689
+ <>
690
+ <SuccessScreen address={completedAddress} onEditAddress={handleEditAddress} />
691
+ {paymentMethod ? (
692
+ <p className="qr-cod-banner__text qr-cod-banner__text--ok" style={{ textAlign: 'center', margin: '8px 16px' }}>
693
+ Paid via {paymentMethod === 'cod' ? 'Cash on Delivery' : 'online payment'}
694
+ </p>
695
+ ) : null}
696
+ {enableCod && merchantId && supabaseFunctionBaseUrl && codSession ? (
697
+ <>
698
+ <CodAvailabilityBanner
699
+ checkoutConfig={checkoutConfig}
700
+ sessionToken={codSession}
701
+ pincode={completedAddress.pincode}
702
+ cartTotalPaise={codCartTotalPaise ?? paymentAmountPaise}
703
+ theme={theme}
704
+ onCodAllowedChange={setCodAllowed}
705
+ />
706
+ {enablePrepaidNudge && codAllowed ? (
707
+ <PrepaidNudge
708
+ copy={prepaidNudgeCopy ?? 'Save more when you pay online — faster delivery & exclusive offers.'}
709
+ ctaUrl={prepaidNudgeCtaUrl}
710
+ theme={theme}
711
+ />
712
+ ) : null}
713
+ </>
714
+ ) : null}
715
+ </>
181
716
  )}
182
717
 
183
718
  {/* Powered-by footer */}