import { useGrainAnalytics } from '@grainql/analytics-web/react';
import { useRouter } from 'next/navigation';
import { useCart } from './useCart';
export function CheckoutButton({ paymentMethod }: { paymentMethod: string }) {
const grain = useGrainAnalytics();
const router = useRouter();
const { items, total, clearCart } = useCart();
const handleCheckout = async () => {
const order = await createOrder(items);
grain.trackCheckout({
orderId: order.id,
total,
currency: 'USD',
items: items.map((item) => ({
id: item.id,
name: item.name,
price: item.price,
quantity: item.quantity
})),
paymentMethod
});
const payment = await processPayment(order.id, paymentMethod);
if (!payment.ok) {
grain.trackCheckout({
orderId: order.id,
total,
currency: 'USD',
paymentMethod,
success: false,
errorMessage: payment.error
});
return;
}
clearCart();
router.push(`/orders/${order.id}`);
};
return <button onClick={handleCheckout}>Complete Purchase</button>;
}