create-brainerce-store 1.28.13 → 1.28.17

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