'use client'; import { useState } from 'react'; import type { Checkout } from 'brainerce'; import { BrainerceError } from 'brainerce'; import { getClient } from '@/core/lib/brainerce'; import { useTranslations } from '@/core/lib/translations'; import { LoadingSpinner } from '@/ui/shared/loading-spinner'; import { cn } from '@/core/lib/utils'; interface GiftCardInputProps { checkoutId: string; /** Cards already on this checkout. Each is removed by its own tenderId. */ tenders: NonNullable; /** * Whether the checkout can still take a card. False once a payment intent * exists — the server refuses every tender change from then on. */ locked: boolean; /** Formats an amount in the checkout's currency. */ formatAmount: (value: string) => string; onUpdate: () => void; className?: string; } /** * DESIGN ME — gift-card redemption control on the checkout page; `tenders` and * `formatAmount` come from the checkout page's own state. * * ⛔ Do NOT design this as a second coupon field. A coupon reduces what the * order is worth; a gift card PAYS for an order that is still worth what it * was. The total does not move and tax is unchanged — only the amount charged * to the payment provider drops. Style the applied card as its own line near * the total, never inside the discount row, or the shopper is shown one number * and charged another and the receipt misstates the taxable base. * * Keep: the list of applied cards (each removable by `tenderId`), the code * field, and the error message. A checkout can carry several cards at once. * * Keep `dir="ltr"` on the input — the code is Latin even on an RTL storefront. * * Refusals are deliberately identical for "no such code", "expired", "already * spent" and "wrong currency": anything that tells them apart is an oracle * someone walks the code space against. Show THIS store's one message for all * of them — never the server's text, which is English and could gain a more * helpful sentence later. * * Two failures are not about the card and must not read as if they were: a 5xx * or dropped connection, and a checkout already locked for payment. When * `locked` is true, do not render the field at all — the server refuses both * applying and removing, changing shipping does not unlock it, and a box that * can never work is worse than no box. * * Building blocks: shadcn/ui primitives in src/components/ui (Button, Card, Badge, Input, Select, Accordion, Dialog, Skeleton, ...) + lucide-react icons are installed and ready to compose with. */ export function GiftCardInput({ checkoutId, tenders, locked, formatAmount, onUpdate, className, }: GiftCardInputProps) { const t = useTranslations('giftCard'); const tc = useTranslations('common'); const [code, setCode] = useState(''); const [applying, setApplying] = useState(false); const [removingId, setRemovingId] = useState(null); const [error, setError] = useState(null); /** `CHECKOUT_LOCKED` is the one 4xx that says nothing about the card. */ function isCheckoutLocked(err: unknown): boolean { if (!(err instanceof BrainerceError)) return false; const details = err.details as { code?: unknown } | null | undefined; return details?.code === 'CHECKOUT_LOCKED'; } async function handleApply() { const trimmed = code.trim(); if (!trimmed || applying) return; try { setApplying(true); setError(null); await getClient().applyGiftCard(checkoutId, trimmed); // Cleared on success only. A rejected code stays in the field so the // shopper can fix a typo instead of re-reading it off the card. setCode(''); onUpdate(); } catch (err) { const refused = err instanceof BrainerceError && err.statusCode < 500; setError( isCheckoutLocked(err) ? t('locked') : refused ? t('invalidCode') : t('applyFailed') ); } finally { setApplying(false); } } async function handleRemove(tenderId: string) { if (removingId) return; try { setRemovingId(tenderId); setError(null); await getClient().removeGiftCard(checkoutId, tenderId); onUpdate(); } catch (err) { setError(isCheckoutLocked(err) ? t('locked') : t('removeFailed')); } finally { setRemovingId(null); } } return (
{tenders.length > 0 && (
    {tenders.map((tender) => (
  • {/* What was applied, not what the card holds. A ₪200 card on a ₪50 order applies ₪50 and keeps the rest for next time — showing the balance here would look like a lost ₪150. */} {t('applied', { amount: formatAmount(tender.amountApplied) })} {!locked && ( )}
  • ))}
)} {locked ? ( tenders.length > 0 ?

{t('lockedHint')}

: null ) : (
{ setCode(e.target.value); if (error) setError(null); }} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleApply(); } }} placeholder={t('placeholder')} aria-label={t('placeholder')} aria-invalid={error ? true : undefined} dir="ltr" autoComplete="off" spellCheck={false} />
)} {error &&

{error}

}
); }