forked from Stellar-split/split-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.tsx
More file actions
793 lines (731 loc) · 31 KB
/
Copy pathpage.tsx
File metadata and controls
793 lines (731 loc) · 31 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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
"use client";
import { useEffect, useRef, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import { splitClient, payWithNonce } from "@/lib/stellar";
import { getFreighterPublicKey } from "@/lib/freighter";
import { formatAmount, parseAmount } from "@stellar-split/sdk";
import PaymentProgress from "@/components/PaymentProgress";
import CrossChainPayment from "@/components/CrossChainPayment";
import type { Invoice } from "@stellar-split/sdk";
import { formatAmount, parseAmount, truncateAddress, type Invoice } from "@stellar-split/sdk";
import { useInvoiceCustomization } from "@/lib/customization";
import type { Locale } from "@/lib/i18n";
import { useInvoiceStream } from "@/hooks/useInvoiceStream";
import type { InvoiceStreamEvent } from "@/hooks/useInvoiceStream";
import PaymentSuggestions from "@/components/PaymentSuggestions";
import FundingProgress from "@/components/FundingProgress";
import StatusBadge from "@/components/StatusBadge";
import StatusTimeline from "@/components/StatusTimeline";
import { InvoiceDetailSkeleton } from "@/components/Skeleton";
import PayModal from "@/components/PayModal";
import PaymentMethodSelector from "@/components/PaymentMethodSelector";
import DeadlineCountdown from "@/components/DeadlineCountdown";
import CopyLinkButton from "@/components/CopyLinkButton";
import CopyButton from "@/components/CopyButton";
import TxConfirmModal from "@/components/TxConfirmModal";
import CancelModal from "@/components/CancelModal";
import DuplicateModal from "@/components/DuplicateModal";
import TransferOwnershipModal from "@/components/TransferOwnershipModal";
import ShareModal from "@/components/ShareModal";
import InvoiceShareQRModal from "@/components/InvoiceShareQRModal";
import VotingPanel from "@/components/VotingPanel";
import DeadlineExtensionPanel from "@/components/DeadlineExtensionPanel";
import SuccessAnimation from "@/components/SuccessAnimation";
import RecipientPayoutTracker from "@/components/RecipientPayoutTracker";
import CloneLineageTree from "@/components/CloneLineageTree";
import CountdownTimer from "@/components/CountdownTimer";
import SplitCalculator from "@/components/SplitCalculator";
import ActivityFeed from "@/components/ActivityFeed";
import InstallmentTracker from "@/components/InstallmentTracker";
import InstallmentPanel from "@/components/InstallmentPanel";
import CoCreatorPanel from "@/components/CoCreatorPanel";
import PaymentChannelPanel from "@/components/PaymentChannelPanel";
import DisputeTimeline from "@/components/DisputeTimeline";
import ConfidentialPaymentFlow from "@/components/ConfidentialPaymentFlow";
import AuditLogTable from "@/components/AuditLogTable";
import VersionHistory from "@/components/VersionHistory";
import CommentSection from "@/components/CommentSection";
import InvoiceTimeline from "@/components/InvoiceTimeline";
import InvoiceExportButton from "@/components/InvoiceExportButton";
import ReleaseBanner from "@/components/ReleaseBanner";
import {
isSubscribedToInvoice,
subscribeToInvoice,
requestNotificationPermission,
} from "@/lib/notifications";
import { cancelReminder, setReminder } from "@/lib/reminders";
import { recordCooldown } from "@/lib/cooldown";
import { exportTimelineAsImage } from "@/lib/timelineImageExport";
import type { PaymentChannelState } from "@/components/PaymentChannelPanel";
const RecipientPieChart = dynamic(() => import("@/components/RecipientPieChart"), { ssr: false });
const InvoiceQR = dynamic(() => import("@/components/InvoiceQR"), { ssr: false });
const FlowDiagram = dynamic(() => import("@/components/FlowDiagram"), { ssr: false });
interface Props {
params: { id: string };
}
/**
* Invoice detail page — shows status, payment progress, and payment options:
* 1. Pay with Freighter (native Stellar)
* 2. Pay from Another Chain (cross-chain bridge via Ethereum / Solana)
*/
const statusConfig: Record<string, { label: string; color: string; icon: string }> = {
Pending: { label: "Pending", color: "bg-yellow-500", icon: "\u23F3" },
Released: { label: "Released", color: "bg-green-500", icon: "\u2705" },
Refunded: { label: "Refunded", color: "bg-gray-500", icon: "\u21A9\uFE0F" },
};
function showToast(message: string, type: "success" | "error" | "info" = "info") {
if (typeof window !== "undefined" && (window as any).__toastContainer?.addToast) {
(window as any).__toastContainer.addToast(message, type);
}
}
export default function InvoiceDetailPage({ params }: Props) {
const { id } = params;
const router = useRouter();
const [invoice, setInvoice] = useState<Invoice | null>(null);
const [publicKey, setPublicKey] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
// Live stream
const {
invoice: streamInvoice,
latestEvent,
isConnected,
error: streamError,
} = useInvoiceStream(id);
const [payAmount, setPayAmount] = useState("");
const [paying, setPaying] = useState(false);
const [txHash, setTxHash] = useState<string | null>(null);
const [showSuccess, setShowSuccess] = useState(false);
const [showAchievement, setShowAchievement] = useState(false);
const [disputing, setDisputing] = useState(false);
const [disputeError, setDisputeError] = useState<string | null>(null);
const [showCancelModal, setShowCancelModal] = useState(false);
const [showShareModal, setShowShareModal] = useState(false);
const [showShareQRModal, setShowShareQRModal] = useState(false);
const [showPayModal, setShowPayModal] = useState(false);
const [showDuplicateModal, setShowDuplicateModal] = useState(false);
const [paymentError, setPaymentError] = useState<string | null>(null);
const [paymentMethod, setPaymentMethod] = useState<"freighter" | "walletconnect">("freighter");
const [amountLocked, setAmountLocked] = useState(false);
const prevPayAmountRef = useRef("");
const [cooldownExpiresAt, setCooldownExpiresAt] = useState<number | null>(null);
const [activeDetailsTab, setActiveDetailsTab] = useState<"audit" | "history" | "notes">("audit");
const [payerNonce, setPayerNonce] = useState<bigint | null>(null);
const prevStatusRef = useRef<string | null>(null);
const timelineRef = useRef<HTMLDivElement>(null);
const [exportingTimeline, setExportingTimeline] = useState(false);
const [notifySubscribed, setNotifySubscribed] = useState(false);
const [notifyDenied, setNotifyDenied] = useState(false);
const [lastFailedPayment, setLastFailedPayment] = useState<{ amount: bigint } | null>(null);
const [retryCount, setRetryCount] = useState(0);
const [channelState, setChannelState] = useState<PaymentChannelState | null>(null);
const [channelLoading, setChannelLoading] = useState(false);
const [channelError, setChannelError] = useState<string | null>(null);
const [previousInvoice, setPreviousInvoice] = useState<Invoice | null>(null);
const [reminderDate, setReminderDate] = useState("");
const [reminderMsg, setReminderMsg] = useState("");
const [hasReminder, setHasReminder] = useState(false);
const [reminderSaved, setReminderSaved] = useState(false);
const [showTransferModal, setShowTransferModal] = useState(false);
const [transferError, setTransferError] = useState<string | null>(null);
const [locale, setLocale] = useState<Locale>("en");
const [showConfidentialFlow, setShowConfidentialFlow] = useState(false);
useEffect(() => {
// TODO: implement notification subscription
// setNotifySubscribed(isSubscribedToInvoice(id));
}, [id]);
const handleNotifyMe = async () => {
// TODO: implement notification permissions
// const permission = await requestNotificationPermission();
// if (permission !== "granted") {
// setNotifyDenied(true);
// return;
// }
// subscribeToInvoice(id);
// setNotifySubscribed(true);
// setNotifyDenied(false);
};
const load = async () => {
const inv = await splitClient.getInvoice(id);
setInvoice(inv);
setLoading(false);
};
useEffect(() => {
load().catch((e) => setError(String(e)));
getFreighterPublicKey().then(setPublicKey).catch(() => null);
// eslint-disable-next-line react-hooks/exhaustive-deps
// Only fallback load if stream hasn't already provided invoice
if (!streamInvoice) {
load().catch((e) => {
setError(String(e));
setLoading(false);
});
}
getFreighterPublicKey()
.then((key) => setPublicKey(key))
.catch(() => null);
}, [id]);
useEffect(() => {
if (!publicKey) return;
// TODO: implement payer nonce
// import("@/lib/paymentNonce").then(({ getPayerNonce }) =>
// getPayerNonce(publicKey).then((n) => setPayerNonce(n)).catch(() => null)
// ).catch(() => null);
}, [publicKey]);
const channelStorageKey = (invoiceId: string, payer: string) => `stellarsplit_channel_${invoiceId}_${payer}`;
const persistChannelState = (state: PaymentChannelState | null) => {
if (typeof window === "undefined" || !publicKey) return;
const key = channelStorageKey(id, publicKey);
if (!state) {
localStorage.removeItem(key);
} else {
localStorage.setItem(
key,
JSON.stringify({
invoiceId: state.invoiceId,
payer: state.payer,
balance: state.balance.toString(),
opened: state.opened,
})
);
}
};
const loadChannelState = () => {
if (typeof window === "undefined" || !publicKey) return null;
const key = channelStorageKey(id, publicKey);
const raw = localStorage.getItem(key);
if (!raw) return null;
try {
const parsed = JSON.parse(raw);
if (parsed.invoiceId !== id || parsed.payer !== publicKey) return null;
return {
invoiceId: parsed.invoiceId,
payer: parsed.payer,
balance: BigInt(parsed.balance),
opened: parsed.opened,
};
} catch {
return null;
}
};
const syncChannelState = (state: PaymentChannelState | null) => {
setChannelState(state);
persistChannelState(state);
};
useEffect(() => {
if (!publicKey) return;
const stored = loadChannelState();
if (stored) {
setChannelState(stored);
}
}, [id, publicKey]);
const applyChannelBalance = (amount: bigint) => {
if (!channelState?.opened || channelState.balance <= 0n) return null;
const used = amount <= channelState.balance ? amount : channelState.balance;
const remainingBalance = channelState.balance - used;
const nextState: PaymentChannelState = {
...channelState,
balance: remainingBalance > 0n ? remainingBalance : 0n,
opened: remainingBalance > 0n,
};
syncChannelState(nextState.opened ? nextState : null);
return channelState;
};
const total = invoice
? invoice.recipients.reduce((s, r) => s + r.amount, 0n)
: 0n;
const handlePay = async (e: React.FormEvent) => {
e.preventDefault();
if (!publicKey || !invoice) return;
const amount = parseAmount(payAmount);
const clientKey = `opt-${Date.now()}`;
const originalChannel = channelState;
const channelUsed = applyChannelBalance(amount);
setPaymentError(null);
setPaying(true);
const originalInvoice = invoice;
const optimisticPayment = { payer: publicKey, amount };
const optimisticFunded = invoice.funded + amount;
setInvoice({
...invoice,
funded: optimisticFunded,
payments: [...invoice.payments, optimisticPayment],
});
try {
const result = await splitClient.pay({
payer: publicKey,
invoiceId: id,
amount,
});
setTxHash(result.txHash);
setShowSuccess(true);
try {
const existing = JSON.parse(localStorage.getItem("stellarsplit_adapter_usage") ?? "[]");
existing.push({ adapter: paymentMethod, timestamp: Date.now() });
localStorage.setItem("stellarsplit_adapter_usage", JSON.stringify(existing));
} catch { /* ignore storage errors */ }
window.dispatchEvent(new CustomEvent("usdc-balance-refresh"));
} catch (err) {
setInvoice(originalInvoice);
setPaymentError(err instanceof Error ? err.message : String(err));
if (channelUsed && originalChannel) {
syncChannelState(originalChannel);
}
setInvoice((prev) => {
if (!prev) return prev;
const pending = prev.payments.find((p) => (p as any).clientKey === clientKey);
if (!pending || !(pending as any).pending) return prev;
return {
...prev,
funded: prev.funded - pending.amount,
payments: prev.payments.filter((p) => (p as any).clientKey !== clientKey),
};
});
setError(String(err));
} finally {
setPaying(false);
}
};
if (loading) {
return (
<main className="max-w-2xl mx-auto px-4 sm:px-6 py-16">
<div className="animate-pulse space-y-4">
<div className="h-8 w-48 bg-gray-700 rounded" />
<div className="h-4 w-full bg-gray-700 rounded" />
<div className="h-4 w-3/4 bg-gray-700 rounded" />
<div className="h-32 w-full bg-gray-700 rounded" />
<div className="h-8 w-32 bg-gray-700 rounded" />
</div>
</main>
);
}
if (error && !invoice) {
return (
<main className="max-w-xl mx-auto w-full px-4 sm:px-6 py-20 overflow-x-hidden">
<InvoiceDetailSkeleton />
</main>
);
}
if (!invoice) return null;
const remaining = total - invoice.funded;
const status = statusConfig[invoice.status] || { label: invoice.status, color: "bg-gray-500", icon: "⌛" };
/**
* The Stellar destination for cross-chain payments is the contract ID.
* The StellarSplitClient is initialised with NEXT_PUBLIC_CONTRACT_ID, so we
* read it from the environment the same way stellar.ts does.
*/
const stellarDestination =
process.env.NEXT_PUBLIC_CONTRACT_ID ?? invoice.token;
return (
<main className="max-w-2xl mx-auto px-4 sm:px-6 py-16">
{/* Reconnecting indicator */}
{showReconnecting && (
<div className="fixed top-4 left-1/2 -translate-x-1/2 z-50 bg-yellow-600 text-white px-4 py-2 rounded-xl shadow-lg flex items-center gap-2 animate-pulse">
<svg className="animate-spin h-4 w-4" viewBox="0 0 24 24" fill="none">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
<span className="text-sm font-medium">Reconnecting...</span>
</div>
)}
{/* Release Banner */}
{showReleaseBanner && (
<ReleaseBanner
invoiceId={id}
onDismiss={() => setShowReleaseBanner(false)}
/>
)}
{/* Header */}
<div className="flex items-start justify-between gap-4 mb-6 flex-wrap">
<div className="flex items-center gap-3 flex-wrap">
<h1 className="text-2xl sm:text-3xl font-bold text-white">
Invoice #{id}
</h1>
<StatusBadge status={invoice.status as any} size="sm" />
<CopyButton text={id} className="!py-1 !px-2 text-xs" />
</div>
<div className="ml-auto flex items-center gap-2 flex-wrap">
<CopyLinkButton url={`${typeof window !== "undefined" ? window.location.origin : ""}/verify/${id}`} />
<button
type="button"
onClick={() => setShowShareModal(true)}
className="px-3 py-1.5 rounded-lg bg-gray-700 hover:bg-gray-600 text-white text-sm transition-colors"
aria-label="Share invoice"
>
Share
</button>
<button
type="button"
onClick={() => setShowDuplicateModal(true)}
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white text-sm transition-colors"
aria-label="Duplicate invoice"
>
Duplicate
</button>
<InvoiceExportButton invoice={invoice} total={total} />
<button
type="button"
onClick={() => setShowShareQRModal(true)}
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-semibold text-white transition-colors"
aria-label="Share invoice via QR"
>
Share via QR
</button>
{(invoice as any).confidential && (
<button
type="button"
onClick={() => setShowConfidentialFlow(true)}
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-semibold text-white transition-colors"
aria-label="Pay confidentially"
>
Pay Confidentially
</button>
)}
<select
value={locale}
onChange={(e) => setLocale(e.target.value as Locale)}
className="px-2 py-1.5 rounded-lg bg-gray-800 border border-gray-700 text-sm transition-colors"
aria-label="Receipt language"
>
<option value="en">EN</option>
<option value="es">ES</option>
<option value="fr">FR</option>
</select>
<button
type="button"
onClick={() => window.print()}
className="px-3 py-1.5 rounded-lg bg-gray-700 hover:bg-gray-600 text-white text-sm transition-colors"
>
Print Invoice
</button>
</div>
</div>
{/* Quick Info Cards */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-8">
<div className="bg-gray-800/60 border border-gray-700 rounded-xl px-4 py-3">
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Creator</p>
<p className="text-sm font-mono text-gray-200 truncate" title={invoice.creator}>
{truncateAddress(invoice.creator, 6)}
</p>
</div>
<div className="bg-gray-800/60 border border-gray-700 rounded-xl px-4 py-3">
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Recipients</p>
<p className="text-2xl font-bold text-white">{invoice.recipients.length}</p>
</div>
<div className="bg-gray-800/60 border border-gray-700 rounded-xl px-4 py-3">
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Payments</p>
<p className="text-2xl font-bold text-white">{invoice.payments.length}</p>
</div>
<div className="bg-gray-800/60 border border-gray-700 rounded-xl px-4 py-3">
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Deadline</p>
<div className="text-sm font-medium text-gray-200">
{invoice.deadline > 0 ? (
<DeadlineCountdown deadline={invoice.deadline} />
) : (
"No deadline"
)}
</div>
</div>
</div>
{/* Progress - updates in real-time via useInvoiceStream */}
<section aria-labelledby="progress-heading" className="mb-8">
<h2 id="progress-heading" className="sr-only">Payment Progress</h2>
<FundingProgress funded={invoice.funded} total={total} token={invoice.token || "USDC"} />
{invoice.deadline > 0 && (
<div className="flex items-center gap-2 mt-3">
<span className="text-sm text-gray-400">Time remaining:</span>
<DeadlineCountdown deadline={invoice.deadline} />
</div>
)}
</section>
{/* QR */}
<div className="mb-8">
<InvoiceQR invoiceId={id} />
</div>
{/* Status Timeline */}
<section className="mb-8" aria-labelledby="timeline-heading">
<h2 id="timeline-heading" className="text-lg font-semibold text-white mb-4">Status Timeline</h2>
<StatusTimeline invoice={invoice} total={total} />
</section>
{/* Payments */}
<section className="mb-8">
<h2 className="text-lg font-semibold text-white mb-3">
Payments ({invoice.payments.length})
</h2>
{invoice.payments.length === 0 ? (
<p className="text-gray-500 text-sm bg-gray-800/40 border border-gray-700 rounded-xl px-4 py-6 text-center">
No payments yet. Be the first to pay!
</p>
) : (
<div className="bg-gray-800/40 border border-gray-700 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-gray-700 text-gray-400 text-xs uppercase tracking-wide">
<th className="text-left px-4 py-2 font-medium">Payer</th>
<th className="text-right px-4 py-2 font-medium">Amount</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-700/50">
{invoice.payments.map((p, i) => (
<tr key={i} className="hover:bg-gray-700/30 transition-colors">
<td className="px-4 py-2 font-mono text-gray-300 truncate max-w-[200px]" title={p.payer}>
{truncateAddress(p.payer)}
</td>
<td className="px-4 py-2 text-right text-indigo-300 font-medium">
{formatAmount(p.amount)} USDC
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
{invoice.status === "Pending" && (
<div className="flex flex-col gap-6">
{/* ── Option 1: Pay with Freighter ──────────────────────────── */}
{publicKey && (
<form onSubmit={handlePay} className="flex flex-col gap-4">
<h2 className="text-lg font-semibold">Pay with Freighter</h2>
<input
type="number"
step="0.0000001"
min="0.0000001"
placeholder="Amount in USDC"
value={payAmount}
onChange={(e) => setPayAmount(e.target.value)}
required
aria-label="Amount in USDC"
className="bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
{error && <p className="text-red-400 text-sm">{error}</p>}
{txHash && (
<p className="text-green-400 text-sm">
Payment sent! Tx: {txHash.slice(0, 12)}…
</p>
)}
<button
type="submit"
disabled={paying}
className="px-6 py-3 rounded-lg bg-indigo-600 hover:bg-indigo-500 font-semibold transition-colors disabled:opacity-50"
>
{paying ? "Sending…" : "Pay"}
</button>
</form>
)}
{/* ── Divider ───────────────────────────────────────────────── */}
<div className="flex items-center gap-3 text-gray-600 text-xs">
<div className="flex-1 border-t border-gray-700" />
<span>or</span>
<div className="flex-1 border-t border-gray-700" />
</div>
{/* ── Option 2: Pay from Another Chain ──────────────────────── */}
<CrossChainPayment
invoiceId={id}
stellarDestination={stellarDestination}
/>
</div>
)}
{invoice.status !== "Pending" && (
<p className="text-gray-400 text-sm">
This invoice is {invoice.status.toLowerCase()} and no longer accepts
payments.
{/* Recipients */}
<RecipientPayoutTracker invoice={invoice} publicKey={publicKey} />
{/* Split Calculator */}
{invoice.status === "Pending" && <SplitCalculator invoice={invoice} />}
<ActivityFeed
invoice={{
...invoice,
payments: invoice.payments.filter((p) => !(p as any).pending),
}}
previousInvoice={previousInvoice}
/>
{/* Installment schedule — only shown to payers with a registered plan */}
{publicKey && (
<>
<InstallmentTracker
invoice={invoice}
publicKey={publicKey}
onPayNow={(amount) => {
setPayAmount(formatAmount(amount));
setShowPayModal(true);
}}
/>
<InstallmentPanel invoiceId={id} publicKey={publicKey} />
</>
)}
{/* Deadline extension voting — shown to payers on Pending invoices */}
{publicKey && (
<VotingPanel invoice={invoice} publicKey={publicKey} />
)}
{/* Deadline extension request/approval flow */}
{invoice.status === "Pending" && (
<DeadlineExtensionPanel
invoiceId={id}
invoiceCreator={invoice.creator}
invoiceDeadline={invoice.deadline}
currentAddress={publicKey}
/>
)}
{/* Co-Creator Management — only shown to primary creator */}
{publicKey && (
<CoCreatorPanel invoice={invoice} publicKey={publicKey} onUpdate={load} />
)}
{/* Payment channel panel for frequent payers - DISABLED due to pre-existing issues */}
{/* TODO: Re-enable when payment channel is fully implemented */}
{/* Pay button → opens modal */}
{invoice.status === "Pending" && publicKey && (
<section className="mb-8 bg-gray-800/60 border border-gray-700 rounded-xl p-6">
<h2 className="text-lg font-semibold text-white mb-4">Pay Toward Invoice</h2>
<PaymentMethodSelector
onMethodChange={setPaymentMethod}
payerAddress={publicKey}
recipientAddress={invoice.recipients[0]?.address}
/>
<form onSubmit={handlePay} className="flex flex-col gap-4 mt-4">
<div>
<label htmlFor="pay-amount" className="block text-sm font-medium text-gray-300 mb-1">
Amount (USDC)
</label>
<input
id="pay-amount"
type="number"
step="0.0000001"
min="0.0000001"
max={formatAmount(total)}
placeholder="0.00"
value={payAmount}
onChange={(e) => setPayAmount(e.target.value)}
required
className="w-full min-h-11 bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
</div>
{paymentError && (
<p role="alert" className="text-red-400 text-sm">{paymentError}</p>
)}
<button
type="submit"
disabled={paying}
className="min-h-12 px-6 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-500 font-semibold text-white transition-colors disabled:opacity-50"
>
{paying ? "Sending Payment…" : `Pay ${payAmount || "0"} USDC`}
</button>
</form>
</section>
)}
{showConfidentialFlow && (invoice as any).confidential && publicKey && (
<ConfidentialPaymentFlow
invoiceId={id}
publicKey={publicKey}
/>
)}
{showPayModal && invoice && publicKey && (
<PayModal
invoice={invoice}
total={total}
publicKey={publicKey}
onPay={async (amount, email) => {
return splitClient.pay({ payer: publicKey, invoiceId: id, amount });
}}
onClose={() => setShowPayModal(false)}
/>
)}
{invoice.status !== "Pending" && (
<p className="text-gray-400 text-sm mb-8">
This invoice is {invoice.status.toLowerCase()} and no longer accepts payments.
</p>
)}
{/* Dispute Timeline — shown when invoice has an active or resolved dispute */}
{/* as any: disputeStatus is not yet declared in the published @stellar-split/sdk Invoice type */}
{(invoice as any).disputeStatus && (
<DisputeTimeline
invoiceId={id}
// as any: disputeStatus is not yet declared in the published @stellar-split/sdk Invoice type
disputeStatus={(invoice as any).disputeStatus}
/>
)}
{/* Activity Timeline */}
<section className="mb-8" aria-labelledby="activity-timeline-heading">
<h2 id="activity-timeline-heading" className="text-lg font-semibold text-white mb-4">Activity Timeline</h2>
<InvoiceTimeline invoiceId={id} />
</section>
{/* Tabbed detail section: Audit Log / History / Notes */}
<section className="mb-8">
<div className="flex gap-1 border-b border-gray-700 mb-4" role="tablist" aria-label="Invoice details">
{(["audit", "history", "notes"] as const).map((tab) => {
const labels: Record<string, string> = { audit: "Audit Log", history: "History", notes: "Notes" };
return (
<button
key={tab}
type="button"
role="tab"
aria-selected={activeDetailsTab === tab}
onClick={() => setActiveDetailsTab(tab)}
className={`px-4 py-2 text-sm font-medium transition-colors rounded-t-lg -mb-px border-b-2 ${
activeDetailsTab === tab
? "border-indigo-500 text-indigo-300"
: "border-transparent text-gray-400 hover:text-gray-200"
}`}
>
{labels[tab]}
</button>
);
})}
</div>
{activeDetailsTab === "audit" && <AuditLogTable invoiceId={id} invoice={invoice ?? undefined} />}
{activeDetailsTab === "history" && <VersionHistory invoiceId={id} />}
{activeDetailsTab === "notes" && publicKey && (
<CommentSection invoiceId={id} walletAddress={publicKey} />
)}
</section>
{showCancelModal && (
<CancelModal
invoiceId={id}
payments={invoice.payments}
onConfirm={async () => {
await (splitClient as any).cancelInvoice(id);
await load();
setShowCancelModal(false);
}}
onClose={() => setShowCancelModal(false)}
/>
)}
{showDuplicateModal && (
<DuplicateModal
invoiceId={id}
onConfirm={(deadlineIso) => {
setShowDuplicateModal(false);
router.push(`/invoice/new?from=${id}&deadline=${deadlineIso}`);
}}
onClose={() => setShowDuplicateModal(false)}
/>
)}
{txHash && showSuccess && (
<SuccessAnimation
invoiceId={id}
txHash={txHash}
onDismiss={() => setShowSuccess(false)}
/>
)}
{txHash && !showSuccess && (
<TxConfirmModal
txHash={txHash}
action="Payment sent"
onClose={() => setTxHash(null)}
/>
)}
<ShareModal
open={showShareModal}
url={`${typeof window !== "undefined" ? window.location.origin : ""}/invoice/${id}`}
onClose={() => setShowShareModal(false)}
/>
<InvoiceShareQRModal
open={showShareQRModal}
invoiceId={id}
onClose={() => setShowShareQRModal(false)}
/>
</main>
);
}