const { useState, useEffect, useCallback, useRef } = React;

const CartItem = ({ item, onUpdateQuantity, onRemove }) => {
    const { products } = useApp();
    const latestProduct = products.find(p => p.id === item.id);
    const stockQuantity = latestProduct?.stock_quantity || 0;
    const currentPrice = latestProduct?.price ?? item.price;
    const atLimit = item.quantity >= stockQuantity;

    return (
        <div className="cart-item">
            <div className="cart-item-image">
                {item.image_url ? (
                    <img src={item.image_url} alt={item.name} className="cart-item-img" />
                ) : (
                    <MetalIcon type={item.metal_type} size="md" />
                )}
            </div>
            <div className="cart-item-details">
                <div className="cart-item-name">{item.name}</div>
                <div className="cart-item-price">NT$ {currentPrice?.toLocaleString()}</div>
                <div className="cart-item-quantity">
                    <button
                        className="qty-btn"
                        onClick={() => onUpdateQuantity(item.id, item.quantity - 1)}
                        aria-label="減少數量"
                    >
                        <svg width="12" height="2" viewBox="0 0 12 2" fill="currentColor">
                            <rect width="12" height="2" rx="1"/>
                        </svg>
                    </button>
                    <span className="qty-value">{item.quantity}</span>
                    <button
                        className="qty-btn"
                        onClick={() => onUpdateQuantity(item.id, item.quantity + 1)}
                        disabled={atLimit}
                        aria-label="增加數量"
                    >
                        <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
                            <rect y="5" width="12" height="2" rx="1"/>
                            <rect x="5" width="2" height="12" rx="1"/>
                        </svg>
                    </button>
                    <button className="remove-btn" onClick={() => onRemove(item.id)}>
                        移除
                    </button>
                </div>
                {atLimit && (
                    <div style={{ color: '#d4a853', fontSize: '0.75rem', marginTop: 4 }}>
                        已達庫存上限（最多可購買 {stockQuantity} 件）
                    </div>
                )}
            </div>
        </div>
    );
};

const CartPage = ({ onCheckout }) => {
    const { cart, products, updateCartQuantity, removeFromCart } = useApp();

    const subtotal = cart.reduce((sum, item) => {
        const latestProduct = products.find(p => p.id === item.id);
        const currentPrice = latestProduct?.price ?? item.price;
        return sum + (currentPrice * item.quantity);
    }, 0);
    const shippingFee = subtotal >= 50000 ? 0 : 150;
    const total = subtotal + shippingFee;

    const animatedTotal = useAnimatedNumber(total);

    if (cart.length === 0) {
        return (
            <div className="cart-page">
                <div className="cart-empty">
                    <div className="cart-empty-icon">
                        <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
                            <circle cx="32" cy="32" r="28" stroke="currentColor" strokeWidth="2" fill="none"/>
                            <path d="M20 28H44M20 36H36" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                        </svg>
                    </div>
                    <p>購物車是空的</p>
                    <p>去看看有什麼好物吧</p>
                </div>
            </div>
        );
    }

    return (
        <div className="cart-page">
            {cart.map((item, index) => (
                <CartItem
                    key={item.id}
                    item={item}
                    onUpdateQuantity={updateCartQuantity}
                    onRemove={removeFromCart}
                />
            ))}

            <div className="cart-summary">
                <div className="summary-row">
                    <span>小計</span>
                    <span>NT$ {subtotal.toLocaleString()}</span>
                </div>
                <div className="summary-row">
                    <span>運費 {subtotal >= 50000 && <small>(滿5萬免運)</small>}</span>
                    <span>NT$ {shippingFee}</span>
                </div>
                <div className="summary-row total">
                    <span>總計</span>
                    <span className="amount">NT$ {animatedTotal.toLocaleString()}</span>
                </div>
            </div>

            <button className="checkout-btn" onClick={onCheckout}>
                前往結帳
            </button>
        </div>
    );
};
