function Products({ notify }) {
    const { products, formatLKR, getProductTotalStock, logActivity } = window.MockData;
    // Get current user from localStorage or simple mock context if available, 
    // strictly we should pass 'user' prop to Products but we can assume 'Admin' for this module since it's admin only
    const currentUser = { name: 'Admin (Manager)' }; 

    const [localProducts, setLocalProducts] = React.useState(products);
    const [searchTerm, setSearchTerm] = React.useState('');
    const [categoryFilter, setCategoryFilter] = React.useState('All');
    
    // Modal & Form State
    const [showModal, setShowModal] = React.useState(false);
    const [isEditMode, setIsEditMode] = React.useState(false);
    
    // Extended Form Data
    const [formData, setFormData] = React.useState({
        id: '', name: '', category: '', brand: '', cost: '', price: '', image: '', 
        description: '',
        isMeasuring: false, // New: Track if it's a measuring item
        measureUnit: 'Meters', // New: Kg, Meters, etc.
        measureStock: 0, // New: Total stock for measuring items
        variations: []
    });
    
    // UI Helper States
    const [imagePreview, setImagePreview] = React.useState('');
    const [isNewCategory, setIsNewCategory] = React.useState(false);
    
    // Variation Input State (Simplified: Size & Stock only)
    const [sizeInput, setSizeInput] = React.useState('');
    const [stockInput, setStockInput] = React.useState('');

    // Derived Categories List
    const categories = React.useMemo(() => {
        const cats = new Set(localProducts.map(p => p.category));
        return ['All', ...Array.from(cats).sort()];
    }, [localProducts]);

    // Common Sizes for suggestions
    const commonSizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'Free Size'];

    const filteredProducts = localProducts.filter(p => {
        const matchesSearch = p.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
                              p.variations.some(v => v.sku.toLowerCase().includes(searchTerm.toLowerCase()));
        const matchesCategory = categoryFilter === 'All' || p.category === categoryFilter;
        return matchesSearch && matchesCategory;
    });

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                setImagePreview(reader.result);
                setFormData({ ...formData, image: reader.result });
            };
            reader.readAsDataURL(file);
        }
    };

    const handleEdit = (product) => {
        // Determine if measuring item based on data structure
        // If variations have size equal to a unit like 'Meters' or 'Kg', treat as measuring
        const firstVar = product.variations[0];
        const isMeasuring = firstVar && (firstVar.size === 'Meters' || firstVar.size === 'Kg' || firstVar.size === 'Yards');
        
        setFormData({ 
            ...product, 
            description: product.description || '',
            isMeasuring: isMeasuring,
            measureUnit: isMeasuring ? firstVar.size : 'Meters',
            measureStock: isMeasuring ? firstVar.stock : 0,
            variations: product.variations || []
        });
        setImagePreview(product.image);
        setIsNewCategory(false);
        setIsEditMode(true);
        setShowModal(true);
    };

    const handleAdd = () => {
        setFormData({
            id: '', name: '', category: '', brand: '', cost: '', price: '', 
            image: 'https://images.unsplash.com/photo-1557683316-973673baf926',
            description: '',
            isMeasuring: false,
            measureUnit: 'Meters',
            measureStock: 0,
            variations: []
        });
        setImagePreview('');
        setIsNewCategory(false);
        setIsEditMode(false);
        setShowModal(true);
    };

    // Helper: Auto Generate Codes
    const generateAutoCodes = (productName, category, brand, sizeOrUnit) => {
        const catCode = (category || 'GEN').substring(0, 3).toUpperCase();
        const brandCode = (brand || 'GEN').substring(0, 3).toUpperCase();
        const nameCode = (productName || 'PROD').split(' ').map(w => w[0]).join('').substring(0, 4).toUpperCase();
        const sizeCode = (sizeOrUnit || 'UNI').substring(0, 3).toUpperCase();
        const timestamp = Date.now().toString().slice(-4);
        const random = Math.floor(1000 + Math.random() * 9000);

        return {
            sku: `${catCode}-${brandCode}-${nameCode}-${sizeCode}-${timestamp}`,
            barcode: `2026${timestamp}${random}`
        };
    };

    const addVariation = () => {
        if (!sizeInput) {
            notify('Error', 'Please select or enter a size', 'error');
            return;
        }
        if (!stockInput || parseInt(stockInput) < 0) {
            notify('Error', 'Please enter valid stock count', 'error');
            return;
        }

        // Auto Generate SKU & Barcode
        const codes = generateAutoCodes(formData.name, formData.category, formData.brand, sizeInput);

        const variation = {
            id: `${formData.id || Date.now()}-${formData.variations.length + 1}`,
            size: sizeInput,
            color: 'N/A', // Deprecated as per requirement
            stock: parseInt(stockInput),
            sku: codes.sku,
            barcode: codes.barcode,
            lowStockThreshold: 5
        };
        
        setFormData({ ...formData, variations: [...formData.variations, variation] });
        // Reset inputs
        setSizeInput('');
        setStockInput('');
    };

    const removeVariation = (idx) => {
        const updated = [...formData.variations];
        updated.splice(idx, 1);
        setFormData({ ...formData, variations: updated });
    };

    const handleSave = async (e) => {
        e.preventDefault();
        
        if (!formData.category) {
            notify('Error', 'Product Category is required', 'error');
            return;
        }

        // Final Data Construction
        let finalVariations = [];

        if (formData.isMeasuring) {
            // For measuring items, create one variation representing the bulk stock
            const codes = generateAutoCodes(formData.name, formData.category, formData.brand, formData.measureUnit);
            finalVariations = [{
                id: `${formData.id || Date.now()}-1`,
                size: formData.measureUnit, // Use unit as size
                color: 'N/A',
                stock: parseFloat(formData.measureStock), // Allow decimals for measuring items? usually integers for simplicity in this mock
                sku: codes.sku,
                barcode: codes.barcode,
                lowStockThreshold: 10
            }];
        } else {
            // Standard items
            if (formData.variations.length === 0) {
                notify('Error', 'Please add at least one size variation', 'error');
                return;
            }
            finalVariations = formData.variations;
        }

        const finalProduct = {
            ...formData,
            variations: finalVariations
        };

        try {
            if (isEditMode) {
                // Check for Price Change
                const oldProduct = localProducts.find(p => p.id === formData.id);
                if (oldProduct && parseFloat(oldProduct.price) !== parseFloat(finalProduct.price)) {
                    logActivity(currentUser, "Price Change", `Updated price of ${finalProduct.name} from ${formatLKR(oldProduct.price)} to ${formatLKR(finalProduct.price)}`);
                }
                // General Update Log
                logActivity(currentUser, "Product Update", `Updated details for ${finalProduct.name}`);

                const result = await window.POSApiService.updateProduct(formData.id, finalProduct);
                if (result.success) {
                    const updated = localProducts.map(p => p.id === formData.id ? finalProduct : p);
                    setLocalProducts(updated);
                    window.MockData.products = updated;
                    notify('Success', 'Product updated successfully', 'success');
                } else {
                    notify('Error', result.error || 'Failed to update product', 'error');
                    return;
                }
            } else {
                // Creation log
                logActivity(currentUser, "New Product", `Created new product: ${finalProduct.name} (${finalProduct.category})`);

                const result = await window.POSApiService.createProduct(finalProduct);
                if (result.success) {
                    // Refresh data from backend to get correct IDs if needed
                    // But for immediate UI feedback we can just append
                    const newId = result.product_id || (localProducts.length > 0 ? Math.max(...localProducts.map(p => p.id)) + 1 : 1);
                    finalProduct.id = newId;
                    
                    const updated = [...localProducts, finalProduct];
                    setLocalProducts(updated);
                    window.MockData.products = updated;
                    notify('Success', 'New product created', 'success');
                } else {
                    notify('Error', result.error || 'Failed to create product', 'error');
                    return;
                }
            }
            setShowModal(false);
        } catch (err) {
            console.error("Save error:", err);
            notify('Error', 'An unexpected error occurred while saving', 'error');
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-2xl font-bold text-gray-900">Product Management</h2>
                <button onClick={handleAdd} className="btn btn-primary">
                    <span className="icon-plus mr-2"></span> Add Product
                </button>
            </div>

            {/* Filter Bar */}
            <div className="card">
                <div className="flex flex-col md:flex-row gap-4 mb-6">
                    <div className="flex-1 relative">
                        <span className="icon-search absolute left-3 top-2.5 text-gray-400"></span>
                        <input 
                            type="text" 
                            placeholder="Search by name, SKU..." 
                            className="input-field pl-10"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                    <select 
                        className="input-field w-full md:w-48 cursor-pointer"
                        value={categoryFilter}
                        onChange={(e) => setCategoryFilter(e.target.value)}
                    >
                        {categories.map(c => <option key={c} value={c}>{c}</option>)}
                    </select>
                </div>

                <div className="overflow-x-auto">
                    <table className="w-full text-left text-sm">
                        <thead className="bg-gray-50 text-gray-600 font-semibold border-b border-gray-200">
                            <tr>
                                <th className="px-4 py-3 rounded-tl-lg">Product</th>
                                <th className="px-4 py-3">Category</th>
                                <th className="px-4 py-3">Brand</th>
                                <th className="px-4 py-3 text-right">Unit Price</th>
                                <th className="px-4 py-3 text-center">Config</th>
                                <th className="px-4 py-3 text-center">Total Stock</th>
                                <th className="px-4 py-3 rounded-tr-lg text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100">
                            {filteredProducts.map(product => {
                                const totalStock = getProductTotalStock(product);
                                const isMeasuring = product.variations[0] && ['Meters', 'Kg', 'Yards'].includes(product.variations[0].size);
                                return (
                                <tr key={product.id} className="hover:bg-gray-50 transition-colors">
                                    <td className="px-4 py-3">
                                        <div className="flex items-center gap-3">
                                            <img src={product.image} alt="" className="w-10 h-10 rounded-md object-cover bg-gray-100" />
                                            <div>
                                                <p className="font-medium text-gray-900">{product.name}</p>
                                                <p className="text-xs text-gray-500">{isMeasuring ? `Sold per ${product.variations[0].size}` : `${product.variations.length} Sizes`}</p>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 text-gray-600">{product.category}</td>
                                    <td className="px-4 py-3 text-gray-600">{product.brand}</td>
                                    <td className="px-4 py-3 text-right font-medium text-gray-900">{formatLKR(product.price)}</td>
                                    <td className="px-4 py-3 text-center">
                                        {isMeasuring ? (
                                             <span className="badge bg-purple-100 text-purple-700">Measuring ({product.variations[0].size})</span>
                                        ) : (
                                            <div className="flex flex-wrap gap-1 justify-center max-w-[150px] mx-auto">
                                                {product.variations.map(v => (
                                                    <span key={v.id} className="px-1.5 py-0.5 bg-gray-100 rounded text-[10px] text-gray-600 border border-gray-200">
                                                        {v.size}
                                                    </span>
                                                ))}
                                            </div>
                                        )}
                                    </td>
                                    <td className="px-4 py-3 text-center">
                                        <span className={`font-bold ${totalStock < 10 ? 'text-red-600' : 'text-green-600'}`}>
                                            {totalStock} {isMeasuring ? product.variations[0].size.toLowerCase() : ''}
                                        </span>
                                    </td>
                                    <td className="px-4 py-3 text-center">
                                        <div className="flex items-center justify-center gap-2">
                                            <button onClick={() => handleEdit(product)} className="text-gray-400 hover:text-[var(--primary)]" title="Edit">
                                                <span className="icon-pencil w-4 h-4"></span>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            )})}
                        </tbody>
                    </table>
                </div>
            </div>
            
            {/* Add/Edit Product Modal */}
            <Modal isOpen={showModal} onClose={() => setShowModal(false)} title={isEditMode ? "Edit Product" : "Add New Product"} size="2xl">
                <form onSubmit={handleSave} className="p-5 space-y-4">
                    <div className="flex flex-col md:flex-row gap-6">
                        {/* Left Column: Image & Basic Info */}
                        <div className="w-full md:w-1/3 space-y-4">
                            <div className="relative w-full aspect-square rounded-lg bg-gray-100 border-2 border-dashed border-gray-300 overflow-hidden group">
                                {imagePreview ? (
                                    <img src={imagePreview} className="w-full h-full object-cover" />
                                ) : (
                                    <div className="flex flex-col items-center justify-center h-full text-gray-400">
                                        <span className="icon-image text-4xl mb-2"></span>
                                        <span className="text-xs">No Image</span>
                                    </div>
                                )}
                                <input 
                                    type="file" 
                                    accept="image/*" 
                                    onChange={handleImageChange}
                                    className="absolute inset-0 opacity-0 cursor-pointer"
                                />
                                <div className="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                                    <span className="text-white text-xs font-bold">Change Image</span>
                                </div>
                            </div>

                            {/* Measuring Item Toggle */}
                            <div className="bg-purple-50 p-3 rounded-lg border border-purple-100">
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input 
                                        type="checkbox" 
                                        className="rounded text-purple-600 focus:ring-purple-500 w-4 h-4"
                                        checked={formData.isMeasuring}
                                        onChange={(e) => setFormData({...formData, isMeasuring: e.target.checked})}
                                    />
                                    <span className="font-bold text-purple-900 text-sm">Measuring Item?</span>
                                </label>
                                <p className="text-[10px] text-purple-700 mt-1 ml-6">Check for fabrics, ropes, or weight-based items.</p>
                            </div>
                            
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Cost Price</label>
                                <input required type="number" className="input-field" value={formData.cost} onChange={(e) => setFormData({...formData, cost: e.target.value})} />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    {formData.isMeasuring ? `Price per ${formData.measureUnit}` : 'Selling Price'}
                                </label>
                                <input required type="number" className="input-field" value={formData.price} onChange={(e) => setFormData({...formData, price: e.target.value})} />
                            </div>
                        </div>

                        {/* Right Column: Details */}
                        <div className="w-full md:w-2/3 space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Product Name</label>
                                <input required type="text" className="input-field" value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} />
                            </div>
                            
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Category</label>
                                    {!isNewCategory ? (
                                        <div className="flex gap-2">
                                            <select 
                                                required 
                                                className="input-field flex-1"
                                                value={formData.category}
                                                onChange={(e) => {
                                                    if (e.target.value === 'NEW') {
                                                        setIsNewCategory(true);
                                                        setFormData({...formData, category: ''});
                                                    } else {
                                                        setFormData({...formData, category: e.target.value});
                                                    }
                                                }}
                                            >
                                                <option value="">Select Category</option>
                                                {categories.filter(c => c !== 'All').map(c => <option key={c} value={c}>{c}</option>)}
                                                <option value="NEW" className="font-bold text-[var(--primary)]">+ Add New Category</option>
                                            </select>
                                        </div>
                                    ) : (
                                        <div className="flex gap-2">
                                            <input 
                                                type="text" 
                                                autoFocus 
                                                className="input-field flex-1" 
                                                placeholder="Enter new category"
                                                value={formData.category} 
                                                onChange={(e) => setFormData({...formData, category: e.target.value})} 
                                            />
                                            <button 
                                                type="button" 
                                                onClick={() => setIsNewCategory(false)}
                                                className="px-3 py-2 bg-gray-200 rounded-lg hover:bg-gray-300"
                                                title="Cancel"
                                            >
                                                <span className="icon-x"></span>
                                            </button>
                                        </div>
                                    )}
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Brand</label>
                                    <input type="text" className="input-field" value={formData.brand} onChange={(e) => setFormData({...formData, brand: e.target.value})} />
                                </div>
                            </div>

                            {/* Dynamic Section based on Type */}
                            {formData.isMeasuring ? (
                                <div className="bg-purple-50 p-4 rounded-xl border border-purple-100">
                                    <h4 className="font-bold text-purple-900 mb-3 text-sm flex items-center gap-2">
                                        <span className="icon-ruler"></span> Measuring Details
                                    </h4>
                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <label className="block text-xs font-bold text-purple-800 mb-1">Unit of Measure</label>
                                            <select 
                                                className="input-field border-purple-200 focus:ring-purple-500"
                                                value={formData.measureUnit}
                                                onChange={(e) => setFormData({...formData, measureUnit: e.target.value})}
                                            >
                                                <option value="Meters">Meters</option>
                                                <option value="Yards">Yards</option>
                                                <option value="Kg">Kilograms (Kg)</option>
                                                <option value="Grams">Grams</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label className="block text-xs font-bold text-purple-800 mb-1">Total Stock ({formData.measureUnit})</label>
                                            <input 
                                                type="number" 
                                                className="input-field border-purple-200 focus:ring-purple-500"
                                                value={formData.measureStock}
                                                onChange={(e) => setFormData({...formData, measureStock: e.target.value})}
                                            />
                                        </div>
                                    </div>
                                    <div className="mt-3 text-xs text-purple-600">
                                        * SKU and Barcode will be generated automatically for this item.
                                    </div>
                                </div>
                            ) : (
                                <div className="bg-gray-50 p-4 rounded-xl border border-gray-200">
                                    <h4 className="font-bold text-gray-800 mb-3 text-sm flex items-center gap-2">
                                        <span className="icon-layers"></span> Size Variations
                                    </h4>
                                    
                                    {/* Existing Variations */}
                                    <div className="space-y-2 mb-4 max-h-32 overflow-y-auto">
                                        {formData.variations.map((v, idx) => (
                                            <div key={idx} className="flex items-center gap-2 bg-white p-2 rounded border border-gray-200 text-xs shadow-sm">
                                                <span className="font-bold w-12 bg-gray-100 py-1 px-2 rounded text-center">{v.size}</span>
                                                <div className="flex-1 px-2">
                                                    <div className="text-gray-900 font-medium">{v.stock} units</div>
                                                    <div className="text-[10px] text-gray-400 font-mono flex gap-2">
                                                        <span>SKU: {v.sku}</span>
                                                        <span>BC: {v.barcode}</span>
                                                    </div>
                                                </div>
                                                <button onClick={() => removeVariation(idx)} className="text-red-500 hover:text-red-700 ml-2 p-1">
                                                    <span className="icon-trash"></span>
                                                </button>
                                            </div>
                                        ))}
                                        {formData.variations.length === 0 && <p className="text-xs text-gray-400 text-center py-4 bg-white border border-dashed rounded">No sizes added yet.</p>}
                                    </div>

                                    {/* Add New Variation */}
                                    <div className="flex gap-2 items-end bg-white p-2 rounded border border-gray-200">
                                        <div className="w-1/3">
                                            <label className="text-[10px] uppercase font-bold text-gray-500 mb-1 block">Size</label>
                                            <input 
                                                list="size-suggestions"
                                                type="text" 
                                                className="input-field text-sm py-1.5" 
                                                placeholder="e.g. XL" 
                                                value={sizeInput} 
                                                onChange={(e) => setSizeInput(e.target.value.toUpperCase())} 
                                            />
                                            <datalist id="size-suggestions">
                                                {commonSizes.map(s => <option key={s} value={s} />)}
                                            </datalist>
                                        </div>
                                        <div className="w-1/3">
                                            <label className="text-[10px] uppercase font-bold text-gray-500 mb-1 block">Stock</label>
                                            <input 
                                                type="number" 
                                                className="input-field text-sm py-1.5" 
                                                placeholder="Qty" 
                                                value={stockInput} 
                                                onChange={(e) => setStockInput(e.target.value)} 
                                            />
                                        </div>
                                        <div className="w-1/3">
                                            <button 
                                                type="button" 
                                                onClick={addVariation} 
                                                className="w-full bg-gray-800 text-white rounded-lg text-xs font-bold py-2.5 hover:bg-black transition-colors"
                                            >
                                                Add Size
                                            </button>
                                        </div>
                                    </div>
                                    <p className="text-[10px] text-gray-400 mt-2 text-center">SKUs and Barcodes are generated automatically.</p>
                                </div>
                            )}
                        </div>
                    </div>

                    <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                        <button type="button" onClick={() => setShowModal(false)} className="btn btn-secondary">Cancel</button>
                        <button type="submit" className="btn btn-primary px-8">{isEditMode ? 'Update Product' : 'Create Product'}</button>
                    </div>
                </form>
            </Modal>
        </div>
    );
}