import React from 'react' import { X, ShoppingBag, Plus, Minus, Trash2, Tag, ArrowRight } from 'lucide-react' import { Link } from 'react-router-dom' import { useCartStore } from '../store/cartStore' import { formatPrice } from '@homaroma/types' import { useTranslation } from 'react-i18next' import { API_BASE } from '../types' export default function CartDrawer() { const { t } = useTranslation() const { isCartOpen, toggleCart, items, updateQuantity, removeFromCart, getCartTotal } = useCartStore() React.useEffect(() => { if (isCartOpen) { document.body.style.overflow = 'hidden' } else { document.body.style.overflow = '' } return () => { document.body.style.overflow = '' } }, [isCartOpen]) if (!isCartOpen) return null return (
{/* Backdrop */}
toggleCart(false)} /> {/* Drawer */}
{/* Header */}

{t('cart.title')} {t('cart.items', { count: items.length })}

{/* Cart Items */}
{items.length === 0 ? (

{t('cart.empty')}

) : ( items.map((item) => (
{item.productName}

{item.productName}

{item.variantSize && (

{item.variantSize}

)} {/* Price row */}
{formatPrice(item.price)} × {item.quantity} = {formatPrice(item.price * item.quantity)}
{/* Quantity controls */}
{item.quantity}
)) )}
{/* Footer */} {items.length > 0 && ( toggleCart(false)} t={t} /> )}
) } function CartDrawerFooter({ subtotal, onClose, t }: { subtotal: number; onClose: () => void; t?: any }) { const [savedCoupon, setSavedCoupon] = React.useState(null) const [discountAmount, setDiscountAmount] = React.useState(0) const [isFreeShipping, setIsFreeShipping] = React.useState(false) const [couponValid, setCouponValid] = React.useState(false) const [activePromos, setActivePromos] = React.useState([]) const [couponInput, setCouponInput] = React.useState('') const [couponLoading, setCouponLoading] = React.useState(false) const [couponError, setCouponError] = React.useState('') React.useEffect(() => { fetch(`${API_BASE}/promotions/active`) .then(res => res.json()) .then(data => { if (Array.isArray(data)) setActivePromos(data) }) .catch(console.error) }, []) React.useEffect(() => { const code = localStorage.getItem('app_active_coupon') setSavedCoupon(code) if (code && subtotal > 0) { fetch(`${API_BASE}/coupons/validate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, cartTotal: subtotalAfterL2 }) }) .then(r => r.json()) .then(data => { if (data.valid) { setCouponValid(true) setDiscountAmount(data.discountAmount || 0) setIsFreeShipping(data.isFreeShipping || false) } else { setCouponValid(false) } }) .catch(() => setCouponValid(false)) } }, [subtotal, activePromos]) const removeCoupon = () => { localStorage.removeItem('app_active_coupon') setSavedCoupon(null) setDiscountAmount(0) setIsFreeShipping(false) setCouponValid(false) setCouponError('') setCouponInput('') } const handleApplyCoupon = async () => { if (!couponInput.trim()) return setCouponLoading(true) setCouponError('') // We must validate with subtotalAfterL2, but since we don't have it defined here yet, // we'll calculate it inline or rely on the effect. Actually, we can just save it to localStorage and let the effect handle it. localStorage.setItem('app_active_coupon', couponInput.toUpperCase()) setSavedCoupon(couponInput.toUpperCase()) setCouponInput('') setCouponLoading(false) } // Calculate Level 1 Promo const promoLevel1 = activePromos.find(p => p.level === 1 && subtotal >= p.minPurchase) const promoLevel1Disc = promoLevel1 ? (promoLevel1.type === 'PERCENTAGE' ? subtotal * (promoLevel1.value / 100) : promoLevel1.value) : 0 const subtotalAfterL1 = Math.max(0, subtotal - promoLevel1Disc) // Calculate Level 2 Promo const promoLevel2 = activePromos.find(p => p.level === 2 && subtotalAfterL1 >= p.minPurchase) const promoLevel2Disc = promoLevel2 ? (promoLevel2.type === 'PERCENTAGE' ? subtotalAfterL1 * (promoLevel2.value / 100) : promoLevel2.value) : 0 const subtotalAfterL2 = Math.max(0, subtotalAfterL1 - promoLevel2Disc) const total = Math.max(0, subtotalAfterL2 - discountAmount) return (
{/* Coupon Input */} {!savedCoupon && (
setCouponInput(e.target.value.toUpperCase())} placeholder={t('cart.couponPlaceholder', 'Discount Code')} className="flex-1 bg-white border border-spa-stone/20 rounded-lg px-3 py-2 text-sm text-pop-black focus:border-spa-forest outline-none uppercase tracking-widest placeholder:text-spa-stone/50" />
{couponError && {couponError}}
)} {/* Totals */}
ราคาสินค้า {formatPrice(subtotal)}
{promoLevel1Disc > 0 && (
{promoLevel1?.name} - {formatPrice(promoLevel1Disc)}
)} {promoLevel2Disc > 0 && (
{promoLevel2?.name} - {formatPrice(promoLevel2Disc)}
)} {(discountAmount > 0 || isFreeShipping) && savedCoupon && (
ส่วนลดคูปอง {savedCoupon} {isFreeShipping ? 'ส่งฟรี' : `- ${formatPrice(discountAmount)}`}
)} {savedCoupon && !couponValid && (
คูปอง {savedCoupon} (ยังไม่ถึงยอดขั้นต่ำ)
)}
รวมสุทธิ {formatPrice(total)}
{/* Checkout button */} ดำเนินการชำระเงิน
) }