import * as React from "react"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { cn, formatNumberPersian, formatToman, resolveErrorMessage } from "@/lib/utils"; type RawVerifyResult = { discount_amount: number; final_price: number; }; type Normalized = { valid: boolean; discount_amount: number; final_price: number; message_fa: string; }; type Props = { open: boolean; onOpenChange: (v: boolean) => void; basePrice: number; // مبلغ اولیه رویداد onVerifyCouponRaw: (code: string) => Promise; onContinue: (coupon?: string, finalPrice?: number) => void; // ادامه‌ی جریان ثبت‌نام/پرداخت }; export default function CouponDialogFa({ open, onOpenChange, basePrice, onVerifyCouponRaw, onContinue, }: Props) { const [code, setCode] = React.useState(""); const [verifying, setVerifying] = React.useState(false); const [res, setRes] = React.useState(null); // اگر نتیجه نداریم، قیمت نهایی = قیمت پایه const finalPrice = res?.final_price ?? basePrice / 10; const handleVerify = async () => { if (!code) return; try { setVerifying(true); // فراخوانی تابع خام که فقط خروجی بک‌اند را می‌دهد const raw = await onVerifyCouponRaw(code); // --- نرمالایز داخل همین کامپوننت --- setRes({ valid: true, discount_amount: (raw.discount_amount ?? 0) / 10, final_price: (raw.final_price ?? basePrice) / 10, message_fa: "کد تخفیف با موفقیت اعمال شد", }); } catch (error) { setRes({ valid: false, discount_amount: 0, final_price: basePrice / 10, // برگرداندن قیمت به حالت اولیه message_fa: resolveErrorMessage(error, "کد تخفیف معتبر نیست"), }); } finally { setVerifying(false); } }; return ( کد تخفیف
setCode(e.target.value)} placeholder="مثلاً OFF20" className="text-right" />
{/* پیام زیر اینپوت: موفق/نامعتبر */} {res && (

{res.message_fa}

)}
قیمت اولیه {formatToman(basePrice)}
{res?.discount_amount ? (
تخفیف - {formatNumberPersian(res.discount_amount)} تومان
) : null}
قیمت نهایی {formatNumberPersian(finalPrice)} تومان
); }