function Promotions() {
    const { promotions, products, formatLKR } = window.MockData;
    const [localPromotions, setLocalPromotions] = React.useState(promotions);
    const [showAddModal, setShowAddModal] = React.useState(false);
    const [isEditMode, setIsEditMode] = React.useState(false);
    
    // Form State
    const [formData, setFormData] = React.useState({
        id: '',
        name: '',
        type: 'seasonal',
        discountType: 'percentage', // percentage, fixed, bogo
        value: 5,
        bogoConfig: { buy: 1, get: 1 },
        startDate: '',
        endDate: '',
        description: '',
        applicableProducts: [] // array of IDs
    });

    // Product Search State in Modal
    const [productSearch, setProductSearch] = React.useState('');

    const resetForm = () => {
        setFormData({
            id: '',
            name: '',
            type: 'seasonal',
            discountType: 'percentage',
            value: 5,
            bogoConfig: { buy: 1, get: 1 },
            startDate: '',
            endDate: '',
            description: '',
            applicableProducts: []
        });
        setProductSearch('');
        setIsEditMode(false);
    };

    const handleSavePromo = (e) => {
        e.preventDefault();

        // Validate value
        const cleanValue = formData.value === '' ? 0 : parseFloat(formData.value);
        const finalData = { ...formData, value: cleanValue };
        
        if (isEditMode) {
            // Update existing (mock only, as backend API lacking update endpoint)
            const updated = localPromotions.map(p => p.id === formData.id ? { ...finalData, isActive: p.isActive } : p);
            setLocalPromotions(updated);
            window.MockData.promotions = updated;
        } else {
            // Create new
            const id = `p-${Date.now()}`;
            const promoToAdd = {
                ...finalData,
                id,
                isActive: true
            };
            
            if (window.POSApiService) {
                window.POSApiService.createPromotion(promoToAdd).catch(e => console.error("API error", e));
            }

            const updated = [...localPromotions, promoToAdd];
            setLocalPromotions(updated);
            window.MockData.promotions = updated;
        }
        
        setShowAddModal(false);
        resetForm();
    };

    const handleEditClick = (promo) => {
        setFormData({
            ...promo,
            bogoConfig: promo.bogoConfig || { buy: 1, get: 1 },
            applicableProducts: promo.applicableProducts || []
        });
        setIsEditMode(true);
        setShowAddModal(true);
    };

    const toggleStatus = (id) => {
        const updated = localPromotions.map(p => 
            p.id === id ? { ...p, isActive: !p.isActive } : p
        );
        setLocalPromotions(updated);
        window.MockData.promotions = updated;
    };

    const deletePromo = async (id) => {
        const ok = await window.AppDialog.confirm(
            'Delete Promotion',
            'Are you sure you want to delete this promotion? This cannot be undone.',
            'Delete'
        );
        if (ok) {
            const updated = localPromotions.filter(p => p.id !== id);
            setLocalPromotions(updated);
            window.MockData.promotions = updated;
        }
    };

    const toggleProductSelection = (productId) => {
        const current = formData.applicableProducts;
        if (current.includes(productId)) {
            setFormData({ ...formData, applicableProducts: current.filter(id => id !== productId) });
        } else {
            setFormData({ ...formData, applicableProducts: [...current, productId] });
        }
    };

    const getIconForType = (type) => {
        switch(type) {
            case 'seasonal': return 'icon-calendar';
            case 'card': return 'icon-credit-card';
            case 'clearance': return 'icon-tag';
            case 'loyalty': return 'icon-crown';
            case 'bogo': return 'icon-layers';
            default: return 'icon-percent';
        }
    };

    // Filter products for modal search
    const filteredProducts = products.filter(p => 
        p.name.toLowerCase().includes(productSearch.toLowerCase()) || 
        p.variations.some(v => v.sku.toLowerCase().includes(productSearch.toLowerCase()))
    );

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-2xl font-bold text-gray-900">Promotions & Offers</h2>
                <button onClick={() => { resetForm(); setShowAddModal(true); }} className="btn btn-primary">
                    <span className="icon-plus mr-2"></span> New Promotion
                </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {localPromotions.map(promo => (
                    <div key={promo.id} className={`card border-l-4 ${promo.isActive ? 'border-l-[var(--primary)]' : 'border-l-gray-300'} relative overflow-hidden group`}>
                        <div className="flex justify-between items-start mb-3">
                            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${promo.isActive ? 'bg-emerald-100 text-[var(--primary)]' : 'bg-gray-100 text-gray-400'}`}>
                                <span className={`${getIconForType(promo.type)} text-xl`}></span>
                            </div>
                            <div className="flex items-center gap-2">
                                <label className="relative inline-flex items-center cursor-pointer">
                                    <input type="checkbox" className="sr-only peer" checked={promo.isActive} onChange={() => toggleStatus(promo.id)} />
                                    <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[var(--primary)]"></div>
                                </label>
                                <button onClick={() => handleEditClick(promo)} className="text-gray-300 hover:text-blue-500">
                                    <span className="icon-pencil"></span>
                                </button>
                                <button onClick={() => deletePromo(promo.id)} className="text-gray-300 hover:text-red-500">
                                    <span className="icon-trash"></span>
                                </button>
                            </div>
                        </div>
                        
                        <h3 className="font-bold text-gray-900 mb-1">{promo.name}</h3>
                        <p className="text-sm text-gray-500 mb-3 min-h-[40px]">{promo.description}</p>
                        
                        <div className="flex items-center justify-between mt-4 pt-3 border-t border-gray-100">
                            <div>
                                <span className="text-2xl font-bold text-gray-800">
                                    {promo.discountType === 'percentage' ? `${promo.value}%` : 
                                     promo.discountType === 'fixed' ? formatLKR(promo.value) : 
                                     `BOGO ${promo.bogoConfig?.buy}+${promo.bogoConfig?.get}`}
                                </span>
                                {promo.discountType !== 'bogo' && <span className="text-xs text-gray-500 ml-1">OFF</span>}
                            </div>
                            <div className="text-right">
                                <p className="text-[10px] text-gray-400 uppercase tracking-wider font-semibold">Valid Until</p>
                                <p className="text-sm font-medium text-gray-700">{promo.endDate || 'Ongoing'}</p>
                            </div>
                        </div>

                        {/* Product Specific Badge */}
                        {promo.applicableProducts && promo.applicableProducts.length > 0 ? (
                            <div className="mt-2 text-xs text-gray-500 flex items-center gap-1">
                                <span className="icon-tag w-3 h-3"></span> {promo.applicableProducts.length} Specific Products
                            </div>
                        ) : (
                            <div className="mt-2 text-xs text-gray-500 flex items-center gap-1">
                                <span className="icon-store w-3 h-3"></span> Store-wide
                            </div>
                        )}

                        {!promo.isActive && (
                            <div className="absolute inset-0 bg-white/60 flex items-center justify-center z-10 pointer-events-none">
                                <span className="bg-gray-800 text-white px-3 py-1 rounded-full text-xs font-bold uppercase tracking-widest">Inactive</span>
                            </div>
                        )}
                    </div>
                ))}
            </div>

            {/* Add/Edit Modal */}
            {showAddModal && (
                <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm animate-fade-in">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl overflow-hidden flex flex-col max-h-[90vh]">
                        <div className="p-5 border-b border-gray-100 bg-gray-50 flex justify-between items-center flex-shrink-0">
                            <h3 className="font-bold text-gray-900">{isEditMode ? 'Edit Promotion' : 'Create New Promotion'}</h3>
                            <button onClick={() => setShowAddModal(false)}><span className="icon-x text-gray-400"></span></button>
                        </div>
                        
                        <div className="flex-1 overflow-y-auto p-6">
                            <form id="promoForm" onSubmit={handleSavePromo} className="space-y-6">
                                {/* Basic Info */}
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="col-span-2">
                                        <label className="block text-sm font-medium text-gray-700 mb-1">Promotion Name</label>
                                        <input 
                                            type="text" 
                                            required 
                                            className="input-field" 
                                            placeholder="e.g. Summer Sale"
                                            value={formData.name}
                                            onChange={(e) => setFormData({...formData, name: e.target.value})}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">Type</label>
                                        <select 
                                            className="input-field"
                                            value={formData.type}
                                            onChange={(e) => setFormData({...formData, type: e.target.value})}
                                        >
                                            <option value="seasonal">Seasonal Offer</option>
                                            <option value="card">Card Offer</option>
                                            <option value="clearance">Stock Clearance</option>
                                            <option value="loyalty">Loyalty Member Offer</option>
                                            <option value="bogo">Buy X Get Y (BOGO)</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">Discount Mode</label>
                                        <select 
                                            className="input-field"
                                            value={formData.discountType}
                                            onChange={(e) => setFormData({...formData, discountType: e.target.value})}
                                        >
                                            <option value="percentage">Percentage (%) Off</option>
                                            <option value="fixed">Fixed Amount (LKR) Off</option>
                                            <option value="bogo">Buy X Get Y Free</option>
                                        </select>
                                    </div>

                                    {/* Conditional Value Fields */}
                                    {formData.discountType === 'bogo' ? (
                                        <div className="col-span-2 grid grid-cols-2 gap-4 bg-blue-50 p-4 rounded-lg border border-blue-100">
                                            <div>
                                                <label className="block text-xs font-bold text-blue-700 mb-1">Buy Quantity</label>
                                                <input 
                                                    type="number" 
                                                    min="1"
                                                    className="input-field border-blue-200 focus:ring-blue-500"
                                                    value={formData.bogoConfig.buy}
                                                    onChange={(e) => setFormData({...formData, bogoConfig: { ...formData.bogoConfig, buy: parseInt(e.target.value) }})}
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-xs font-bold text-blue-700 mb-1">Get Free Quantity</label>
                                                <input 
                                                    type="number" 
                                                    min="1"
                                                    className="input-field border-blue-200 focus:ring-blue-500"
                                                    value={formData.bogoConfig.get}
                                                    onChange={(e) => setFormData({...formData, bogoConfig: { ...formData.bogoConfig, get: parseInt(e.target.value) }})}
                                                />
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="col-span-2">
                                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                                {formData.discountType === 'percentage' ? 'Percentage Value (%)' : 'Fixed Amount (LKR)'}
                                            </label>
                                            <input 
                                                type="number" 
                                                required 
                                                min="1" 
                                                className="input-field font-bold text-lg"
                                                value={formData.value}
                                                onChange={(e) => {
                                                    const val = e.target.value;
                                                    setFormData({
                                                        ...formData, 
                                                        value: val === '' ? '' : parseFloat(val)
                                                    });
                                                }}
                                            />
                                        </div>
                                    )}

                                    {/* Dates */}
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                                        <input 
                                            type="date" 
                                            required 
                                            className="input-field"
                                            value={formData.startDate}
                                            onChange={(e) => setFormData({...formData, startDate: e.target.value})}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
                                        <input 
                                            type="date" 
                                            required 
                                            className="input-field"
                                            value={formData.endDate}
                                            onChange={(e) => setFormData({...formData, endDate: e.target.value})}
                                        />
                                    </div>

                                    {/* Description */}
                                    <div className="col-span-2">
                                        <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
                                        <textarea 
                                            className="input-field h-20 resize-none" 
                                            placeholder="Details about the offer..."
                                            value={formData.description}
                                            onChange={(e) => setFormData({...formData, description: e.target.value})}
                                        ></textarea>
                                    </div>
                                </div>

                                {/* Product Selection */}
                                <div className="border-t border-gray-200 pt-6">
                                    <h4 className="font-bold text-gray-800 mb-2 flex items-center justify-between">
                                        <span>Applicable Products</span>
                                        <span className="text-xs font-normal bg-gray-100 px-2 py-1 rounded">
                                            {formData.applicableProducts.length === 0 ? 'Applied Store-wide' : `${formData.applicableProducts.length} Products Selected`}
                                        </span>
                                    </h4>
                                    
                                    <div className="bg-gray-50 p-4 rounded-xl border border-gray-200">
                                        <div className="relative mb-3">
                                            <span className="icon-search absolute left-3 top-2.5 text-gray-400"></span>
                                            <input 
                                                type="text" 
                                                placeholder="Search by name or code to select products..." 
                                                className="input-field pl-10 text-sm"
                                                value={productSearch}
                                                onChange={(e) => setProductSearch(e.target.value)}
                                            />
                                        </div>
                                        
                                        <div className="max-h-40 overflow-y-auto space-y-1 bg-white rounded-lg border border-gray-200">
                                            {filteredProducts.map(p => {
                                                const isSelected = formData.applicableProducts.includes(p.id);
                                                return (
                                                    <div 
                                                        key={p.id} 
                                                        onClick={() => toggleProductSelection(p.id)}
                                                        className={`p-2 flex items-center gap-3 cursor-pointer hover:bg-gray-50 text-sm border-b border-gray-50 last:border-0 ${isSelected ? 'bg-emerald-50' : ''}`}
                                                    >
                                                        <div className={`w-4 h-4 rounded border flex items-center justify-center ${isSelected ? 'bg-[var(--primary)] border-[var(--primary)]' : 'border-gray-300'}`}>
                                                            {isSelected && <span className="icon-check text-white text-[10px]"></span>}
                                                        </div>
                                                        <img src={p.image} className="w-8 h-8 rounded bg-gray-100 object-cover" />
                                                        <div className="flex-1">
                                                            <div className="font-medium text-gray-800">{p.name}</div>
                                                            <div className="text-xs text-gray-500">{p.variations[0].sku}</div>
                                                        </div>
                                                        {isSelected && <span className="text-xs text-[var(--primary)] font-bold">Selected</span>}
                                                    </div>
                                                );
                                            })}
                                            {filteredProducts.length === 0 && (
                                                <div className="p-4 text-center text-gray-400 text-sm">No products found</div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        
                        <div className="p-5 border-t border-gray-100 bg-gray-50 flex justify-end gap-3 flex-shrink-0">
                            <button onClick={() => setShowAddModal(false)} className="btn btn-secondary">Cancel</button>
                            <button onClick={() => document.getElementById('promoForm').requestSubmit()} className="btn btn-primary">
                                {isEditMode ? 'Update Promotion' : 'Create Promotion'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}