function Inventory({ notify }) {
    const { products, getProductTotalStock, logActivity } = window.MockData;
    const currentUser = { name: 'Admin (Manager)' }; // Mock user context
    const [localProducts, setLocalProducts] = React.useState(products);
    
    // Modal State
    const [showStockModal, setShowStockModal] = React.useState(false);
    const [selectedProduct, setSelectedProduct] = React.useState(null);
    const [stockAdjustments, setStockAdjustments] = React.useState({}); // Map of variationId -> newStock

    const handleManageStock = (product) => {
        setSelectedProduct(product);
        const initialAdjustments = {};
        product.variations.forEach(v => {
            initialAdjustments[v.id] = v.stock;
        });
        setStockAdjustments(initialAdjustments);
        setShowStockModal(true);
    };

    const handleAdjustmentChange = (vid, val) => {
        setStockAdjustments(prev => ({
            ...prev,
            [vid]: parseInt(val) || 0
        }));
    };

    const saveStockChanges = () => {
        const updated = localProducts.map(p => {
            if (p.id === selectedProduct.id) {
                // Check for changes and log
                p.variations.forEach(v => {
                    const newStock = stockAdjustments[v.id];
                    if (newStock !== undefined && newStock !== v.stock) {
                        const diff = newStock - v.stock;
                        const actionType = diff > 0 ? "Stock Added" : "Stock Removed";
                        logActivity(
                            currentUser, 
                            "Inventory Adjustment", 
                            `${actionType}: ${p.name} (${v.size}) changed by ${diff > 0 ? '+' : ''}${diff} (Old: ${v.stock}, New: ${newStock})`
                        );
                    }
                });

                return {
                    ...p,
                    variations: p.variations.map(v => ({
                        ...v,
                        stock: stockAdjustments[v.id] !== undefined ? stockAdjustments[v.id] : v.stock
                    }))
                };
            }
            return p;
        });
        
        setLocalProducts(updated);
        window.MockData.products = updated;
        setShowStockModal(false);
        notify('Success', 'Stock levels updated successfully', 'success');
    };

    return (
        <div className="space-y-6">
            <h2 className="text-2xl font-bold text-gray-900">Inventory & Stock Intelligence</h2>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="card bg-gradient-to-br from-indigo-500 to-purple-600 text-white border-none">
                    <h3 className="text-indigo-100 text-sm font-medium mb-1">Total Stock Items</h3>
                    <p className="text-3xl font-bold">
                        {localProducts.reduce((acc, p) => acc + getProductTotalStock(p), 0)}
                    </p>
                    <p className="text-indigo-200 text-xs mt-2">Across {localProducts.length} Products</p>
                </div>
                <div className="card bg-gradient-to-br from-red-500 to-orange-600 text-white border-none">
                    <h3 className="text-red-100 text-sm font-medium mb-1">Low Stock Variations</h3>
                    <p className="text-3xl font-bold">
                        {localProducts.reduce((acc, p) => acc + p.variations.filter(v => v.stock < v.lowStockThreshold).length, 0)}
                    </p>
                    <p className="text-red-200 text-xs mt-2">Immediate attention needed</p>
                </div>
            </div>

            <div className="card">
                <h3 className="font-bold text-gray-800 mb-4">Stock Levels by Variation</h3>
                <div className="space-y-4">
                    {localProducts.map(product => (
                        <div key={product.id} className="p-4 border border-gray-100 rounded-lg bg-gray-50">
                            <div className="flex justify-between items-start mb-3">
                                <div className="flex items-center gap-3">
                                    <img src={product.image} className="w-10 h-10 rounded object-cover" />
                                    <div>
                                        <h4 className="font-medium text-gray-900">{product.name}</h4>
                                        <p className="text-xs text-gray-500">{product.variations.length} Variants</p>
                                    </div>
                                </div>
                                <button 
                                    onClick={() => handleManageStock(product)}
                                    className="text-xs text-[var(--primary)] font-medium border border-[var(--primary)] px-3 py-1.5 rounded hover:bg-[var(--primary)] hover:text-white transition-colors"
                                >
                                    Adjust Stock
                                </button>
                            </div>
                            
                            <div className="overflow-x-auto">
                                <table className="w-full text-xs text-left">
                                    <thead>
                                        <tr className="text-gray-500 border-b border-gray-200">
                                            <th className="py-2">Variation</th>
                                            <th className="py-2">SKU</th>
                                            <th className="py-2 text-center">Barcode</th>
                                            <th className="py-2 text-right">Current Stock</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {product.variations.map(v => (
                                            <tr key={v.id} className="border-b border-gray-100 last:border-0">
                                                <td className="py-2 font-medium">{v.size} {v.color && `(${v.color})`}</td>
                                                <td className="py-2 text-gray-500 font-mono">{v.sku}</td>
                                                <td className="py-2 text-center font-mono text-gray-400">{v.barcode}</td>
                                                <td className="py-2 text-right">
                                                    <span className={`px-2 py-1 rounded ${v.stock < v.lowStockThreshold ? 'bg-red-100 text-red-700 font-bold' : 'bg-green-100 text-green-700'}`}>
                                                        {v.stock}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    ))}
                </div>
            </div>

            {/* Manage Stock Modal */}
            <Modal isOpen={showStockModal} onClose={() => setShowStockModal(false)} title="Adjust Stock Levels">
                <div className="p-5">
                    {selectedProduct && (
                        <div className="space-y-4">
                            <div className="bg-gray-50 p-3 rounded-lg border border-gray-100 mb-4 flex items-center gap-3">
                                <img src={selectedProduct.image} className="w-12 h-12 rounded object-cover" />
                                <div>
                                    <h4 className="font-bold text-gray-900">{selectedProduct.name}</h4>
                                    <p className="text-xs text-gray-500">{selectedProduct.variations.length} variations</p>
                                </div>
                            </div>
                            
                            <div className="max-h-[300px] overflow-y-auto pr-2 space-y-3">
                                {selectedProduct.variations.map(v => (
                                    <div key={v.id} className="flex items-center justify-between p-2 border-b border-gray-100">
                                        <div>
                                            <p className="font-medium text-sm">{v.size} {v.color && `(${v.color})`}</p>
                                            <p className="text-xs text-gray-400 font-mono">{v.sku}</p>
                                        </div>
                                        <div className="flex items-center gap-2">
                                            <button 
                                                onClick={() => handleAdjustmentChange(v.id, (stockAdjustments[v.id] || 0) - 1)}
                                                className="w-8 h-8 bg-gray-100 rounded hover:bg-gray-200"
                                            >-</button>
                                            <input 
                                                type="number" 
                                                className="w-16 text-center border rounded py-1 font-bold"
                                                value={stockAdjustments[v.id]}
                                                onChange={(e) => handleAdjustmentChange(v.id, e.target.value)}
                                            />
                                            <button 
                                                onClick={() => handleAdjustmentChange(v.id, (stockAdjustments[v.id] || 0) + 1)}
                                                className="w-8 h-8 bg-gray-100 rounded hover:bg-gray-200"
                                            >+</button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                            
                            <div className="pt-4 border-t border-gray-100 mt-4">
                                <button onClick={saveStockChanges} className="btn btn-primary w-full">Confirm Updates</button>
                            </div>
                        </div>
                    )}
                </div>
            </Modal>
        </div>
    );
}