'use client'; import { useState } from 'react'; import { Tag } from 'lucide-react'; import type { Cart } from 'brainerce'; import { getClient } from '@/core/lib/brainerce'; import { useTranslations } from '@/core/lib/translations'; import { LoadingSpinner } from '@/ui/shared/loading-spinner'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { cn } from '@/core/lib/utils'; interface CouponInputProps { cart: Cart; /** When provided, uses applyCheckoutCoupon/removeCheckoutCoupon instead of * applyCoupon/removeCoupon. Always pass this when a checkout session exists. */ checkoutId?: string; onUpdate: () => void; className?: string; } export function CouponInput({ cart, checkoutId, onUpdate, className }: CouponInputProps) { const t = useTranslations('coupon'); const tc = useTranslations('common'); const [code, setCode] = useState(''); const [applying, setApplying] = useState(false); const [removing, setRemoving] = useState(false); const [error, setError] = useState(null); const appliedCoupon = cart.couponCode || null; async function handleApply() { const trimmed = code.trim(); if (!trimmed || applying) return; try { setApplying(true); setError(null); const client = getClient(); if (checkoutId) { await client.applyCheckoutCoupon(checkoutId, trimmed); } else { await client.applyCoupon(cart.id, trimmed); } setCode(''); onUpdate(); } catch (err) { const message = err instanceof Error ? err.message : t('invalidCode'); setError(message); } finally { setApplying(false); } } async function handleRemove() { if (removing) return; try { setRemoving(true); setError(null); const client = getClient(); if (checkoutId) { await client.removeCheckoutCoupon(checkoutId); } else { await client.removeCoupon(cart.id); } onUpdate(); } catch (err) { console.error('Failed to remove coupon:', err); } finally { setRemoving(false); } } // Show applied coupon if (appliedCoupon) { return (
); } return (
{ setCode(e.target.value); if (error) setError(null); }} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleApply(); } }} placeholder={t('placeholder')} className={cn('h-9 flex-1 rounded', error && 'border-destructive')} />
{error &&

{error}

}
); }