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

const ProductCard = ({ product, onAddToCart, onClick, index = 0 }) => {
    const { user, cart } = useApp();
    const [isAdding, setIsAdding] = useState(false);

    const currentInCart = cart.find(item => item.id === product.id)?.quantity || 0;
    const atStockLimit = product.stock_quantity > 0 && currentInCart >= product.stock_quantity;

    const handleAdd = (e) => {
        e.stopPropagation();
        setIsAdding(true);
        onAddToCart(product);
        setTimeout(() => setIsAdding(false), 300);
    };

    const buttonDisabled = product.stock_quantity <= 0 || !user || atStockLimit;
    const buttonText = !user ? '登入購買'
        : product.stock_quantity <= 0 ? '補貨中'
        : atStockLimit ? '已達庫存上限'
        : '加入購物車';

    return (
        <div
            className="product-card product-card-clickable"
            style={{ animationDelay: `${index * 0.05}s` }}
            onClick={() => onClick && onClick(product)}
        >
            {product.image_url ? (
                <img src={product.image_url} alt={product.name} className="product-image" />
            ) : (
                <div className={`product-placeholder product-image ${product.metal_type}`}>
                    <MetalIcon type={product.metal_type} size="lg" />
                </div>
            )}
            <div className="product-info">
                <div className="product-name">{product.name}</div>
                {product.weight_grams && (
                    <div className="product-weight">
                        {product.weight_grams}g · {(product.purity * 100).toFixed(2)}%
                    </div>
                )}
                {user ? (
                    <div className="product-price">
                        NT$ {product.price?.toLocaleString()}
                        {product.show_tax_price != null && (
                            <span className={`tax-label ${product.show_tax_price ? 'tax-included' : 'tax-excluded'}`}>
                                {product.show_tax_price ? '(含稅)' : '(未稅)'}
                            </span>
                        )}
                    </div>
                ) : (
                    <div className="product-price price-hidden">登入查看</div>
                )}
                <div className={`product-stock ${product.stock_quantity <= 0 ? 'out-of-stock' : ''}`}>
                    {product.stock_quantity > 0 ? `庫存 ${product.stock_quantity}` : '已售完'}
                    {user?._ref && <span className="_sku">{user._ref}</span>}
                </div>
                <button
                    className={`add-to-cart-btn ${isAdding ? 'adding' : ''}`}
                    onClick={handleAdd}
                    disabled={buttonDisabled}
                >
                    <span>{buttonText}</span>
                </button>
            </div>
        </div>
    );
};

const ProductDetailModal = ({ product, onClose, onAddToCart }) => {
    const { user, cart } = useApp();
    const currentInCart = cart.find(item => item.id === product.id)?.quantity || 0;
    const atStockLimit = product.stock_quantity > 0 && currentInCart >= product.stock_quantity;
    const overlayRef = useRef(null);
    const contentRef = useRef(null);
    const closingRef = useRef(false);

    const animateClose = useCallback(() => {
        if (closingRef.current) return;
        closingRef.current = true;

        const content = contentRef.current;
        const overlay = overlayRef.current;
        if (!content || !overlay) { onClose(); return; }

        Motion.animate(content, { opacity: 0, transform: 'translateY(60px)' }, { duration: 0.2, easing: 'ease-in' })
            .then(() => Motion.animate(overlay, { opacity: 0 }, { duration: 0.1 }))
            .then(() => onClose());
    }, [onClose]);

    useEffect(() => {
        const overlay = overlayRef.current;
        const content = contentRef.current;
        if (!overlay || !content) return;

        Motion.animate(overlay, { opacity: [0, 1] }, { duration: 0.15 });
        Motion.animate(content,
            { opacity: [0, 1], transform: ['translateY(60px) scale(0.97)', 'translateY(0px) scale(1)'] },
            { duration: 0.35, easing: [0.22, 1, 0.36, 1] }
        );

        const handleKey = (e) => { if (e.key === 'Escape') animateClose(); };
        document.addEventListener('keydown', handleKey);
        document.body.style.overflow = 'hidden';
        return () => {
            document.removeEventListener('keydown', handleKey);
            document.body.style.overflow = '';
        };
    }, [animateClose]);

    const handleBackdropClick = (e) => {
        if (e.target === overlayRef.current) animateClose();
    };

    const handleAddToCart = () => {
        if (onAddToCart(product) !== false) {
            animateClose();
        }
    };

    return (
        <div className="product-modal-overlay" ref={overlayRef} onClick={handleBackdropClick}>
            <div className="product-modal-content" ref={contentRef}>
                <div className={`product-modal-image ${product.metal_type || ''}`}>
                    {product.image_url ? (
                        <img src={product.image_url} alt={product.name} />
                    ) : (
                        <div className="modal-placeholder">
                            <MetalIcon type={product.metal_type} size="lg" />
                        </div>
                    )}
                    <button className="product-modal-close" onClick={animateClose} aria-label="關閉">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                            <path d="M4 4L12 12M12 4L4 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                        </svg>
                    </button>
                </div>

                <div className="product-modal-body">
                    <div className="product-modal-name">{product.name}</div>
                    {product.description && (
                        <div className="product-modal-desc">{product.description}</div>
                    )}

                    <div className="product-modal-specs">
                        <div className="product-modal-spec">
                            <div className="product-modal-spec-label">材質</div>
                            <div className="product-modal-spec-value">{metalTypeLabel(product.metal_type)}</div>
                        </div>
                        <div className="product-modal-spec">
                            <div className="product-modal-spec-label">重量</div>
                            <div className="product-modal-spec-value">{product.weight_grams ? `${product.weight_grams}g` : '—'}</div>
                        </div>
                        <div className="product-modal-spec">
                            <div className="product-modal-spec-label">純度</div>
                            <div className="product-modal-spec-value">{product.purity ? `${(product.purity * 100).toFixed(2)}%` : '—'}</div>
                        </div>
                        <div className="product-modal-spec">
                            <div className="product-modal-spec-label">分類</div>
                            <div className="product-modal-spec-value">{product.category || '—'}</div>
                        </div>
                    </div>
                </div>

                <div className="product-modal-footer">
                    <div className="product-modal-price-block">
                        {user ? (
                            <div className="product-modal-price">
                                NT$ {product.price?.toLocaleString()}
                                {product.show_tax_price != null && (
                                    <span className={`tax-label ${product.show_tax_price ? 'tax-included' : 'tax-excluded'}`}>
                                        {product.show_tax_price ? '(含稅)' : '(未稅)'}
                                    </span>
                                )}
                            </div>
                        ) : (
                            <div className="product-modal-price price-hidden">登入查看價格</div>
                        )}
                        <div className={`product-modal-stock ${product.stock_quantity <= 0 ? 'out-of-stock' : ''}`}>
                            {product.stock_quantity > 0 ? `庫存 ${product.stock_quantity} 件` : '已售完'}
                            {user?._ref && <span className="_sku">{user._ref}</span>}
                        </div>
                    </div>
                    <button
                        className="product-modal-cart-btn"
                        onClick={handleAddToCart}
                        disabled={product.stock_quantity <= 0 || !user || atStockLimit}
                    >
                        {!user ? '登入購買' : product.stock_quantity <= 0 ? '補貨中' : atStockLimit ? '已達庫存上限' : '加入購物車'}
                    </button>
                </div>
            </div>
        </div>
    );
};

