"use client"; import { useState } from "react"; import { X } from "lucide-react"; import { cn } from "@/app/lib/utils"; import { useMoney } from "@/app/pos/currency"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { AppliedGiftCard } from "@/app/lib/types"; import { checkPosGiftCard, cardCover } from "@/app/lib/services/posGiftCards"; // add-gift-card-counter: the cashier enters up to 3 gift card codes to pay towards a POS total. // Codes are checked against the balance API; refused codes show an error, applied cards show // what they contribute and the remaining balance. interface GiftCardCodesFieldProps { cards: AppliedGiftCard[]; total: number; onChange: (cards: AppliedGiftCard[]) => void; disabled: boolean; } export function GiftCardCodesField({ cards, total, onChange, disabled }: GiftCardCodesFieldProps) { const money = useMoney(); const t = useT(); const [leftPre, leftPost] = t("PosLeftToPay").split("{amount}"); const [code, setCode] = useState(""); const [checking, setChecking] = useState(false); const [error, setError] = useState(null); const { perCard, left } = cardCover(cards, total); async function apply() { const normalised = code.replace(/[\s-]/g, "").toUpperCase(); if (!normalised) return; // Duplicate: refuse without calling the API if (cards.some((c) => c.code === normalised)) { setError("PosGcAlreadyApplied"); return; } setChecking(true); setError(null); try { const res = await checkPosGiftCard(normalised); onChange([...cards, { code: normalised, last4: res.last4, balance: res.balance }]); } catch (err) { setError(err instanceof Error && err.message ? err.message : "PosGcCheckFailed"); } finally { setChecking(false); setCode(""); } } function remove(index: number) { onChange(cards.filter((_, i) => i !== index)); } return (
{t("PosGiftCards")}
{cards.map((card, i) => (
•••• {card.last4}{" "} {t("PosGcCoverage", { amount: money(perCard[i]), balance: money(card.balance) })}
))} {cards.length > 0 && (
{leftPre}{money(left)}{leftPost}
)} {error &&

{t(error)}

}
setCode(e.target.value)} disabled={disabled || checking || cards.length >= 3} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); apply(); } }} className={cn( "flex-1 rounded-md border bg-background px-3 py-1.5 text-sm outline-none", "placeholder:text-muted-foreground", "focus:ring-2 focus:ring-primary/30", )} placeholder={t("PosEnterCode")} />
); }