import { useState, useEffect, useCallback, useRef } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import QRCode from 'qrcode'; import { Trash2, Bot, CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { PasswordInput } from '@/components/ui/password-input'; import { Label } from '@/components/ui/label'; import { Checkbox } from '@/components/ui/checkbox'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter, } from '@/components/ui/dialog'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import type { AIProvider } from '@/contexts/AISettingsContext'; import { ExternalFavicon } from '@/components/ExternalFavicon'; import { useToast } from '@/hooks/useToast'; import { useAICredits } from '@/hooks/useAICredits'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useAppContext } from '@/hooks/useAppContext'; interface AIProviderConfigDialogProps { open: boolean; onOpenChange: (open: boolean) => void; provider: AIProvider; onUpdate: (provider: AIProvider) => void; onRemove: () => void; } interface Payment { object: 'payment'; id: string; status: 'pending' | 'completed' | 'failed' | 'expired'; amount: number; fee: number; total: number; method: 'stripe' | 'lightning'; description: string; url: string; created_at: number; completed_at?: number; expires_at: number; } interface PaymentsResponse { object: 'list'; data: Payment[]; has_more: boolean; url: string; } interface AddCreditsRequest { amount: number; method: 'stripe' | 'lightning'; redirect_url?: string; } interface Giftcard { object: 'giftcard'; id: string; code: string; amount: number; redeemed: boolean; created_at?: number; } interface GiftcardsResponse { object: 'list'; data: Giftcard[]; has_more: boolean; } interface CreateGiftcardRequest { amount: number; quantity: number; } interface RedeemGiftcardRequest { code: string; } interface GiftcardRedemption { object: 'giftcard_redemption'; amount: number; } const PRESET_AMOUNTS = [5, 10, 25, 50, 100]; interface LightningPaymentProps { invoice: string; amount: number; paymentId: string; provider: AIProvider; onClose: () => void; onPaymentCompleted: () => void; } function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPaymentCompleted }: LightningPaymentProps) { const { t } = useTranslation(); const { user } = useCurrentUser(); const { config } = useAppContext(); const queryClient = useQueryClient(); const [qrDataUrl, setQrDataUrl] = useState(''); const [isWebLNAvailable, setIsWebLNAvailable] = useState(false); const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false); const [showCopiedTooltip, setShowCopiedTooltip] = useState(false); const [paymentCompleted, setPaymentCompleted] = useState(false); const { toast } = useToast(); const formatCurrency = useCallback((amount: number) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2, }).format(amount); }, []); useEffect(() => { // Generate QR code QRCode.toDataURL(invoice, { width: 256, margin: 2, color: { dark: '#000000', light: '#ffffff', }, }) .then(setQrDataUrl) .catch(console.error); // Check for WebLN availability setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window); }, [invoice]); // Poll payment status useEffect(() => { // Don't poll if payment already completed if (paymentCompleted) return; let intervalId: NodeJS.Timeout | null = null; const pollPaymentStatus = async () => { // Double-check in case state updated during async operation if (paymentCompleted) return; try { const ai = createAIClient(provider, user, config.corsProxy); const payment = await ai.get(`/credits/payments/${paymentId}`) as Payment; if (payment.status === 'completed') { // Mark as completed to prevent further polling setPaymentCompleted(true); // Clear the interval immediately if (intervalId) { clearInterval(intervalId); intervalId = null; } // Update credits balance queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Update payments list queryClient.invalidateQueries({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Show toast toast({ title: t('paymentCompleted'), description: t('creditsAddedToAccount', { amount: formatCurrency(payment.amount) }), }); // Close dialog immediately onPaymentCompleted(); } else if (payment.status === 'failed') { // Mark as completed to prevent further polling setPaymentCompleted(true); // Clear the interval immediately if (intervalId) { clearInterval(intervalId); intervalId = null; } toast({ title: t('paymentFailed'), description: t('paymentFailed'), variant: 'destructive', }); } else if (payment.status === 'expired') { // Mark as completed to prevent further polling setPaymentCompleted(true); // Clear the interval immediately if (intervalId) { clearInterval(intervalId); intervalId = null; } toast({ title: t('paymentExpired'), description: t('paymentExpiredMessage'), variant: 'destructive', }); } } catch (error) { console.error('Failed to poll payment status:', error); } }; // Poll immediately on mount pollPaymentStatus(); // Then poll every 3 seconds intervalId = setInterval(pollPaymentStatus, 3000); return () => { if (intervalId) { clearInterval(intervalId); } }; }, [paymentId, provider, user, config.corsProxy, queryClient, toast, t, onPaymentCompleted, formatCurrency, paymentCompleted]); const handleWebLNPay = async () => { if (!window.webln) return; try { setIsPayingWithWebLN(true); await window.webln.enable(); await window.webln.sendPayment(invoice); toast({ title: t('paymentSent'), description: t('lightningPaymentSent'), }); onClose(); } catch (error) { console.error('WebLN payment failed:', error); toast({ title: t('paymentFailed'), description: error instanceof Error ? error.message : t('failedToSendLightning'), variant: 'destructive', }); } finally { setIsPayingWithWebLN(false); } }; const handleCopyInvoice = () => { navigator.clipboard.writeText(invoice); setShowCopiedTooltip(true); setTimeout(() => setShowCopiedTooltip(false), 2000); }; return (

{t('lightningPayment')}

{t('payWithLightning', { amount: formatCurrency(amount) })}

{/* QR Code */}
{qrDataUrl ? (
Lightning Invoice QR Code
) : (
)}
{/* Payment Buttons */}
{isWebLNAvailable && ( )}
{showCopiedTooltip && (
{t('copied')}
)}
); } export function AIProviderConfigDialog({ open, onOpenChange, provider, onUpdate, onRemove, }: AIProviderConfigDialogProps) { const { t } = useTranslation(); const { user } = useCurrentUser(); const { config } = useAppContext(); const { toast } = useToast(); const queryClient = useQueryClient(); const [localProvider, setLocalProvider] = useState(provider); // Check if provider supports credits const { data: credits, error: creditsError, isLoading: isLoadingCredits } = useAICredits(provider); const supportsCredits = !creditsError && credits !== undefined; // Credits state const [amount, setAmount] = useState(10); const [debouncedAmount, setDebouncedAmount] = useState(10); const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe'); const [lightningInvoice, setLightningInvoice] = useState(null); const [lightningPaymentId, setLightningPaymentId] = useState(null); const [lightningTotal, setLightningTotal] = useState(10); const [refreshingPayments, setRefreshingPayments] = useState>(new Set()); const amountDebounceTimer = useRef(null); const [giftcardAmount, setGiftcardAmount] = useState(10); const [giftcardQuantity, setGiftcardQuantity] = useState(1); const [redeemCode, setRedeemCode] = useState(''); const [copiedCode, setCopiedCode] = useState(null); const [isPrintingQRCodes, setIsPrintingQRCodes] = useState(false); // Default to 'credits' tab const [activeTab, setActiveTab] = useState('credits'); // Reset local state when provider changes or dialog opens useEffect(() => { if (open) { setLocalProvider(provider); } }, [provider, open]); // Set active tab based on credits support useEffect(() => { if (open && !isLoadingCredits) { // Default to 'credits' tab if credits are supported, otherwise 'edit' if (supportsCredits) { setActiveTab('credits'); } else { setActiveTab('edit'); } } }, [open, supportsCredits, isLoadingCredits]); // Debounce amount changes to avoid excessive API calls useEffect(() => { if (amountDebounceTimer.current) { clearTimeout(amountDebounceTimer.current); } amountDebounceTimer.current = setTimeout(() => { setDebouncedAmount(amount); }, 500); // Wait 500ms after user stops typing return () => { if (amountDebounceTimer.current) { clearTimeout(amountDebounceTimer.current); } }; }, [amount]); // Query for payment preview (to get fee information) const { data: paymentPreview, isLoading: isLoadingPreview } = useQuery({ queryKey: ['ai-payment-preview', provider.nostr ? user?.pubkey ?? '' : '', provider.id, debouncedAmount, paymentMethod], queryFn: async (): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const request: AddCreditsRequest = { amount: debouncedAmount, method: paymentMethod, }; if (paymentMethod === 'stripe') { request.redirect_url = window.location.origin + '/settings/ai'; } return await ai.post('/credits/add', { body: request, }) as Payment; }, enabled: open && supportsCredits && debouncedAmount > 0, retry: false, refetchOnWindowFocus: false, staleTime: Infinity, gcTime: 1000 * 60 * 10, }); // Query for payment history const { data: payments, isLoading: isLoadingPayments } = useQuery({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const data = await ai.get('/credits/payments?status=completed&limit=50') as PaymentsResponse; return data.data; }, enabled: open && supportsCredits, retry: false, refetchOnWindowFocus: false, }); // Query for gift cards const { data: giftcards, isLoading: isLoadingGiftcards } = useQuery({ queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const data = await ai.get('/credits/giftcards?limit=50') as GiftcardsResponse; return data.data; }, enabled: open && supportsCredits, retry: false, refetchOnWindowFocus: false, }); // Mutation for adding credits const addCreditsMutation = useMutation({ mutationFn: async (request: AddCreditsRequest): Promise => { const ai = createAIClient(provider, user, config.corsProxy); return await ai.post('/credits/add', { body: request, }) as Payment; }, onSuccess: (payment) => { if (payment.method === 'stripe') { window.open(payment.url, '_blank'); toast({ title: t('paymentInitiated'), description: t('stripeCheckoutOpened'), }); } else if (payment.method === 'lightning') { setLightningInvoice(payment.url); setLightningPaymentId(payment.id); setLightningTotal(payment.total); } queryClient.invalidateQueries({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); }, onError: (error: Error) => { const errorMessage = error?.message || t('paymentFailed'); toast({ title: t('paymentFailed'), description: errorMessage, variant: 'destructive', }); }, }); // Mutation for checking payment status const checkPaymentMutation = useMutation({ mutationFn: async (paymentId: string): Promise => { const ai = createAIClient(provider, user, config.corsProxy); return await ai.get(`/credits/payments/${paymentId}`) as Payment; }, onMutate: async (paymentId: string) => { setRefreshingPayments(prev => new Set(prev).add(paymentId)); }, onSuccess: (updatedPayment) => { setRefreshingPayments(prev => { const newSet = new Set(prev); newSet.delete(updatedPayment.id); return newSet; }); queryClient.setQueryData( ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], (oldPayments) => { if (!oldPayments) return oldPayments; return oldPayments.map(payment => payment.id === updatedPayment.id ? updatedPayment : payment ); } ); if (updatedPayment.status === 'completed') { queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); toast({ title: t('paymentCompleted'), description: t('creditsAddedToAccount', { amount: formatCurrency(updatedPayment.amount) }), }); } else if (updatedPayment.status === 'failed') { toast({ title: t('paymentFailed'), description: t('paymentFailed'), variant: 'destructive', }); } else if (updatedPayment.status === 'expired') { toast({ title: t('paymentExpired'), description: t('paymentExpiredMessage'), variant: 'destructive', }); } }, onError: (error: Error, paymentId: string) => { setRefreshingPayments(prev => { const newSet = new Set(prev); newSet.delete(paymentId); return newSet; }); const errorMessage = error?.message || t('failedToCheckPaymentStatus'); toast({ title: t('refreshFailed'), description: errorMessage, variant: 'destructive', }); }, }); // Mutation for creating gift cards const createGiftcardMutation = useMutation({ mutationFn: async (request: CreateGiftcardRequest): Promise => { const ai = createAIClient(provider, user, config.corsProxy); const response = await ai.post('/credits/giftcards', { body: request, }) as GiftcardsResponse; return response.data; }, onSuccess: (giftcards) => { toast({ title: t('giftCardCreated'), description: t('successfullyCreatedGiftCards', { count: giftcards.length }), }); queryClient.invalidateQueries({ queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); setGiftcardAmount(10); setGiftcardQuantity(1); }, onError: (error: Error) => { const errorMessage = error?.message || t('failedToCreateGiftCards'); toast({ title: t('creationFailed'), description: errorMessage, variant: 'destructive', }); }, }); // Mutation for redeeming gift cards const redeemGiftcardMutation = useMutation({ mutationFn: async (request: RedeemGiftcardRequest): Promise => { const ai = createAIClient(provider, user, config.corsProxy); return await ai.post('/credits/giftcards/redeem', { body: request, }) as GiftcardRedemption; }, onSuccess: (redemption) => { toast({ title: t('giftCardRedeemed'), description: t('creditsAddedToAccount', { amount: formatCurrency(redemption.amount) }), }); queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); setRedeemCode(''); }, onError: (error: Error) => { const errorMessage = error?.message || t('failedToRedeemGiftCard'); toast({ title: t('redemptionFailed'), description: errorMessage, variant: 'destructive', }); }, }); const handleSave = () => { onUpdate(localProvider); onOpenChange(false); }; const handleDelete = () => { onRemove(); onOpenChange(false); }; const handleAddCredits = () => { if (amount <= 0) { toast({ title: t('invalidAmount'), description: t('enterValidAmount'), variant: 'destructive', }); return; } if (paymentPreview) { if (paymentPreview.method === 'stripe') { window.open(paymentPreview.url, '_blank'); toast({ title: t('paymentInitiated'), description: t('stripeCheckoutOpened'), }); } else if (paymentPreview.method === 'lightning') { setLightningInvoice(paymentPreview.url); setLightningPaymentId(paymentPreview.id); setLightningTotal(paymentPreview.total); } queryClient.invalidateQueries({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); queryClient.invalidateQueries({ queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); queryClient.invalidateQueries({ queryKey: ['ai-payment-preview', provider.nostr ? user?.pubkey ?? '' : '', provider.id, amount, paymentMethod], }); } else { const request: AddCreditsRequest = { amount, method: paymentMethod, }; if (paymentMethod === 'stripe') { request.redirect_url = window.location.origin + '/settings/ai'; } addCreditsMutation.mutate(request); } }; const handleCreateGiftcard = () => { if (giftcardAmount <= 0) { toast({ title: t('invalidAmount'), description: t('enterValidAmount'), variant: 'destructive', }); return; } if (giftcardQuantity <= 0 || giftcardQuantity > 100) { toast({ title: t('invalidQuantity'), description: t('quantityBetween'), variant: 'destructive', }); return; } createGiftcardMutation.mutate({ amount: giftcardAmount, quantity: giftcardQuantity, }); }; const handleRedeemGiftcard = () => { const trimmedCode = redeemCode.trim(); if (!trimmedCode) { toast({ title: t('invalidCode'), description: t('enterGiftCardCodePrompt'), variant: 'destructive', }); return; } redeemGiftcardMutation.mutate({ code: trimmedCode }); }; const handleCopyCode = (code: string) => { const url = new URL('/giftcard', window.location.origin); url.hash = new URLSearchParams({ baseURL: provider.baseURL, code: code, }).toString(); navigator.clipboard.writeText(url.toString()); setCopiedCode(code); setTimeout(() => setCopiedCode(null), 2000); }; const handlePrintGiftcards = async () => { if (!giftcards || giftcards.length === 0) return; const activeGiftcards = giftcards.filter(gc => !gc.redeemed); if (activeGiftcards.length === 0) { toast({ title: t('noActiveGiftCards'), description: t('noActiveGiftCardsToPrint'), variant: 'destructive', }); return; } setIsPrintingQRCodes(true); try { const qrCodePromises = activeGiftcards.map(async (giftcard) => { const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(giftcard.code)}`; const qrDataUrl = await QRCode.toDataURL(url, { width: 256, margin: 2, color: { dark: '#000000', light: '#ffffff', }, }); return { ...giftcard, qrDataUrl, }; }); const giftcardsWithQR = await Promise.all(qrCodePromises); const printWindow = window.open('', '_blank'); if (!printWindow) { throw new Error(t('failedToOpenPrintWindow')); } const printHTML = ` Shakespeare AI Gift Cards
${giftcardsWithQR.map(gc => `
Shakespeare AI Gift Card
QR Code
${formatCurrency(gc.amount)}
${gc.code}
`).join('')}
`; printWindow.document.write(printHTML); printWindow.document.close(); printWindow.onload = () => { setTimeout(() => { printWindow.print(); }, 250); }; } catch (error) { console.error('Failed to generate QR codes:', error); toast({ title: t('printFailed'), description: error instanceof Error ? error.message : t('failedToGenerateQRCodes'), variant: 'destructive', }); } finally { setIsPrintingQRCodes(false); } }; const handleDownloadCSV = () => { if (!giftcards || giftcards.length === 0) return; const activeGiftcards = giftcards.filter(gc => !gc.redeemed); if (activeGiftcards.length === 0) { toast({ title: t('noActiveGiftCards'), description: t('noActiveGiftCardsToDownload'), variant: 'destructive', }); return; } try { const headers = ['Code', 'Amount', 'Status', 'Created Date', 'Redemption URL']; const rows = activeGiftcards.map(gc => { const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(gc.code)}`; const createdDate = gc.created_at ? new Date(gc.created_at * 1000).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : 'N/A'; return [ gc.code, Number(gc.amount).toFixed(2), gc.redeemed ? 'Redeemed' : 'Active', createdDate, url ]; }); const csvContent = [ headers.join(','), ...rows.map(row => row.map(cell => `"${cell}"`).join(',')) ].join('\n'); const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); const link = document.createElement('a'); const url = URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', `shakespeare-giftcards-${new Date().toISOString().split('T')[0]}.csv`); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); toast({ title: t('csvDownloaded'), description: t('downloadedGiftCards', { count: activeGiftcards.length }), }); } catch (error) { console.error('Failed to generate CSV:', error); toast({ title: t('downloadFailed'), description: error instanceof Error ? error.message : t('failedToGenerateCSV'), variant: 'destructive', }); } }; // Shared utility functions const formatCurrency = (amount: number) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2, }).format(amount); }; const formatDate = (timestamp: number) => { const date = new Date(timestamp * 1000); const now = new Date(); const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)); if (diffDays === 0) { return new Intl.DateTimeFormat('en-US', { hour: '2-digit', minute: '2-digit', }).format(date); } else if (diffDays === 1) { return t('yesterday'); } else if (diffDays < 7) { return new Intl.DateTimeFormat('en-US', { weekday: 'short', }).format(date); } else { return new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', }).format(date); } }; const getStatusIcon = (status: Payment['status']) => { switch (status) { case 'completed': return ; case 'failed': return ; case 'expired': return ; case 'pending': default: return ; } }; // Render functions for shared content const renderEditContent = () => (
setLocalProvider({ ...localProvider, name: e.target.value })} />
setLocalProvider({ ...localProvider, baseURL: e.target.value })} />
{localProvider.openSecret && (
setLocalProvider({ ...localProvider, openSecret: e.target.value })} />
)} {!localProvider.nostr && (
setLocalProvider({ ...localProvider, apiKey: e.target.value })} />
)}
setLocalProvider({ ...localProvider, proxy: checked === true || undefined })} />
); const renderCreditsContent = () => { return (
{/* Credits Balance Display */} {credits && (
{t('availableCredits')}
{formatCurrency(credits.amount)}
)}
{/* Buy Credits Accordion */}
{t('buyCredits')}
setAmount(Number(e.target.value) || 0)} placeholder={t('enterAmount')} className="text-center text-lg font-medium" />
{PRESET_AMOUNTS.map((preset) => ( ))}
setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full"> {t('creditCard')} {t('lightning')}
{paymentPreview && paymentPreview.fee > 0 && (
{t('credits')} {formatCurrency(paymentPreview.amount)}
{t('processingFee')} {formatCurrency(paymentPreview.fee)}
{t('total')} {formatCurrency(paymentPreview.total)}
)}
{/* Transaction History Accordion */}
{t('recentTransactions')}
{isLoadingPayments ? (
) : !payments || payments.length === 0 ? (

{t('noTransactionsYet')}

{t('paymentHistoryAppears')}

) : (
{payments.map((payment) => (
{getStatusIcon(payment.status)} {payment.method === 'stripe' ? t('creditCard') : t('lightning')}

{formatCurrency(payment.amount)}

{payment.fee > 0 && (

+{formatCurrency(payment.fee)}

)}
{formatDate(payment.created_at)} {payment.status === 'pending' && (
{payment.url && ( )}
)}
))}
)}
{/* Redeem Gift Card Accordion */}
{t('redeemGiftCard')}
setRedeemCode(e.target.value)} placeholder={t('enterGiftCardCode')} className="flex-1" />
{/* Create Gift Card Accordion */}
{t('createGiftCard')}
setGiftcardAmount(Number(e.target.value))} placeholder={t('enterAmount')} className="text-center" />
setGiftcardQuantity(Number(e.target.value))} placeholder={t('qty')} className="text-center" />
{PRESET_AMOUNTS.map((preset) => ( ))}
{/* Your Gift Cards Accordion */}
{t('yourGiftCards')}
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
)} {isLoadingGiftcards ? (
) : !giftcards || giftcards.length === 0 ? (

{t('noGiftCardsYet')}

{t('createGiftCardsToShare')}

) : (
{giftcards.map((giftcard) => (
{t('giftCard')} {giftcard.redeemed ? t('redeemed') : t('active')}

{formatCurrency(giftcard.amount)}

{giftcard.code}
{copiedCode === giftcard.code && (
{t('copied')}
)}
{giftcard.created_at && (
{t('created')} {formatDate(giftcard.created_at)}
)}
))}
)}
); }; return ( e.preventDefault()} className={supportsCredits ? "max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none" : "max-w-md" } >
{localProvider.baseURL ? ( } /> ) : ( )} {localProvider.name}
{!supportsCredits && ( Configure your AI provider settings )}
{supportsCredits ? ( <> {lightningInvoice ? (
{ setLightningInvoice(null); setLightningPaymentId(null); }} onPaymentCompleted={() => { setLightningInvoice(null); setLightningPaymentId(null); }} />
) : ( {t('credits')} {t('edit')} {renderCreditsContent()} {renderEditContent()} )} ) : ( <> {renderEditContent()} )}
); }