create-brainerce-store 1.27.4 → 1.27.6

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.
Files changed (32) hide show
  1. package/dist/index.js +12 -1
  2. package/messages/en.json +382 -378
  3. package/messages/he.json +382 -378
  4. package/package.json +46 -46
  5. package/templates/nextjs/base/next.config.ts +31 -31
  6. package/templates/nextjs/base/src/app/account/page.tsx +1 -1
  7. package/templates/nextjs/base/src/app/auth/callback/page.tsx +2 -1
  8. package/templates/nextjs/base/src/app/cart/page.tsx +1 -1
  9. package/templates/nextjs/base/src/app/checkout/page.tsx +973 -972
  10. package/templates/nextjs/base/src/app/forgot-password/page.tsx +1 -1
  11. package/templates/nextjs/base/src/app/layout.tsx.ejs +6 -5
  12. package/templates/nextjs/base/src/app/login/page.tsx +1 -2
  13. package/templates/nextjs/base/src/app/order-confirmation/page.tsx +271 -271
  14. package/templates/nextjs/base/src/app/page.tsx +1 -1
  15. package/templates/nextjs/base/src/app/payment-complete/page.tsx +59 -59
  16. package/templates/nextjs/base/src/app/products/[slug]/product-client-section.tsx +27 -12
  17. package/templates/nextjs/base/src/app/products/page.tsx +8 -3
  18. package/templates/nextjs/base/src/app/register/page.tsx +1 -2
  19. package/templates/nextjs/base/src/app/reset-password/page.tsx +1 -2
  20. package/templates/nextjs/base/src/app/verify-email/page.tsx +1 -2
  21. package/templates/nextjs/base/src/components/auth/login-form.tsx +1 -1
  22. package/templates/nextjs/base/src/components/checkout/custom-fields-step.tsx +258 -184
  23. package/templates/nextjs/base/src/components/checkout/payment-step.tsx +592 -592
  24. package/templates/nextjs/base/src/components/layout/footer.tsx +1 -1
  25. package/templates/nextjs/base/src/components/layout/header.tsx +1 -2
  26. package/templates/nextjs/base/src/components/products/product-card.tsx +1 -2
  27. package/templates/nextjs/base/src/components/products/recommendation-section.tsx +1 -1
  28. package/templates/nextjs/base/src/lib/navigation.tsx.ejs +60 -0
  29. package/templates/nextjs/themes/luxury/globals.css +399 -399
  30. package/templates/nextjs/themes/luxury/theme.json +23 -23
  31. package/templates/nextjs/themes/playful/globals.css +400 -400
  32. package/templates/nextjs/themes/playful/theme.json +23 -23
