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()
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.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 }: { 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)
React.useEffect(() => {
const code = localStorage.getItem('irelax_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: subtotal })
})
.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])
const removeCoupon = () => {
localStorage.removeItem('irelax_active_coupon')
setSavedCoupon(null)
setDiscountAmount(0)
setIsFreeShipping(false)
setCouponValid(false)
}
return (
{/* Totals */}
ราคาสินค้า
{formatPrice(subtotal)}
{(discountAmount > 0 || isFreeShipping) && savedCoupon && (
ส่วนลดคูปอง
{savedCoupon}
{isFreeShipping ? 'ส่งฟรี' : `- ${formatPrice(discountAmount)}`}
)}
{savedCoupon && !couponValid && (
คูปอง {savedCoupon} (ยังไม่ถึงยอดขั้นต่ำ)
)}
รวมสุทธิ
{formatPrice(Math.max(0, subtotal - discountAmount))}
{/* Checkout button */}
ดำเนินการชำระเงิน
)
}