import { useState, useEffect, useMemo } from 'react'; import { X, CheckCircle, Loader2, Minus, Plus } from 'lucide-react'; import { Elements } from '@stripe/react-stripe-js'; import { StripePaymentForm } from './StripePaymentForm'; import { stripePromise } from '@/infrastructure/stripe'; import { usePurchaseCommands } from '../hooks/usePurchaseCommands'; import { useConfirmCommandPurchase } from '../hooks/useConfirmCommandPurchase'; import { useTranslation } from '@/i18n/TranslationProvider'; const MIN_QTY = 1; const MAX_QTY = 100; interface CommandPackage { size: 100 | 1000; price: number; } interface CommandPurchasePanelProps { packages: CommandPackage[]; currency: string; onClose: () => void; onSuccess: () => void; } export function CommandPurchasePanel({ packages, currency, onClose, onSuccess }: CommandPurchasePanelProps) { const { t } = useTranslation(); const purchaseMutation = usePurchaseCommands(); const confirmMutation = useConfirmCommandPurchase(); const [selectedSize, setSelectedSize] = useState<100 | 1000>(packages[0]?.size ?? 100); const [quantity, setQuantity] = useState(1); const [isComplete, setIsComplete] = useState(false); const [error, setError] = useState(null); const clampQty = (n: number) => Math.max(MIN_QTY, Math.min(MAX_QTY, Math.floor(n))); // Auto-close after success useEffect(() => { if (!isComplete) return; const timer = setTimeout(() => { onSuccess(); onClose(); }, 2000); return () => clearTimeout(timer); }, [isComplete, onSuccess, onClose]); const selectedPackage = packages.find((p) => p.size === selectedSize); const clientSecret = purchaseMutation.data?.clientSecret; const totals = useMemo(() => { const packPrice = selectedPackage?.price ?? 0; return { commands: selectedSize * quantity, cost: Number((packPrice * quantity).toFixed(2)), }; }, [selectedSize, quantity, selectedPackage?.price]); const handleBuy = () => { setError(null); purchaseMutation.mutate({ packageSize: selectedSize, quantity }, { onError: (err) => setError((err as Error).message || 'Failed to initialize payment'), }); }; const handleStripeSuccess = (paymentIntentId: string) => { confirmMutation.mutate(paymentIntentId, { onSuccess: () => setIsComplete(true), onError: (err) => setError((err as Error).message || 'Purchase confirmation failed'), }); }; const handleStripeError = (msg: string) => { setError(msg); }; const isLoading = purchaseMutation.isPending; const isProcessing = confirmMutation.isPending; return ( <> {/* Backdrop */}