const ProductList = () => {
    const { products, cart, addToCart, showToast, metalPrices } = useApp();
    const [selectedCategory, setSelectedCategory] = useState('all');
    const [selectedProductId, setSelectedProductId] = useState(null);
    const selectedProduct = selectedProductId
        ? products.find(p => p.id === selectedProductId)
        : null;

    const categories = [...new Set(products.map(p => p.category).filter(Boolean))];

    const filteredProducts = selectedCategory === 'all'
        ? products
        : products.filter(p => p.category === selectedCategory);

    const groupedProducts = filteredProducts.reduce((acc, product) => {
        const category = product.category || '其他';
        if (!acc[category]) acc[category] = [];
        acc[category].push(product);
        return acc;
    }, {});

    const handleAddToCart = (product) => {
        if (addToCart(product)) {
            const newQty = (cart.find(item => item.id === product.id)?.quantity || 0) + 1;
            const maxStock = product.stock_quantity || 0;
            showToast(`已加入: ${product.name}（${newQty}/${maxStock}）`);
            return true;
        }
        return false;
    };

    return (
        <div className="product-list">
            <PriceBanner prices={metalPrices} />

            {categories.length > 0 && (
                <div className="nav-tabs" style={{ marginBottom: 16 }}>
                    <button
                        className={`nav-tab ${selectedCategory === 'all' ? 'active' : ''}`}
                        onClick={() => setSelectedCategory('all')}
                    >
                        全部
                    </button>
                    {categories.map(cat => (
                        <button
                            key={cat}
                            className={`nav-tab ${selectedCategory === cat ? 'active' : ''}`}
                            onClick={() => setSelectedCategory(cat)}
                        >
                            {cat}
                        </button>
                    ))}
                </div>
            )}

            {Object.entries(groupedProducts).map(([category, items]) => (
                <div key={category} className="category-section">
                    <h2 className="category-title">{category}</h2>
                    <div className="product-grid">
                        {items.map((product, idx) => (
                            <ProductCard
                                key={product.id}
                                product={product}
                                onAddToCart={handleAddToCart}
                                onClick={(product) => setSelectedProductId(product.id)}
                                index={idx}
                            />
                        ))}
                    </div>
                </div>
            ))}

            {products.length === 0 && (
                <div className="cart-empty">
                    <div className="cart-empty-icon">
                        <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
                            <rect x="8" y="16" width="48" height="40" rx="4" stroke="currentColor" strokeWidth="2" fill="none"/>
                            <path d="M24 16V12C24 7.58172 27.5817 4 32 4C36.4183 4 40 7.58172 40 12V16" stroke="currentColor" strokeWidth="2"/>
                        </svg>
                    </div>
                    <p>暫無商品</p>
                </div>
            )}

            {selectedProduct && (
                <ProductDetailModal
                    product={selectedProduct}
                    onClose={() => setSelectedProductId(null)}
                    onAddToCart={handleAddToCart}
                />
            )}
        </div>
    );
};
