@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,5 +1,5 @@
1
1
  /*!
2
- * @quantaroute/checkout v1.3.2
2
+ * @quantaroute/checkout v1.4.0
3
3
  * (c) 2026 QuantaRoute – https://quantaroute.com
4
4
  * Released under the MIT License.
5
5
  *
@@ -18,1287 +18,240 @@
18
18
  * expo-osm-sdk >= 2.0.0
19
19
  * expo-location >= 17.0.0
20
20
  */
21
- import { jsxs, jsx, Fragment } from "react/jsx-runtime";
22
- import { useState, useCallback, useRef, useId, useEffect, useReducer, useMemo } from "react";
23
- import maplibregl from "maplibre-gl";
24
- const DIGIPIN_GRID = [
25
- ["F", "C", "9", "8"],
26
- ["J", "3", "2", "7"],
27
- ["K", "4", "5", "6"],
28
- ["L", "M", "P", "T"]
29
- ];
30
- const BOUNDS = {
31
- minLat: 2.5,
32
- maxLat: 38.5,
33
- minLon: 63.5,
34
- maxLon: 99.5
35
- };
36
- function getDigiPin(lat, lon) {
37
- if (lat < BOUNDS.minLat || lat > BOUNDS.maxLat) {
38
- throw new Error(
39
- `Latitude ${lat} out of range. Must be between ${BOUNDS.minLat} and ${BOUNDS.maxLat}`
40
- );
41
- }
42
- if (lon < BOUNDS.minLon || lon > BOUNDS.maxLon) {
43
- throw new Error(
44
- `Longitude ${lon} out of range. Must be between ${BOUNDS.minLon} and ${BOUNDS.maxLon}`
45
- );
46
- }
47
- let minLat = BOUNDS.minLat;
48
- let maxLat = BOUNDS.maxLat;
49
- let minLon = BOUNDS.minLon;
50
- let maxLon = BOUNDS.maxLon;
51
- let digiPin = "";
52
- for (let level = 1; level <= 10; level++) {
53
- const latDiv = (maxLat - minLat) / 4;
54
- const lonDiv = (maxLon - minLon) / 4;
55
- let row = 3 - Math.floor((lat - minLat) / latDiv);
56
- let col = Math.floor((lon - minLon) / lonDiv);
57
- row = Math.max(0, Math.min(row, 3));
58
- col = Math.max(0, Math.min(col, 3));
59
- digiPin += DIGIPIN_GRID[row][col];
60
- if (level === 3 || level === 6) digiPin += "-";
61
- maxLat = minLat + latDiv * (4 - row);
62
- minLat = minLat + latDiv * (3 - row);
63
- minLon = minLon + lonDiv * col;
64
- maxLon = minLon + lonDiv;
65
- }
66
- return digiPin;
67
- }
68
- function getLatLngFromDigiPin(digiPin) {
69
- const pin = digiPin.replace(/-/g, "");
70
- if (pin.length !== 10) {
71
- throw new Error("Invalid DIGIPIN: must be 10 characters (excluding dashes)");
72
- }
73
- let minLat = BOUNDS.minLat;
74
- let maxLat = BOUNDS.maxLat;
75
- let minLon = BOUNDS.minLon;
76
- let maxLon = BOUNDS.maxLon;
77
- for (let i = 0; i < 10; i++) {
78
- const char = pin[i];
79
- let found = false;
80
- let ri = -1;
81
- let ci = -1;
82
- for (let r = 0; r < 4; r++) {
83
- for (let c = 0; c < 4; c++) {
84
- if (DIGIPIN_GRID[r][c] === char) {
85
- ri = r;
86
- ci = c;
87
- found = true;
88
- break;
89
- }
90
- }
91
- if (found) break;
92
- }
93
- if (!found) {
94
- throw new Error(`Invalid character in DIGIPIN: '${char}'`);
95
- }
96
- const latDiv = (maxLat - minLat) / 4;
97
- const lonDiv = (maxLon - minLon) / 4;
98
- const lat1 = maxLat - latDiv * (ri + 1);
99
- const lat2 = maxLat - latDiv * ri;
100
- const lon1 = minLon + lonDiv * ci;
101
- const lon2 = minLon + lonDiv * (ci + 1);
102
- minLat = lat1;
103
- maxLat = lat2;
104
- minLon = lon1;
105
- maxLon = lon2;
106
- }
107
- return {
108
- latitude: ((minLat + maxLat) / 2).toFixed(6),
109
- longitude: ((minLon + maxLon) / 2).toFixed(6)
110
- };
111
- }
112
- function isValidDigiPin(digiPin) {
113
- if (!digiPin || typeof digiPin !== "string") return false;
114
- if (!/^[A-Z0-9]{3}-[A-Z0-9]{3}-[A-Z0-9]{4}$/i.test(digiPin.trim())) return false;
115
- try {
116
- getLatLngFromDigiPin(digiPin.trim().toUpperCase());
117
- return true;
118
- } catch {
119
- return false;
120
- }
121
- }
122
- function isWithinIndia(lat, lon) {
123
- return lat >= BOUNDS.minLat && lat <= BOUNDS.maxLat && lon >= BOUNDS.minLon && lon <= BOUNDS.maxLon;
124
- }
125
- const DEFAULT_BASE_URL = "https://api.quantaroute.com";
126
- const DIGIPIN_PATTERN = /^[FC98J327K456LMPT]{3}-[FC98J327K456LMPT]{3}-[FC98J327K456LMPT]{4}$/i;
127
- function makeTimeoutSignal(ms) {
128
- if (typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") {
129
- return AbortSignal.timeout(ms);
130
- }
131
- const ctrl = new AbortController();
132
- setTimeout(() => ctrl.abort(), ms);
133
- return ctrl.signal;
134
- }
135
- async function lookupLocation(lat, lng, apiKey, baseUrl = DEFAULT_BASE_URL) {
136
- const url = `${baseUrl.replace(/\/$/, "")}/v1/location/lookup`;
137
- let res;
138
- try {
139
- res = await fetch(url, {
140
- method: "POST",
141
- headers: {
142
- "Content-Type": "application/json",
143
- "x-api-key": apiKey
144
- },
145
- body: JSON.stringify({ latitude: lat, longitude: lng }),
146
- signal: makeTimeoutSignal(15e3)
147
- });
148
- } catch (err) {
149
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
150
- throw new Error("Request timed out. Check your internet connection.");
151
- }
152
- throw new Error(`Network error: ${err instanceof Error ? err.message : String(err)}`);
153
- }
154
- if (!res.ok) {
155
- let body = "";
156
- try {
157
- body = await res.text();
158
- } catch {
159
- }
160
- if (res.status === 401 || res.status === 403) {
161
- throw new Error("Invalid API key. Check your QuantaRoute API key.");
162
- }
163
- if (res.status === 429) {
164
- throw new Error("Rate limit exceeded. Upgrade your plan or try again later.");
165
- }
166
- throw new Error(`API error ${res.status}: ${body || res.statusText}`);
167
- }
168
- const data = await res.json();
169
- if (!data.success) {
170
- throw new Error(data.message ?? "Location lookup failed");
171
- }
172
- return data;
173
- }
174
- function looksLikeDigiPin(input) {
175
- return DIGIPIN_PATTERN.test(input.trim().toUpperCase());
176
- }
177
- async function autocompleteAddress(query, apiKey, baseUrl = DEFAULT_BASE_URL, limit = 5, userLat, userLng) {
178
- let url = `${baseUrl.replace(/\/$/, "")}/v1/digipin/autocomplete?q=${encodeURIComponent(query.trim())}&limit=${Math.min(limit, 10)}`;
179
- if (typeof userLat === "number" && typeof userLng === "number") {
180
- url += `&lat=${userLat.toFixed(6)}&lng=${userLng.toFixed(6)}`;
181
- }
182
- let res;
183
- try {
184
- res = await fetch(url, {
185
- method: "GET",
186
- headers: { "x-api-key": apiKey },
187
- signal: makeTimeoutSignal(8e3)
188
- });
189
- } catch (err) {
190
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
191
- throw new Error("Autocomplete request timed out.");
192
- }
193
- throw new Error(`Network error: ${err instanceof Error ? err.message : String(err)}`);
194
- }
195
- if (!res.ok) {
196
- if (res.status === 401 || res.status === 403) {
197
- throw new Error("Invalid API key.");
198
- }
199
- if (res.status === 429) {
200
- throw new Error("Rate limit exceeded.");
201
- }
202
- return [];
203
- }
204
- const data = await res.json();
205
- return data.success ? data.data ?? [] : [];
206
- }
207
- async function reverseGeocode(digipin, apiKey, baseUrl = DEFAULT_BASE_URL) {
208
- const url = `${baseUrl.replace(/\/$/, "")}/v1/digipin/reverse`;
209
- let res;
210
- try {
211
- res = await fetch(url, {
212
- method: "POST",
213
- headers: {
214
- "Content-Type": "application/json",
215
- "x-api-key": apiKey
216
- },
217
- body: JSON.stringify({ digipin }),
218
- signal: makeTimeoutSignal(15e3)
219
- });
220
- } catch (err) {
221
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
222
- throw new Error("Request timed out. Check your internet connection.");
223
- }
224
- throw new Error(`Network error: ${err instanceof Error ? err.message : String(err)}`);
225
- }
226
- if (!res.ok) {
227
- let body = "";
228
- try {
229
- body = await res.text();
230
- } catch {
231
- }
232
- if (res.status === 401 || res.status === 403) {
233
- throw new Error("Invalid API key. Check your QuantaRoute API key.");
234
- }
235
- if (res.status === 429) {
236
- throw new Error("Rate limit exceeded. Upgrade your plan or try again later.");
237
- }
238
- throw new Error(`API error ${res.status}: ${body || res.statusText}`);
239
- }
240
- const data = await res.json();
241
- if (!data.success) {
242
- throw new Error(data.message ?? "Reverse geocoding failed");
243
- }
244
- return data;
245
- }
246
- function useGeolocation() {
247
- const [state, setState] = useState({ loading: false, error: null });
248
- const locate = useCallback((onSuccess) => {
249
- if (!navigator.geolocation) {
250
- setState({ loading: false, error: "Geolocation is not supported by your browser." });
251
- return;
252
- }
253
- setState({ loading: true, error: null });
254
- navigator.geolocation.getCurrentPosition(
255
- ({ coords }) => {
256
- setState({ loading: false, error: null });
257
- onSuccess(coords.latitude, coords.longitude);
258
- },
259
- (err) => {
260
- let message = "Unable to get location.";
261
- if (err.code === err.PERMISSION_DENIED) {
262
- message = "Location permission denied. Please enable it in browser settings.";
263
- } else if (err.code === err.POSITION_UNAVAILABLE) {
264
- message = "Location unavailable. Try again or place the pin manually.";
265
- } else if (err.code === err.TIMEOUT) {
266
- message = "Location request timed out. Try again.";
267
- }
268
- setState({ loading: false, error: message });
269
- },
270
- { enableHighAccuracy: true, timeout: 12e3, maximumAge: 0 }
271
- );
272
- }, []);
273
- const clearError = useCallback(() => {
274
- setState((s) => ({ ...s, error: null }));
275
- }, []);
276
- return { ...state, locate, clearError };
277
- }
278
- const INDIA_CENTER = { lat: 13.00427, lng: 77.589291 };
279
- const MIN_ZOOM = 6;
280
- const OVERVIEW_ZOOM = 9;
281
- const STREET_ZOOM = 18;
282
- const CARTO_STYLE_URL = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json";
283
- const PIN_W = 40;
284
- const PIN_H = 52;
285
- function computeDigiPinSafe(la, lo) {
286
- if (!isWithinIndia(la, lo)) return null;
287
- try {
288
- return getDigiPin(la, lo);
289
- } catch {
290
- return null;
291
- }
292
- }
293
- function createPinElement() {
294
- const el = document.createElement("div");
295
- el.className = "qr-pin";
296
- el.setAttribute("aria-label", "Drag to adjust your location");
297
- el.style.width = `${PIN_W}px`;
298
- el.style.height = `${PIN_H}px`;
299
- el.innerHTML = `
300
- <svg
301
- class="qr-pin__svg"
302
- width="${PIN_W}"
303
- height="${PIN_H}"
304
- viewBox="0 0 ${PIN_W} ${PIN_H}"
305
- overflow="visible"
306
- fill="none"
307
- xmlns="http://www.w3.org/2000/svg"
308
- aria-hidden="true"
309
- >
310
- <defs>
311
- <!--
312
- The filter region must be generous enough to contain the shadow blur.
313
- stdDeviation=3 → ~9px blur radius; our region extends 50% on each side.
314
- overflow="visible" on the <svg> lets it paint outside the viewport.
315
- -->
316
- <filter id="qr-pin-shadow" x="-60%" y="-40%" width="220%" height="220%">
317
- <feDropShadow dx="0" dy="3" stdDeviation="3.5"
318
- flood-color="#000" flood-opacity="0.28"/>
319
- </filter>
320
- </defs>
321
-
322
- <!-- Teardrop body — tip is at (20, 52) = bottom-center of the SVG -->
323
- <path
324
- d="M20 0C9.402 0 0 9.402 0 20C0 34 20 52 20 52S40 34 40 20C40 9.402 30.598 0 20 0Z"
325
- fill="#0ea5e9"
326
- filter="url(#qr-pin-shadow)"
327
- />
328
- <!-- Dot inside the pin -->
329
- <circle cx="20" cy="20" r="9" fill="white"/>
330
- <circle cx="20" cy="20" r="5" fill="#0ea5e9"/>
331
- </svg>
332
-
333
- <!--
334
- Pulse ring — position: absolute inside .qr-pin (position: relative).
335
- bottom: -(height/2) → bottom: -10px centres the 20×20 circle
336
- exactly at y = PIN_H = 52px = the pin tip coordinate.
337
- -->
338
- <div class="qr-pin__pulse" aria-hidden="true"></div>
339
- `;
340
- return el;
341
- }
342
- const MapPinSelector = ({
343
- onLocationConfirm,
344
- defaultLat,
345
- defaultLng,
346
- mapHeight = "380px",
347
- theme: _theme = "light",
348
- indiaBoundaryUrl,
349
- enableSearch = true,
350
- apiKey,
351
- apiBaseUrl
352
- }) => {
353
- const containerRef = useRef(null);
354
- const mapRef = useRef(null);
355
- const markerRef = useRef(null);
356
- const initLat = defaultLat ?? INDIA_CENTER.lat;
357
- const initLng = defaultLng ?? INDIA_CENTER.lng;
358
- const hasDefault = defaultLat !== void 0 && defaultLng !== void 0;
359
- const [lat, setLat] = useState(initLat);
360
- const [lng, setLng] = useState(initLng);
361
- const [digipin, setDigipin] = useState(
362
- () => computeDigiPinSafe(initLat, initLng)
363
- );
364
- const [mapLoaded, setMapLoaded] = useState(false);
365
- const [searchQuery, setSearchQuery] = useState("");
366
- const [suggestions, setSuggestions] = useState([]);
367
- const [searchLoading, setSearchLoading] = useState(false);
368
- const [searchError, setSearchError] = useState(null);
369
- const [dropdownOpen, setDropdownOpen] = useState(false);
370
- const debounceRef = useRef(null);
371
- const searchInputRef = useRef(null);
372
- const listboxId = useId();
373
- const { loading: geoLoading, error: geoError, locate, clearError } = useGeolocation();
374
- const refreshDigipin = useCallback((la, lo) => {
375
- setDigipin(computeDigiPinSafe(la, lo));
376
- }, []);
377
- const flyToCoord = useCallback((la, lo) => {
378
- var _a;
379
- setLat(la);
380
- setLng(lo);
381
- refreshDigipin(la, lo);
382
- if (mapRef.current) {
383
- mapRef.current.flyTo({ center: [lo, la], zoom: STREET_ZOOM, duration: 900, essential: true });
384
- }
385
- (_a = markerRef.current) == null ? void 0 : _a.setLngLat([lo, la]);
386
- }, [refreshDigipin]);
387
- const handleSearchChange = useCallback((e) => {
388
- const value = e.target.value;
389
- setSearchQuery(value);
390
- setSearchError(null);
391
- if (debounceRef.current) clearTimeout(debounceRef.current);
392
- const trimmed = value.trim();
393
- if (!trimmed) {
394
- setSuggestions([]);
395
- setDropdownOpen(false);
396
- setSearchLoading(false);
397
- return;
398
- }
399
- if (looksLikeDigiPin(trimmed)) {
400
- try {
401
- const coords = getLatLngFromDigiPin(trimmed.toUpperCase());
402
- const la = parseFloat(coords.latitude);
403
- const lo = parseFloat(coords.longitude);
404
- flyToCoord(la, lo);
405
- setSuggestions([]);
406
- setDropdownOpen(false);
407
- setSearchQuery(trimmed.toUpperCase());
408
- } catch {
409
- setSearchError("Invalid DigiPin code");
410
- }
411
- return;
412
- }
413
- if (trimmed.length < 3) {
414
- setSuggestions([]);
415
- setDropdownOpen(false);
416
- return;
417
- }
418
- setSearchLoading(true);
419
- debounceRef.current = setTimeout(async () => {
420
- try {
421
- const key = apiKey ?? "";
422
- const results = await autocompleteAddress(trimmed, key, apiBaseUrl, 5, lat, lng);
423
- setSuggestions(results);
424
- setDropdownOpen(results.length > 0);
425
- } catch (err) {
426
- setSearchError(err instanceof Error ? err.message : "Search failed");
427
- setSuggestions([]);
428
- setDropdownOpen(false);
429
- } finally {
430
- setSearchLoading(false);
431
- }
432
- }, 400);
433
- }, [apiKey, apiBaseUrl, flyToCoord]);
434
- const handleSuggestionSelect = useCallback((s) => {
435
- var _a;
436
- flyToCoord(s.coordinates.latitude, s.coordinates.longitude);
437
- setSearchQuery("");
438
- setSuggestions([]);
439
- setDropdownOpen(false);
440
- (_a = searchInputRef.current) == null ? void 0 : _a.blur();
441
- }, [flyToCoord]);
442
- const handleSearchKeyDown = useCallback((e) => {
443
- if (e.key === "Escape") {
444
- setSuggestions([]);
445
- setDropdownOpen(false);
446
- setSearchQuery("");
447
- }
448
- }, []);
449
- useEffect(() => {
450
- if (!containerRef.current) return;
451
- const boundaryPromise = indiaBoundaryUrl ? fetch(indiaBoundaryUrl).then((r) => r.ok ? r.json() : null).catch(() => null) : Promise.resolve(null);
452
- const initZoom = hasDefault ? STREET_ZOOM : OVERVIEW_ZOOM;
453
- const map = new maplibregl.Map({
454
- container: containerRef.current,
455
- style: CARTO_STYLE_URL,
456
- center: [initLng, initLat],
457
- zoom: initZoom,
458
- minZoom: MIN_ZOOM,
459
- // lock: cannot zoom out past level 7
460
- attributionControl: false,
461
- // Smooth touch gestures on mobile (tap center for zoom)
462
- touchZoomRotate: true
463
- });
464
- map.addControl(
465
- new maplibregl.AttributionControl({
466
- compact: true,
467
- customAttribution: '© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors &nbsp;© <a href="https://carto.com/attributions" target="_blank" rel="noopener">CARTO</a>'
468
- }),
469
- "bottom-right"
470
- );
471
- map.addControl(
472
- new maplibregl.NavigationControl({ showCompass: false }),
473
- "top-right"
474
- );
475
- map.on("load", () => {
476
- setMapLoaded(true);
477
- boundaryPromise.then((geoJson) => {
478
- if (!geoJson || !map.isStyleLoaded()) return;
479
- try {
480
- map.addSource("india-boundary", {
481
- type: "geojson",
482
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
483
- data: geoJson
484
- });
485
- map.addLayer({
486
- id: "india-boundary-line",
487
- type: "line",
488
- source: "india-boundary",
489
- paint: {
490
- "line-color": "#94a3b8",
491
- // slate-400 — subtle grey
492
- "line-width": 1.5,
493
- "line-opacity": 0.65
494
- }
495
- });
496
- } catch {
497
- }
498
- });
499
- const pinEl = createPinElement();
500
- const marker = new maplibregl.Marker({
501
- element: pinEl,
502
- draggable: true,
503
- anchor: "bottom"
504
- }).setLngLat([initLng, initLat]).addTo(map);
505
- marker.on("drag", () => {
506
- const pos = marker.getLngLat();
507
- setLat(pos.lat);
508
- setLng(pos.lng);
509
- refreshDigipin(pos.lat, pos.lng);
510
- });
511
- marker.on("dragend", () => {
512
- const pos = marker.getLngLat();
513
- map.easeTo({ center: [pos.lng, pos.lat], duration: 250 });
514
- });
515
- markerRef.current = marker;
516
- });
517
- map.on("click", (e) => {
518
- var _a;
519
- const pos = e.lngLat;
520
- (_a = markerRef.current) == null ? void 0 : _a.setLngLat([pos.lng, pos.lat]);
521
- setLat(pos.lat);
522
- setLng(pos.lng);
523
- refreshDigipin(pos.lat, pos.lng);
524
- map.easeTo({ center: [pos.lng, pos.lat], duration: 200 });
525
- });
526
- mapRef.current = map;
527
- return () => {
528
- map.remove();
529
- mapRef.current = null;
530
- markerRef.current = null;
531
- };
532
- }, []);
533
- const handleLocateMe = useCallback(() => {
534
- clearError();
535
- locate((userLat, userLng) => {
536
- var _a;
537
- setLat(userLat);
538
- setLng(userLng);
539
- refreshDigipin(userLat, userLng);
540
- if (mapRef.current) {
541
- mapRef.current.flyTo({
542
- center: [userLng, userLat],
543
- zoom: STREET_ZOOM,
544
- duration: 1400,
545
- essential: true
546
- });
547
- }
548
- (_a = markerRef.current) == null ? void 0 : _a.setLngLat([userLng, userLat]);
549
- });
550
- }, [locate, clearError, refreshDigipin]);
551
- const handleConfirm = useCallback(() => {
552
- if (digipin) {
553
- onLocationConfirm(lat, lng, digipin);
554
- }
555
- }, [lat, lng, digipin, onLocationConfirm]);
556
- const isInIndia = digipin !== null;
557
- const canConfirm = isInIndia && mapLoaded;
558
- return /* @__PURE__ */ jsxs("div", { className: "qr-map-wrapper", children: [
559
- /* @__PURE__ */ jsxs("div", { className: "qr-step-header", children: [
560
- /* @__PURE__ */ jsx("div", { className: "qr-step-badge", children: "1" }),
561
- /* @__PURE__ */ jsxs("div", { className: "qr-step-text", children: [
562
- /* @__PURE__ */ jsx("span", { className: "qr-step-title", children: "Pin Your Location" }),
563
- /* @__PURE__ */ jsx("span", { className: "qr-step-sub", children: "Tap the map or drag the pin to your exact home / office" })
564
- ] })
565
- ] }),
566
- enableSearch && /* @__PURE__ */ jsxs("div", { className: "qr-search-bar", role: "search", children: [
567
- /* @__PURE__ */ jsxs("div", { className: "qr-search-bar__input-wrap", children: [
568
- /* @__PURE__ */ jsxs(
569
- "svg",
570
- {
571
- className: "qr-search-bar__icon",
572
- "aria-hidden": "true",
573
- viewBox: "0 0 24 24",
574
- fill: "none",
575
- stroke: "currentColor",
576
- strokeWidth: "2",
577
- strokeLinecap: "round",
578
- strokeLinejoin: "round",
579
- children: [
580
- /* @__PURE__ */ jsx("circle", { cx: "11", cy: "11", r: "8" }),
581
- /* @__PURE__ */ jsx("path", { d: "M21 21l-4.35-4.35" })
582
- ]
583
- }
584
- ),
585
- /* @__PURE__ */ jsx(
586
- "input",
587
- {
588
- ref: searchInputRef,
589
- type: "search",
590
- className: "qr-search-bar__input",
591
- placeholder: "Search address, 'pharmacy near me', or DigiPin…",
592
- value: searchQuery,
593
- onChange: handleSearchChange,
594
- onKeyDown: handleSearchKeyDown,
595
- autoComplete: "off",
596
- autoCorrect: "off",
597
- autoCapitalize: "characters",
598
- spellCheck: false,
599
- "aria-label": "Search address or DigiPin",
600
- "aria-autocomplete": "list",
601
- "aria-controls": dropdownOpen ? listboxId : void 0,
602
- "aria-expanded": dropdownOpen
603
- }
604
- ),
605
- searchLoading && /* @__PURE__ */ jsx("span", { className: "qr-search-bar__spinner qr-spinner qr-spinner--sm", "aria-hidden": "true" }),
606
- searchQuery && !searchLoading && /* @__PURE__ */ jsx(
607
- "button",
608
- {
609
- type: "button",
610
- className: "qr-search-bar__clear",
611
- onClick: () => {
612
- setSearchQuery("");
613
- setSuggestions([]);
614
- setDropdownOpen(false);
615
- setSearchError(null);
616
- },
617
- "aria-label": "Clear search",
618
- tabIndex: -1,
619
- children: "×"
620
- }
621
- )
622
- ] }),
623
- searchError && /* @__PURE__ */ jsx("p", { className: "qr-search-bar__error", role: "alert", children: searchError }),
624
- dropdownOpen && suggestions.length > 0 && /* @__PURE__ */ jsx(
625
- "ul",
626
- {
627
- id: listboxId,
628
- className: "qr-search-bar__dropdown",
629
- role: "listbox",
630
- "aria-label": "Address suggestions",
631
- children: suggestions.map((s, i) => /* @__PURE__ */ jsxs(
632
- "li",
633
- {
634
- className: "qr-search-bar__suggestion",
635
- role: "option",
636
- "aria-selected": "false",
637
- onMouseDown: (e) => {
638
- e.preventDefault();
639
- handleSuggestionSelect(s);
640
- },
641
- children: [
642
- /* @__PURE__ */ jsxs(
643
- "svg",
644
- {
645
- className: "qr-search-bar__suggestion-icon",
646
- "aria-hidden": "true",
647
- viewBox: "0 0 24 24",
648
- fill: "none",
649
- stroke: "currentColor",
650
- strokeWidth: "1.8",
651
- strokeLinecap: "round",
652
- strokeLinejoin: "round",
653
- children: [
654
- /* @__PURE__ */ jsx("path", { d: "M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z" }),
655
- /* @__PURE__ */ jsx("circle", { cx: "12", cy: "9", r: "2.5" })
656
- ]
657
- }
658
- ),
659
- /* @__PURE__ */ jsxs("div", { className: "qr-search-bar__suggestion-text", children: [
660
- /* @__PURE__ */ jsx("span", { className: "qr-search-bar__suggestion-name", children: s.displayName }),
661
- s.address && s.address !== s.displayName && /* @__PURE__ */ jsx("span", { className: "qr-search-bar__suggestion-sub", children: s.address })
662
- ] })
663
- ]
664
- },
665
- i
666
- ))
667
- }
668
- ),
669
- /* @__PURE__ */ jsxs("p", { className: "qr-search-bar__hint", children: [
670
- /* @__PURE__ */ jsx("span", { className: "qr-search-bar__hint-chip", children: "DigiPin" }),
671
- "Type your DigiPin code for instant offline lookup — no API call"
672
- ] })
673
- ] }),
674
- /* @__PURE__ */ jsxs("div", { className: "qr-map-outer", style: { height: mapHeight }, children: [
675
- /* @__PURE__ */ jsx("div", { ref: containerRef, className: "qr-map-canvas" }),
676
- digipin && /* @__PURE__ */ jsxs("div", { className: "qr-digipin-badge", "aria-live": "polite", "aria-label": `DigiPin: ${digipin}`, children: [
677
- /* @__PURE__ */ jsx("span", { className: "qr-digipin-badge__label", children: "DigiPin" }),
678
- /* @__PURE__ */ jsx("span", { className: "qr-digipin-badge__code", children: digipin })
679
- ] }),
680
- !isInIndia && mapLoaded && /* @__PURE__ */ jsx("div", { className: "qr-map-notice", role: "status", children: "Move map to India to get a DigiPin" }),
681
- /* @__PURE__ */ jsx(
682
- "button",
683
- {
684
- className: `qr-locate-btn${geoLoading ? " qr-locate-btn--loading" : ""}`,
685
- onClick: handleLocateMe,
686
- disabled: geoLoading,
687
- title: "Use my current location",
688
- "aria-label": "Use my current location",
689
- type: "button",
690
- children: geoLoading ? /* @__PURE__ */ jsx("span", { className: "qr-spinner", "aria-hidden": "true" }) : /* @__PURE__ */ jsxs(
691
- "svg",
692
- {
693
- "aria-hidden": "true",
694
- viewBox: "0 0 24 24",
695
- fill: "none",
696
- stroke: "currentColor",
697
- strokeWidth: "2",
698
- strokeLinecap: "round",
699
- strokeLinejoin: "round",
700
- children: [
701
- /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "3", fill: "currentColor", stroke: "none" }),
702
- /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "7" }),
703
- /* @__PURE__ */ jsx("path", { d: "M12 2v3M12 19v3M2 12h3M19 12h3" })
704
- ]
705
- }
706
- )
707
- }
708
- ),
709
- geoError && /* @__PURE__ */ jsxs("div", { className: "qr-geo-error", role: "alert", children: [
710
- /* @__PURE__ */ jsx("span", { children: geoError }),
711
- /* @__PURE__ */ jsx(
712
- "button",
713
- {
714
- type: "button",
715
- className: "qr-geo-error__dismiss",
716
- onClick: clearError,
717
- "aria-label": "Dismiss error",
718
- children: "×"
719
- }
720
- )
721
- ] })
722
- ] }),
723
- mapLoaded && /* @__PURE__ */ jsxs("div", { className: "qr-coords-strip", "aria-label": "Current pin coordinates", children: [
724
- /* @__PURE__ */ jsxs("span", { children: [
725
- lat.toFixed(5),
726
- "° N"
727
- ] }),
728
- /* @__PURE__ */ jsx("span", { className: "qr-coords-sep", children: "·" }),
729
- /* @__PURE__ */ jsxs("span", { children: [
730
- lng.toFixed(5),
731
- "° E"
732
- ] })
733
- ] }),
734
- /* @__PURE__ */ jsxs("div", { className: "qr-map-actions", children: [
735
- /* @__PURE__ */ jsxs(
736
- "button",
737
- {
738
- type: "button",
739
- className: "qr-btn qr-btn--primary qr-btn--full",
740
- onClick: handleConfirm,
741
- disabled: !canConfirm,
742
- children: [
743
- "Confirm Location",
744
- /* @__PURE__ */ jsx(
745
- "svg",
746
- {
747
- "aria-hidden": "true",
748
- viewBox: "0 0 24 24",
749
- fill: "none",
750
- stroke: "currentColor",
751
- strokeWidth: "2.5",
752
- strokeLinecap: "round",
753
- strokeLinejoin: "round",
754
- children: /* @__PURE__ */ jsx("path", { d: "M5 12h14M12 5l7 7-7 7" })
755
- }
756
- )
757
- ]
758
- }
759
- ),
760
- !isInIndia && mapLoaded && /* @__PURE__ */ jsx("p", { className: "qr-map-hint", children: "Move the pin to a location in India to continue" })
761
- ] })
762
- ] });
763
- };
764
- const INITIAL_FIELDS = {
765
- flatNumber: "",
766
- floorNumber: "",
767
- buildingName: "",
768
- streetName: ""
769
- };
770
- function parseAddressComponents(components) {
771
- const fields = {};
772
- if (components.name) {
773
- fields.buildingName = components.name;
774
- } else if (components.building_name) {
775
- fields.buildingName = components.building_name;
776
- } else if (components.addr_housename) {
777
- fields.buildingName = components.addr_housename;
778
- }
779
- const streetParts = [];
780
- if (components.road) {
781
- streetParts.push(components.road);
782
- }
783
- if (components.suburb) {
784
- streetParts.push(components.suburb);
785
- }
786
- if (streetParts.length > 0) {
787
- fields.streetName = streetParts.join(", ");
788
- }
789
- return fields;
790
- }
791
- function reducer(state, action) {
792
- switch (action.type) {
793
- case "LOAD_START":
794
- return { status: "loading" };
795
- case "LOAD_SUCCESS": {
796
- const preFilled = parseAddressComponents(action.addressComponents);
797
- return {
798
- status: "ready",
799
- adminInfo: action.adminInfo,
800
- alternatives: action.alternatives || [],
801
- selectedLocality: action.adminInfo.locality,
802
- fields: { ...INITIAL_FIELDS, ...preFilled },
803
- submitting: false
804
- };
805
- }
806
- case "LOAD_ERROR":
807
- return { status: "error", message: action.message };
808
- case "SET_FIELD":
809
- if (state.status !== "ready") return state;
810
- return { ...state, fields: { ...state.fields, [action.key]: action.value } };
811
- case "SET_LOCALITY":
812
- if (state.status !== "ready") return state;
813
- return { ...state, selectedLocality: action.locality };
814
- case "SUBMIT_START":
815
- if (state.status !== "ready") return state;
816
- return { ...state, submitting: true };
817
- case "SUBMIT_END":
818
- if (state.status !== "ready") return state;
819
- return { ...state, submitting: false };
820
- default:
821
- return state;
822
- }
823
- }
824
- const AddressForm = ({
825
- digipin,
826
- lat,
827
- lng,
828
- apiKey,
829
- apiBaseUrl,
830
- onAddressComplete,
831
- onBack,
832
- onError
833
- }) => {
834
- const [state, dispatch] = useReducer(reducer, { status: "loading" });
835
- const fetchAdminInfo = useCallback(async () => {
836
- dispatch({ type: "LOAD_START" });
837
- try {
838
- const [adminRes, reverseRes] = await Promise.all([
839
- lookupLocation(lat, lng, apiKey, apiBaseUrl),
840
- reverseGeocode(digipin, apiKey, apiBaseUrl)
841
- ]);
842
- dispatch({
843
- type: "LOAD_SUCCESS",
844
- adminInfo: adminRes.data.administrative_info,
845
- alternatives: adminRes.data.alternatives || [],
846
- addressComponents: reverseRes.data.addressComponents
847
- });
848
- } catch (err) {
849
- const msg = err instanceof Error ? err.message : "Failed to fetch address data.";
850
- dispatch({ type: "LOAD_ERROR", message: msg });
851
- onError == null ? void 0 : onError(err instanceof Error ? err : new Error(msg));
852
- }
853
- }, [digipin, lat, lng, apiKey, apiBaseUrl, onError]);
854
- useEffect(() => {
855
- void fetchAdminInfo();
856
- }, [fetchAdminInfo]);
857
- const handleSubmit = useCallback(
858
- (e) => {
859
- e.preventDefault();
860
- if (state.status !== "ready") return;
861
- const { adminInfo, selectedLocality, fields } = state;
862
- const parts = [
863
- fields.flatNumber,
864
- fields.floorNumber ? `Floor ${fields.floorNumber}` : "",
865
- fields.buildingName,
866
- fields.streetName,
867
- selectedLocality,
868
- // Use selected locality (may be from alternatives)
869
- adminInfo.district,
870
- adminInfo.state,
871
- adminInfo.pincode
872
- ].filter(Boolean);
873
- const complete = {
874
- digipin,
875
- lat,
876
- lng,
877
- state: adminInfo.state,
878
- district: adminInfo.district,
879
- division: adminInfo.division,
880
- locality: selectedLocality,
881
- // Use selected locality
882
- pincode: adminInfo.pincode,
883
- delivery: adminInfo.delivery,
884
- country: adminInfo.country ?? "India",
885
- ...fields,
886
- formattedAddress: parts.join(", ")
887
- };
888
- dispatch({ type: "SUBMIT_START" });
889
- try {
890
- onAddressComplete(complete);
891
- } finally {
892
- dispatch({ type: "SUBMIT_END" });
893
- }
894
- },
895
- [state, digipin, lat, lng, onAddressComplete]
896
- );
897
- return /* @__PURE__ */ jsxs("div", { className: "qr-form-wrapper", children: [
898
- /* @__PURE__ */ jsxs("div", { className: "qr-step-header", children: [
899
- /* @__PURE__ */ jsx(
900
- "button",
901
- {
902
- type: "button",
903
- className: "qr-back-btn",
904
- onClick: onBack,
905
- "aria-label": "Back to map",
906
- children: /* @__PURE__ */ jsx(
907
- "svg",
908
- {
909
- "aria-hidden": "true",
910
- viewBox: "0 0 24 24",
911
- fill: "none",
912
- stroke: "currentColor",
913
- strokeWidth: "2.5",
914
- strokeLinecap: "round",
915
- strokeLinejoin: "round",
916
- children: /* @__PURE__ */ jsx("path", { d: "M19 12H5M12 19l-7-7 7-7" })
917
- }
918
- )
919
- }
920
- ),
921
- /* @__PURE__ */ jsx("div", { className: "qr-step-badge", children: "2" }),
922
- /* @__PURE__ */ jsxs("div", { className: "qr-step-text", children: [
923
- /* @__PURE__ */ jsx("span", { className: "qr-step-title", children: "Add Address Details" }),
924
- /* @__PURE__ */ jsx("span", { className: "qr-step-sub", children: "Flat number and building info" })
925
- ] })
926
- ] }),
927
- /* @__PURE__ */ jsxs("div", { className: "qr-form-digipin-strip", children: [
928
- /* @__PURE__ */ jsxs(
929
- "svg",
930
- {
931
- "aria-hidden": "true",
932
- viewBox: "0 0 24 24",
933
- fill: "none",
934
- stroke: "currentColor",
935
- strokeWidth: "2",
936
- strokeLinecap: "round",
937
- strokeLinejoin: "round",
938
- children: [
939
- /* @__PURE__ */ jsx("path", { d: "M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z" }),
940
- /* @__PURE__ */ jsx("circle", { cx: "12", cy: "10", r: "3" })
941
- ]
942
- }
943
- ),
944
- /* @__PURE__ */ jsx("span", { className: "qr-form-digipin-strip__label", children: "DigiPin" }),
945
- /* @__PURE__ */ jsx("span", { className: "qr-form-digipin-strip__code", children: digipin })
946
- ] }),
947
- state.status === "loading" && /* @__PURE__ */ jsxs("div", { className: "qr-loading-state", "aria-busy": "true", "aria-label": "Fetching address details", children: [
948
- /* @__PURE__ */ jsx("div", { className: "qr-spinner qr-spinner--lg", "aria-hidden": "true" }),
949
- /* @__PURE__ */ jsx("p", { className: "qr-loading-state__text", children: "Fetching address details…" })
950
- ] }),
951
- state.status === "error" && /* @__PURE__ */ jsxs("div", { className: "qr-error-state", role: "alert", children: [
952
- /* @__PURE__ */ jsx("div", { className: "qr-error-state__icon", "aria-hidden": "true", children: "⚠" }),
953
- /* @__PURE__ */ jsx("p", { className: "qr-error-state__msg", children: state.message }),
954
- /* @__PURE__ */ jsx(
955
- "button",
956
- {
957
- type: "button",
958
- className: "qr-btn qr-btn--secondary qr-btn--sm",
959
- onClick: () => void fetchAdminInfo(),
960
- children: "Retry"
961
- }
962
- )
963
- ] }),
964
- state.status === "ready" && /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "qr-form", noValidate: true, children: [
965
- /* @__PURE__ */ jsxs("fieldset", { className: "qr-fieldset", children: [
966
- /* @__PURE__ */ jsxs("legend", { className: "qr-fieldset__legend", children: [
967
- /* @__PURE__ */ jsx("span", { className: "qr-fieldset__icon", "aria-hidden": "true", children: "📍" }),
968
- "Auto-detected from your pin"
969
- ] }),
970
- /* @__PURE__ */ jsxs("div", { className: "qr-auto-grid", children: [
971
- /* @__PURE__ */ jsxs("div", { className: "qr-auto-row", children: [
972
- /* @__PURE__ */ jsx("span", { className: "qr-auto-row__label", children: "State" }),
973
- /* @__PURE__ */ jsx("span", { className: "qr-auto-row__value", children: state.adminInfo.state })
974
- ] }),
975
- /* @__PURE__ */ jsxs("div", { className: "qr-auto-row", children: [
976
- /* @__PURE__ */ jsx("span", { className: "qr-auto-row__label", children: "District" }),
977
- /* @__PURE__ */ jsx("span", { className: "qr-auto-row__value", children: state.adminInfo.district })
978
- ] }),
979
- /* @__PURE__ */ jsxs("div", { className: "qr-auto-row qr-auto-row--full", children: [
980
- /* @__PURE__ */ jsx("span", { className: "qr-auto-row__label", children: "Locality" }),
981
- state.alternatives.length > 0 ? /* @__PURE__ */ jsxs(
982
- "select",
983
- {
984
- className: "qr-auto-row__select",
985
- value: state.selectedLocality,
986
- onChange: (e) => dispatch({ type: "SET_LOCALITY", locality: e.target.value }),
987
- "aria-label": "Select locality",
988
- children: [
989
- /* @__PURE__ */ jsx("option", { value: state.adminInfo.locality, children: state.adminInfo.locality }),
990
- state.alternatives.map((alt, idx) => /* @__PURE__ */ jsx("option", { value: alt.name, children: alt.name }, idx))
991
- ]
992
- }
993
- ) : /* @__PURE__ */ jsx("span", { className: "qr-auto-row__value", children: state.selectedLocality })
994
- ] }),
995
- /* @__PURE__ */ jsxs("div", { className: "qr-auto-row", children: [
996
- /* @__PURE__ */ jsx("span", { className: "qr-auto-row__label", children: "Pincode" }),
997
- /* @__PURE__ */ jsx("span", { className: "qr-auto-row__value qr-auto-row__value--pin", children: state.adminInfo.pincode })
998
- ] })
999
- ] })
1000
- ] }),
1001
- /* @__PURE__ */ jsxs("fieldset", { className: "qr-fieldset", children: [
1002
- /* @__PURE__ */ jsxs("legend", { className: "qr-fieldset__legend", children: [
1003
- /* @__PURE__ */ jsx("span", { className: "qr-fieldset__icon", "aria-hidden": "true", children: "🏠" }),
1004
- "Your details"
1005
- ] }),
1006
- /* @__PURE__ */ jsxs("div", { className: "qr-fields-grid", children: [
1007
- /* @__PURE__ */ jsxs("div", { className: "qr-field qr-field--full", children: [
1008
- /* @__PURE__ */ jsxs("label", { className: "qr-field__label", htmlFor: "qr-flatNumber", children: [
1009
- "Flat / House Number",
1010
- /* @__PURE__ */ jsx("span", { className: "qr-required", "aria-hidden": "true", children: "*" })
1011
- ] }),
1012
- /* @__PURE__ */ jsx(
1013
- "input",
1014
- {
1015
- id: "qr-flatNumber",
1016
- type: "text",
1017
- className: "qr-field__input",
1018
- placeholder: "e.g. 4B, Flat 201, House No. 12",
1019
- value: state.fields.flatNumber,
1020
- onChange: (e) => dispatch({ type: "SET_FIELD", key: "flatNumber", value: e.target.value }),
1021
- autoComplete: "address-line1",
1022
- required: true,
1023
- "aria-required": "true"
1024
- }
1025
- )
1026
- ] }),
1027
- /* @__PURE__ */ jsxs("div", { className: "qr-field", children: [
1028
- /* @__PURE__ */ jsxs("label", { className: "qr-field__label", htmlFor: "qr-floorNumber", children: [
1029
- "Floor",
1030
- /* @__PURE__ */ jsx("span", { className: "qr-optional", children: "optional" })
1031
- ] }),
1032
- /* @__PURE__ */ jsx(
1033
- "input",
1034
- {
1035
- id: "qr-floorNumber",
1036
- type: "text",
1037
- className: "qr-field__input",
1038
- placeholder: "e.g. 3rd, Ground",
1039
- value: state.fields.floorNumber,
1040
- onChange: (e) => dispatch({ type: "SET_FIELD", key: "floorNumber", value: e.target.value })
1041
- }
1042
- )
1043
- ] }),
1044
- /* @__PURE__ */ jsxs("div", { className: "qr-field", children: [
1045
- /* @__PURE__ */ jsxs("label", { className: "qr-field__label", htmlFor: "qr-buildingName", children: [
1046
- "Building / Society",
1047
- /* @__PURE__ */ jsx("span", { className: "qr-optional", children: "optional" })
1048
- ] }),
1049
- /* @__PURE__ */ jsx(
1050
- "input",
1051
- {
1052
- id: "qr-buildingName",
1053
- type: "text",
1054
- className: "qr-field__input",
1055
- placeholder: "e.g. Sunshine Apts, DDA Colony",
1056
- value: state.fields.buildingName,
1057
- onChange: (e) => dispatch({ type: "SET_FIELD", key: "buildingName", value: e.target.value }),
1058
- autoComplete: "address-line2"
1059
- }
1060
- )
1061
- ] }),
1062
- /* @__PURE__ */ jsxs("div", { className: "qr-field qr-field--full", children: [
1063
- /* @__PURE__ */ jsxs("label", { className: "qr-field__label", htmlFor: "qr-streetName", children: [
1064
- "Street / Area",
1065
- /* @__PURE__ */ jsx("span", { className: "qr-optional", children: "optional" })
1066
- ] }),
1067
- /* @__PURE__ */ jsx(
1068
- "input",
1069
- {
1070
- id: "qr-streetName",
1071
- type: "text",
1072
- className: "qr-field__input",
1073
- placeholder: "e.g. MG Road, Sector 12",
1074
- value: state.fields.streetName,
1075
- onChange: (e) => dispatch({ type: "SET_FIELD", key: "streetName", value: e.target.value }),
1076
- autoComplete: "address-level3"
1077
- }
1078
- )
1079
- ] })
1080
- ] })
1081
- ] }),
1082
- /* @__PURE__ */ jsxs("div", { className: "qr-form-actions", children: [
1083
- /* @__PURE__ */ jsxs(
1084
- "button",
1085
- {
1086
- type: "button",
1087
- className: "qr-btn qr-btn--ghost",
1088
- onClick: onBack,
1089
- children: [
1090
- /* @__PURE__ */ jsx(
1091
- "svg",
1092
- {
1093
- "aria-hidden": "true",
1094
- viewBox: "0 0 24 24",
1095
- fill: "none",
1096
- stroke: "currentColor",
1097
- strokeWidth: "2",
1098
- strokeLinecap: "round",
1099
- strokeLinejoin: "round",
1100
- children: /* @__PURE__ */ jsx("path", { d: "M19 12H5M12 19l-7-7 7-7" })
1101
- }
1102
- ),
1103
- "Adjust Pin"
1104
- ]
1105
- }
1106
- ),
1107
- /* @__PURE__ */ jsx(
1108
- "button",
1109
- {
1110
- type: "submit",
1111
- className: "qr-btn qr-btn--primary qr-btn--grow",
1112
- disabled: state.submitting || !state.fields.flatNumber.trim(),
1113
- children: state.submitting ? /* @__PURE__ */ jsxs(Fragment, { children: [
1114
- /* @__PURE__ */ jsx("span", { className: "qr-spinner qr-spinner--sm", "aria-hidden": "true" }),
1115
- "Saving…"
1116
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1117
- "Save Address",
1118
- /* @__PURE__ */ jsx(
1119
- "svg",
1120
- {
1121
- "aria-hidden": "true",
1122
- viewBox: "0 0 24 24",
1123
- fill: "none",
1124
- stroke: "currentColor",
1125
- strokeWidth: "2.5",
1126
- strokeLinecap: "round",
1127
- strokeLinejoin: "round",
1128
- children: /* @__PURE__ */ jsx("path", { d: "M20 6L9 17l-5-5" })
1129
- }
1130
- )
1131
- ] })
1132
- }
1133
- )
1134
- ] })
1135
- ] })
1136
- ] });
1137
- };
1138
- const SuccessScreen = ({ address, onEditAddress }) => /* @__PURE__ */ jsxs("div", { className: "qr-success", children: [
1139
- /* @__PURE__ */ jsx("div", { className: "qr-success__icon", "aria-hidden": "true", children: /* @__PURE__ */ jsxs("svg", { viewBox: "0 0 52 52", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [
1140
- /* @__PURE__ */ jsx("circle", { cx: "26", cy: "26", r: "26", fill: "var(--qr-success, #10b981)", opacity: "0.12" }),
1141
- /* @__PURE__ */ jsx("circle", { cx: "26", cy: "26", r: "20", fill: "var(--qr-success, #10b981)" }),
1142
- /* @__PURE__ */ jsx(
1143
- "path",
1144
- {
1145
- d: "M15 26l8 8 14-16",
1146
- stroke: "white",
1147
- strokeWidth: "3",
1148
- strokeLinecap: "round",
1149
- strokeLinejoin: "round"
1150
- }
1151
- )
1152
- ] }) }),
1153
- /* @__PURE__ */ jsx("h3", { className: "qr-success__title", children: "Address Saved!" }),
1154
- /* @__PURE__ */ jsx("p", { className: "qr-success__address", children: address.formattedAddress }),
1155
- /* @__PURE__ */ jsx("div", { className: "qr-success__meta", children: /* @__PURE__ */ jsxs("span", { className: "qr-digipin-badge qr-digipin-badge--inline", children: [
1156
- /* @__PURE__ */ jsx("span", { className: "qr-digipin-badge__label", children: "DigiPin" }),
1157
- /* @__PURE__ */ jsx("span", { className: "qr-digipin-badge__code", children: address.digipin })
1158
- ] }) }),
1159
- /* @__PURE__ */ jsx("button", { type: "button", className: "qr-btn qr-btn--ghost qr-btn--sm", onClick: onEditAddress, children: "Change Address" })
1160
- ] });
1161
- const CheckoutWidget = ({
1162
- apiKey,
1163
- apiBaseUrl = "https://api.quantaroute.com",
1164
- onComplete,
1165
- onError,
1166
- defaultLat,
1167
- defaultLng,
1168
- theme = "light",
1169
- className = "",
1170
- style,
1171
- mapHeight = "380px",
1172
- title = "Add Delivery Address",
1173
- indiaBoundaryUrl,
1174
- enableSearch = true
1175
- }) => {
1176
- const [step, setStep] = useState("map");
1177
- const [confirmedLocation, setConfirmedLocation] = useState(null);
1178
- const [completedAddress, setCompletedAddress] = useState(null);
1179
- const handleLocationConfirm = (lat, lng, digipin) => {
1180
- setConfirmedLocation({ lat, lng, digipin });
1181
- setStep("form");
1182
- };
1183
- const handleAddressComplete = (address) => {
1184
- setCompletedAddress(address);
1185
- setStep("done");
1186
- onComplete(address);
1187
- };
1188
- const handleBack = () => {
1189
- setStep("map");
1190
- };
1191
- const handleEditAddress = () => {
1192
- setStep("map");
1193
- setConfirmedLocation(null);
1194
- setCompletedAddress(null);
1195
- };
1196
- const renderStepDots = () => /* @__PURE__ */ jsxs("div", { className: "qr-progress", "aria-label": "Progress: step ${ step === 'map' ? 1 : 2 } of 2", role: "progressbar", children: [
1197
- /* @__PURE__ */ jsx("div", { className: `qr-progress__dot ${step === "map" || step === "form" || step === "done" ? "qr-progress__dot--active" : ""}` }),
1198
- /* @__PURE__ */ jsx("div", { className: `qr-progress__line ${step === "form" || step === "done" ? "qr-progress__line--active" : ""}` }),
1199
- /* @__PURE__ */ jsx("div", { className: `qr-progress__dot ${step === "form" || step === "done" ? "qr-progress__dot--active" : ""}` })
1200
- ] });
1201
- return /* @__PURE__ */ jsxs(
1202
- "div",
1203
- {
1204
- className: `qr-checkout qr-checkout--${theme} ${className}`,
1205
- style,
1206
- "data-testid": "quantaroute-checkout",
1207
- children: [
1208
- step !== "done" && /* @__PURE__ */ jsxs("div", { className: "qr-header", children: [
1209
- /* @__PURE__ */ jsxs("div", { className: "qr-header__brand", children: [
1210
- /* @__PURE__ */ jsxs(
1211
- "svg",
1212
- {
1213
- className: "qr-header__logo",
1214
- "aria-hidden": "true",
1215
- viewBox: "0 0 24 24",
1216
- fill: "none",
1217
- stroke: "currentColor",
1218
- strokeWidth: "2",
1219
- strokeLinecap: "round",
1220
- strokeLinejoin: "round",
1221
- children: [
1222
- /* @__PURE__ */ jsx("path", { d: "M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z" }),
1223
- /* @__PURE__ */ jsx("circle", { cx: "12", cy: "10", r: "3" })
1224
- ]
1225
- }
1226
- ),
1227
- /* @__PURE__ */ jsx("span", { className: "qr-header__title", children: title })
1228
- ] }),
1229
- renderStepDots()
1230
- ] }),
1231
- step === "map" && /* @__PURE__ */ jsx(
1232
- MapPinSelector,
1233
- {
1234
- onLocationConfirm: handleLocationConfirm,
1235
- defaultLat,
1236
- defaultLng,
1237
- mapHeight,
1238
- theme,
1239
- indiaBoundaryUrl,
1240
- enableSearch,
1241
- apiKey,
1242
- apiBaseUrl
1243
- }
1244
- ),
1245
- step === "form" && confirmedLocation && /* @__PURE__ */ jsx(
1246
- AddressForm,
1247
- {
1248
- digipin: confirmedLocation.digipin,
1249
- lat: confirmedLocation.lat,
1250
- lng: confirmedLocation.lng,
1251
- apiKey,
1252
- apiBaseUrl,
1253
- onAddressComplete: handleAddressComplete,
1254
- onBack: handleBack,
1255
- onError,
1256
- theme
1257
- }
1258
- ),
1259
- step === "done" && completedAddress && /* @__PURE__ */ jsx(SuccessScreen, { address: completedAddress, onEditAddress: handleEditAddress }),
1260
- /* @__PURE__ */ jsxs("div", { className: "qr-footer", children: [
1261
- /* @__PURE__ */ jsx("span", { children: "Powered by" }),
1262
- /* @__PURE__ */ jsx(
1263
- "a",
1264
- {
1265
- href: "https://quantaroute.com",
1266
- target: "_blank",
1267
- rel: "noopener noreferrer",
1268
- className: "qr-footer__link",
1269
- children: "QuantaRoute"
1270
- }
1271
- ),
1272
- /* @__PURE__ */ jsx("span", { className: "qr-footer__flag", "aria-label": "Made in India", children: "🇮🇳" })
1273
- ] })
1274
- ]
1275
- }
1276
- );
1277
- };
1278
- function useDigiPin(lat, lng) {
1279
- return useMemo(() => {
1280
- if (!isWithinIndia(lat, lng)) return null;
1281
- try {
1282
- return getDigiPin(lat, lng);
1283
- } catch {
1284
- return null;
1285
- }
1286
- }, [lat, lng]);
1287
- }
1288
- export {
1289
- AddressForm,
1290
- CheckoutWidget,
1291
- BOUNDS as DIGIPIN_BOUNDS,
1292
- MapPinSelector,
1293
- autocompleteAddress,
1294
- CheckoutWidget as default,
1295
- getDigiPin,
1296
- getLatLngFromDigiPin,
1297
- isValidDigiPin,
1298
- isWithinIndia,
1299
- looksLikeDigiPin,
1300
- lookupLocation,
1301
- reverseGeocode,
1302
- useDigiPin,
1303
- useGeolocation
1304
- };
21
+ import{jsxs as e,jsx as r,Fragment as n}from"react/jsx-runtime"
22
+ import a,{useState as t,useCallback as i,useRef as o,useId as l,useEffect as s,useReducer as d,useMemo as c}from"react"
23
+ import u from"maplibre-gl"
24
+ const h=[["F","C","9","8"],["J","3","2","7"],["K","4","5","6"],["L","M","P","T"]],p={minLat:2.5,maxLat:38.5,minLon:63.5,maxLon:99.5}
25
+ function m(e,r){if(e<p.minLat||e>p.maxLat)throw new Error(`Latitude ${e} out of range. Must be between ${p.minLat} and ${p.maxLat}`)
26
+ if(r<p.minLon||r>p.maxLon)throw new Error(`Longitude ${r} out of range. Must be between ${p.minLon} and ${p.maxLon}`)
27
+ let n=p.minLat,a=p.maxLat,t=p.minLon,i=p.maxLon,o=""
28
+ for(let l=1;l<=10;l++){const s=(a-n)/4,d=(i-t)/4
29
+ let c=3-Math.floor((e-n)/s),u=Math.floor((r-t)/d)
30
+ c=Math.max(0,Math.min(c,3)),u=Math.max(0,Math.min(u,3)),o+=h[c][u],3!==l&&6!==l||(o+="-"),a=n+s*(4-c),n+=s*(3-c),t+=d*u,i=t+d}return o}function f(e){const r=e.replace(/-/g,"")
31
+ if(10!==r.length)throw new Error("Invalid DIGIPIN: must be 10 characters (excluding dashes)")
32
+ let n=p.minLat,a=p.maxLat,t=p.minLon,i=p.maxLon
33
+ for(let e=0;e<10;e++){const o=r[e]
34
+ let l=!1,s=-1,d=-1
35
+ for(let e=0;e<4;e++){for(let r=0;r<4;r++)if(h[e][r]===o){s=e,d=r,l=!0
36
+ break}if(l)break}if(!l)throw new Error(`Invalid character in DIGIPIN: '${o}'`)
37
+ const c=(a-n)/4,u=(i-t)/4,p=t+u*(d+1)
38
+ n=a-c*(s+1),a-=c*s,t+=u*d,i=p}return{latitude:((n+a)/2).toFixed(6),longitude:((t+i)/2).toFixed(6)}}function y(e){if(!e||"string"!=typeof e)return!1
39
+ if(!/^[A-Z0-9]{3}-[A-Z0-9]{3}-[A-Z0-9]{4}$/i.test(e.trim()))return!1
40
+ try{return f(e.trim().toUpperCase()),!0}catch{return!1}}function b(e,r){return e>=p.minLat&&e<=p.maxLat&&r>=p.minLon&&r<=p.maxLon}const v="https://api.quantaroute.com",_=/^[FC98J327K456LMPT]{3}-[FC98J327K456LMPT]{3}-[FC98J327K456LMPT]{4}$/i
41
+ function g(e){if("undefined"!=typeof AbortSignal&&"function"==typeof AbortSignal.timeout)return AbortSignal.timeout(e)
42
+ const r=new AbortController
43
+ return setTimeout(()=>r.abort(),e),r.signal}async function q(e,r,n,a=v){const t=`${a.replace(/\/$/,"")}/v1/location/lookup`
44
+ let i
45
+ try{i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n},body:JSON.stringify({latitude:e,longitude:r}),signal:g(15e3)})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw new Error("Request timed out. Check your internet connection.")
46
+ throw new Error(`Network error: ${e instanceof Error?e.message:String(e)}`)}if(!i.ok){let e=""
47
+ try{e=await i.text()}catch{}if(401===i.status||403===i.status)throw new Error("Invalid API key. Check your QuantaRoute API key.")
48
+ if(429===i.status)throw new Error("Rate limit exceeded. Upgrade your plan or try again later.")
49
+ throw new Error(`API error ${i.status}: ${e||i.statusText}`)}const o=await i.json()
50
+ if(!o.success)throw new Error(o.message??"Location lookup failed")
51
+ return o}async function w(e,r,n=v){const a=e.replace(/\D/g,"").slice(0,6)
52
+ if(!/^[1-9][0-9]{5}$/.test(a))throw new Error("Pincode must be a 6-digit number starting with 1–9.")
53
+ const t=`${n.replace(/\/$/,"")}/v1/pincode/validate/${a}`
54
+ let i
55
+ try{i=await fetch(t,{method:"GET",headers:{"x-api-key":r},signal:g(12e3)})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw new Error("Pincode validation timed out.")
56
+ throw new Error(`Network error: ${e instanceof Error?e.message:String(e)}`)}if(!i.ok){if(401===i.status||403===i.status)throw new Error("Invalid API key.")
57
+ if(429===i.status)throw new Error("Rate limit exceeded.")
58
+ let e=""
59
+ try{e=await i.text()}catch{}throw new Error(`Pincode validation failed (${i.status}): ${e||i.statusText}`)}const o=await i.json()
60
+ if(!o.success||!o.data)throw new Error(o.message??"Pincode validation failed.")
61
+ return o.data}function N(e){return e.some(e=>"delivery"===(e.delivery??"").trim().toLowerCase())}function k(e){return _.test(e.trim().toUpperCase())}async function C(e,r,n=v,a=5,t,i){let o,l=`${n.replace(/\/$/,"")}/v1/digipin/autocomplete?q=${encodeURIComponent(e.trim())}&limit=${Math.min(a,10)}`
62
+ "number"==typeof t&&"number"==typeof i&&(l+=`&lat=${t.toFixed(6)}&lng=${i.toFixed(6)}`)
63
+ try{o=await fetch(l,{method:"GET",headers:{"x-api-key":r},signal:g(8e3)})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw new Error("Autocomplete request timed out.")
64
+ throw new Error(`Network error: ${e instanceof Error?e.message:String(e)}`)}if(!o.ok){if(401===o.status||403===o.status)throw new Error("Invalid API key.")
65
+ if(429===o.status)throw new Error("Rate limit exceeded.")
66
+ return[]}const s=await o.json()
67
+ return s.success?s.data??[]:[]}async function x(e,r,n=v){const a=`${n.replace(/\/$/,"")}/v1/digipin/reverse`
68
+ let t
69
+ try{t=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":r},body:JSON.stringify({digipin:e}),signal:g(15e3)})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw new Error("Request timed out. Check your internet connection.")
70
+ throw new Error(`Network error: ${e instanceof Error?e.message:String(e)}`)}if(!t.ok){let e=""
71
+ try{e=await t.text()}catch{}if(401===t.status||403===t.status)throw new Error("Invalid API key. Check your QuantaRoute API key.")
72
+ if(429===t.status)throw new Error("Rate limit exceeded. Upgrade your plan or try again later.")
73
+ throw new Error(`API error ${t.status}: ${e||t.statusText}`)}const i=await t.json()
74
+ if(!i.success)throw new Error(i.message??"Reverse geocoding failed")
75
+ return i}function E(){const[e,r]=t({loading:!1,error:null})
76
+ return{...e,locate:i(e=>{navigator.geolocation?(r({loading:!0,error:null}),navigator.geolocation.getCurrentPosition(({coords:n})=>{r({loading:!1,error:null}),e(n.latitude,n.longitude)},e=>{let n="Unable to get location."
77
+ e.code===e.PERMISSION_DENIED?n="Location permission denied. Please enable it in browser settings.":e.code===e.POSITION_UNAVAILABLE?n="Location unavailable. Try again or place the pin manually.":e.code===e.TIMEOUT&&(n="Location request timed out. Try again."),r({loading:!1,error:n})},{enableHighAccuracy:!0,timeout:12e3,maximumAge:0})):r({loading:!1,error:"Geolocation is not supported by your browser."})},[]),clearError:i(()=>{r(e=>({...e,error:null}))},[])}}function S(e,r){if(!b(e,r))return null
78
+ try{return m(e,r)}catch{return null}}const L="#0ea5e9",I=({onLocationConfirm:n,defaultLat:a,defaultLng:d,mapHeight:c="380px",theme:h="light",indiaBoundaryUrl:p,enableSearch:m=!0,apiKey:y,apiBaseUrl:b,brandColor:v=L})=>{const _=o(null),g=o(null),q=o(null),w=a??13.00427,N=d??77.589291,x=void 0!==a&&void 0!==d,[I,P]=t(w),[T,A]=t(N),[B,D]=t(()=>S(w,N)),[M,$]=t(!1),[O,F]=t(""),[U,R]=t([]),[j,W]=t(!1),[J,z]=t(null),[V,H]=t(!1),K=o(null),G=o(null),Z=l(),{loading:Y,error:Q,locate:X,clearError:ee}=E(),re=i((e,r)=>{D(S(e,r))},[]),ne=i((e,r)=>{var n
79
+ P(e),A(r),re(e,r),g.current&&g.current.flyTo({center:[r,e],zoom:18,duration:900,essential:!0}),null==(n=q.current)||n.setLngLat([r,e])},[re]),ae=i(e=>{const r=e.target.value
80
+ F(r),z(null),K.current&&clearTimeout(K.current)
81
+ const n=r.trim()
82
+ if(!n)return R([]),H(!1),void W(!1)
83
+ if(k(n))try{const e=f(n.toUpperCase()),r=parseFloat(e.latitude),a=parseFloat(e.longitude)
84
+ ne(r,a),R([]),H(!1),F(n.toUpperCase())}catch{z("Invalid DigiPin code")}else{if(n.length<3)return R([]),void H(!1)
85
+ W(!0),K.current=setTimeout(async()=>{try{const e=y??"",r=await C(n,e,b,5,I,T)
86
+ R(r),H(r.length>0)}catch(e){z(e instanceof Error?e.message:"Search failed"),R([]),H(!1)}finally{W(!1)}},400)}},[y,b,ne]),te=i(e=>{var r
87
+ ne(e.coordinates.latitude,e.coordinates.longitude),F(""),R([]),H(!1),null==(r=G.current)||r.blur()},[ne]),ie=i(e=>{"Escape"===e.key&&(R([]),H(!1),F(""))},[])
88
+ s(()=>{if(!_.current)return
89
+ const e=p?fetch(p).then(e=>e.ok?e.json():null).catch(()=>null):Promise.resolve(null),r=x?18:9,n=new u.Map({container:_.current,style:"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",center:[N,w],zoom:r,minZoom:6,attributionControl:!1,touchZoomRotate:!0})
90
+ return n.addControl(new u.AttributionControl({compact:!0,customAttribution:'© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors &nbsp;© <a href="https://carto.com/attributions" target="_blank" rel="noopener">CARTO</a>'}),"bottom-right"),n.addControl(new u.NavigationControl({showCompass:!1}),"top-right"),n.on("load",()=>{$(!0),e.then(e=>{if(e&&n.isStyleLoaded())try{n.addSource("india-boundary",{type:"geojson",data:e}),n.addLayer({id:"india-boundary-line",type:"line",source:"india-boundary",paint:{"line-color":"#94a3b8","line-width":1.5,"line-opacity":.65}})}catch{}})
91
+ const r=function(e=L){const r=document.createElement("div")
92
+ return r.className="qr-pin",r.setAttribute("aria-label","Drag to adjust your location"),r.style.width="40px",r.style.height="52px",r.innerHTML=`\n <svg\n class="qr-pin__svg"\n width="40"\n height="52"\n viewBox="0 0 40 52"\n overflow="visible"\n fill="none"\n xmlns="http://www.w3.org/2000/svg"\n aria-hidden="true"\n >\n <defs>\n \x3c!--\n The filter region must be generous enough to contain the shadow blur.\n stdDeviation=3 → ~9px blur radius; our region extends 50% on each side.\n overflow="visible" on the <svg> lets it paint outside the viewport.\n --\x3e\n <filter id="qr-pin-shadow" x="-60%" y="-40%" width="220%" height="220%">\n <feDropShadow dx="0" dy="3" stdDeviation="3.5"\n flood-color="#000" flood-opacity="0.28"/>\n </filter>\n </defs>\n\n \x3c!-- Teardrop body — tip is at (20, 52) = bottom-center of the SVG --\x3e\n <path\n d="M20 0C9.402 0 0 9.402 0 20C0 34 20 52 20 52S40 34 40 20C40 9.402 30.598 0 20 0Z"\n fill="${e}"\n filter="url(#qr-pin-shadow)"\n />\n \x3c!-- Dot inside the pin --\x3e\n <circle cx="20" cy="20" r="9" fill="white"/>\n <circle cx="20" cy="20" r="5" fill="${e}"/>\n </svg>\n\n \x3c!--\n Pulse ring — position: absolute inside .qr-pin (position: relative).\n bottom: -(height/2) → bottom: -10px centres the 20×20 circle\n exactly at y = PIN_H = 52px = the pin tip coordinate.\n --\x3e\n <div class="qr-pin__pulse" aria-hidden="true"></div>\n `,r}(v),a=new u.Marker({element:r,draggable:!0,anchor:"bottom"}).setLngLat([N,w]).addTo(n)
93
+ a.on("drag",()=>{const e=a.getLngLat()
94
+ P(e.lat),A(e.lng),re(e.lat,e.lng)}),a.on("dragend",()=>{const e=a.getLngLat()
95
+ n.easeTo({center:[e.lng,e.lat],duration:250})}),q.current=a}),n.on("click",e=>{var r
96
+ const a=e.lngLat
97
+ null==(r=q.current)||r.setLngLat([a.lng,a.lat]),P(a.lat),A(a.lng),re(a.lat,a.lng),n.easeTo({center:[a.lng,a.lat],duration:200})}),g.current=n,()=>{n.remove(),g.current=null,q.current=null}},[])
98
+ const oe=i(()=>{ee(),X((e,r)=>{var n
99
+ P(e),A(r),re(e,r),g.current&&g.current.flyTo({center:[r,e],zoom:18,duration:1400,essential:!0}),null==(n=q.current)||n.setLngLat([r,e])})},[X,ee,re]),le=i(()=>{B&&n(I,T,B)},[I,T,B,n]),se=null!==B,de=se&&M
100
+ return e("div",{className:"qr-map-wrapper",children:[e("div",{className:"qr-step-header",children:[r("div",{className:"qr-step-badge",children:"1"}),e("div",{className:"qr-step-text",children:[r("span",{className:"qr-step-title",children:"Pin Your Location"}),r("span",{className:"qr-step-sub",children:"Tap the map or drag the pin to your exact home / office"})]})]}),m&&e("div",{className:"qr-search-bar",role:"search",children:[e("div",{className:"qr-search-bar__input-wrap",children:[e("svg",{className:"qr-search-bar__icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("circle",{cx:"11",cy:"11",r:"8"}),r("path",{d:"M21 21l-4.35-4.35"})]}),r("input",{ref:G,type:"search",className:"qr-search-bar__input",placeholder:"Search address, 'pharmacy near me', or DigiPin…",value:O,onChange:ae,onKeyDown:ie,autoComplete:"off",autoCorrect:"off",autoCapitalize:"characters",spellCheck:!1,"aria-label":"Search address or DigiPin","aria-autocomplete":"list","aria-controls":V?Z:void 0,"aria-expanded":V}),j&&r("span",{className:"qr-search-bar__spinner qr-spinner qr-spinner--sm","aria-hidden":"true"}),O&&!j&&r("button",{type:"button",className:"qr-search-bar__clear",onClick:()=>{F(""),R([]),H(!1),z(null)},"aria-label":"Clear search",tabIndex:-1,children:"×"})]}),J&&r("p",{className:"qr-search-bar__error",role:"alert",children:J}),V&&U.length>0&&r("ul",{id:Z,className:"qr-search-bar__dropdown",role:"listbox","aria-label":"Address suggestions",children:U.map((n,a)=>e("li",{className:"qr-search-bar__suggestion",role:"option","aria-selected":"false",onMouseDown:e=>{e.preventDefault(),te(n)},children:[e("svg",{className:"qr-search-bar__suggestion-icon","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z"}),r("circle",{cx:"12",cy:"9",r:"2.5"})]}),e("div",{className:"qr-search-bar__suggestion-text",children:[r("span",{className:"qr-search-bar__suggestion-name",children:n.displayName}),n.address&&n.address!==n.displayName&&r("span",{className:"qr-search-bar__suggestion-sub",children:n.address})]})]},a))}),e("p",{className:"qr-search-bar__hint",children:[r("span",{className:"qr-search-bar__hint-chip",children:"DigiPin"}),"Type your DigiPin code for instant offline lookup — no API call"]})]}),e("div",{className:"qr-map-outer",style:{height:c},children:[r("div",{ref:_,className:"qr-map-canvas"}),B&&e("div",{className:"qr-digipin-badge","aria-live":"polite","aria-label":`DigiPin: ${B}`,children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:B})]}),!se&&M&&r("div",{className:"qr-map-notice",role:"status",children:"Move map to India to get a DigiPin"}),r("button",{className:"qr-locate-btn"+(Y?" qr-locate-btn--loading":""),onClick:oe,disabled:Y,title:"Use my current location","aria-label":"Use my current location",type:"button",children:Y?r("span",{className:"qr-spinner","aria-hidden":"true"}):e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"}),r("circle",{cx:"12",cy:"12",r:"7"}),r("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]})}),Q&&e("div",{className:"qr-geo-error",role:"alert",children:[r("span",{children:Q}),r("button",{type:"button",className:"qr-geo-error__dismiss",onClick:ee,"aria-label":"Dismiss error",children:"×"})]})]}),M&&e("div",{className:"qr-coords-strip","aria-label":"Current pin coordinates",children:[e("span",{children:[I.toFixed(5),"° N"]}),r("span",{className:"qr-coords-sep",children:"·"}),e("span",{children:[T.toFixed(5),"° E"]})]}),e("div",{className:"qr-map-actions",children:[e("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full",onClick:le,disabled:!de,children:["Confirm Location",r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M5 12h14M12 5l7 7-7 7"})})]}),!se&&M&&r("p",{className:"qr-map-hint",children:"Move the pin to a location in India to continue"})]})]})},P={flatNumber:"",floorNumber:"",buildingName:"",streetName:""}
101
+ function T(e,r){switch(r.type){case"LOAD_START":return{status:"loading"}
102
+ case"LOAD_SUCCESS":{const e=function(e){const r={}
103
+ e.name?r.buildingName=e.name:e.building_name?r.buildingName=e.building_name:e.addr_housename&&(r.buildingName=e.addr_housename)
104
+ const n=[]
105
+ return e.road&&n.push(e.road),e.suburb&&n.push(e.suburb),n.length>0&&(r.streetName=n.join(", ")),r}(r.addressComponents)
106
+ return{status:"ready",adminInfo:r.adminInfo,alternatives:r.alternatives||[],selectedLocality:r.adminInfo.locality,fields:{...P,...e},submitting:!1,pincodeHasDelivery:r.pincodeHasDelivery}}case"LOAD_ERROR":return{status:"error",message:r.message}
107
+ case"SET_FIELD":return"ready"!==e.status?e:{...e,fields:{...e.fields,[r.key]:r.value}}
108
+ case"SET_LOCALITY":return"ready"!==e.status?e:{...e,selectedLocality:r.locality}
109
+ case"SUBMIT_START":return"ready"!==e.status?e:{...e,submitting:!0}
110
+ case"SUBMIT_END":return"ready"!==e.status?e:{...e,submitting:!1}
111
+ default:return e}}const A=({digipin:a,lat:t,lng:o,apiKey:l,apiBaseUrl:c,onAddressComplete:u,onBack:h,onError:p})=>{const[m,f]=d(T,{status:"loading"}),y=i(async()=>{var e
112
+ f({type:"LOAD_START"})
113
+ try{const[r,n]=await Promise.all([q(t,o,l,c),x(a,l,c)]),i=(null==(e=r.data.administrative_info.pincode)?void 0:e.replace(/\D/g,"").slice(0,6))??""
114
+ if(6!==i.length)return f({type:"LOAD_ERROR",message:"Could not determine a valid 6-digit pincode for this location. Please adjust the map pin."}),void(null==p||p(new Error("Missing or invalid pincode")))
115
+ const s=await w(i,l,c)
116
+ if(!s.isValid)return f({type:"LOAD_ERROR",message:"This location resolves to a pincode that is not in the India Post database. Please move the map pin to a valid address."}),void(null==p||p(new Error("Invalid pincode for location")))
117
+ const d=N(s.offices)
118
+ f({type:"LOAD_SUCCESS",adminInfo:r.data.administrative_info,alternatives:r.data.alternatives||[],addressComponents:n.data.addressComponents,pincodeHasDelivery:d})}catch(e){const r=e instanceof Error?e.message:"Failed to fetch address data."
119
+ f({type:"LOAD_ERROR",message:r}),null==p||p(e instanceof Error?e:new Error(r))}},[a,t,o,l,c,p])
120
+ s(()=>{y()},[y])
121
+ const b=i(e=>{if(e.preventDefault(),"ready"!==m.status)return
122
+ const{adminInfo:r,selectedLocality:n,fields:i}=m,l=[i.flatNumber,i.floorNumber?`Floor ${i.floorNumber}`:"",i.buildingName,i.streetName,n,r.district,r.state,r.pincode].filter(Boolean),s={digipin:a,lat:t,lng:o,state:r.state,district:r.district,division:r.division,locality:n,pincode:r.pincode,delivery:r.delivery,country:r.country??"India",...i,formattedAddress:l.join(", ")}
123
+ f({type:"SUBMIT_START"})
124
+ try{u(s)}finally{f({type:"SUBMIT_END"})}},[m,a,t,o,u])
125
+ return e("div",{className:"qr-form-wrapper",children:[e("div",{className:"qr-step-header",children:[r("button",{type:"button",className:"qr-back-btn",onClick:h,"aria-label":"Back to map",children:r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M19 12H5M12 19l-7-7 7-7"})})}),r("div",{className:"qr-step-badge",children:"2"}),e("div",{className:"qr-step-text",children:[r("span",{className:"qr-step-title",children:"Add Address Details"}),r("span",{className:"qr-step-sub",children:"Flat number and building info"})]})]}),e("div",{className:"qr-form-digipin-strip",children:[e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"}),r("circle",{cx:"12",cy:"10",r:"3"})]}),r("span",{className:"qr-form-digipin-strip__label",children:"DigiPin"}),r("span",{className:"qr-form-digipin-strip__code",children:a})]}),"loading"===m.status&&e("div",{className:"qr-loading-state","aria-busy":"true","aria-label":"Fetching address details",children:[r("div",{className:"qr-spinner qr-spinner--lg","aria-hidden":"true"}),r("p",{className:"qr-loading-state__text",children:"Fetching address details…"})]}),"error"===m.status&&e("div",{className:"qr-error-state",role:"alert",children:[r("div",{className:"qr-error-state__icon","aria-hidden":"true",children:"⚠"}),r("p",{className:"qr-error-state__msg",children:m.message}),r("button",{type:"button",className:"qr-btn qr-btn--secondary qr-btn--sm",onClick:()=>{y()},children:"Retry"})]}),"ready"===m.status&&e("form",{onSubmit:b,className:"qr-form",noValidate:!0,children:[e("fieldset",{className:"qr-fieldset",children:[e("legend",{className:"qr-fieldset__legend",children:[r("span",{className:"qr-fieldset__icon","aria-hidden":"true",children:"📍"}),"Auto-detected from your pin"]}),e("div",{className:"qr-auto-grid",children:[e("div",{className:"qr-auto-row",children:[r("span",{className:"qr-auto-row__label",children:"State"}),r("span",{className:"qr-auto-row__value",children:m.adminInfo.state})]}),e("div",{className:"qr-auto-row",children:[r("span",{className:"qr-auto-row__label",children:"District"}),r("span",{className:"qr-auto-row__value",children:m.adminInfo.district})]}),e("div",{className:"qr-auto-row qr-auto-row--full",children:[r("span",{className:"qr-auto-row__label",children:"Locality"}),m.alternatives.length>0?e("select",{className:"qr-auto-row__select",value:m.selectedLocality,onChange:e=>f({type:"SET_LOCALITY",locality:e.target.value}),"aria-label":"Select locality",children:[r("option",{value:m.adminInfo.locality,children:m.adminInfo.locality}),m.alternatives.map((e,n)=>r("option",{value:e.name,children:e.name},n))]}):r("span",{className:"qr-auto-row__value",children:m.selectedLocality})]}),e("div",{className:"qr-auto-row",children:[r("span",{className:"qr-auto-row__label",children:"Pincode"}),r("span",{className:"qr-auto-row__value qr-auto-row__value--pin",children:m.adminInfo.pincode})]})]})]}),!m.pincodeHasDelivery&&e("div",{className:"qr-pincode-banner qr-pincode-banner--warning",role:"status","aria-live":"polite",children:[r("span",{className:"qr-pincode-banner__icon","aria-hidden":"true",children:"⚠"}),e("div",{className:"qr-pincode-banner__text",children:[r("strong",{children:"Non-delivery area"}),r("span",{children:"This pincode has no India Post home-delivery office. Courier delivery may be limited — confirm with your seller before placing the order."})]})]}),e("fieldset",{className:"qr-fieldset",children:[e("legend",{className:"qr-fieldset__legend",children:[r("span",{className:"qr-fieldset__icon","aria-hidden":"true",children:"🏠"}),"Your details"]}),e("div",{className:"qr-fields-grid",children:[e("div",{className:"qr-field qr-field--full",children:[e("label",{className:"qr-field__label",htmlFor:"qr-flatNumber",children:["Flat / House Number",r("span",{className:"qr-required","aria-hidden":"true",children:"*"})]}),r("input",{id:"qr-flatNumber",type:"text",className:"qr-field__input",placeholder:"e.g. 4B, Flat 201, House No. 12",value:m.fields.flatNumber,onChange:e=>f({type:"SET_FIELD",key:"flatNumber",value:e.target.value}),autoComplete:"address-line1",required:!0,"aria-required":"true"})]}),e("div",{className:"qr-field",children:[e("label",{className:"qr-field__label",htmlFor:"qr-floorNumber",children:["Floor",r("span",{className:"qr-optional",children:"optional"})]}),r("input",{id:"qr-floorNumber",type:"text",className:"qr-field__input",placeholder:"e.g. 3rd, Ground",value:m.fields.floorNumber,onChange:e=>f({type:"SET_FIELD",key:"floorNumber",value:e.target.value})})]}),e("div",{className:"qr-field",children:[e("label",{className:"qr-field__label",htmlFor:"qr-buildingName",children:["Building / Society",r("span",{className:"qr-optional",children:"optional"})]}),r("input",{id:"qr-buildingName",type:"text",className:"qr-field__input",placeholder:"e.g. Sunshine Apts, DDA Colony",value:m.fields.buildingName,onChange:e=>f({type:"SET_FIELD",key:"buildingName",value:e.target.value}),autoComplete:"address-line2"})]}),e("div",{className:"qr-field qr-field--full",children:[e("label",{className:"qr-field__label",htmlFor:"qr-streetName",children:["Street / Area",r("span",{className:"qr-optional",children:"optional"})]}),r("input",{id:"qr-streetName",type:"text",className:"qr-field__input",placeholder:"e.g. MG Road, Sector 12",value:m.fields.streetName,onChange:e=>f({type:"SET_FIELD",key:"streetName",value:e.target.value}),autoComplete:"address-level3"})]})]})]}),e("div",{className:"qr-form-actions",children:[e("button",{type:"button",className:"qr-btn qr-btn--ghost",onClick:h,children:[r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M19 12H5M12 19l-7-7 7-7"})}),"Adjust Pin"]}),r("button",{type:"submit",className:"qr-btn qr-btn--primary qr-btn--grow",disabled:m.submitting||!m.fields.flatNumber.trim(),children:m.submitting?e(n,{children:[r("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}),"Saving…"]}):e(n,{children:["Save Address",r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M20 6L9 17l-5-5"})})]})})]})]})]})}
126
+ async function B(e,r){const n=await fetch(`${e.functionBaseUrl}/checkout-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"send",mobile:r,merchant_id:e.merchantId})}),a=await n.json().catch(()=>({}))
127
+ if(!n.ok||!a.success)throw new Error(a.error??"Failed to send OTP. Please try again.")}async function D(e,r,n,a){const t=await fetch(`${e.functionBaseUrl}/checkout-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"verify",mobile:r,otp:n,merchant_id:e.merchantId,...a})}),i=await t.json().catch(()=>({}))
128
+ if(!t.ok||!i.success)throw new Error(i.error??"Invalid or expired OTP.")
129
+ return i}function M(e){return{"Content-Type":"application/json","x-session-token":e}}async function $(e,r){const n=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"list"})}),a=await n.json().catch(()=>({}))
130
+ if(!n.ok||!a.success)throw new Error(a.error??"Failed to load saved addresses.")
131
+ return a.data??[]}async function O(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"create",address:n})}),t=await a.json().catch(()=>({}))
132
+ if(!a.ok||!t.success)throw new Error(t.error??"Failed to save address.")
133
+ return t.data}async function F(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"delete",address_id:n})}),t=await a.json().catch(()=>({}))
134
+ if(!a.ok||!t.success)throw new Error(t.error??"Failed to delete address.")}async function U(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"set_default",address_id:n})}),t=await a.json().catch(()=>({}))
135
+ if(!a.ok||!t.success)throw new Error(t.error??"Failed to set default address.")}async function R(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"address_completed",data:n})}),t=await a.json().catch(()=>({}))
136
+ !a.ok||t.success}async function j(e,r){const n=await fetch(`${e.functionBaseUrl}/checkout-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"send",email:r,merchant_id:e.merchantId})}),a=await n.json().catch(()=>({}))
137
+ if(!n.ok||!a.success)throw new Error(a.error??"Failed to send OTP. Please try again.")}async function W(e,r,n,a){const t=await fetch(`${e.functionBaseUrl}/checkout-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"verify",email:r,code:n,merchant_id:e.merchantId,...a})}),i=await t.json().catch(()=>({}))
138
+ if(!t.ok||!i.success)throw new Error(i.error??"Invalid or expired code.")
139
+ return i}async function J(e,r,n,a){const t={action:"cod_eligibility",pincode:n}
140
+ void 0!==a&&(t.cart_total_paise=a)
141
+ const i=await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify(t)}),o=await i.json().catch(()=>({}))
142
+ if(!i.ok||!o.success)throw new Error(o.error??"Failed to check COD eligibility.")
143
+ return o.data}async function z(e,r,n){try{const a={"Content-Type":"application/json"}
144
+ n&&(a["x-session-token"]=n),await fetch(`${e.functionBaseUrl}/checkout-funnel-events`,{method:"POST",headers:a,body:JSON.stringify({merchant_id:e.merchantId,...r})})}catch{}}async function V(e,r,n){try{await fetch(`${e.functionBaseUrl}/checkout-addresses`,{method:"POST",headers:M(r),body:JSON.stringify({action:"abandon",last_step:n})})}catch{}}async function H(e,r){const n=await fetch(`${e.functionBaseUrl}/checkout-offers`,{method:"GET",headers:M(r)}),a=await n.json().catch(()=>({}))
145
+ return n.ok&&a.success?a.data??null:null}async function K(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-payment`,{method:"POST",headers:M(r),body:JSON.stringify({action:"create_order",amount_paise:n})}),t=await a.json().catch(()=>({}))
146
+ if(!a.ok||!t.success)throw new Error(t.error??"Failed to create payment order.")
147
+ return t.data}async function G(e,r,n){const a=await fetch(`${e.functionBaseUrl}/checkout-payment`,{method:"POST",headers:M(r),body:JSON.stringify({action:"verify",...n})}),t=await a.json().catch(()=>({}))
148
+ if(!a.ok||!t.success)throw new Error(t.error??"Payment verification failed.")
149
+ return{payment_method:t.payment_method}}async function Z(e,r){const n=await fetch(`${e.functionBaseUrl}/checkout-payment`,{method:"POST",headers:M(r),body:JSON.stringify({action:"record_cod"})}),a=await n.json().catch(()=>({}))
150
+ if(!n.ok||!a.success)throw new Error(a.error??"Failed to record COD selection.")
151
+ return{payment_method:a.payment_method}}async function Y(e,r){const n=await fetch(`${e}/checkout-admin?action=cod_config`,{headers:{"x-api-key":r}}),a=await n.json().catch(()=>({}))
152
+ return n.ok&&a.success?{prepaid_nudge_copy:a.data.prepaid_nudge_copy,prepaid_nudge_cta_url:a.data.prepaid_nudge_cta_url}:null}const Q=({onOtpSent:a,onSkip:l,functionBaseUrl:s,merchantId:d})=>{const[c,u]=t(""),[h,p]=t(!1),[m,f]=t(null),y=o(null),b=i(e=>{u(e.target.value.replace(/\D/g,"").slice(0,10)),f(null)},[]),v=i(async e=>{var r
153
+ if(e.preventDefault(),10!==c.length)return f("Enter a valid 10-digit mobile number."),void(null==(r=y.current)||r.focus())
154
+ p(!0),f(null)
155
+ try{await B({functionBaseUrl:s,merchantId:d},`+91${c}`),a(`+91${c}`)}catch(e){f(e instanceof Error?e.message:"Failed to send OTP. Please try again.")}finally{p(!1)}},[c,s,d,a])
156
+ return e("div",{className:"qr-auth-step",children:[r("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r("path",{d:"M16 14h4l2 5-2.5 1.5a11 11 0 005 5L26 23l5 2v4c0 1.1-.9 2-2 2A18 18 0 0114 16c0-1.1.9-2 2-2z",stroke:"var(--qr-primary)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}),r("h3",{className:"qr-auth-step__title",children:"Faster checkout"}),r("p",{className:"qr-auth-step__sub",children:"Enter your mobile to load saved addresses"}),e("form",{onSubmit:v,noValidate:!0,children:[e("div",{className:"qr-phone-field"+(m?" qr-phone-field--error":""),children:[r("span",{className:"qr-phone-field__prefix","aria-hidden":"true",children:"+91"}),r("input",{ref:y,type:"tel",inputMode:"numeric",className:"qr-phone-field__input",placeholder:"98765 43210",value:c,onChange:b,maxLength:10,autoComplete:"tel-national","aria-label":"Mobile number","aria-describedby":m?"qr-phone-error":void 0,"aria-invalid":!!m,disabled:h})]}),m&&r("p",{id:"qr-phone-error",className:"qr-auth-step__error",role:"alert",children:m}),r("button",{type:"submit",className:"qr-btn qr-btn--primary qr-btn--full",disabled:h||10!==c.length,children:h?r("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):e(n,{children:["Send OTP",r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M5 12h14M12 5l7 7-7 7"})})]})})]}),r("button",{type:"button",className:"qr-auth-step__skip",onClick:l,disabled:h,children:"Skip, enter address manually"})]})}
157
+ function X(e){const r=e.replace(/\D/g,"")
158
+ return r.length<4?e:`+91 ${r.slice(2,7)} **${r.slice(-3)}`}const ee=({mobile:n,onVerified:a,onBack:l,functionBaseUrl:d,merchantId:c,sessionContext:u})=>{const[h,p]=t(Array(6).fill("")),[m,f]=t(!1),[y,b]=t(null),[v,_]=t(30),[g,q]=t(!1),w=o([]),N=o(null)
159
+ s(()=>(N.current=setInterval(()=>{_(e=>e<=1?(clearInterval(N.current),0):e-1)},1e3),()=>{N.current&&clearInterval(N.current)}),[])
160
+ const k=e=>{var r
161
+ null==(r=w.current[e])||r.focus()},C=i((e,r)=>{const n=r.replace(/\D/g,"").slice(-1)
162
+ b(null),p(r=>{const a=[...r]
163
+ return a[e]=n,a}),n&&e<5&&k(e+1)},[]),x=i((e,r)=>{"Backspace"===r.key?h[e]?p(r=>{const n=[...r]
164
+ return n[e]="",n}):e>0&&(p(r=>{const n=[...r]
165
+ return n[e-1]="",n}),k(e-1)):"ArrowLeft"===r.key&&e>0?k(e-1):"ArrowRight"===r.key&&e<5&&k(e+1)},[h]),E=i(e=>{e.preventDefault()
166
+ const r=e.clipboardData.getData("text").replace(/\D/g,"").slice(0,6)
167
+ if(!r)return
168
+ const n=Array(6).fill("")
169
+ r.split("").forEach((e,r)=>{n[r]=e}),p(n),b(null),k(Math.min(r.length,5))},[]),S=h.join(""),L=6===S.length&&!h.includes(""),I=i(async()=>{if(L){f(!0),b(null)
170
+ try{const e=await D({functionBaseUrl:d,merchantId:c},n,S,u)
171
+ a(e.session_token,e.buyer_id,e.session_id)}catch(e){b(e instanceof Error?e.message:"Verification failed. Please try again."),p(Array(6).fill("")),k(0)}finally{f(!1)}}},[L,S,n,d,c,a,u])
172
+ s(()=>{L&&!m&&I()},[L])
173
+ const P=i(async()=>{if(!(v>0||g)){q(!0),b(null),p(Array(6).fill(""))
174
+ try{await B({functionBaseUrl:d,merchantId:c},n),_(30),N.current=setInterval(()=>{_(e=>e<=1?(clearInterval(N.current),0):e-1)},1e3),k(0)}catch(e){b(e instanceof Error?e.message:"Failed to resend OTP.")}finally{q(!1)}}},[v,g,d,c,n])
175
+ return e("div",{className:"qr-auth-step",children:[r("button",{type:"button",className:"qr-back-btn qr-back-btn--auth",onClick:l,disabled:m,children:r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M19 12H5M12 5l-7 7 7 7"})})}),r("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r("rect",{x:"13",y:"16",width:"22",height:"16",rx:"2",stroke:"var(--qr-primary)",strokeWidth:"1.8",fill:"none"}),r("path",{d:"M13 22h22",stroke:"var(--qr-primary)",strokeWidth:"1.8"}),r("circle",{cx:"18",cy:"29",r:"1.5",fill:"var(--qr-primary)"}),r("circle",{cx:"24",cy:"29",r:"1.5",fill:"var(--qr-primary)"}),r("circle",{cx:"30",cy:"29",r:"1.5",fill:"var(--qr-primary)"})]})}),r("h3",{className:"qr-auth-step__title",children:"Enter OTP"}),e("p",{className:"qr-auth-step__sub",children:["Sent to ",r("strong",{children:X(n)})]}),r("div",{className:"qr-otp-boxes",role:"group","aria-label":"Enter one-time password",children:h.map((e,n)=>r("input",{ref:e=>{w.current[n]=e},type:"text",inputMode:"numeric",maxLength:1,className:`qr-otp-box${e?" qr-otp-box--filled":""}${y?" qr-otp-box--error":""}`,value:e,onChange:e=>C(n,e.target.value),onKeyDown:e=>x(n,e),onPaste:E,onFocus:e=>e.target.select(),"aria-label":`OTP digit ${n+1}`,disabled:m,autoComplete:0===n?"one-time-code":"off"},n))}),y&&r("p",{className:"qr-auth-step__error",role:"alert",children:y}),r("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full",onClick:I,disabled:!L||m,children:m?r("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):"Verify OTP"}),r("p",{className:"qr-auth-step__resend",children:v>0?e("span",{children:["Resend OTP in ",v,"s"]}):r("button",{type:"button",className:"qr-link-btn",onClick:P,disabled:g,children:g?"Sending…":"Resend OTP"})})]})},re=()=>e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H4a1 1 0 01-1-1V9.5z"}),r("path",{d:"M9 21V12h6v9"})]}),ne=()=>e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[r("rect",{x:"2",y:"7",width:"20",height:"14",rx:"2"}),r("path",{d:"M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"})]}),ae=()=>e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z"}),r("circle",{cx:"12",cy:"9",r:"2.5"})]})
176
+ function te({label:e}){return r("home"===e?re:"work"===e?ne:ae,{})}function ie({address:a,onUse:t,onDelete:i,onSetDefault:o,deleting:l}){const s=[a.flat_number,a.building_name,a.street_name,a.locality,a.district,a.state,a.pincode].filter(Boolean),d=[a.flat_number,a.building_name,a.street_name].filter(Boolean).join(", "),c=[a.locality,a.district].filter(Boolean).join(", "),u=[a.state,a.pincode].filter(Boolean).join(" – "),h=s.length>0?void 0:a.locality||a.district||a.state
177
+ return e("div",{className:"qr-addr-card"+(a.is_default?" qr-addr-card--default":""),children:[e("div",{className:"qr-addr-card__header",children:[r("div",{className:"qr-addr-card__label-icon",children:r(te,{label:a.label})}),r("span",{className:"qr-addr-card__label",children:a.label.charAt(0).toUpperCase()+a.label.slice(1)}),a.is_default&&r("span",{className:"qr-addr-card__default-badge",children:"Default"}),e("div",{className:"qr-addr-card__actions",children:[!a.is_default&&r("button",{type:"button",className:"qr-icon-btn",title:"Set as default",onClick:o,"aria-label":"Set as default address",children:r("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:r("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),r("button",{type:"button",className:"qr-icon-btn qr-icon-btn--danger",title:"Delete address",onClick:i,disabled:l,"aria-label":"Delete address",children:l?r("span",{className:"qr-spinner qr-spinner--xs","aria-hidden":"true"}):e("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[r("polyline",{points:"3 6 5 6 21 6"}),r("path",{d:"M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"}),r("path",{d:"M10 11v6M14 11v6"}),r("path",{d:"M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"})]})})]})]}),e("div",{className:"qr-addr-card__body",children:[h?r("p",{className:"qr-addr-card__line",children:h}):e(n,{children:[d&&r("p",{className:"qr-addr-card__line",children:d}),c&&r("p",{className:"qr-addr-card__line qr-addr-card__line--muted",children:c}),u&&r("p",{className:"qr-addr-card__line qr-addr-card__line--muted",children:u})]}),e("div",{className:"qr-addr-card__meta",children:[e("span",{className:"qr-digipin-badge qr-digipin-badge--inline qr-digipin-badge--sm",children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:a.digipin})]}),a.saved_at_brand&&e("span",{className:"qr-addr-card__brand-chip",title:`First saved at ${a.saved_at_brand}`,children:[r("svg",{viewBox:"0 0 12 12",fill:"currentColor","aria-hidden":"true",children:r("path",{d:"M1 1h4.5l5.5 5.5-4.5 4.5L1 5.5V1zm2 1.5a.75.75 0 100 1.5.75.75 0 000-1.5z"})}),a.saved_at_brand]})]})]}),r("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full qr-btn--sm",onClick:t,children:"Deliver here"})]})}const oe=({sessionToken:n,functionBaseUrl:a,merchantId:o,onSelectAddress:l,onAddNew:d})=>{const[c,u]=t([]),[h,p]=t(!0),[m,f]=t(null),[y,b]=t(null),v={functionBaseUrl:a,merchantId:o},_=i(async()=>{p(!0),f(null)
178
+ try{const e=await $(v,n)
179
+ if(0===e.length)return void d()
180
+ u(e)}catch(e){f(e instanceof Error?e.message:"Failed to load addresses.")}finally{p(!1)}},[n])
181
+ s(()=>{_()},[_])
182
+ const g=i(async e=>{b(e)
183
+ try{await F(v,n,e),u(r=>{const n=r.filter(r=>r.id!==e)
184
+ return 0===n.length&&d(),n})}catch(e){f(e instanceof Error?e.message:"Failed to delete address.")}finally{b(null)}},[n,d]),q=i(async e=>{try{await U(v,n,e),u(r=>r.map(r=>({...r,is_default:r.id===e})))}catch(e){f(e instanceof Error?e.message:"Failed to set default.")}},[n])
185
+ return h?r("div",{className:"qr-saved-step",children:r("div",{className:"qr-saved-step__loading","aria-live":"polite",children:r("span",{className:"qr-spinner","aria-label":"Loading addresses"})})}):m&&0===c.length?e("div",{className:"qr-saved-step",children:[r("p",{className:"qr-auth-step__error",role:"alert",children:m}),r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--full",onClick:_,children:"Retry"}),r("button",{type:"button",className:"qr-auth-step__skip",onClick:d,children:"Enter address manually"})]}):e("div",{className:"qr-saved-step",children:[e("div",{className:"qr-step-header",children:[r("div",{className:"qr-step-badge qr-step-badge--saved",children:e("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z"}),r("circle",{cx:"12",cy:"9",r:"2.5"})]})}),e("div",{className:"qr-step-text",children:[r("span",{className:"qr-step-title",children:"Saved Addresses"}),r("span",{className:"qr-step-sub",children:"Pick one or add a new location"})]})]}),m&&r("p",{className:"qr-auth-step__error",role:"alert",children:m}),r("div",{className:"qr-saved-step__list",children:c.map(e=>r(ie,{address:e,onUse:()=>l(e),onDelete:()=>g(e.id),onSetDefault:()=>q(e.id),deleting:y===e.id},e.id))}),e("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--full",onClick:d,children:[r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M12 5v14M5 12h14"})}),"Add new address"]})]})},le=({checkoutConfig:n,sessionToken:a,pincode:i,cartTotalPaise:o,theme:l="light",onCodAllowedChange:d})=>{const[c,u]=t("loading"),[h,p]=t(!1),[m,f]=t()
186
+ return s(()=>{let e=!1
187
+ return u("loading"),(async()=>{try{const r=await J(n,a,i,o)
188
+ if(e)return
189
+ p(r.cod_allowed),null==d||d(r.cod_allowed),f(r.cod_allowed?void 0:r.reason?function(e){switch(e){case"cod_disabled":return"Cash on Delivery is not enabled for this store."
190
+ case"pincode_blocked":return"COD is not available for this pincode."
191
+ case"cart_value_exceeded":return"COD is not available for this order value."
192
+ case"invalid_pincode":return"Enter a valid pincode to check COD."
193
+ default:return"COD is not available."}}(r.reason):void 0),u("ready")}catch{e||(u("error"),p(!1),f("Could not verify COD. Try again."))}})(),()=>{e=!0}},[n,a,i,o]),e("div",{className:"qr-cod-banner"+("dark"===l?" qr-cod-banner--dark":""),role:"status","aria-live":"polite",children:[r("div",{className:"qr-cod-banner__title",children:"Cash on Delivery"}),"loading"===c&&r("p",{className:"qr-cod-banner__text qr-cod-banner__text--muted",children:"Checking availability…"}),"error"===c&&r("p",{className:"qr-cod-banner__text qr-cod-banner__text--warn",children:m}),"ready"===c&&h&&r("p",{className:"qr-cod-banner__text qr-cod-banner__text--ok",children:"Available for this address."}),"ready"===c&&!h&&m&&r("p",{className:"qr-cod-banner__text qr-cod-banner__text--muted",children:m})]})},se=({copy:n,ctaUrl:a,theme:t="light"})=>e("div",{className:"qr-prepaid-nudge"+("dark"===t?" qr-prepaid-nudge--dark":""),role:"complementary","aria-label":"Prepaid offer",children:[r("p",{className:"qr-prepaid-nudge__copy",children:n}),a?r("a",{href:a,className:"qr-btn qr-btn--primary qr-btn--sm qr-prepaid-nudge__cta",target:"_blank",rel:"noopener noreferrer",children:"Pay online instead"}):null]}),de="https://checkout.razorpay.com/v1/checkout.js",ce=({checkoutConfig:n,sessionToken:a,sessionId:i,amountPaise:o,enableCod:l=!1,codAllowed:d=!1,theme:c="light",onComplete:u,onBack:h,onEvent:p})=>{const[m,f]=t(!1),[y,b]=t(null),v="dark"===c
194
+ s(()=>{null==p||p("payment_step_viewed")},[p])
195
+ const _=`₹${(o/100).toLocaleString("en-IN")}`
196
+ return e("div",{className:"qr-payment-step"+(v?" qr-payment-step--dark":""),children:[h?r("button",{type:"button",className:"qr-back-btn qr-back-btn--auth",onClick:h,disabled:m,children:"← Back"}):null,r("h3",{className:"qr-auth-step__title",children:"Choose payment"}),e("p",{className:"qr-auth-step__sub",children:["Order total: ",r("strong",{children:_})]}),y?r("p",{className:"qr-auth-step__error",role:"alert",children:y}):null,r("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full",onClick:async()=>{f(!0),b(null)
197
+ try{await(window.Razorpay?Promise.resolve():new Promise((e,r)=>{const n=document.querySelector(`script[src="${de}"]`)
198
+ if(n)return void n.addEventListener("load",()=>e())
199
+ const a=document.createElement("script")
200
+ a.src=de,a.async=!0,a.onload=()=>e(),a.onerror=()=>r(new Error("Failed to load Razorpay")),document.body.appendChild(a)}))
201
+ const e=await K(n,a,o)
202
+ await new Promise((r,t)=>{window.Razorpay?new window.Razorpay({key:e.razorpay_key_id,amount:e.amount_paise,currency:e.currency,order_id:e.razorpay_order_id,name:"Checkout",handler:async e=>{try{const t=await G(n,a,{razorpay_order_id:e.razorpay_order_id,razorpay_payment_id:e.razorpay_payment_id,razorpay_signature:e.razorpay_signature,payment_method:"prepaid"})
203
+ null==p||p("payment_method_selected",t.payment_method),u(t.payment_method),r()}catch(e){t(e)}},modal:{ondismiss:()=>t(new Error("Payment cancelled"))}}).open():t(new Error("Razorpay unavailable"))})}catch(e){b(e instanceof Error?e.message:"Payment failed")}finally{f(!1)}},disabled:m,children:m?"Processing…":`Pay ${_} online`}),l&&d?r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--full",onClick:async()=>{f(!0),b(null)
204
+ try{const e=await Z(n,a)
205
+ null==p||p("payment_method_selected",e.payment_method),u(e.payment_method)}catch(e){b(e instanceof Error?e.message:"Failed to select COD")}finally{f(!1)}},disabled:m,style:{marginTop:8},children:"Cash on Delivery"}):null,i?e("p",{className:"qr-payment-step__meta",children:["Session ",i.slice(0,8),"…"]}):null]})},ue=({onOtpSent:a,onSkip:l,functionBaseUrl:s,merchantId:d})=>{const[c,u]=t(""),[h,p]=t(!1),[m,f]=t(null),y=o(null),b=i(e=>{u(e.target.value.trim()),f(null)},[]),v=i(async e=>{var r
206
+ if(e.preventDefault(),!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(c))return f("Enter a valid email address."),void(null==(r=y.current)||r.focus())
207
+ p(!0),f(null)
208
+ try{await j({functionBaseUrl:s,merchantId:d},c),a(c.toLowerCase())}catch(e){f(e instanceof Error?e.message:"Failed to send code. Please try again.")}finally{p(!1)}},[c,s,d,a])
209
+ return e("div",{className:"qr-auth-step",children:[r("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r("rect",{x:"11",y:"15",width:"26",height:"18",rx:"3",stroke:"var(--qr-primary)",strokeWidth:"1.8",fill:"none"}),r("path",{d:"M11 18l13 9 13-9",stroke:"var(--qr-primary)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-auth-step__title",children:"Faster checkout"}),r("p",{className:"qr-auth-step__sub",children:"Enter your email to load saved addresses"}),e("form",{onSubmit:v,noValidate:!0,children:[r("div",{className:"qr-email-field"+(m?" qr-email-field--error":""),children:r("input",{ref:y,type:"email",inputMode:"email",className:"qr-email-field__input",placeholder:"you@example.com",value:c,onChange:b,autoComplete:"email","aria-label":"Email address","aria-describedby":m?"qr-email-error":void 0,"aria-invalid":!!m,disabled:h})}),m&&r("p",{id:"qr-email-error",className:"qr-auth-step__error",role:"alert",children:m}),r("button",{type:"submit",className:"qr-btn qr-btn--primary qr-btn--full",disabled:h||c.length<5,children:h?r("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):e(n,{children:["Send Code",r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M5 12h14M12 5l7 7-7 7"})})]})})]}),r("button",{type:"button",className:"qr-auth-step__skip",onClick:l,disabled:h,children:"Skip, enter address manually"})]})}
210
+ function he(e){const[r,n]=e.split("@")
211
+ return!n||r.length<=1?e:`${r[0]}***@${n}`}const pe=({email:n,onVerified:a,onBack:l,functionBaseUrl:d,merchantId:c,sessionContext:u})=>{const[h,p]=t(Array(6).fill("")),[m,f]=t(!1),[y,b]=t(null),[v,_]=t(60),[g,q]=t(!1),w=o([]),N=o(null)
212
+ s(()=>(N.current=setInterval(()=>{_(e=>e<=1?(clearInterval(N.current),0):e-1)},1e3),()=>{N.current&&clearInterval(N.current)}),[])
213
+ const k=e=>{var r
214
+ return null==(r=w.current[e])?void 0:r.focus()},C=i((e,r)=>{const n=r.replace(/\D/g,"").slice(-1)
215
+ b(null),p(r=>{const a=[...r]
216
+ return a[e]=n,a}),n&&e<5&&k(e+1)},[]),x=i((e,r)=>{"Backspace"===r.key?h[e]?p(r=>{const n=[...r]
217
+ return n[e]="",n}):e>0&&(p(r=>{const n=[...r]
218
+ return n[e-1]="",n}),k(e-1)):"ArrowLeft"===r.key&&e>0?k(e-1):"ArrowRight"===r.key&&e<5&&k(e+1)},[h]),E=i(e=>{e.preventDefault()
219
+ const r=e.clipboardData.getData("text").replace(/\D/g,"").slice(0,6)
220
+ if(!r)return
221
+ const n=Array(6).fill("")
222
+ r.split("").forEach((e,r)=>{n[r]=e}),p(n),b(null),k(Math.min(r.length,5))},[]),S=h.join(""),L=6===S.length&&!h.includes(""),I=i(async()=>{if(L){f(!0),b(null)
223
+ try{const e=await W({functionBaseUrl:d,merchantId:c},n,S,u)
224
+ a(e.session_token,e.buyer_id,e.session_id)}catch(e){b(e instanceof Error?e.message:"Verification failed. Please try again."),p(Array(6).fill("")),k(0)}finally{f(!1)}}},[L,S,n,d,c,a,u])
225
+ s(()=>{L&&!m&&I()},[L])
226
+ const P=i(async()=>{if(!(v>0||g)){q(!0),b(null),p(Array(6).fill(""))
227
+ try{await j({functionBaseUrl:d,merchantId:c},n),_(60),N.current=setInterval(()=>{_(e=>e<=1?(clearInterval(N.current),0):e-1)},1e3),k(0)}catch(e){b(e instanceof Error?e.message:"Failed to resend code.")}finally{q(!1)}}},[v,g,d,c,n])
228
+ return e("div",{className:"qr-auth-step",children:[r("button",{type:"button",className:"qr-back-btn qr-back-btn--auth",onClick:l,disabled:m,children:r("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r("path",{d:"M19 12H5M12 5l-7 7 7 7"})})}),r("div",{className:"qr-auth-step__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"24",cy:"24",r:"24",fill:"var(--qr-primary-light)"}),r("rect",{x:"11",y:"15",width:"26",height:"18",rx:"3",stroke:"var(--qr-primary)",strokeWidth:"1.8",fill:"none"}),r("path",{d:"M11 18l13 9 13-9",stroke:"var(--qr-primary)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-auth-step__title",children:"Check your email"}),e("p",{className:"qr-auth-step__sub",children:["6-digit code sent to ",r("strong",{children:he(n)})]}),r("div",{className:"qr-otp-boxes",role:"group","aria-label":"Enter verification code",children:h.map((e,n)=>r("input",{ref:e=>{w.current[n]=e},type:"text",inputMode:"numeric",maxLength:1,className:`qr-otp-box${e?" qr-otp-box--filled":""}${y?" qr-otp-box--error":""}`,value:e,onChange:e=>C(n,e.target.value),onKeyDown:e=>x(n,e),onPaste:E,onFocus:e=>e.target.select(),"aria-label":`Code digit ${n+1}`,disabled:m,autoComplete:0===n?"one-time-code":"off"},n))}),y&&r("p",{className:"qr-auth-step__error",role:"alert",children:y}),r("button",{type:"button",className:"qr-btn qr-btn--primary qr-btn--full",onClick:I,disabled:!L||m,children:m?r("span",{className:"qr-spinner qr-spinner--sm","aria-hidden":"true"}):"Verify Code"}),r("p",{className:"qr-auth-step__resend",children:v>0?e("span",{children:["Resend code in ",v,"s"]}):r("button",{type:"button",className:"qr-link-btn",onClick:P,disabled:g,children:g?"Sending…":"Resend Code"})})]})}
229
+ function me(e){if("undefined"!=typeof window){const e=window.innerWidth
230
+ return e<768?"mobile":e<1024?"tablet":"desktop"}const r=(e??"").toLowerCase()
231
+ return/ipad|tablet/.test(r)?"tablet":/mobile|iphone|android/.test(r)?"mobile":"desktop"}function fe(){return"web"}function ye(){const e=function(){if("undefined"!=typeof navigator&&navigator.userAgent)return navigator.userAgent.slice(0,512)}()
232
+ return{deviceType:me(e),platform:"web",userAgent:e}}const be=["utm_source","utm_medium","utm_campaign"]
233
+ function ve(e){try{const r=new URL(e??("undefined"!=typeof window?window.location.href:"")),n={}
234
+ for(const e of be){const a=r.searchParams.get(e)
235
+ a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}function _e(e){return Boolean(e.utm_source||e.utm_medium||e.utm_campaign)}const ge=({address:n,onEditAddress:a})=>e("div",{className:"qr-success",children:[r("div",{className:"qr-success__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-success__title",children:"Address Saved!"}),r("p",{className:"qr-success__address",children:n.formattedAddress}),r("div",{className:"qr-success__meta",children:e("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:n.digipin})]})}),r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:a,children:"Change Address"})]}),qe=({apiKey:l,apiBaseUrl:d="https://api.quantaroute.com",onComplete:u,onError:h,defaultLat:p,defaultLng:m,theme:f="light",className:y="",style:b,mapHeight:v="380px",title:_="Add Delivery Address",indiaBoundaryUrl:g,enableSearch:q=!0,enablePhoneAuth:w=!1,merchantId:N="",supabaseFunctionBaseUrl:k="",brandColor:C,logoUrl:x,headerBanner:E,onCheckoutEvent:S,enableCod:L=!1,codCartTotalPaise:P,codSessionToken:T="",enableEmailAuth:B=!1,variant:D,utmParams:M,enablePayment:$=!1,paymentAmountPaise:F,onPaymentComplete:U,enablePrepaidNudge:j=!1,prepaidNudgeCopy:W,prepaidNudgeCtaUrl:J})=>{const K=w?"phone":B?"email":"none",G="phone"===K?"phone":"email"===K?"email":"map",Z=Boolean($&&F&&k),[Y,X]=t(G),[re,ne]=t(null),[ae,te]=t(null),[ie,de]=t(null),[he,me]=t(""),[fe,be]=t(!1),[_e,qe]=t(null),[we,Ne]=t(null),ke=o(Y),Ce=c(()=>M??ve(),[M]),xe=c(()=>ye(),[]),Ee=c(()=>({utm_source:Ce.utm_source,utm_medium:Ce.utm_medium,utm_campaign:Ce.utm_campaign,device_type:xe.deviceType,platform:xe.platform,user_agent:xe.userAgent,experiment_variant:D}),[Ce,xe,D]),Se={functionBaseUrl:k,merchantId:N},Le=(null==ie?void 0:ie.sessionToken)||T
236
+ s(()=>{ke.current=Y},[Y])
237
+ const Ie=i(e=>{const r={...e,sessionId:e.sessionId??(null==ie?void 0:ie.sessionId),buyerId:e.buyerId??(null==ie?void 0:ie.buyerId),authChannel:e.authChannel??("phone"===K?"phone":"email"===K?"email":"none"),deviceType:e.deviceType??xe.deviceType,platform:e.platform??xe.platform,userAgent:e.userAgent??xe.userAgent,experimentVariant:e.experimentVariant??D,timestamp:(new Date).toISOString()}
238
+ if(S)try{S(r)}catch{}N&&k&&z(Se,{event_type:r.type,step:r.step,buyer_id:r.buyerId,auth_channel:r.authChannel,device_type:r.deviceType,platform:r.platform,user_agent:r.userAgent,payment_method:r.paymentMethod,experiment_variant:r.experimentVariant},null==ie?void 0:ie.sessionToken).catch(()=>{})},[ie,K,xe,D,S,N,k,Se])
239
+ s(()=>{if(!N||!k)return
240
+ const e=()=>{"done"!==ke.current&&(null==ie?void 0:ie.sessionToken)&&(V(Se,ie.sessionToken,ke.current).catch(()=>{}),Ie({type:"session_abandoned",step:ke.current}))}
241
+ return window.addEventListener("pagehide",e),()=>window.removeEventListener("pagehide",e)},[null==ie?void 0:ie.sessionToken,N,k,Se,Ie]),s(()=>{(null==ie?void 0:ie.sessionToken)&&N&&k&&H(Se,ie.sessionToken).then(qe).catch(()=>qe(null))},[null==ie?void 0:ie.sessionToken,N,k,Se])
242
+ const Pe=c(()=>function(e,r){const n=null==r?void 0:r.trim()
243
+ if(!n)return e
244
+ const a={"--qr-primary":n,"--qr-primary-dark":n,"--qr-border-focus":n,"--qr-primary-light":`color-mix(in srgb, ${n} 18%, white)`}
245
+ return e?{...e,...a}:a}(b,C),[b,C]),Te=()=>{Ie({type:"auth_skipped",step:"map"}),X("map")},Ae=async e=>{if(te(e),Ie({type:"address_completed",step:Z?"payment":"done",digipin:e.digipin,buyerId:null==ie?void 0:ie.buyerId}),null==ie?void 0:ie.sessionToken){R(Se,ie.sessionToken,{pincode:e.pincode,digipin:e.digipin,state:e.state,district:e.district,locality:e.locality}).catch(()=>{})
246
+ try{await O(Se,ie.sessionToken,{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,locality:e.locality,pincode:e.pincode,delivery_status:e.delivery,flat_number:e.flatNumber,floor_number:e.floorNumber,building_name:e.buildingName,street_name:e.streetName,full_address_json:e,label:"home",is_default:!0})}catch{}}Z&&Le?X("payment"):(X("done"),u(e))}
247
+ s(()=>{const e={phone:"phone_step_viewed",email:"email_step_viewed",saved:"saved_addresses_viewed",map:"map_step_viewed",form:"form_step_viewed",payment:"payment_step_viewed"}[Y]
248
+ e&&Ie({type:e,step:Y,buyerId:null==ie?void 0:ie.buyerId})},[Y]),s(()=>{B&&"email"===K&&(N&&k||null==h||h(new Error("enableEmailAuth requires merchantId and supabaseFunctionBaseUrl on CheckoutWidget.")))},[B,K,N,k,h])
249
+ const Be=function(e,r,n){if("none"===r){if(n){const r=["map","form","payment","done"].indexOf(e)
250
+ return-1===r?0:r}return"map"===e?0:"form"===e?1:2}const a=("email"===r?n?["email","email-otp","saved","map","form","payment","done"]:["email","email-otp","saved","map","form","done"]:n?["phone","otp","saved","map","form","payment","done"]:["phone","otp","saved","map","form","done"]).indexOf(e)
251
+ return-1===a?0:a}(Y,K,Z),De=function(e,r){return"none"===e?r?3:2:r?6:5}(K,Z)
252
+ return e("div",{className:`qr-checkout qr-checkout--${f} ${y}`,style:Pe,"data-testid":"quantaroute-checkout",children:["done"!==Y&&e(n,{children:[e("div",{className:"qr-header",children:[e("div",{className:"qr-header__brand",children:[x?r("img",{src:x,alt:"",className:"qr-header__logo-img",width:28,height:28,decoding:"async"}):e("svg",{className:"qr-header__logo","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"}),r("circle",{cx:"12",cy:"10",r:"3"})]}),r("span",{className:"qr-header__title",children:_})]}),(()=>{const n=Array.from({length:De+1},(e,r)=>r)
253
+ return r("div",{className:"qr-progress",role:"progressbar","aria-valuenow":Be+1,"aria-valuemin":1,"aria-valuemax":De+1,"aria-label":`Step ${Be+1} of ${De+1}`,children:n.map(n=>e(a.Fragment,{children:[r("div",{className:"qr-progress__dot"+(Be>=n?" qr-progress__dot--active":"")}),n<De&&r("div",{className:"qr-progress__line"+(Be>n?" qr-progress__line--active":"")})]},n))})})()]}),E?r("div",{className:"qr-header-banner",role:"region","aria-label":"Merchant message",children:E}):null,_e?e("div",{className:"qr-offer-banner",role:"region","aria-label":"Special offer",children:[_e.banner_copy,_e.banner_cta_url?e(n,{children:[" ",r("a",{href:_e.banner_cta_url,target:"_blank",rel:"noopener noreferrer",children:"Learn more"})]}):null]}):null]}),"email"===Y&&B&&r(ue,{onOtpSent:e=>{me(e),Ie({type:"email_otp_sent",step:"email-otp",mobile:e}),X("email-otp")},onSkip:Te,functionBaseUrl:k,merchantId:N}),"email-otp"===Y&&B&&he&&r(pe,{email:he,onVerified:(e,r,n)=>{de({mobile:he,sessionToken:e,sessionId:n??"",buyerId:r}),Ie({type:"email_verified",step:"saved",buyerId:r,sessionId:n}),X("saved")},onBack:()=>X("email"),functionBaseUrl:k,merchantId:N,sessionContext:Ee}),"phone"===Y&&w&&r(Q,{onOtpSent:e=>{de(r=>({mobile:e,sessionToken:"",sessionId:"",buyerId:(null==r?void 0:r.buyerId)??""})),Ie({type:"otp_sent",step:"otp",mobile:e}),X("otp")},onSkip:Te,functionBaseUrl:k,merchantId:N}),"otp"===Y&&ie&&r(ee,{mobile:ie.mobile,onVerified:(e,r,n)=>{de({mobile:(null==ie?void 0:ie.mobile)??"",sessionToken:e,sessionId:n??"",buyerId:r}),Ie({type:"phone_verified",step:"saved",buyerId:r,sessionId:n}),X("saved")},onBack:()=>X("phone"),functionBaseUrl:k,merchantId:N,sessionContext:Ee}),"saved"===Y&&(null==ie?void 0:ie.sessionToken)&&r(oe,{sessionToken:ie.sessionToken,functionBaseUrl:k,merchantId:N,onSelectAddress:e=>{Ie({type:"saved_address_selected",step:Z?"payment":"done",buyerId:null==ie?void 0:ie.buyerId,digipin:e.digipin}),(null==ie?void 0:ie.sessionToken)&&R(Se,ie.sessionToken,{pincode:e.pincode,digipin:e.digipin,state:e.state,district:e.district,locality:e.locality}).catch(()=>{})
254
+ const r={digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,division:"",locality:e.locality,pincode:e.pincode,delivery:e.delivery_status,country:"India",flatNumber:e.flat_number,floorNumber:e.floor_number,buildingName:e.building_name,streetName:e.street_name,formattedAddress:[e.flat_number,e.building_name,e.street_name,e.locality,e.district,e.state,e.pincode].filter(Boolean).join(", ")}
255
+ Ae(r)},onAddNew:()=>X("map")}),"map"===Y&&r(I,{onLocationConfirm:(e,r,n)=>{ne({lat:e,lng:r,digipin:n}),Ie({type:"location_confirmed",step:"form",digipin:n,buyerId:null==ie?void 0:ie.buyerId}),X("form")},defaultLat:p,defaultLng:m,mapHeight:v,theme:f,indiaBoundaryUrl:g,enableSearch:q,apiKey:l,apiBaseUrl:d,brandColor:C}),"form"===Y&&re&&r(A,{digipin:re.digipin,lat:re.lat,lng:re.lng,apiKey:l,apiBaseUrl:d,onAddressComplete:async e=>{await Ae(e)},onBack:()=>{"form"===Y?X("map"):"map"===Y&&(null==ie?void 0:ie.sessionToken)?X("saved"):"email-otp"===Y&&X("email")},onError:h,theme:f}),"payment"===Y&&Z&&Le&&F&&r(ce,{checkoutConfig:Se,sessionToken:Le,sessionId:null==ie?void 0:ie.sessionId,amountPaise:F,enableCod:L,codAllowed:fe,theme:f,onComplete:e=>{Ne(e),Ie({type:"payment_method_selected",step:"done",paymentMethod:e}),X("done"),ae&&u(ae),null==U||U({paymentMethod:e,sessionId:null==ie?void 0:ie.sessionId})},onBack:()=>X("form"),onEvent:(e,r)=>Ie({type:e,step:"payment",paymentMethod:r,buyerId:null==ie?void 0:ie.buyerId})}),"done"===Y&&ae&&e(n,{children:[r(ge,{address:ae,onEditAddress:()=>{Ie({type:"widget_reset",step:G}),X(G),ne(null),te(null)}}),we?e("p",{className:"qr-cod-banner__text qr-cod-banner__text--ok",style:{textAlign:"center",margin:"8px 16px"},children:["Paid via ","cod"===we?"Cash on Delivery":"online payment"]}):null,L&&N&&k&&Le?e(n,{children:[r(le,{checkoutConfig:Se,sessionToken:Le,pincode:ae.pincode,cartTotalPaise:P??F,theme:f,onCodAllowedChange:be}),j&&fe?r(se,{copy:W??"Save more when you pay online — faster delivery & exclusive offers.",ctaUrl:J,theme:f}):null]}):null]}),e("div",{className:"qr-footer",children:[r("span",{children:"Powered by"}),r("a",{href:"https://quantaroute.com",target:"_blank",rel:"noopener noreferrer",className:"qr-footer__link",children:"QuantaRoute"}),r("span",{className:"qr-footer__flag","aria-label":"Made in India",children:"🇮🇳"})]})]})}
256
+ function we(e,r){return c(()=>{if(!b(e,r))return null
257
+ try{return m(e,r)}catch{return null}},[e,r])}export{A as AddressForm,qe as CheckoutWidget,le as CodAvailabilityBanner,p as DIGIPIN_BOUNDS,pe as EmailOtpStep,ue as EmailStep,I as MapPinSelector,ee as OtpStep,ce as PaymentStep,Q as PhoneStep,se as PrepaidNudge,oe as SavedAddressStep,C as autocompleteAddress,ve as captureUtmFromUrl,J as checkCodEligibility,O as createAddress,K as createPaymentOrder,qe as default,F as deleteAddress,me as detectDeviceType,fe as detectPlatform,Y as fetchPrepaidNudgeConfig,H as fetchSessionOffer,m as getDigiPin,f as getLatLngFromDigiPin,ye as getWebDeviceContext,_e as hasUtmParams,y as isValidDigiPin,b as isWithinIndia,$ as listAddresses,z as logFunnelEvent,k as looksLikeDigiPin,q as lookupLocation,R as notifyAddressCompleted,V as notifySessionAbandoned,N as pincodeHasDeliveryOffice,Z as recordCodPayment,x as reverseGeocode,j as sendEmailOtp,B as sendOtp,U as setDefaultAddress,we as useDigiPin,E as useGeolocation,w as validatePincode,W as verifyEmailOtp,D as verifyOtp,G as verifyPayment}