@quantaroute/checkout 1.3.2 → 1.4.0

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