-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpage.tsx
More file actions
572 lines (518 loc) · 27.8 KB
/
Copy pathpage.tsx
File metadata and controls
572 lines (518 loc) · 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
'use client';
import { useState, useEffect, useCallback } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, ArrowRight, CheckCircle, Wallet, DollarSign, RefreshCw, Plus, Building2 } from 'lucide-react';
import { StellarWalletsKit } from '@creit-tech/stellar-wallets-kit/sdk';
import { defaultModules } from '@creit-tech/stellar-wallets-kit/modules/utils';
import { SwkAppDarkTheme } from '@creit-tech/stellar-wallets-kit/types';
import { api } from '@/lib/api';
// Sandbox usa stellar_testnet; prod usaría 'Public Global Stellar Network ; September 2015'
const NETWORK_PASSPHRASE =
process.env.NEXT_PUBLIC_BLINDPAY_NETWORK === 'stellar'
? 'Public Global Stellar Network ; September 2015'
: 'Test SDF Network ; September 2015';
type Step = 'setup' | 'quote' | 'done';
type Country = 'AR' | 'BR' | 'CO';
// Destinos de off-ramp. AR (BlindPay) está activo; BR/CO (Abroad) quedan
// como roadmap hasta cerrar el onboarding de partner de Abroad.
const DESTINATIONS: { code: Country; flag: string; currency: string; provider: string; enabled: boolean }[] = [
{ code: 'AR', flag: '🇦🇷', currency: 'ARS', provider: 'BlindPay', enabled: true },
{ code: 'BR', flag: '🇧🇷', currency: 'BRL', provider: 'Abroad', enabled: false },
{ code: 'CO', flag: '🇨🇴', currency: 'COP', provider: 'Abroad', enabled: false },
];
interface Customer { id: string; first_name: string; last_name: string; email: string; kyc_status: string }
interface BankAccount { id: string; type: string; transfers_type: string; transfers_account: string; beneficiary_name: string; status: string }
interface Quote {
id: string; expires_at: number; sender_amount: number; receiver_amount: number;
blindpay_quotation: number; flat_fee: number; partner_fee_amount: number;
contract: { address: string; amount: string; network: { name: string } };
}
// Genera un CBU argentino con checksum válido y número de cuenta único (basado en el tiempo).
function makeValidCbu(): string {
const bankBranch = '0170099'; // Banco Galicia (3) + sucursal (4)
const acc = String(Date.now()).slice(-13).padStart(13, '0');
const ck = (d: string, w: number[]) => {
let s = 0;
for (let i = 0; i < d.length; i++) s += parseInt(d[i], 10) * w[i];
return (10 - (s % 10)) % 10;
};
const c1 = ck(bankBranch, [7, 1, 3, 9, 7, 1, 3]);
const c2 = ck(acc, [3, 9, 7, 1, 3, 9, 7, 1, 3, 9, 7, 1, 3]);
return `${bankBranch}${c1}${acc}${c2}`;
}
export default function OfframpPage() {
const [step, setStep] = useState<Step>('setup');
const [country, setCountry] = useState<Country>('AR');
const [customers, setCustomers] = useState<Customer[]>([]);
const [customerId, setCustomerId] = useState('');
const [bankAccounts, setBankAccounts] = useState<BankAccount[]>([]);
const [bankAccountId, setBankAccountId] = useState('');
const [usdAmount, setUsdAmount] = useState('50');
// crear cuenta ARS — generamos un CBU válido ÚNICO por sesión (checksum OK, Banco Galicia).
// Único para no chocar con "ya guardado" en BlindPay si se reusa un CBU en el mismo receiver.
const [demoCbu] = useState(makeValidCbu);
const [showNewAccount, setShowNewAccount] = useState(false);
const [newCbu, setNewCbu] = useState(demoCbu);
const [newCbuType, setNewCbuType] = useState<'CBU' | 'CVU' | 'ALIAS'>('CBU');
const [quote, setQuote] = useState<Quote | null>(null);
const [walletAddress, setWalletAddress] = useState('');
const [receipt, setReceipt] = useState<{ id: string; status: string } | null>(null);
const [loading, setLoading] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
// cargar clientes al montar
useEffect(() => {
api.blindpay.customers()
.then((list) => {
const arr = Array.isArray(list) ? list : [];
setCustomers(arr);
const approved = arr.find((c) => c.kyc_status === 'approved') ?? arr[0];
if (approved) setCustomerId(approved.id);
})
.catch((e) => setError(`No se pudieron cargar clientes: ${e.message}`));
}, []);
const loadBankAccounts = useCallback(async (cid: string) => {
setBusy('accounts');
setError(null);
setNotice(null);
try {
const list = await api.blindpay.bankAccounts(cid);
const arr = Array.isArray(list) ? list : [];
const ars = arr.filter((b) => b.type === 'transfers_bitso');
setBankAccounts(ars);
setBankAccountId(ars[0]?.id ?? '');
if (ars.length === 0) setShowNewAccount(true);
} catch {
// El listado del sandbox de BlindPay se rompe por datos pre-cargados con CPF inválido.
// Degradamos: el usuario crea una cuenta ARS nueva y usamos el id que devuelve el POST.
setBankAccounts([]);
setBankAccountId('');
setShowNewAccount(true);
setNotice('No se pudo listar cuentas (quirk del sandbox de BlindPay). Creá una cuenta ARS para continuar.');
} finally {
setBusy(null);
}
}, []);
useEffect(() => { if (customerId) loadBankAccounts(customerId); }, [customerId, loadBankAccounts]);
async function handleCreateAccount() {
if (newCbuType === 'ALIAS') {
// BlindPay valida el formato del alias; exigimos un alias plausible para no romper el flujo.
if (!/^[a-zA-Z0-9][a-zA-Z0-9.\-]{5,19}$/.test(newCbu) || !/[.\-]/.test(newCbu)) {
return setError('El alias debe tener 6–20 caracteres e incluir un punto, ej: mi.alias.mp');
}
} else if (!/^\d{22}$/.test(newCbu)) {
return setError('El CBU o CVU debe tener 22 dígitos');
}
const customer = customers.find((c) => c.id === customerId);
const beneficiary = customer ? `${customer.first_name} ${customer.last_name}`.trim() : 'Passpay';
setBusy('create-account');
setError(null);
try {
const created = await api.blindpay.createBankAccount(customerId, {
transfers_type: newCbuType,
transfers_account: newCbu,
beneficiary_name: beneficiary,
});
// Usamos el id devuelto directamente (no re-listamos: el GET del sandbox está roto)
const account: BankAccount = {
id: created.id,
type: 'transfers_bitso',
transfers_type: newCbuType,
transfers_account: newCbu,
beneficiary_name: beneficiary,
status: created.status ?? 'approved',
};
setBankAccounts((prev) => [account, ...prev.filter((b) => b.id !== account.id)]);
setBankAccountId(account.id);
setShowNewAccount(false);
setNewCbu('');
setNotice(null);
} catch (e: any) {
setError(e.message);
} finally {
setBusy(null);
}
}
async function handleGetQuote() {
setError(null);
const amount = parseFloat(usdAmount);
if (!amount || amount <= 0) return setError('Ingresá un monto válido');
if (!bankAccountId) return setError('Elegí o creá una cuenta ARS de destino');
setLoading(true);
try {
const q = await api.blindpay.quote({
bank_account_id: bankAccountId,
request_amount: Math.round(amount * 100), // a centavos
currency_type: 'sender',
});
setQuote(q);
setStep('quote');
} catch (e: any) {
setError(e.message);
} finally {
setLoading(false);
}
}
// Autoriza (XDR fresco), firma y ejecuta el payout para una quote dada.
async function signAndPayout(quoteId: string, address: string) {
const auth = await api.blindpay.authorize({ quote_id: quoteId, sender_wallet_address: address });
// BlindPay devuelve el XDR en transaction_hash (snake_case); cubrimos todas las variantes
const unsignedXdr = auth.transaction_hash ?? auth.transactionHash ?? auth.xdr ?? auth.unsigned_xdr;
if (!unsignedXdr) throw new Error('No pudimos preparar la operación. Probá de nuevo en un momento.');
const { signedTxXdr } = await StellarWalletsKit.signTransaction(unsignedXdr, {
networkPassphrase: NETWORK_PASSPHRASE,
address,
});
return api.blindpay.payout({
quote_id: quoteId,
signed_transaction: signedTxXdr,
sender_wallet_address: address,
});
}
async function handleAuthorizeAndSign() {
if (!quote) return;
setError(null);
setLoading(true);
try {
StellarWalletsKit.init({ modules: defaultModules(), theme: SwkAppDarkTheme });
const { address } = await StellarWalletsKit.authModal();
setWalletAddress(address);
let payout;
try {
payout = await signAndPayout(quote.id, address);
} catch (e: any) {
const m = String(e.message || '');
// Auto-recuperación: quote vencida (dura 5 min) o secuencia Stellar vieja →
// re-cotizamos y pedimos UNA firma nueva con XDR fresco.
if (/expired|expirad|bad_seq|sequence|tx_too_late|quote.*not.*found|invalid.*quote/i.test(m)) {
setNotice('La cotización venció; renovándola…');
const q2 = await api.blindpay.quote({
bank_account_id: bankAccountId,
request_amount: Math.round(parseFloat(usdAmount) * 100),
currency_type: 'sender',
});
setQuote(q2);
setNotice(null);
payout = await signAndPayout(q2.id, address);
} else {
throw e;
}
}
setReceipt(payout);
setStep('done');
} catch (e: any) {
const msg = String(e.message || '');
if (/trust the asset issuer|no trust|op_no_trust/i.test(msg)) {
setError('Tu wallet de testnet no tiene el trustline a USDB. Tocá "Fondear USDB de prueba" abajo y volvé a intentar.');
} else if (/underfunded|insufficient|op_underfunded/i.test(msg)) {
setError('Tu wallet no tiene saldo de USDB en testnet. Fondeá USDB de prueba y reintentá.');
} else if (/bad_seq|sequence/i.test(msg)) {
setError('La red rechazó la operación por secuencia (varios retiros seguidos). Esperá unos segundos y reintentá.');
} else {
setError(msg);
}
} finally {
setLoading(false);
}
}
// Fondeo de USDB de prueba (testnet): crea el trustline, lo firma y lo transmite a Horizon.
async function handleFundUsdb() {
setError(null);
setNotice(null);
setBusy('fund');
try {
StellarWalletsKit.init({ modules: defaultModules(), theme: SwkAppDarkTheme });
const { address } = await StellarWalletsKit.authModal();
const tl = await api.blindpay.trustline({ address });
const xdr = tl.xdr ?? tl.transactionHash;
if (!xdr) throw new Error('No se pudo preparar el trustline. Probá de nuevo.');
const { signedTxXdr } = await StellarWalletsKit.signTransaction(xdr, {
networkPassphrase: NETWORK_PASSPHRASE,
address,
});
// transmitir el trustline a Horizon (testnet)
const { Transaction, Networks, Horizon } = await import('@stellar/stellar-sdk');
const server = new Horizon.Server('https://horizon-testnet.stellar.org');
await server.submitTransaction(new Transaction(signedTxXdr, Networks.TESTNET));
// intentar mintear USDB (best-effort; el sandbox de BlindPay a veces falla)
let minted = false;
try {
const r = await api.blindpay.mintUsdb({ address, signedXdr: signedTxXdr });
minted = r?.success !== false;
} catch { /* mint flaky en el sandbox */ }
setNotice(
minted
? '✓ Trustline USDB creado y USDB de prueba fondeado. Ya podés firmar el retiro.'
: '✓ Trustline USDB creado. El mint de prueba de BlindPay no respondió; si tenés USDB en la wallet ya podés retirar.'
);
} catch (e: any) {
setError(`No se pudo crear el trustline: ${e.message}`);
} finally {
setBusy(null);
}
}
const fmt = (cents: number) => (cents / 100).toLocaleString('es-AR', { maximumFractionDigits: 2 });
return (
<div className="min-h-screen bg-gradient-to-b from-slate-900 via-slate-800 to-slate-900 text-white">
<div className="px-4 pt-6 pb-10 max-w-md mx-auto">
<Link href="/" className="inline-flex p-2 rounded-lg hover:bg-slate-700/50 transition-colors mb-4">
<ArrowLeft className="w-5 h-5" />
</Link>
<div className="text-center mb-6">
<Image src="/passpay-logo.svg" alt="Passpay" width={180} height={56} priority className="w-auto h-auto max-w-xs mx-auto" />
<p className="text-slate-400 text-sm mt-2">Pasá tus dólares a pesos en tu cuenta · Procesado por BlindPay</p>
</div>
{/* pasos */}
<div className="flex items-center justify-center gap-3 mb-8">
{(['setup', 'quote', 'done'] as Step[]).map((s, i) => (
<div key={s} className="flex items-center gap-2">
<div className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold transition-all
${step === s ? 'bg-[#5B4BF5] text-white scale-110'
: (['setup', 'quote', 'done'].indexOf(step) > i) ? 'bg-[#2DD4BF] text-slate-900' : 'bg-slate-700 text-slate-400'}`}>
{(['setup', 'quote', 'done'].indexOf(step) > i) ? '✓' : i + 1}
</div>
{i < 2 && <div className={`w-8 h-0.5 ${(['setup', 'quote', 'done'].indexOf(step) > i) ? 'bg-[#2DD4BF]' : 'bg-slate-700'}`} />}
</div>
))}
</div>
<AnimatePresence mode="wait">
{/* PASO 1 — setup */}
{step === 'setup' && (
<motion.div key="setup" initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} className="space-y-4">
<h2 className="text-xl font-bold text-center mb-2">Configurá el retiro</h2>
{/* destino / país — AR (BlindPay) activo; BR/CO (Abroad) próximamente */}
<div>
<label className="text-xs text-slate-400 mb-1 block">Destino</label>
<div className="grid grid-cols-3 gap-2">
{DESTINATIONS.map((d) => {
const active = country === d.code;
return (
<button
key={d.code}
type="button"
onClick={() => d.enabled && setCountry(d.code)}
disabled={!d.enabled}
title={d.enabled ? `${d.currency} · ${d.provider}` : `${d.provider} · próximamente`}
className={`relative p-3 rounded-xl border text-center transition-all ${active
? 'border-[#5B4BF5] bg-[#5B4BF5]/10'
: d.enabled
? 'border-slate-600 bg-slate-800/50 hover:border-slate-500'
: 'border-slate-700 bg-slate-800/30 opacity-50 cursor-not-allowed'}`}
>
<div className="text-lg leading-none">{d.flag}</div>
<div className="text-xs font-medium mt-1">{d.currency}</div>
<div className="text-[10px] text-slate-400">{d.provider}</div>
{!d.enabled && (
<span className="absolute -top-1.5 -right-1.5 text-[8px] bg-[#FFB020] text-slate-900 font-bold px-1.5 py-0.5 rounded-full">
Pronto
</span>
)}
</button>
);
})}
</div>
</div>
{/* cliente */}
<div>
<label className="text-xs text-slate-400 mb-1 block">Cliente (identidad verificada)</label>
<select
value={customerId}
onChange={(e) => setCustomerId(e.target.value)}
className="w-full bg-slate-800 border border-slate-600 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-[#5B4BF5] text-sm"
>
{customers.length === 0 && <option>Cargando…</option>}
{customers.map((c) => (
<option key={c.id} value={c.id}>
{c.first_name} {c.last_name} · {c.kyc_status}
</option>
))}
</select>
</div>
{/* cuenta ARS */}
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-xs text-slate-400">Cuenta ARS de destino</label>
<button onClick={() => setShowNewAccount((v) => !v)} className="text-xs text-[#2DD4BF] hover:text-[#5B4BF5] inline-flex items-center gap-1">
<Plus className="w-3 h-3" /> Nueva CBU/CVU
</button>
</div>
{notice && (
<p className="text-[#FFB020] text-xs bg-[#FFB020]/10 rounded-lg px-3 py-2 mb-2">{notice}</p>
)}
{busy === 'accounts' ? (
<div className="text-slate-500 text-sm py-3 flex items-center gap-2"><RefreshCw className="w-4 h-4 animate-spin" /> cargando cuentas…</div>
) : bankAccounts.length > 0 ? (
<div className="space-y-2">
{bankAccounts.map((b) => (
<button
key={b.id}
onClick={() => setBankAccountId(b.id)}
className={`w-full text-left p-3 rounded-xl border transition-all flex items-center gap-3 ${bankAccountId === b.id
? 'border-[#5B4BF5] bg-[#5B4BF5]/10' : 'border-slate-600 bg-slate-800/50 hover:border-slate-500'}`}
>
<Building2 className="w-4 h-4 text-[#2DD4BF] shrink-0" />
<div className="min-w-0">
<div className="text-sm font-medium truncate">{b.beneficiary_name}</div>
<div className="text-[11px] text-slate-400 font-mono">{b.transfers_type} {b.transfers_account} · {b.status}</div>
</div>
</button>
))}
</div>
) : (
<p className="text-slate-500 text-sm py-2">Este cliente no tiene cuentas ARS. Creá una ↑</p>
)}
{showNewAccount && (
<motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="mt-3 p-3 rounded-xl bg-slate-800/70 border border-slate-700 space-y-2">
<div className="flex gap-2">
{(['CBU', 'CVU', 'ALIAS'] as const).map((t) => (
<button key={t} onClick={() => { setNewCbuType(t); setNewCbu(t === 'ALIAS' ? '' : demoCbu); setError(null); }}
className={`flex-1 py-1.5 rounded-lg text-xs font-semibold ${newCbuType === t ? 'bg-[#5B4BF5] text-white' : 'bg-slate-700 text-slate-300'}`}>
{t}
</button>
))}
</div>
<input
value={newCbu}
onChange={(e) => setNewCbu(e.target.value)}
placeholder={newCbuType === 'ALIAS' ? 'mi.alias.mp' : '22 dígitos'}
className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:border-[#5B4BF5]"
/>
<button
onClick={handleCreateAccount}
disabled={busy === 'create-account'}
className="w-full py-2 rounded-lg bg-[#2DD4BF] text-slate-900 font-semibold text-sm disabled:opacity-50 flex items-center justify-center gap-2"
>
{busy === 'create-account' ? <RefreshCw className="w-4 h-4 animate-spin" /> : 'Crear cuenta ARS'}
</button>
</motion.div>
)}
</div>
{/* monto */}
<div>
<label className="text-xs text-slate-400 mb-1 block">Cuántos dólares querés pasar a pesos</label>
<div className="relative">
<DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
<input
type="number" min="1" step="0.01" value={usdAmount}
onChange={(e) => setUsdAmount(e.target.value)}
className="w-full bg-slate-800 border border-slate-600 rounded-xl pl-9 pr-4 py-3 text-white focus:outline-none focus:border-[#5B4BF5]"
/>
</div>
</div>
{error && <p className="text-red-400 text-sm bg-red-400/10 rounded-lg px-3 py-2 break-words">{error}</p>}
{notice && <p className="text-[#16E0A3] text-sm bg-[#16E0A3]/10 rounded-lg px-3 py-2 break-words">{notice}</p>}
<button
onClick={handleGetQuote}
disabled={loading || !bankAccountId}
className="w-full h-14 rounded-xl font-semibold bg-gradient-to-r from-[#5B4BF5] to-[#3D2FD6] hover:opacity-90 disabled:opacity-40 flex items-center justify-center gap-2 transition-all"
>
{loading ? <RefreshCw className="w-5 h-5 animate-spin" /> : <><ArrowRight className="w-5 h-5" /> Cotizar</>}
</button>
{/* Fondeo de USDB de prueba (testnet): la wallet necesita trustline + saldo de USDB */}
<button
onClick={handleFundUsdb}
disabled={busy === 'fund'}
className="w-full h-11 rounded-xl text-sm font-medium border border-[#FFB020]/40 bg-[#FFB020]/10 text-[#FFB020] hover:bg-[#FFB020]/20 disabled:opacity-50 flex items-center justify-center gap-2 transition-all"
>
{busy === 'fund' ? <RefreshCw className="w-4 h-4 animate-spin" /> : '🪙 Fondear USDB de prueba (testnet)'}
</button>
<p className="text-[11px] text-slate-500 text-center -mt-1">
Tu wallet de testnet necesita un trustline a USDB para poder retirar. Esto lo crea.
</p>
</motion.div>
)}
{/* PASO 2 — quote + firma */}
{step === 'quote' && quote && (
<motion.div key="quote" initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} className="space-y-5">
<h2 className="text-xl font-bold text-center">Confirmá y firmá</h2>
<div className="bg-slate-800/50 border border-slate-700 rounded-2xl p-5 space-y-3">
<div className="flex justify-between items-center">
<span className="text-slate-400 text-sm">Enviás</span>
<span className="font-bold text-lg">{fmt(quote.sender_amount)} USDC</span>
</div>
<div className="flex justify-between items-center">
<span className="text-slate-400 text-sm">Recibís</span>
<span className="font-bold text-lg text-[#2DD4BF]">{fmt(quote.receiver_amount)} ARS</span>
</div>
<div className="flex justify-between items-center">
<span className="text-slate-400 text-sm">Tasa</span>
<span className="text-slate-300 text-sm">1 USD ≈ {quote.blindpay_quotation?.toLocaleString('es-AR')} ARS</span>
</div>
{quote.flat_fee > 0 && (
<div className="flex justify-between items-center">
<span className="text-slate-400 text-sm">Fee fijo</span>
<span className="text-slate-300 text-sm">{fmt(quote.flat_fee)} USDC</span>
</div>
)}
<div className="border-t border-slate-700 pt-3 flex justify-between items-center">
<span className="text-slate-400 text-sm">Red</span>
<span className="text-slate-300 text-sm">{quote.contract?.network?.name ?? 'Stellar'}</span>
</div>
</div>
<p className="text-slate-400 text-sm text-center">
Confirmás la operación con tu billetera: enviás {fmt(quote.sender_amount)} USDC y se acreditan
{fmt(quote.receiver_amount)} ARS en la cuenta de destino.
</p>
{error && <p className="text-red-400 text-sm bg-red-400/10 rounded-lg px-3 py-2 break-words">{error}</p>}
<div className="flex gap-3">
<button onClick={() => { setStep('setup'); setError(null); }}
className="flex-1 h-14 rounded-xl font-semibold border border-slate-600 hover:border-slate-400 text-slate-300 transition-all">
Volver
</button>
<button onClick={handleAuthorizeAndSign} disabled={loading}
className="flex-1 h-14 rounded-xl font-semibold bg-gradient-to-r from-[#5B4BF5] to-[#3D2FD6] hover:opacity-90 disabled:opacity-50 flex items-center justify-center gap-2 transition-all">
{loading ? <RefreshCw className="w-5 h-5 animate-spin" /> : <><Wallet className="w-5 h-5" /> Firmar</>}
</button>
</div>
</motion.div>
)}
{/* PASO 3 — recibo */}
{step === 'done' && receipt && (
<motion.div key="done" initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} className="space-y-5 text-center">
<motion.div initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: 'spring', delay: 0.1 }}>
<CheckCircle className="w-20 h-20 text-[#2DD4BF] mx-auto" />
</motion.div>
<h2 className="text-2xl font-bold">¡Retiro iniciado!</h2>
<p className="text-slate-400 text-sm">BlindPay está procesando la transferencia a la cuenta ARS de destino.</p>
<div className="bg-slate-800/50 border border-[#2DD4BF]/30 rounded-2xl p-5 text-left space-y-3">
<div className="flex justify-between">
<span className="text-slate-400 text-sm">ID de operación</span>
<span className="font-mono text-xs text-slate-300 truncate max-w-[180px]">{receipt.id}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-400 text-sm">Estado</span>
<span className="text-[#2DD4BF] font-semibold text-sm capitalize">{receipt.status}</span>
</div>
{quote && (
<div className="flex justify-between">
<span className="text-slate-400 text-sm">Recibirá</span>
<span className="text-[#2DD4BF] font-bold">{fmt(quote.receiver_amount)} ARS</span>
</div>
)}
{walletAddress && (
<div className="flex justify-between">
<span className="text-slate-400 text-sm">Desde wallet</span>
<span className="font-mono text-xs text-slate-400">{walletAddress.slice(0, 6)}…{walletAddress.slice(-4)}</span>
</div>
)}
</div>
<div className="flex gap-3">
<button onClick={() => { setStep('setup'); setQuote(null); setReceipt(null); setError(null); }}
className="flex-1 h-12 rounded-xl border border-slate-600 hover:border-[#5B4BF5] text-slate-300 hover:text-white transition-all text-sm font-medium">
Nuevo retiro
</button>
<Link href="/" className="flex-1 h-12 rounded-xl bg-[#5B4BF5]/20 border border-[#5B4BF5]/40 hover:bg-[#5B4BF5]/30 text-[#8B7CF8] flex items-center justify-center text-sm font-medium transition-all">
Inicio
</Link>
</div>
</motion.div>
)}
</AnimatePresence>
<p className="text-center text-xs text-slate-600 mt-8">Cambio de dólares a pesos · Procesado por BlindPay {NETWORK_PASSPHRASE.includes('Test') ? '· Modo prueba' : ''}</p>
</div>
</div>
);
}