import { useState, useEffect, useRef } from 'react'; import { nip19 } from 'nostr-tools'; import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/wallet/useBitcoin'; import { useNsecAccess } from '@/hooks/useNsecAccess'; import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin'; import { QRModal } from '@/components/ui/qr-modal'; import { TransactionCard } from './PaymentCard'; import { ConsolidationModal } from './ConsolidationModal'; import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'; import * as VisuallyHidden from '@radix-ui/react-visually-hidden'; import { TransactionHistory } from './TransactionHistory'; import { ScrollArea } from '@/components/ui/scroll-area'; import { ChevronUp, Send, Download, ScanLine } from 'lucide-react'; import { Button } from '@/components/ui/button'; import type { QRScanResult } from '@/hooks/wallet/useQRCode'; interface BitcoinWalletProps { toast: ReturnType['toast']; generateQRCode: (text: string) => Promise; copyToClipboard: (text: string) => Promise; user?: { pubkey: string }; onRequestQRScanner: () => void; onQRResult?: (result: QRScanResult) => void; onWalletHeaderPropsChange?: (props: any) => void; } export function BitcoinWallet({ toast, generateQRCode, copyToClipboard, user, onRequestQRScanner, onQRResult, onWalletHeaderPropsChange, }: BitcoinWalletProps) { const { hasNsecAccess } = useNsecAccess(); const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null; const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress); const { utxos, isConsolidating, bitcoinMaxAmount, fetchBitcoinUtxos, handleSendMax, handleBitcoinSend, handleBitcoinReceive, handleConsolidateUtxos, } = useBitcoinOperations(bitcoinAddress); const { data: bitcoinTransactions = [], isLoading: isBitcoinTransactionsLoading } = useBitcoinTransactionHistory(bitcoinAddress); // Bitcoin state const [bitcoinAmount, setBitcoinAmount] = useState(''); const [bitcoinRecipient, setBitcoinRecipient] = useState(''); const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState(null); const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false); const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState(''); const [showConsolidationModal, setShowConsolidationModal] = useState(false); const [showSendModal, setShowSendModal] = useState(false); const [showReceiveModal, setShowReceiveModal] = useState(false); const [showHistoryModal, setShowHistoryModal] = useState(false); // UTXO state const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false); // Fetch UTXOs when component mounts useEffect(() => { if (bitcoinAddress) { fetchBitcoinUtxos(); } }, [bitcoinAddress, fetchBitcoinUtxos]); // Handle drawer close with state reset const handleSendDrawerClose = (open: boolean) => { setShowSendModal(open); if (!open) { setBitcoinAmount(''); setBitcoinRecipient(''); setPendingBitcoinRecipient(null); } }; const handleReceiveDrawerClose = (open: boolean) => { setShowReceiveModal(open); }; // Handle focus management when drawers open useEffect(() => { if (showSendModal || showReceiveModal || showHistoryModal) { const activeElement = document.activeElement as HTMLElement; if (activeElement && activeElement.blur) { activeElement.blur(); } } }, [showSendModal, showReceiveModal, showHistoryModal]); // Handle QR scan results (called from parent WalletContainer) useEffect(() => { if (!onQRResult) return; const handleQRResult = (result: QRScanResult) => { if (result.type === 'bitcoin_address') { setBitcoinRecipient(result.value); setPendingBitcoinRecipient(result.value); setShowSendModal(true); toast({ title: "Bitcoin Address Scanned", description: "Enter amount to send", }); } else if (result.type === 'npub') { try { const decoded = nip19.decode(result.value); if (decoded.type === 'npub') { const address = nostrPubkeyToBitcoinAddress(decoded.data); setBitcoinRecipient(address); setPendingBitcoinRecipient(address); setShowSendModal(true); toast({ title: "Nostr npub Scanned", description: "Enter amount to send", }); } } catch (err) { toast({ variant: "destructive", title: "Invalid npub", description: "Could not decode npub", }); } } }; // Store handler for parent to call (window as any).__bitcoinWalletQRHandler = handleQRResult; return () => { delete (window as any).__bitcoinWalletQRHandler; }; }, [onQRResult, toast]); const totalBalance = bitcoinBalanceData?.balance || 0; // Expose WalletHeader props to parent WalletContainer // Use ref to track previous values and prevent infinite loops const prevPropsRef = useRef<{ utxosLength?: number; utxoDropdownOpen?: boolean; isConsolidating?: boolean; }>({}); useEffect(() => { if (!onWalletHeaderPropsChange) return; // Check if values actually changed const currentProps = { utxosLength: utxos?.length, utxoDropdownOpen, isConsolidating, }; const prevProps = prevPropsRef.current; const hasChanged = prevProps.utxosLength !== currentProps.utxosLength || prevProps.utxoDropdownOpen !== currentProps.utxoDropdownOpen || prevProps.isConsolidating !== currentProps.isConsolidating; if (!hasChanged && Object.keys(prevProps).length > 0) { // Values haven't changed, skip update return; } // Update ref prevPropsRef.current = currentProps; // Send updated props onWalletHeaderPropsChange({ utxos, utxoDropdownOpen, setUtxoDropdownOpen, onShowConsolidationModal: () => setShowConsolidationModal(true), isConsolidating, onShowBitcoinAddressQR: async (qr: string) => { setBitcoinAddressQRCode(qr); setShowBitcoinAddressQR(true); }, }); }, [ onWalletHeaderPropsChange, utxos?.length, utxoDropdownOpen, isConsolidating, // Note: Functions (setUtxoDropdownOpen, etc.) are not in deps // because they're stable setters or we accept they may change // The ref-based change detection ensures we only update when primitives change ]); return ( <> {/* Action Buttons and Transaction History Container */}
{/* Action Buttons */}
{/* Transaction History Button */}
{/* Modals */} <> {/* Consolidation Modal */} setShowConsolidationModal(false)} utxos={utxos} onConfirm={handleConsolidateUtxos} isConsolidating={isConsolidating} /> {/* Bitcoin Address QR Modal */} setShowBitcoinAddressQR(false)} title="Bitcoin Address" description="Scan this QR code to send Bitcoin to your address" qrCodeUrl={bitcoinAddressQRCode} content={bitcoinAddress || ''} icon="qr" /> {/* Bottom Drawer Modals */} Send Send Bitcoin on-chain
{}} lightningInvoice="" setLightningInvoice={() => {}} lightningAddressInput="" setLightningAddressInput={() => {}} lightningAddressAmount="" setLightningAddressAmount={() => {}} pendingLightningAddress={null} setPendingLightningAddress={() => {}} decodedInvoiceAmount={null} setDecodedInvoiceAmount={() => {}} pendingInvoice={null} setPendingInvoice={() => {}} tokenInput="" setTokenInput={() => {}} quoteAmount="" setQuoteAmount={() => {}} activeMintUrl={null} onSend={() => { handleBitcoinSend( bitcoinAmount, pendingBitcoinRecipient, setBitcoinAmount, setBitcoinRecipient, setPendingBitcoinRecipient, setShowSendModal ); }} onReceive={() => {}} isResolvingAddress={false} isLoading={isBitcoinBalanceLoading} bitcoinAddress={bitcoinAddress || ''} bitcoinAmount={bitcoinAmount} setBitcoinAmount={setBitcoinAmount} bitcoinRecipient={bitcoinRecipient} setBitcoinRecipient={setBitcoinRecipient} pendingBitcoinRecipient={pendingBitcoinRecipient} setPendingBitcoinRecipient={setPendingBitcoinRecipient} hasNsecAccess={hasNsecAccess} bitcoinMaxAmount={bitcoinMaxAmount} onSendMax={() => handleSendMax(setBitcoinAmount)} />
Receive Receive Bitcoin on-chain
{}} lightningInvoice="" setLightningInvoice={() => {}} lightningAddressInput="" setLightningAddressInput={() => {}} lightningAddressAmount="" setLightningAddressAmount={() => {}} pendingLightningAddress={null} setPendingLightningAddress={() => {}} decodedInvoiceAmount={null} setDecodedInvoiceAmount={() => {}} pendingInvoice={null} setPendingInvoice={() => {}} tokenInput="" setTokenInput={() => {}} quoteAmount="" setQuoteAmount={() => {}} activeMintUrl={null} onSend={() => {}} onReceive={() => { handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR); setShowReceiveModal(false); }} isResolvingAddress={false} isLoading={isBitcoinBalanceLoading} bitcoinAddress={bitcoinAddress || ''} bitcoinAmount="" setBitcoinAmount={() => {}} bitcoinRecipient="" setBitcoinRecipient={() => {}} pendingBitcoinRecipient={null} setPendingBitcoinRecipient={() => {}} hasNsecAccess={hasNsecAccess} />
Transactions View your Bitcoin transaction history ); }