@@ -1,592 +1,592 @@
1
- 'use client';
2
-
3
- import { useEffect, useState, useRef, useCallback } from 'react';
4
- import type { PaymentIntent, PaymentClientSdk } from 'brainerce';
5
- import { getClient } from '@/lib/brainerce';
6
- import { useTranslations } from '@/lib/translations';
7
- import { LoadingSpinner } from '@/components/shared/loading-spinner';
8
- import { cn } from '@/lib/utils';
9
-
10
- /**
11
- * Backward-compat defaults when backend doesn't return clientSdk.
12
- */
13
- const LEGACY_GROW_SDK: PaymentClientSdk = {
14
- renderType: 'sdk-widget',
15
- scriptUrl: 'https://cdn.meshulam.co.il/sdk/gs.min.js',
16
- globalName: 'growPayment',
17
- initMethod: 'init',
18
- renderMethod: 'renderPaymentOptions',
19
- containerId: 'grow-payment-container',
20
- initConfig: { version: 1, environment: 'DEV' },
21
- additionalScripts: [
22
- { url: 'https://meshulam.co.il/_media/js/apple_pay_sdk/sdk.min.js', optional: true },
23
- ],
24
- bodyStyles:
25
- '[id*="Gr0W8-"],[id*="Gr0W8-"] *,[class*="Gr0W8-"],[class*="Gr0W8-"] *{direction:ltr !important;text-align:left}',
26
- };
27
-
28
- interface PaymentStepProps {
29
- checkoutId: string;
30
- className?: string;
31
- }
32
-
33
- function resolveClientSdk(
34
- intent: PaymentIntent | null,
35
- preloadedSdk?: PaymentClientSdk | null
36
- ): PaymentClientSdk {
37
- const fullSdk = [preloadedSdk, intent?.clientSdk].find((s) => s?.renderType);
38
- const runtimeSdk = intent?.clientSdk;
39
- if (fullSdk) {
40
- if (!runtimeSdk || runtimeSdk === fullSdk) return fullSdk;
41
- return {
42
- ...fullSdk,
43
- ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
44
- ...(runtimeSdk.initConfig
45
- ? { initConfig: { ...fullSdk.initConfig, ...runtimeSdk.initConfig } }
46
- : {}),
47
- };
48
- }
49
- const legacy = intent?.provider === 'grow' ? LEGACY_GROW_SDK : null;
50
- if (legacy && runtimeSdk) {
51
- return {
52
- ...legacy,
53
- ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
54
- ...(runtimeSdk.initConfig
55
- ? { initConfig: { ...legacy.initConfig, ...runtimeSdk.initConfig } }
56
- : {}),
57
- };
58
- }
59
- if (legacy) return legacy;
60
- return { renderType: 'redirect' };
61
- }
62
-
63
- function extractMessage(response: unknown): string {
64
- if (typeof response === 'string') return response;
65
- return (response as { message?: string })?.message || '';
66
- }
67
-
68
- export function PaymentStep({ checkoutId, className }: PaymentStepProps) {
69
- const t = useTranslations('checkout');
70
- const [paymentIntent, setPaymentIntent] = useState<PaymentIntent | null>(null);
71
- const [preloadedSdk, setPreloadedSdk] = useState<PaymentClientSdk | null>(null);
72
- const [loading, setLoading] = useState(true);
73
- const [error, setError] = useState<string | null>(null);
74
- const [sdkReady, setSdkReady] = useState(false);
75
- const walletOpenRef = useRef(false);
76
- const initialized = useRef(false);
77
-
78
- // Stable refs for SDK event callbacks (avoids stale closures in onload)
79
- const cbRef = useRef({
80
- onSuccess: (_r: unknown) => {},
81
- onFailure: (_r: unknown) => {},
82
- onError: (_r: unknown) => {},
83
- onTimeout: () => {},
84
- onWalletChange: (_s: string) => {},
85
- retryRender: () => {},
86
- });
87
-
88
- const handleSuccess = useCallback(
89
- async (response: unknown) => {
90
- console.info('Payment SDK success:', JSON.stringify(response));
91
- try {
92
- const client = getClient();
93
- const resp = response as Record<string, unknown>;
94
- const data = (resp?.data && typeof resp.data === 'object' ? resp.data : resp) as
95
- | Record<string, unknown>
96
- | undefined;
97
- await client.confirmSdkPayment(checkoutId, data || undefined);
98
- } catch (err) {
99
- console.warn('Failed to confirm payment with backend:', err);
100
- }
101
- window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
102
- },
103
- [checkoutId]
104
- );
105
-
106
- cbRef.current = {
107
- onSuccess: handleSuccess,
108
- onFailure: (response: unknown) => {
109
- console.error('Payment SDK failure:', response);
110
- setError(extractMessage(response) || t('paymentError'));
111
- },
112
- onError: (response: unknown) => {
113
- const TRANSIENT = [
114
- 'Wallet not initialized',
115
- "SDK was not loaded as needed and therefore can't run",
116
- ];
117
- const msg = extractMessage(response);
118
- if (TRANSIENT.some((e) => msg.includes(e))) {
119
- console.info('Payment SDK: transient error, retrying render in 1s:', msg);
120
- setTimeout(() => cbRef.current.retryRender(), 1000);
121
- return;
122
- }
123
- console.error('Payment SDK error:', response);
124
- setError(msg || t('paymentError'));
125
- },
126
- onTimeout: () => {
127
- console.warn('Payment SDK: wallet timed out');
128
- setError(t('paymentTimedOut'));
129
- },
130
- onWalletChange: (state: string) => {
131
- console.info('Payment SDK wallet state:', state);
132
- if (state === 'open') {
133
- walletOpenRef.current = true;
134
- setSdkReady(true);
135
- }
136
- if (state === 'close') setSdkReady(false);
137
- },
138
- retryRender: () => {},
139
- };
140
-
141
- // =========================================================================
142
- // MAIN EFFECT — Follows Grow SDK docs exactly:
143
- //
144
- // Step 1: Load gs.min.js (insertBefore, as docs show)
145
- // Step 2: s.onload → growPayment.init({ environment, version, events })
146
- // This triggers the SDK to load mp.min.js → CSS, HTML, params, services
147
- // Step 3: createPaymentIntent (starts wallet timer — should be AFTER init)
148
- // Step 4: growPayment.renderPaymentOptions(authCode)
149
- //
150
- // "call createPaymentProcess right before you need to render the wallet"
151
- // =========================================================================
152
- useEffect(() => {
153
- if (initialized.current) return;
154
- initialized.current = true;
155
-
156
- const client = getClient();
157
- const iframeSuccessUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}`;
158
- const iframeFailedUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}&failed=true`;
159
- const redirectSuccessUrl = `${window.location.origin}/order-confirmation?checkout_id=${checkoutId}`;
160
- const cancelUrl = `${window.location.origin}/checkout?checkout_id=${checkoutId}&canceled=true`;
161
-
162
- let sdkInitDone = false;
163
- let currentSdk: PaymentClientSdk | null = null;
164
- const cleanups: (() => void)[] = [];
165
-
166
- // --- Load SDK script exactly as Grow docs show ---
167
- function loadScript(sdk: PaymentClientSdk) {
168
- if (!sdk.scriptUrl || !sdk.globalName) return;
169
-
170
- // Inject bodyStyles
171
- if (sdk.bodyStyles && !document.querySelector('style[data-payment-sdk]')) {
172
- const style = document.createElement('style');
173
- style.setAttribute('data-payment-sdk', 'true');
174
- style.textContent = sdk.bodyStyles;
175
- document.head.appendChild(style);
176
- cleanups.push(() => style.remove());
177
- }
178
-
179
- // Additional scripts (Apple Pay etc.) — fire and forget
180
- if (sdk.additionalScripts) {
181
- for (const extra of sdk.additionalScripts) {
182
- if (document.querySelector(`script[src="${extra.url}"]`)) continue;
183
- const s = document.createElement('script');
184
- s.type = 'text/javascript';
185
- s.async = true;
186
- s.src = extra.url;
187
- const ref = document.getElementsByTagName('script')[0];
188
- if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
189
- else document.head.appendChild(s);
190
- }
191
- }
192
-
193
- // Already loaded? Init immediately
194
- if ((window as any)[sdk.globalName]) {
195
- initSdk(sdk);
196
- return;
197
- }
198
-
199
- // Already loading (from a previous call)? Wait for it instead of duplicating
200
- if (document.querySelector(`script[src="${sdk.scriptUrl}"]`)) {
201
- const waitId = setInterval(() => {
202
- if ((window as any)[sdk.globalName!]) {
203
- clearInterval(waitId);
204
- initSdk(sdk);
205
- }
206
- }, 100);
207
- cleanups.push(() => clearInterval(waitId));
208
- return;
209
- }
210
-
211
- // Load main SDK — insertBefore first <script> as Grow docs show
212
- const s = document.createElement('script');
213
- s.type = 'text/javascript';
214
- s.async = true;
215
- s.src = sdk.scriptUrl;
216
- s.onload = () => initSdk(sdk); // init DIRECTLY in onload
217
- s.onerror = () => {
218
- console.error('Payment SDK: script load failed');
219
- setError(t('failedToLoadPaymentSdk'));
220
- };
221
- const ref = document.getElementsByTagName('script')[0];
222
- if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
223
- else document.head.appendChild(s);
224
- }
225
-
226
- // --- Init: called in s.onload (as Grow docs require) ---
227
- function initSdk(sdk: PaymentClientSdk) {
228
- if (sdkInitDone) return; // Guard against double init
229
-
230
- const global = (window as any)[sdk.globalName!];
231
- if (!global) {
232
- setError(t('failedToLoadPaymentSdk'));
233
- return;
234
- }
235
-
236
- const method = sdk.initMethod || 'init';
237
- const config = {
238
- ...(sdk.initConfig || {}),
239
- events: {
240
- onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
241
- onFailure: (r: unknown) => cbRef.current.onFailure(r),
242
- onError: (r: unknown) => cbRef.current.onError(r),
243
- onTimeout: () => cbRef.current.onTimeout(),
244
- onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
245
- },
246
- };
247
-
248
- console.info(`Payment SDK: calling ${method}()`);
249
- global[method](config);
250
- sdkInitDone = true;
251
- }
252
-
253
- // --- Render: call once, then safety-net retries if wallet doesn't open ---
254
- // Grow SDK sometimes silently swallows renderPaymentOptions when its
255
- // internal resources (mp.min.js etc.) aren't fully loaded yet.
256
- // Strategy: render once, then retry up to 3 times with increasing delays
257
- // (2s, 3s, 4s) if onWalletChange("open") hasn't fired.
258
- let pendingRender: { sdk: PaymentClientSdk; intent: PaymentIntent } | null = null;
259
- let renderAttempts = 0;
260
- const MAX_RENDER_ATTEMPTS = 4;
261
-
262
- function renderPayment(sdk: PaymentClientSdk, intent: PaymentIntent) {
263
- const global = (window as any)[sdk.globalName!];
264
- if (!global || walletOpenRef.current) return;
265
-
266
- const renderMethod = sdk.renderMethod || 'renderPaymentOptions';
267
- const renderArg = sdk.renderArg || intent.clientSecret;
268
- renderAttempts++;
269
-
270
- try {
271
- global[renderMethod](renderArg);
272
- console.info(`Payment SDK: renderPaymentOptions called (attempt ${renderAttempts})`);
273
- } catch (err) {
274
- console.info('Payment SDK: render threw, will retry in 1s');
275
- }
276
-
277
- // Safety net: if wallet doesn't open within a delay, retry
278
- if (renderAttempts < MAX_RENDER_ATTEMPTS) {
279
- const delay = 1000 + renderAttempts * 1000; // 2s, 3s, 4s
280
- const retryId = setTimeout(() => {
281
- if (!walletOpenRef.current) {
282
- console.info(`Payment SDK: wallet not open after ${delay}ms, retrying render...`);
283
- renderPayment(sdk, intent);
284
- }
285
- }, delay);
286
- cleanups.push(() => clearTimeout(retryId));
287
- }
288
- }
289
-
290
- function retryRender() {
291
- if (pendingRender && !walletOpenRef.current) {
292
- renderPayment(pendingRender.sdk, pendingRender.intent);
293
- }
294
- }
295
-
296
- // =============================================
297
- // Execution flow
298
- // =============================================
299
-
300
- // A) Get SDK config from providers (fast, no wallet timer)
301
- const providerPromise = client
302
- .getPaymentProviders()
303
- .then((res) => {
304
- const sdk = res.defaultProvider?.clientSdk;
305
- if (sdk) setPreloadedSdk(sdk);
306
- return sdk || null;
307
- })
308
- .catch(() => null);
309
-
310
- // B) Load + init SDK as early as possible (skip for sandbox)
311
- providerPromise.then((providerSdk) => {
312
- if (providerSdk?.renderType === 'sandbox') return;
313
- if (providerSdk?.renderType === 'sdk-widget' && providerSdk.scriptUrl) {
314
- currentSdk = providerSdk;
315
- loadScript(providerSdk);
316
- }
317
- });
318
-
319
- // C) Create payment intent (starts wallet timer)
320
- // Wait for provider info so we can choose the right success URL:
321
- // iframe providers redirect inside the iframe to /payment-complete (postMessage),
322
- // redirect providers go straight to /order-confirmation.
323
- const intentPromise = providerPromise
324
- .then((providerSdk) => {
325
- const isIframe = providerSdk?.renderType === 'iframe';
326
- const successUrl = isIframe ? iframeSuccessUrl : redirectSuccessUrl;
327
- const failedUrl = isIframe ? iframeFailedUrl : cancelUrl;
328
- return client.createPaymentIntent(checkoutId, {
329
- successUrl,
330
- cancelUrl: failedUrl,
331
- });
332
- })
333
- .then((intent) => {
334
- setPaymentIntent(intent);
335
- return intent;
336
- })
337
- .catch((err) => {
338
- setError(err instanceof Error ? err.message : t('paymentError'));
339
- return null;
340
- })
341
- .finally(() => setLoading(false));
342
-
343
- // D) When both ready: resolve final SDK config and render
344
- Promise.all([providerPromise, intentPromise]).then(([providerSdk, intent]) => {
345
- if (!intent) return;
346
-
347
- const sdk = resolveClientSdk(intent, providerSdk);
348
- currentSdk = sdk;
349
-
350
- // Sandbox mode — no SDK to load, UI handles it
351
- if (sdk.renderType === 'sandbox') return;
352
-
353
- if (sdk.renderType === 'redirect') {
354
- window.location.href = intent.clientSecret;
355
- return;
356
- }
357
-
358
- // Iframe mode: listen for postMessage from the /payment-complete callback
359
- // page that loads inside the iframe after the provider redirects on completion.
360
- if (sdk.renderType === 'iframe') {
361
- const handleMessage = (event: MessageEvent) => {
362
- if (event.origin !== window.location.origin) return;
363
- if (event.data?.type !== 'brainerce:payment-complete') return;
364
-
365
- const params = event.data.data as Record<string, string> | undefined;
366
- if (params?.failed === 'true') {
367
- setError(t('paymentError'));
368
- return;
369
- }
370
-
371
- // Map provider-specific params to normalized format for
372
- // server-side verification (e.g. CardCom lowprofilecode → paymentIntentId)
373
- const lowProfileCode = params?.lowprofilecode || params?.LowProfileCode;
374
- const normalized: Record<string, unknown> = { ...params };
375
- if (lowProfileCode) {
376
- normalized.paymentIntentId = lowProfileCode;
377
- }
378
-
379
- // Trigger server-side verification + order creation
380
- handleSuccess(normalized);
381
- };
382
- window.addEventListener('message', handleMessage);
383
- cleanups.push(() => window.removeEventListener('message', handleMessage));
384
- return;
385
- }
386
-
387
- if (sdk.renderType !== 'sdk-widget' || !sdk.globalName) return;
388
-
389
- // Store for retryRender from onError callback
390
- pendingRender = { sdk, intent };
391
- cbRef.current.retryRender = retryRender;
392
-
393
- // If SDK wasn't loaded from providers, load + init now
394
- if (!sdkInitDone) {
395
- loadScript(sdk);
396
- // Wait for init to complete, then render once
397
- const id = setInterval(() => {
398
- if (sdkInitDone) {
399
- clearInterval(id);
400
- renderPayment(sdk, intent);
401
- }
402
- }, 100);
403
- cleanups.push(() => clearInterval(id));
404
- return;
405
- }
406
-
407
- // Re-init with final config if environment changed
408
- if (sdk.initConfig?.environment && currentSdk) {
409
- const global = (window as any)[sdk.globalName];
410
- if (global) {
411
- const method = sdk.initMethod || 'init';
412
- global[method]({
413
- ...(sdk.initConfig || {}),
414
- events: {
415
- onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
416
- onFailure: (r: unknown) => cbRef.current.onFailure(r),
417
- onError: (r: unknown) => cbRef.current.onError(r),
418
- onTimeout: () => cbRef.current.onTimeout(),
419
- onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
420
- },
421
- });
422
- }
423
- }
424
-
425
- // SDK ready — render once
426
- renderPayment(sdk, intent);
427
- });
428
-
429
- return () => cleanups.forEach((fn) => fn());
430
- }, [checkoutId]);
431
-
432
- // --- UI ---
433
-
434
- if (loading) {
435
- return (
436
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
437
- <LoadingSpinner size="lg" />
438
- <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
439
- </div>
440
- );
441
- }
442
-
443
- if (error) {
444
- const isNotConfigured =
445
- error.toLowerCase().includes('not configured') ||
446
- error.toLowerCase().includes('no payment') ||
447
- error.toLowerCase().includes('provider');
448
- return (
449
- <div className={cn('py-12 text-center', className)}>
450
- <svg
451
- className="text-muted-foreground mx-auto mb-4 h-12 w-12"
452
- fill="none"
453
- viewBox="0 0 24 24"
454
- stroke="currentColor"
455
- >
456
- <path
457
- strokeLinecap="round"
458
- strokeLinejoin="round"
459
- strokeWidth={1.5}
460
- d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
461
- />
462
- </svg>
463
- <h3 className="text-foreground mb-2 text-lg font-semibold">
464
- {isNotConfigured ? t('paymentNotConfigured') : t('paymentError')}
465
- </h3>
466
- <p className="text-muted-foreground mx-auto max-w-md text-sm">
467
- {isNotConfigured ? t('paymentNotConfiguredDesc') : error}
468
- </p>
469
- </div>
470
- );
471
- }
472
-
473
- if (!paymentIntent) return null;
474
-
475
- const sdk = resolveClientSdk(paymentIntent, preloadedSdk);
476
-
477
- if (sdk.renderType === 'sandbox') {
478
- const handleCompleteSandbox = async () => {
479
- setLoading(true);
480
- try {
481
- const client = getClient();
482
- await client.completeGuestCheckout(checkoutId);
483
- window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
484
- } catch (err) {
485
- setError(err instanceof Error ? err.message : t('paymentError'));
486
- setLoading(false);
487
- }
488
- };
489
-
490
- return (
491
- <div className={cn('py-8 text-center', className)}>
492
- <div className="mx-auto max-w-md rounded-lg border border-amber-200 bg-amber-50 p-6">
493
- <svg
494
- className="mx-auto mb-3 h-10 w-10 text-amber-500"
495
- fill="none"
496
- viewBox="0 0 24 24"
497
- stroke="currentColor"
498
- >
499
- <path
500
- strokeLinecap="round"
501
- strokeLinejoin="round"
502
- strokeWidth={1.5}
503
- d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"
504
- />
505
- </svg>
506
- <h3 className="text-foreground mb-1 text-lg font-semibold">{t('sandboxTitle')}</h3>
507
- <p className="text-muted-foreground mb-4 text-sm">{t('sandboxDescription')}</p>
508
- <button
509
- onClick={handleCompleteSandbox}
510
- className="inline-flex items-center rounded-md bg-amber-500 px-6 py-2.5 text-sm font-medium text-white transition-colors hover:bg-amber-600"
511
- >
512
- {t('completeTestOrder')}
513
- </button>
514
- </div>
515
- </div>
516
- );
517
- }
518
-
519
- if (sdk.renderType === 'sdk-widget') {
520
- const containerId =
521
- sdk.containerId || `${paymentIntent.provider || 'payment'}-payment-container`;
522
- return (
523
- <div className={cn('py-4', className)}>
524
- {!sdkReady && (
525
- <div className="flex flex-col items-center justify-center py-8">
526
- <LoadingSpinner size="lg" />
527
- <p className="text-muted-foreground mt-4 text-sm">{t('loadingPaymentOptions')}</p>
528
- </div>
529
- )}
530
- <div id={containerId} />
531
- </div>
532
- );
533
- }
534
-
535
- if (sdk.renderType === 'iframe') {
536
- return (
537
- <>
538
- {/* Modal overlay */}
539
- <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/50 py-6 backdrop-blur-sm">
540
- <div className="relative mx-4 w-full max-w-md rounded-2xl bg-white shadow-2xl">
541
- {/* Close button */}
542
- <button
543
- onClick={() => {
544
- window.location.href = `/checkout?checkout_id=${checkoutId}&canceled=true`;
545
- }}
546
- className="absolute end-3 top-3 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-white/80 text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-700"
547
- aria-label="Close"
548
- >
549
- <svg
550
- width="14"
551
- height="14"
552
- viewBox="0 0 14 14"
553
- fill="none"
554
- stroke="currentColor"
555
- strokeWidth="2"
556
- strokeLinecap="round"
557
- >
558
- <path d="M1 1l12 12M13 1L1 13" />
559
- </svg>
560
- </button>
561
- <iframe
562
- src={paymentIntent.clientSecret}
563
- className="w-full rounded-2xl border-0"
564
- style={{ height: '80vh' }}
565
- title={t('payment')}
566
- allow="payment"
567
- />
568
- </div>
569
- </div>
570
- {/* Placeholder so the checkout layout doesn't collapse */}
571
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
572
- <LoadingSpinner size="lg" />
573
- <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
574
- </div>
575
- </>
576
- );
577
- }
578
-
579
- return (
580
- <div className={cn('flex flex-col items-center justify-center py-12', className)}>
581
- <LoadingSpinner size="lg" />
582
- <p className="text-muted-foreground mt-4 text-sm">{t('redirectingToPayment')}</p>
583
- <p className="text-muted-foreground mt-2 text-xs">
584
- {t('redirectingHint')}
585
- <a href={paymentIntent.clientSecret} className="text-primary hover:underline">
586
- {t('clickHere')}
587
- </a>
588
- .
589
- </p>
590
- </div>
591
- );
592
- }
1
+ 'use client';
2
+
3
+ import { useEffect, useState, useRef, useCallback } from 'react';
4
+ import type { PaymentIntent, PaymentClientSdk } from 'brainerce';
5
+ import { getClient } from '@/lib/brainerce';
6
+ import { useTranslations } from '@/lib/translations';
7
+ import { LoadingSpinner } from '@/components/shared/loading-spinner';
8
+ import { cn } from '@/lib/utils';
9
+
10
+ /**
11
+ * Backward-compat defaults when backend doesn't return clientSdk.
12
+ */
13
+ const LEGACY_GROW_SDK: PaymentClientSdk = {
14
+ renderType: 'sdk-widget',
15
+ scriptUrl: 'https://cdn.meshulam.co.il/sdk/gs.min.js',
16
+ globalName: 'growPayment',
17
+ initMethod: 'init',
18
+ renderMethod: 'renderPaymentOptions',
19
+ containerId: 'grow-payment-container',
20
+ initConfig: { version: 1, environment: 'DEV' },
21
+ additionalScripts: [
22
+ { url: 'https://meshulam.co.il/_media/js/apple_pay_sdk/sdk.min.js', optional: true },
23
+ ],
24
+ bodyStyles:
25
+ '[id*="Gr0W8-"],[id*="Gr0W8-"] *,[class*="Gr0W8-"],[class*="Gr0W8-"] *{direction:ltr !important;text-align:left}',
26
+ };
27
+
28
+ interface PaymentStepProps {
29
+ checkoutId: string;
30
+ className?: string;
31
+ }
32
+
33
+ function resolveClientSdk(
34
+ intent: PaymentIntent | null,
35
+ preloadedSdk?: PaymentClientSdk | null
36
+ ): PaymentClientSdk {
37
+ const fullSdk = [preloadedSdk, intent?.clientSdk].find((s) => s?.renderType);
38
+ const runtimeSdk = intent?.clientSdk;
39
+ if (fullSdk) {
40
+ if (!runtimeSdk || runtimeSdk === fullSdk) return fullSdk;
41
+ return {
42
+ ...fullSdk,
43
+ ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
44
+ ...(runtimeSdk.initConfig
45
+ ? { initConfig: { ...fullSdk.initConfig, ...runtimeSdk.initConfig } }
46
+ : {}),
47
+ };
48
+ }
49
+ const legacy = intent?.provider === 'grow' ? LEGACY_GROW_SDK : null;
50
+ if (legacy && runtimeSdk) {
51
+ return {
52
+ ...legacy,
53
+ ...(runtimeSdk.renderArg ? { renderArg: runtimeSdk.renderArg } : {}),
54
+ ...(runtimeSdk.initConfig
55
+ ? { initConfig: { ...legacy.initConfig, ...runtimeSdk.initConfig } }
56
+ : {}),
57
+ };
58
+ }
59
+ if (legacy) return legacy;
60
+ return { renderType: 'redirect' };
61
+ }
62
+
63
+ function extractMessage(response: unknown): string {
64
+ if (typeof response === 'string') return response;
65
+ return (response as { message?: string })?.message || '';
66
+ }
67
+
68
+ export function PaymentStep({ checkoutId, className }: PaymentStepProps) {
69
+ const t = useTranslations('checkout');
70
+ const [paymentIntent, setPaymentIntent] = useState<PaymentIntent | null>(null);
71
+ const [preloadedSdk, setPreloadedSdk] = useState<PaymentClientSdk | null>(null);
72
+ const [loading, setLoading] = useState(true);
73
+ const [error, setError] = useState<string | null>(null);
74
+ const [sdkReady, setSdkReady] = useState(false);
75
+ const walletOpenRef = useRef(false);
76
+ const initialized = useRef(false);
77
+
78
+ // Stable refs for SDK event callbacks (avoids stale closures in onload)
79
+ const cbRef = useRef({
80
+ onSuccess: (_r: unknown) => {},
81
+ onFailure: (_r: unknown) => {},
82
+ onError: (_r: unknown) => {},
83
+ onTimeout: () => {},
84
+ onWalletChange: (_s: string) => {},
85
+ retryRender: () => {},
86
+ });
87
+
88
+ const handleSuccess = useCallback(
89
+ async (response: unknown) => {
90
+ console.info('Payment SDK success:', JSON.stringify(response));
91
+ try {
92
+ const client = getClient();
93
+ const resp = response as Record<string, unknown>;
94
+ const data = (resp?.data && typeof resp.data === 'object' ? resp.data : resp) as
95
+ | Record<string, unknown>
96
+ | undefined;
97
+ await client.confirmSdkPayment(checkoutId, data || undefined);
98
+ } catch (err) {
99
+ console.warn('Failed to confirm payment with backend:', err);
100
+ }
101
+ window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
102
+ },
103
+ [checkoutId]
104
+ );
105
+
106
+ cbRef.current = {
107
+ onSuccess: handleSuccess,
108
+ onFailure: (response: unknown) => {
109
+ console.error('Payment SDK failure:', response);
110
+ setError(extractMessage(response) || t('paymentError'));
111
+ },
112
+ onError: (response: unknown) => {
113
+ const TRANSIENT = [
114
+ 'Wallet not initialized',
115
+ "SDK was not loaded as needed and therefore can't run",
116
+ ];
117
+ const msg = extractMessage(response);
118
+ if (TRANSIENT.some((e) => msg.includes(e))) {
119
+ console.info('Payment SDK: transient error, retrying render in 1s:', msg);
120
+ setTimeout(() => cbRef.current.retryRender(), 1000);
121
+ return;
122
+ }
123
+ console.error('Payment SDK error:', response);
124
+ setError(msg || t('paymentError'));
125
+ },
126
+ onTimeout: () => {
127
+ console.warn('Payment SDK: wallet timed out');
128
+ setError(t('paymentTimedOut'));
129
+ },
130
+ onWalletChange: (state: string) => {
131
+ console.info('Payment SDK wallet state:', state);
132
+ if (state === 'open') {
133
+ walletOpenRef.current = true;
134
+ setSdkReady(true);
135
+ }
136
+ if (state === 'close') setSdkReady(false);
137
+ },
138
+ retryRender: () => {},
139
+ };
140
+
141
+ // =========================================================================
142
+ // MAIN EFFECT — Follows Grow SDK docs exactly:
143
+ //
144
+ // Step 1: Load gs.min.js (insertBefore, as docs show)
145
+ // Step 2: s.onload → growPayment.init({ environment, version, events })
146
+ // This triggers the SDK to load mp.min.js → CSS, HTML, params, services
147
+ // Step 3: createPaymentIntent (starts wallet timer — should be AFTER init)
148
+ // Step 4: growPayment.renderPaymentOptions(authCode)
149
+ //
150
+ // "call createPaymentProcess right before you need to render the wallet"
151
+ // =========================================================================
152
+ useEffect(() => {
153
+ if (initialized.current) return;
154
+ initialized.current = true;
155
+
156
+ const client = getClient();
157
+ const iframeSuccessUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}`;
158
+ const iframeFailedUrl = `${window.location.origin}/payment-complete?checkout_id=${checkoutId}&failed=true`;
159
+ const redirectSuccessUrl = `${window.location.origin}/order-confirmation?checkout_id=${checkoutId}`;
160
+ const cancelUrl = `${window.location.origin}/checkout?checkout_id=${checkoutId}&canceled=true`;
161
+
162
+ let sdkInitDone = false;
163
+ let currentSdk: PaymentClientSdk | null = null;
164
+ const cleanups: (() => void)[] = [];
165
+
166
+ // --- Load SDK script exactly as Grow docs show ---
167
+ function loadScript(sdk: PaymentClientSdk) {
168
+ if (!sdk.scriptUrl || !sdk.globalName) return;
169
+
170
+ // Inject bodyStyles
171
+ if (sdk.bodyStyles && !document.querySelector('style[data-payment-sdk]')) {
172
+ const style = document.createElement('style');
173
+ style.setAttribute('data-payment-sdk', 'true');
174
+ style.textContent = sdk.bodyStyles;
175
+ document.head.appendChild(style);
176
+ cleanups.push(() => style.remove());
177
+ }
178
+
179
+ // Additional scripts (Apple Pay etc.) — fire and forget
180
+ if (sdk.additionalScripts) {
181
+ for (const extra of sdk.additionalScripts) {
182
+ if (document.querySelector(`script[src="${extra.url}"]`)) continue;
183
+ const s = document.createElement('script');
184
+ s.type = 'text/javascript';
185
+ s.async = true;
186
+ s.src = extra.url;
187
+ const ref = document.getElementsByTagName('script')[0];
188
+ if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
189
+ else document.head.appendChild(s);
190
+ }
191
+ }
192
+
193
+ // Already loaded? Init immediately
194
+ if ((window as any)[sdk.globalName]) {
195
+ initSdk(sdk);
196
+ return;
197
+ }
198
+
199
+ // Already loading (from a previous call)? Wait for it instead of duplicating
200
+ if (document.querySelector(`script[src="${sdk.scriptUrl}"]`)) {
201
+ const waitId = setInterval(() => {
202
+ if ((window as any)[sdk.globalName!]) {
203
+ clearInterval(waitId);
204
+ initSdk(sdk);
205
+ }
206
+ }, 100);
207
+ cleanups.push(() => clearInterval(waitId));
208
+ return;
209
+ }
210
+
211
+ // Load main SDK — insertBefore first <script> as Grow docs show
212
+ const s = document.createElement('script');
213
+ s.type = 'text/javascript';
214
+ s.async = true;
215
+ s.src = sdk.scriptUrl;
216
+ s.onload = () => initSdk(sdk); // init DIRECTLY in onload
217
+ s.onerror = () => {
218
+ console.error('Payment SDK: script load failed');
219
+ setError(t('failedToLoadPaymentSdk'));
220
+ };
221
+ const ref = document.getElementsByTagName('script')[0];
222
+ if (ref?.parentNode) ref.parentNode.insertBefore(s, ref);
223
+ else document.head.appendChild(s);
224
+ }
225
+
226
+ // --- Init: called in s.onload (as Grow docs require) ---
227
+ function initSdk(sdk: PaymentClientSdk) {
228
+ if (sdkInitDone) return; // Guard against double init
229
+
230
+ const global = (window as any)[sdk.globalName!];
231
+ if (!global) {
232
+ setError(t('failedToLoadPaymentSdk'));
233
+ return;
234
+ }
235
+
236
+ const method = sdk.initMethod || 'init';
237
+ const config = {
238
+ ...(sdk.initConfig || {}),
239
+ events: {
240
+ onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
241
+ onFailure: (r: unknown) => cbRef.current.onFailure(r),
242
+ onError: (r: unknown) => cbRef.current.onError(r),
243
+ onTimeout: () => cbRef.current.onTimeout(),
244
+ onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
245
+ },
246
+ };
247
+
248
+ console.info(`Payment SDK: calling ${method}()`);
249
+ global[method](config);
250
+ sdkInitDone = true;
251
+ }
252
+
253
+ // --- Render: call once, then safety-net retries if wallet doesn't open ---
254
+ // Grow SDK sometimes silently swallows renderPaymentOptions when its
255
+ // internal resources (mp.min.js etc.) aren't fully loaded yet.
256
+ // Strategy: render once, then retry up to 3 times with increasing delays
257
+ // (2s, 3s, 4s) if onWalletChange("open") hasn't fired.
258
+ let pendingRender: { sdk: PaymentClientSdk; intent: PaymentIntent } | null = null;
259
+ let renderAttempts = 0;
260
+ const MAX_RENDER_ATTEMPTS = 4;
261
+
262
+ function renderPayment(sdk: PaymentClientSdk, intent: PaymentIntent) {
263
+ const global = (window as any)[sdk.globalName!];
264
+ if (!global || walletOpenRef.current) return;
265
+
266
+ const renderMethod = sdk.renderMethod || 'renderPaymentOptions';
267
+ const renderArg = sdk.renderArg || intent.clientSecret;
268
+ renderAttempts++;
269
+
270
+ try {
271
+ global[renderMethod](renderArg);
272
+ console.info(`Payment SDK: renderPaymentOptions called (attempt ${renderAttempts})`);
273
+ } catch (err) {
274
+ console.info('Payment SDK: render threw, will retry in 1s');
275
+ }
276
+
277
+ // Safety net: if wallet doesn't open within a delay, retry
278
+ if (renderAttempts < MAX_RENDER_ATTEMPTS) {
279
+ const delay = 1000 + renderAttempts * 1000; // 2s, 3s, 4s
280
+ const retryId = setTimeout(() => {
281
+ if (!walletOpenRef.current) {
282
+ console.info(`Payment SDK: wallet not open after ${delay}ms, retrying render...`);
283
+ renderPayment(sdk, intent);
284
+ }
285
+ }, delay);
286
+ cleanups.push(() => clearTimeout(retryId));
287
+ }
288
+ }
289
+
290
+ function retryRender() {
291
+ if (pendingRender && !walletOpenRef.current) {
292
+ renderPayment(pendingRender.sdk, pendingRender.intent);
293
+ }
294
+ }
295
+
296
+ // =============================================
297
+ // Execution flow
298
+ // =============================================
299
+
300
+ // A) Get SDK config from providers (fast, no wallet timer)
301
+ const providerPromise = client
302
+ .getPaymentProviders()
303
+ .then((res) => {
304
+ const sdk = res.defaultProvider?.clientSdk;
305
+ if (sdk) setPreloadedSdk(sdk);
306
+ return sdk || null;
307
+ })
308
+ .catch(() => null);
309
+
310
+ // B) Load + init SDK as early as possible (skip for sandbox)
311
+ providerPromise.then((providerSdk) => {
312
+ if (providerSdk?.renderType === 'sandbox') return;
313
+ if (providerSdk?.renderType === 'sdk-widget' && providerSdk.scriptUrl) {
314
+ currentSdk = providerSdk;
315
+ loadScript(providerSdk);
316
+ }
317
+ });
318
+
319
+ // C) Create payment intent (starts wallet timer)
320
+ // Wait for provider info so we can choose the right success URL:
321
+ // iframe providers redirect inside the iframe to /payment-complete (postMessage),
322
+ // redirect providers go straight to /order-confirmation.
323
+ const intentPromise = providerPromise
324
+ .then((providerSdk) => {
325
+ const isIframe = providerSdk?.renderType === 'iframe';
326
+ const successUrl = isIframe ? iframeSuccessUrl : redirectSuccessUrl;
327
+ const failedUrl = isIframe ? iframeFailedUrl : cancelUrl;
328
+ return client.createPaymentIntent(checkoutId, {
329
+ successUrl,
330
+ cancelUrl: failedUrl,
331
+ });
332
+ })
333
+ .then((intent) => {
334
+ setPaymentIntent(intent);
335
+ return intent;
336
+ })
337
+ .catch((err) => {
338
+ setError(err instanceof Error ? err.message : t('paymentError'));
339
+ return null;
340
+ })
341
+ .finally(() => setLoading(false));
342
+
343
+ // D) When both ready: resolve final SDK config and render
344
+ Promise.all([providerPromise, intentPromise]).then(([providerSdk, intent]) => {
345
+ if (!intent) return;
346
+
347
+ const sdk = resolveClientSdk(intent, providerSdk);
348
+ currentSdk = sdk;
349
+
350
+ // Sandbox mode — no SDK to load, UI handles it
351
+ if (sdk.renderType === 'sandbox') return;
352
+
353
+ if (sdk.renderType === 'redirect') {
354
+ window.location.href = intent.clientSecret;
355
+ return;
356
+ }
357
+
358
+ // Iframe mode: listen for postMessage from the /payment-complete callback
359
+ // page that loads inside the iframe after the provider redirects on completion.
360
+ if (sdk.renderType === 'iframe') {
361
+ const handleMessage = (event: MessageEvent) => {
362
+ if (event.origin !== window.location.origin) return;
363
+ if (event.data?.type !== 'brainerce:payment-complete') return;
364
+
365
+ const params = event.data.data as Record<string, string> | undefined;
366
+ if (params?.failed === 'true') {
367
+ setError(t('paymentError'));
368
+ return;
369
+ }
370
+
371
+ // Map provider-specific params to normalized format for
372
+ // server-side verification (e.g. CardCom lowprofilecode → paymentIntentId)
373
+ const lowProfileCode = params?.lowprofilecode || params?.LowProfileCode;
374
+ const normalized: Record<string, unknown> = { ...params };
375
+ if (lowProfileCode) {
376
+ normalized.paymentIntentId = lowProfileCode;
377
+ }
378
+
379
+ // Trigger server-side verification + order creation
380
+ handleSuccess(normalized);
381
+ };
382
+ window.addEventListener('message', handleMessage);
383
+ cleanups.push(() => window.removeEventListener('message', handleMessage));
384
+ return;
385
+ }
386
+
387
+ if (sdk.renderType !== 'sdk-widget' || !sdk.globalName) return;
388
+
389
+ // Store for retryRender from onError callback
390
+ pendingRender = { sdk, intent };
391
+ cbRef.current.retryRender = retryRender;
392
+
393
+ // If SDK wasn't loaded from providers, load + init now
394
+ if (!sdkInitDone) {
395
+ loadScript(sdk);
396
+ // Wait for init to complete, then render once
397
+ const id = setInterval(() => {
398
+ if (sdkInitDone) {
399
+ clearInterval(id);
400
+ renderPayment(sdk, intent);
401
+ }
402
+ }, 100);
403
+ cleanups.push(() => clearInterval(id));
404
+ return;
405
+ }
406
+
407
+ // Re-init with final config if environment changed
408
+ if (sdk.initConfig?.environment && currentSdk) {
409
+ const global = (window as any)[sdk.globalName];
410
+ if (global) {
411
+ const method = sdk.initMethod || 'init';
412
+ global[method]({
413
+ ...(sdk.initConfig || {}),
414
+ events: {
415
+ onSuccess: (r: unknown) => cbRef.current.onSuccess(r),
416
+ onFailure: (r: unknown) => cbRef.current.onFailure(r),
417
+ onError: (r: unknown) => cbRef.current.onError(r),
418
+ onTimeout: () => cbRef.current.onTimeout(),
419
+ onWalletChange: (s: string) => cbRef.current.onWalletChange(s),
420
+ },
421
+ });
422
+ }
423
+ }
424
+
425
+ // SDK ready — render once
426
+ renderPayment(sdk, intent);
427
+ });
428
+
429
+ return () => cleanups.forEach((fn) => fn());
430
+ }, [checkoutId]);
431
+
432
+ // --- UI ---
433
+
434
+ if (loading) {
435
+ return (
436
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
437
+ <LoadingSpinner size="lg" />
438
+ <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
439
+ </div>
440
+ );
441
+ }
442
+
443
+ if (error) {
444
+ const isNotConfigured =
445
+ error.toLowerCase().includes('not configured') ||
446
+ error.toLowerCase().includes('no payment') ||
447
+ error.toLowerCase().includes('provider');
448
+ return (
449
+ <div className={cn('py-12 text-center', className)}>
450
+ <svg
451
+ className="text-muted-foreground mx-auto mb-4 h-12 w-12"
452
+ fill="none"
453
+ viewBox="0 0 24 24"
454
+ stroke="currentColor"
455
+ >
456
+ <path
457
+ strokeLinecap="round"
458
+ strokeLinejoin="round"
459
+ strokeWidth={1.5}
460
+ d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
461
+ />
462
+ </svg>
463
+ <h3 className="text-foreground mb-2 text-lg font-semibold">
464
+ {isNotConfigured ? t('paymentNotConfigured') : t('paymentError')}
465
+ </h3>
466
+ <p className="text-muted-foreground mx-auto max-w-md text-sm">
467
+ {isNotConfigured ? t('paymentNotConfiguredDesc') : error}
468
+ </p>
469
+ </div>
470
+ );
471
+ }
472
+
473
+ if (!paymentIntent) return null;
474
+
475
+ const sdk = resolveClientSdk(paymentIntent, preloadedSdk);
476
+
477
+ if (sdk.renderType === 'sandbox') {
478
+ const handleCompleteSandbox = async () => {
479
+ setLoading(true);
480
+ try {
481
+ const client = getClient();
482
+ await client.completeGuestCheckout(checkoutId);
483
+ window.location.href = `/order-confirmation?checkout_id=${checkoutId}`;
484
+ } catch (err) {
485
+ setError(err instanceof Error ? err.message : t('paymentError'));
486
+ setLoading(false);
487
+ }
488
+ };
489
+
490
+ return (
491
+ <div className={cn('py-8 text-center', className)}>
492
+ <div className="mx-auto max-w-md rounded-lg border border-amber-200 bg-amber-50 p-6">
493
+ <svg
494
+ className="mx-auto mb-3 h-10 w-10 text-amber-500"
495
+ fill="none"
496
+ viewBox="0 0 24 24"
497
+ stroke="currentColor"
498
+ >
499
+ <path
500
+ strokeLinecap="round"
501
+ strokeLinejoin="round"
502
+ strokeWidth={1.5}
503
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4.5c-.77-.833-2.694-.833-3.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"
504
+ />
505
+ </svg>
506
+ <h3 className="text-foreground mb-1 text-lg font-semibold">{t('sandboxTitle')}</h3>
507
+ <p className="text-muted-foreground mb-4 text-sm">{t('sandboxDescription')}</p>
508
+ <button
509
+ onClick={handleCompleteSandbox}
510
+ className="inline-flex items-center rounded-md bg-amber-500 px-6 py-2.5 text-sm font-medium text-white transition-colors hover:bg-amber-600"
511
+ >
512
+ {t('completeTestOrder')}
513
+ </button>
514
+ </div>
515
+ </div>
516
+ );
517
+ }
518
+
519
+ if (sdk.renderType === 'sdk-widget') {
520
+ const containerId =
521
+ sdk.containerId || `${paymentIntent.provider || 'payment'}-payment-container`;
522
+ return (
523
+ <div className={cn('py-4', className)}>
524
+ {!sdkReady && (
525
+ <div className="flex flex-col items-center justify-center py-8">
526
+ <LoadingSpinner size="lg" />
527
+ <p className="text-muted-foreground mt-4 text-sm">{t('loadingPaymentOptions')}</p>
528
+ </div>
529
+ )}
530
+ <div id={containerId} />
531
+ </div>
532
+ );
533
+ }
534
+
535
+ if (sdk.renderType === 'iframe') {
536
+ return (
537
+ <>
538
+ {/* Modal overlay */}
539
+ <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/50 py-6 backdrop-blur-sm">
540
+ <div className="relative mx-4 w-full max-w-md rounded-2xl bg-white shadow-2xl">
541
+ {/* Close button */}
542
+ <button
543
+ onClick={() => {
544
+ window.location.href = `/checkout?checkout_id=${checkoutId}&canceled=true`;
545
+ }}
546
+ className="absolute end-3 top-3 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-white/80 text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-700"
547
+ aria-label="Close"
548
+ >
549
+ <svg
550
+ width="14"
551
+ height="14"
552
+ viewBox="0 0 14 14"
553
+ fill="none"
554
+ stroke="currentColor"
555
+ strokeWidth="2"
556
+ strokeLinecap="round"
557
+ >
558
+ <path d="M1 1l12 12M13 1L1 13" />
559
+ </svg>
560
+ </button>
561
+ <iframe
562
+ src={paymentIntent.clientSecret}
563
+ className="w-full rounded-2xl border-0"
564
+ style={{ height: '80vh' }}
565
+ title={t('payment')}
566
+ allow="payment"
567
+ />
568
+ </div>
569
+ </div>
570
+ {/* Placeholder so the checkout layout doesn't collapse */}
571
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
572
+ <LoadingSpinner size="lg" />
573
+ <p className="text-muted-foreground mt-4 text-sm">{t('preparingPayment')}</p>
574
+ </div>
575
+ </>
576
+ );
577
+ }
578
+
579
+ return (
580
+ <div className={cn('flex flex-col items-center justify-center py-12', className)}>
581
+ <LoadingSpinner size="lg" />
582
+ <p className="text-muted-foreground mt-4 text-sm">{t('redirectingToPayment')}</p>
583
+ <p className="text-muted-foreground mt-2 text-xs">
584
+ {t('redirectingHint')}
585
+ <a href={paymentIntent.clientSecret} className="text-primary hover:underline">
586
+ {t('clickHere')}
587
+ </a>
588
+ .
589
+ </p>
590
+ </div>
591
+ );
592
+ }