function POS({ notify, user, onChangeView }) {
    const { products, customers, paymentMethods, promotions, formatLKR, findProductByBarcode, findCreditNote, redeemCreditNote } = window.MockData;
    const [cart, setCart] = React.useState([]);
    const [searchQuery, setSearchQuery] = React.useState('');
    const [barcodeInput, setBarcodeInput] = React.useState('');
    const [isProcessing, setIsProcessing] = React.useState(false); // prevents double-click duplicate transactions
    
    // Customer Search States
    const [selectedCustomer, setSelectedCustomer] = React.useState(null);
    const [customerSearchQuery, setCustomerSearchQuery] = React.useState('');
    const [showCustomerResults, setShowCustomerResults] = React.useState(false);

    const [showPaymentModal, setShowPaymentModal] = React.useState(false);
    const [errorMsg, setErrorMsg] = React.useState('');
    
    // Promotion States
    const [activePromotions, setActivePromotions] = React.useState([]); // Global active promo IDs
    const [showPromoModal, setShowPromoModal] = React.useState(false);
    
    // Manual Removed Promos: Map of uniqueId -> boolean
    const [manualRemovedPromos, setManualRemovedPromos] = React.useState({});

    // Cash Payment States
    const [isCashPayment, setIsCashPayment] = React.useState(false);
    const [cashReceived, setCashReceived] = React.useState('');
    
    // Invoice Lookup State
    const [viewInvoice, setViewInvoice] = React.useState(null);
    const [changeDue, setChangeDue] = React.useState(0);

    // Credit Redemption Modal
    const [showCreditModal, setShowCreditModal] = React.useState(false);
    const [creditSearch, setCreditSearch] = React.useState('');

    // Refs
    const barcodeInputRef = React.useRef(null);
    const cashInputRef = React.useRef(null);
    const creditInputRef = React.useRef(null);

    // Initialize Active Promotions (Activate all by default on load for demo)
    React.useEffect(() => {
        const activeIds = promotions.filter(p => p.isActive).map(p => p.id);
        setActivePromotions(activeIds);
    }, []);

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

    // Filter Customers
    const filteredCustomers = customers.filter(c => 
        (c.name.toLowerCase().includes(customerSearchQuery.toLowerCase()) || 
         c.phone.includes(customerSearchQuery)) &&
        (!selectedCustomer || c.id !== selectedCustomer.id)
    );

    const handleCustomerSelect = (customer) => {
        setSelectedCustomer(customer);
        setCustomerSearchQuery('');
        setShowCustomerResults(false);
    };

    React.useEffect(() => {
        if (errorMsg) {
            const timer = setTimeout(() => setErrorMsg(''), 3000);
            return () => clearTimeout(timer);
        }
    }, [errorMsg]);

    React.useEffect(() => {
        if (isCashPayment && cashInputRef.current) cashInputRef.current.focus();
    }, [isCashPayment]);

    React.useEffect(() => {
        if (showCreditModal && creditInputRef.current) creditInputRef.current.focus();
    }, [showCreditModal]);

    // --- Core Cart Logic ---
    const addToCart = React.useCallback((product, variation = null) => {
        const targetVariation = variation || product.variations[0];
        
        // --- INVENTORY CHECK ---
        if (targetVariation.stock <= 0) {
            notify('Stock Error', `${product.name} (${targetVariation.size}) is out of stock!`, 'error');
            return;
        }

        const uniqueId = `${product.id}-${targetVariation.id}`;
        const existingItem = cart.find(item => item.uniqueId === uniqueId);
        
        if (existingItem) {
            if (existingItem.qty + 1 > targetVariation.stock) {
                notify('Stock Limit', `Only ${targetVariation.stock} units of ${product.name} (${targetVariation.size}) available in stock.`, 'warning');
                return;
            }
            setCart(prevCart => prevCart.map(item => 
                item.uniqueId === uniqueId ? { ...item, qty: item.qty + 1 } : item
            ));
        } else {
            setCart(prevCart => [...prevCart, { 
                ...product, 
                variation: targetVariation,
                uniqueId: uniqueId,
                qty: 1,
                price: product.price,
                type: 'product' 
            }]);
        }
    }, [cart, notify]);

    const addCreditNoteToCart = React.useCallback((creditNote) => {
        if (creditNote.isUsed) {
            notify('Error', 'This Credit Note has already been redeemed!', 'error');
            return;
        }
        // Check if already in cart
        if (cart.some(item => item.type === 'credit' && item.id === creditNote.creditId)) {
            notify('Info', 'Credit Note already applied!', 'info');
            return;
        }
        
        const isVoucher = creditNote.type === 'VOUCHER';
        
        setCart(prevCart => [...prevCart, {
            id: creditNote.creditId,
            name: isVoucher ? "Gift Voucher" : "Exchange Credit",
            variation: { size: isVoucher ? 'Voucher' : 'Return', sku: creditNote.creditId },
            uniqueId: creditNote.creditId,
            qty: 1,
            price: creditNote.amount, // Negative amount
            type: 'credit',
            image: isVoucher ? 'https://cdn-icons-png.flaticon.com/512/3219/3219355.png' : 'https://cdn-icons-png.flaticon.com/512/2331/2331941.png', 
            barcode: creditNote.barcode
        }]);
        notify('Success', `${isVoucher ? 'Gift Voucher' : 'Credit Note'} applied!`, 'success');
    }, [cart, notify]);

    // --- Silent Barcode Scanner Implementation ---
    // Instead of stealing focus, we use a global listener that accumulates keys
    React.useEffect(() => {
        let lastKeyTime = Date.now();
        let buffer = '';

        const processBarcode = (scannedCode) => {
            const code = scannedCode.trim().replace(/\s/g, '');
            if (!code) return;

            // 1. Check for Invoice Scan (e.g., INV-1001)
            if (code.toUpperCase().startsWith('INV-')) {
                const invoiceId = code.toUpperCase();
                const trx = window.MockData.transactions.find(t => t.id === invoiceId);
                if (trx) {
                    const details = window.MockData.getMockInvoiceDetails(invoiceId);
                    if (details) setViewInvoice({ ...trx, ...details });
                    else setErrorMsg(`Invoice ${invoiceId} details not found`);
                } else {
                    setErrorMsg(`Invoice ${invoiceId} not found`);
                }
                return;
            }

            // 2. Try to find product
            const scannedProduct = findProductByBarcode(code);
            if (scannedProduct) {
                addToCart(scannedProduct, scannedProduct.selectedVariation);
            } else {
                // 3. Try finding credit note
                const creditNote = findCreditNote(code);
                if (creditNote) {
                    addCreditNoteToCart(creditNote);
                } else {
                    setErrorMsg('Item not found: ' + code);
                }
            }
        };

        const handleGlobalKeyDown = (e) => {
            const isTyping = e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA';
            if (isTyping) return;

            const currentTime = Date.now();
            if (currentTime - lastKeyTime > 100) buffer = '';

            if (e.key === 'Enter') {
                if (buffer.length > 2) {
                    processBarcode(buffer);
                    buffer = '';
                }
            } else if (e.key.length === 1) {
                buffer += e.key;
            }
            lastKeyTime = currentTime;
        };

        document.addEventListener('keydown', handleGlobalKeyDown);
        return () => document.removeEventListener('keydown', handleGlobalKeyDown);
    }, [addToCart, addCreditNoteToCart, findProductByBarcode, findCreditNote]);

    const handleBarcodeScan = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            // Force strict trimming to ensure sync with Label Center
            const scannedCode = barcodeInput.trim().replace(/\s/g, ''); 
            if (!scannedCode) return;

            // 1. Check for Invoice Scan (e.g., INV-1001)
            if (scannedCode.toUpperCase().startsWith('INV-')) {
                const invoiceId = scannedCode.toUpperCase();
                // Find transaction
                const trx = window.MockData.transactions.find(t => t.id === invoiceId);
                if (trx) {
                    // Load details
                    const details = window.MockData.getMockInvoiceDetails(invoiceId);
                    if (details) {
                        setViewInvoice({ ...trx, ...details });
                    } else {
                        setErrorMsg(`Invoice ${invoiceId} details not found`);
                    }
                } else {
                    setErrorMsg(`Invoice ${invoiceId} not found`);
                }
                setBarcodeInput('');
                return;
            }

            // 2. Try to find product
            const scannedProduct = findProductByBarcode(scannedCode);
            if (scannedProduct) {
                addToCart(scannedProduct, scannedProduct.selectedVariation);
            } else {
                // 3. Try finding credit note (by barcode OR ID)
                const creditNote = findCreditNote(scannedCode);
                if (creditNote) {
                    addCreditNoteToCart(creditNote);
                } else {
                    setErrorMsg('Item not found (Product, Invoice or Credit Note)');
                }
            }
            setBarcodeInput('');
        }
    };

    // Dedicated Credit Note Lookup Handler
    const handleCreditNoteLookup = (e) => {
        e.preventDefault();
        const note = findCreditNote(creditSearch);
        if (note) {
            addCreditNoteToCart(note);
            setShowCreditModal(false);
            setCreditSearch('');
        } else {
            setErrorMsg('Invalid Credit Note ID or Barcode');
        }
    };

    const removeFromCart = (uniqueId) => {
        setCart(cart.filter(item => item.uniqueId !== uniqueId));
    };

    const updateQty = (uniqueId, change) => {
        setCart(cart.map(item => {
            if (item.uniqueId === uniqueId) {
                if (item.type === 'credit') return item;
                const newQty = item.qty + change;
                
                if (newQty < 1) return item;
                
                // --- INVENTORY CHECK ---
                if (change > 0 && newQty > item.variation.stock) {
                    notify('Stock Limit', `Only ${item.variation.stock} units available in stock.`, 'warning');
                    return item;
                }

                return { ...item, qty: newQty };
            }
            return item;
        }));
    };

    const togglePromoForItem = (uniqueId) => {
        setManualRemovedPromos(prev => ({
            ...prev,
            [uniqueId]: !prev[uniqueId]
        }));
    };

    // --- Promotion Calculation Logic ---

    // 1. Calculate Line Item Totals
    const calculatedCart = cart.map(item => {
        // Credit Notes: simple pass through
        if (item.type === 'credit') {
            return { 
                ...item, 
                finalTotal: item.price, // Amount is negative 
                discount: 0 
            };
        }

        let itemTotal = item.price * item.qty;
        let itemDiscount = 0;
        let appliedPromoName = '';
        
        if (!manualRemovedPromos[item.uniqueId]) {
            const applicablePromos = promotions.filter(p => 
                p.isActive && 
                Array.isArray(p.applicableProducts) && 
                p.applicableProducts.includes(item.id) &&
                activePromotions.includes(p.id)
            );

            applicablePromos.sort((a, b) => (a.discountType === 'bogo' ? -1 : 1));

            if (applicablePromos.length > 0) {
                const promo = applicablePromos[0];
                appliedPromoName = promo.name;

                if (promo.discountType === 'bogo') {
                    const { buy, get } = promo.bogoConfig;
                    const setSize = buy + get;
                    const freeSets = Math.floor(item.qty / setSize);
                    const freeQty = freeSets * get;
                    itemDiscount = freeQty * item.price;
                } else if (promo.discountType === 'fixed') {
                    itemDiscount = promo.value * item.qty;
                } else if (promo.discountType === 'percentage') {
                    itemDiscount = itemTotal * (promo.value / 100);
                }
            }
        }

        return {
            ...item,
            finalTotal: itemTotal - itemDiscount,
            discount: itemDiscount,
            appliedPromoName
        };
    });

    // 2. Subtotal
    const subtotal = calculatedCart.reduce((acc, item) => acc + item.finalTotal, 0);

    // 3. Cart-Level Promotions
    let cartLevelDiscount = 0;
    let cartPromoName = '';
    
    const cartPromos = promotions.filter(p => 
        p.isActive && 
        (!p.applicableProducts || p.applicableProducts.length === 0) &&
        activePromotions.includes(p.id) &&
        !(isCashPayment && p.type === 'card')
    );

    if (cartPromos.length > 0) {
        const promo = cartPromos[0];
        cartPromoName = promo.name;
        // Calculate base for discount: exclude credit notes and items that already got an item-level discount
        const eligibleForCartPromo = calculatedCart.filter(i => i.type !== 'credit' && i.discount === 0);
        const productSubtotal = eligibleForCartPromo.reduce((acc, i) => acc + i.finalTotal, 0);

        if (promo.discountType === 'fixed') {
            cartLevelDiscount = promo.value;
        } else if (promo.discountType === 'percentage') {
            cartLevelDiscount = productSubtotal * (promo.value / 100);
        }
    }

    const finalTotal = subtotal - cartLevelDiscount;

    // --- Actions ---

    const togglePromotion = (promoId) => {
        if (activePromotions.includes(promoId)) {
            setActivePromotions(activePromotions.filter(id => id !== promoId));
        } else {
            setActivePromotions([...activePromotions, promoId]);
        }
    };

    const handleCheckout = () => {
        if (cart.length === 0) return;
        if (finalTotal < 0) {
            setErrorMsg('Cannot checkout with negative total. Manual refund required.');
            return;
        }
        setShowPaymentModal(true);
        setIsCashPayment(false);
        setCashReceived('');
        setChangeDue(0);
    };

    const handleCashInput = (amount) => {
        setCashReceived(amount);
        const received = parseFloat(amount) || 0;
        setChangeDue(received - finalTotal);
    };

    const finalizeSale = async (methodId) => {
        // GUARD: prevent double-click / double submission
        if (isProcessing) return;
        setIsProcessing(true);

        const method = paymentMethods.find(m => m.id === methodId);
        let cashDetails = null;
        if (methodId === 'cash') {
            const received = parseFloat(cashReceived) || 0;
            if (received < finalTotal) {
                notify('Payment Error', 'Received amount is less than total bill amount!', 'error');
                setIsProcessing(false);
                return;
            }
            cashDetails = { received, change: received - finalTotal };
        }

        // Redeem used credit notes
        cart.forEach(item => {
            if (item.type === 'credit') redeemCreditNote(item.id); // pass ID or barcode
        });

        // Generate the invoice ID before sending to backend
        const invoiceId = `INV-${Date.now().toString().slice(-6)}`;

        const transactionData = {
            id: invoiceId, // Send the ID to the backend
            date: new Date().toISOString().slice(0, 19).replace('T', ' '),
            customer_id: selectedCustomer ? selectedCustomer.id : null,
            cashier_id: user && user.id ? user.id : 'admin',
            total_amount: subtotal,
            discount_amount: cartLevelDiscount,
            final_amount: finalTotal,
            payment_method: method ? method.name : 'Cash',
            status: 'completed',
            notes: 'Sale via POS',
            items: calculatedCart.map(item => ({
                product_id: item.id,
                variation_id: item.type === 'credit' ? null : item.variation?.id,
                quantity: item.qty,
                unit_price: item.price,
                discount_amount: item.discount,
                line_total: item.finalTotal
            }))
        };

        // Log transaction for debugging purposes
        console.log("Creating Transaction:", JSON.stringify(transactionData, null, 2));

        try {
            let finalInvoiceId;
            if (window.POSApiService) {
                const res = await window.POSApiService.createTransaction(transactionData);
                if (!res.success) throw new Error(res.error || "Failed to sync transaction");
                finalInvoiceId = res.transaction_id || invoiceId;
            } else {
                finalInvoiceId = invoiceId;
            }
            
            // Sync local data so Reports update immediately without a page refresh
            // Field names MUST match what Reports.js/Dashboard reads (normalized format)
            if (window.MockData && Array.isArray(window.MockData.transactions)) {
                const paymentLabel = method ? method.name : 'Cash';
                window.MockData.transactions.unshift({
                    id: finalInvoiceId,
                    date: transactionData.date,           // 'date' not 'transaction_date'
                    total: finalTotal,                    // 'total' not 'final_amount'
                    payment: paymentLabel,                // 'payment' not 'payment_method'
                    status: 'Completed',                  // Capital C — matches Reports filter
                    customer: selectedCustomer ? selectedCustomer.name : 'Guest',
                    customerId: transactionData.customer_id || null,
                    cashierId: transactionData.cashier_id,
                    items: transactionData.items.length,
                    discount_amount: transactionData.discount_amount,
                    total_amount: transactionData.total_amount,
                    final_amount: finalTotal,
                    notes: transactionData.notes
                });
            }
            
            generateReceipt(finalInvoiceId, calculatedCart, finalTotal, cartLevelDiscount, selectedCustomer, method ? method.name : 'Cash', cashDetails, user ? user.name : 'Unknown');
            setTimeout(() => {
                if (window.setupPrintConfig) window.setupPrintConfig('receipt');
                window.print();
            }, 500);

            setCart([]);
            setSelectedCustomer(null);
            setShowPaymentModal(false);
            setIsCashPayment(false);
            setManualRemovedPromos({});
            notify('Sale Completed', `Invoice ${finalInvoiceId} generated successfully`, 'success');
        } catch(err) {
            console.error("Transaction Error", err);
            notify('Transaction Error', err.message, 'error');
        } finally {
            setIsProcessing(false); // always release the lock
        }
    };

        // Helper to generate Receipt HTML
    const generateReceipt = (invoiceId, items, total, cartDiscount, customer, paymentMethod, cashDetails, cashierName) => {
        const printArea = document.getElementById('receipt-print-area');
        const labelArea = document.getElementById('print-area');

        if (!printArea) return;
        
        // Toggle print class
        document.body.classList.remove('printing-labels');
        document.body.classList.add('printing-receipt');
        
        // Clear BOTH areas to prevent overlap
        printArea.innerHTML = '';
        if (labelArea) labelArea.innerHTML = '';

        const now = new Date();
        // Safe ID for selector
        const safeId = invoiceId.replace(/[^a-zA-Z0-9]/g, '_');

        let itemsHtml = '';
        let subtotalAmt = 0;
        
        items.forEach(item => {
            const isCredit = item.type === 'credit';
            const originalPrice = item.price * item.qty;
            subtotalAmt += item.finalTotal;

            // Ensure promo name display is safe
            const promoText = item.discount > 0 ? 
                `<div style="font-weight:600; font-size:10px; margin-top:1px; color:#444;">* Promo: ${item.appliedPromoName} (-${formatLKR(item.discount)})</div>` : '';

            itemsHtml += `
                <tr>
                    <td class="desc">
                        ${isCredit ? '<b>CREDIT NOTE REDEEMED</b>' : item.name}<br/>
                        <span style="color:#555;font-size:10px;">${item.variation?.sku || 'N/A'}</span>
                        ${promoText}
                    </td>
                    <td class="qty">${item.qty}</td>
                    <td class="price">
                        ${item.discount > 0 ? `<span style="text-decoration:line-through; font-size:10px; color:#666;">${formatLKR(originalPrice)}</span><br/>` : ''}
                        ${formatLKR(item.finalTotal)}
                    </td>
                </tr>
            `;
        });

        printArea.innerHTML = `
            <div class="receipt-container">
                <div class="receipt-header">
                    <div class="receipt-logo">
                        <img src="components/noahvelle%20black%20logo%20no%20bg.png" alt="NOAHVELLE" />
                    </div>
                    <div class="receipt-meta">Shop 6, Level 3, Majestic City,<br/>No. 10, Station road, Colombo 4.</div>
                    <div class="receipt-meta" style="margin-top:5px; border-top:1px dotted #ccc; padding-top:2px;">
                        Date: ${now.toLocaleDateString()} &nbsp; Time: ${now.toLocaleTimeString()}
                    </div>
                    <div class="receipt-meta">Invoice: <b>${invoiceId}</b></div>
                </div>
                <table class="receipt-items">
                    <thead><tr><th class="desc">Item</th><th class="qty">Qty</th><th class="price">Amount</th></tr></thead>
                    <tbody>${itemsHtml}</tbody>
                </table>
                <div class="receipt-totals">
                    ${cartDiscount > 0 ? `
                        <div class="receipt-row"><span>Subtotal</span><span>${formatLKR(subtotalAmt + cartDiscount)}</span></div>
                        <div class="receipt-row"><span>Add. Discount</span><span>-${formatLKR(cartDiscount)}</span></div>
                    ` : ''}
                    <div class="receipt-row grand-total"><span>TOTAL PAYABLE</span><span>${formatLKR(total)}</span></div>
                    <div class="receipt-row" style="margin-top:5px;"><span>Customer</span><span>${customer ? customer.name : 'Guest'}</span></div>
                    <div class="receipt-row"><span>Cashier</span><span>${cashierName}</span></div>
                    <div class="receipt-row"><span>Payment</span><span>${paymentMethod}</span></div>
                    ${cashDetails ? `
                        <div class="receipt-row" style="border-top:1px dotted #ccc; margin-top:5px; padding-top:2px;"><span>Cash</span><span>${formatLKR(cashDetails.received)}</span></div>
                        <div class="receipt-row"><span>Change</span><span>${formatLKR(cashDetails.change)}</span></div>
                    ` : ''}
                </div>
                <div class="receipt-footer"><p>Thank you for shopping with NOAHVELLE!<br/>Returns within 3 days with receipt.</p></div>
                <div class="receipt-barcode-container"><svg id="receipt-barcode-${safeId}" class="receipt-barcode-svg"></svg></div>
                
                <div style="text-align: center; font-size: 10px; margin-top: 15px; color: #000; border-top: 1px solid #000; padding-top: 5px; font-weight: 700;">
                    <div>System Design and Developed by Pandan Labs</div>
                    <div style="font-size: 12px; margin-top: 2px; white-space: nowrap;">+94 70 693 2532</div>
                </div>
            </div>
        `;

        // Render Barcode with delay
        setTimeout(() => {
            try { 
                const barcodeLib = window.JsBarcode || (typeof JsBarcode !== 'undefined' ? JsBarcode : null);
                if (barcodeLib) {
                    barcodeLib(`#receipt-barcode-${safeId}`, invoiceId, { 
                        format: "CODE128", 
                        width: 2, 
                        height: 50, 
                        displayValue: true, 
                        fontSize: 14, 
                        margin: 0,
                        flat: true
                    }); 
                }
            } catch(e){
                console.error("Receipt barcode error:", e);
            }
        }, 100);
    };

    return (
        <div className="h-[calc(100vh-8rem)] flex gap-6 relative">
            {errorMsg && (
                <div className="absolute top-4 left-1/2 transform -translate-x-1/2 bg-red-600 text-white px-6 py-3 rounded-full shadow-lg z-50 flex items-center gap-2 animate-bounce">
                    <span className="icon-circle-alert text-xl"></span>
                    <span className="font-bold">{errorMsg}</span>
                </div>
            )}

            {/* Left Side: Product Selection */}
            <div className="flex-1 flex flex-col gap-4">
                {/* Barcode Scanner Indicator */}
                <div className="bg-slate-900 p-4 rounded-xl flex items-center gap-4 shadow-lg border border-slate-700">
                    <div className="w-12 h-12 bg-emerald-500/20 rounded-full flex items-center justify-center text-emerald-400 animate-pulse">
                        <span className="icon-scan-barcode text-2xl"></span>
                    </div>
                    <div className="flex-1">
                        <label className="text-slate-400 text-xs font-bold uppercase tracking-wider">Silent Barcode Scanner Active</label>
                        <p className="text-slate-500 text-sm">System is ready to scan. No need to click any bar.</p>
                        <input 
                            ref={barcodeInputRef}
                            type="text" 
                            style={{ position: 'absolute', opacity: 0, pointerEvents: 'none' }}
                            value={barcodeInput}
                            onChange={(e) => setBarcodeInput(e.target.value)}
                            onKeyDown={handleBarcodeScan}
                        />
                    </div>
                </div>

                {/* Search */}
                <div className="card p-4 flex gap-4">
                    <div className="relative flex-1">
                        <span className="icon-search absolute left-3 top-2.5 text-gray-400"></span>
                        <input 
                            type="text" 
                            placeholder="Search products..." 
                            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--primary)]"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                        />
                    </div>
                </div>

                {/* Product List */}
                <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 overflow-y-auto pr-2 pb-2">
                    {filteredProducts.map(product => (
                        <div 
                            key={product.id} 
                            onClick={() => addToCart(product)}
                            className="bg-white p-3 rounded-xl border border-gray-200 hover:shadow-md hover:border-[var(--primary)] cursor-pointer transition-all"
                        >
                            <div className="h-32 bg-gray-100 rounded-lg mb-3 overflow-hidden relative">
                                <img src={product.image} alt={product.name} className="w-full h-full object-cover" />
                                {/* Show if product has active promo */}
                                {promotions.some(p => p.isActive && p.applicableProducts?.includes(product.id)) && (
                                    <div className="absolute top-2 right-2 bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm">
                                        OFFER
                                    </div>
                                )}
                            </div>
                            <h3 className="font-semibold text-gray-800 text-sm truncate">{product.name}</h3>
                            <div className="flex justify-between items-center mt-2">
                                <span className="text-[var(--primary)] font-bold">{formatLKR(product.price)}</span>
                                <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded">{product.variations.length} Sizes</span>
                            </div>
                        </div>
                    ))}
                </div>
            </div>

            {/* Right Side: Cart */}
            <div className="w-[400px] flex flex-col card p-0 overflow-hidden">
                {/* Header */}
                <div className="p-4 border-b border-gray-100 bg-gray-50">
                    <div className="flex justify-between items-center mb-2">
                        <span className="text-sm font-semibold text-gray-600">Customer</span>
                        <button 
                            onClick={() => onChangeView('customers')}
                            className="text-[var(--primary)] text-sm font-medium hover:underline"
                        >
                            + New
                        </button>
                    </div>
                    
                    {/* Selected Customer Display or Search */}
                    {selectedCustomer ? (
                        <div className="flex items-center justify-between bg-white p-2 rounded-lg border border-emerald-200 shadow-sm">
                            <div className="flex items-center gap-2 overflow-hidden">
                                <div className="w-8 h-8 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center font-bold text-xs flex-shrink-0">
                                    {selectedCustomer.name.charAt(0)}
                                </div>
                                <div className="min-w-0">
                                    <p className="text-sm font-bold text-gray-800 truncate">{selectedCustomer.name}</p>
                                    <p className="text-[10px] text-gray-500 font-mono">{selectedCustomer.phone}</p>
                                </div>
                            </div>
                            <button onClick={() => setSelectedCustomer(null)} className="text-gray-400 hover:text-red-500 p-1">
                                <span className="icon-x"></span>
                            </button>
                        </div>
                    ) : (
                        <div className="relative">
                            <div className="relative">
                                <span className="icon-search absolute left-3 top-2.5 text-gray-400 text-sm"></span>
                                <input 
                                    type="text" 
                                    placeholder="Search by Name or Phone..." 
                                    className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-1 focus:ring-[var(--primary)] outline-none"
                                    value={customerSearchQuery}
                                    onChange={(e) => {
                                        setCustomerSearchQuery(e.target.value);
                                        setShowCustomerResults(true);
                                    }}
                                    onFocus={() => setShowCustomerResults(true)}
                                />
                            </div>
                            
                            {showCustomerResults && customerSearchQuery && (
                                <div className="absolute top-full left-0 right-0 mt-1 bg-white rounded-lg shadow-xl border border-gray-100 max-h-48 overflow-y-auto z-20">
                                    {filteredCustomers.length > 0 ? (
                                        filteredCustomers.map(c => (
                                            <div 
                                                key={c.id} 
                                                onClick={() => handleCustomerSelect(c)}
                                                className="p-2 hover:bg-gray-50 cursor-pointer border-b border-gray-50 last:border-0"
                                            >
                                                <p className="text-sm font-medium text-gray-800">{c.name}</p>
                                                <p className="text-xs text-gray-500 flex items-center gap-1">
                                                    <span className="icon-phone w-3 h-3"></span> {c.phone}
                                                </p>
                                            </div>
                                        ))
                                    ) : (
                                        <div className="p-3 text-center text-xs text-gray-400">No customers found</div>
                                    )}
                                </div>
                            )}
                        </div>
                    )}
                    {/* Click outside to close results listener could be added here or handled via simple layout */}
                    {showCustomerResults && customerSearchQuery && (
                        <div className="fixed inset-0 z-10" onClick={() => setShowCustomerResults(false)}></div>
                    )}
                </div>

                {/* Items */}
                <div className="flex-1 overflow-y-auto p-4 space-y-3">
                    {calculatedCart.length === 0 ? (
                        <div className="h-full flex flex-col items-center justify-center text-gray-400 opacity-50">
                            <span className="icon-shopping-cart text-4xl mb-2"></span>
                            <p>Cart is empty</p>
                        </div>
                    ) : (
                        calculatedCart.map(item => (
                            <div key={item.uniqueId} className={`flex gap-3 items-center p-2 rounded-lg ${item.type === 'credit' ? 'bg-red-50 border border-red-200' : 'bg-white'}`}>
                                <div className="w-10 h-10 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
                                    <img src={item.image} className="w-full h-full object-cover" />
                                </div>
                                <div className="flex-1 min-w-0">
                                    <h4 className={`text-sm font-medium truncate ${item.type === 'credit' ? 'text-red-700' : 'text-gray-900'}`}>{item.name}</h4>
                                    <div className="flex items-center gap-2 text-xs text-gray-500">
                                        {item.type === 'credit' ? (
                                             <span className="font-bold text-red-600 font-mono">{item.uniqueId}</span>
                                        ) : (
                                             <span className="font-bold">{formatLKR(item.price)}</span>
                                        )}
                                    </div>
                                    {/* Show discount info */}
                                    {item.discount > 0 ? (
                                        <div className="text-[10px] text-green-600 font-bold flex items-center gap-1 mt-1 group cursor-pointer" onClick={() => togglePromoForItem(item.uniqueId)} title="Click to remove promo">
                                            <span className="icon-tag w-3 h-3"></span> {item.appliedPromoName} (-{formatLKR(item.discount)})
                                            <span className="hidden group-hover:inline-block icon-x text-red-500 ml-1"></span>
                                        </div>
                                    ) : (
                                        manualRemovedPromos[item.uniqueId] && (
                                            <div className="text-[10px] text-gray-400 font-medium flex items-center gap-1 mt-1 cursor-pointer hover:text-green-600" onClick={() => togglePromoForItem(item.uniqueId)}>
                                                <span className="icon-ban w-3 h-3"></span> Promo Removed (Click to Restore)
                                            </div>
                                        )
                                    )}
                                </div>
                                <div className="flex flex-col items-end gap-1">
                                    <div className="flex items-center gap-2">
                                        {item.type !== 'credit' && (
                                            <>
                                                <button className="w-5 h-5 rounded-full bg-gray-100 flex items-center justify-center text-xs" onClick={() => updateQty(item.uniqueId, -1)}>-</button>
                                                <span className="text-sm font-medium w-4 text-center">{item.qty}</span>
                                                <button className="w-5 h-5 rounded-full bg-gray-100 flex items-center justify-center text-xs" onClick={() => updateQty(item.uniqueId, 1)}>+</button>
                                            </>
                                        )}
                                        <button className="text-gray-300 hover:text-red-500 ml-1" onClick={() => removeFromCart(item.uniqueId)}>
                                            <span className="icon-trash text-xs"></span>
                                        </button>
                                    </div>
                                    <div className={`font-bold text-sm ${item.type === 'credit' ? 'text-red-600' : 'text-gray-900'}`}>{formatLKR(item.finalTotal)}</div>
                                </div>
                            </div>
                        ))
                    )}
                </div>

                {/* Footer / Calculations */}
                <div className="p-4 bg-gray-50 border-t border-gray-200 space-y-2">
                    <div className="flex gap-2">
                        {/* Add Promo Button */}
                        <button 
                            onClick={() => setShowPromoModal(true)}
                            className="flex-1 py-2 border border-dashed border-[var(--primary)] text-[var(--primary)] rounded-lg text-sm font-medium hover:bg-emerald-50 transition-colors flex items-center justify-center gap-2"
                        >
                            <span className="icon-ticket-percent"></span> Offers
                        </button>
                        {/* Add Credit Note Button */}
                        <button 
                            onClick={() => setShowCreditModal(true)}
                            className="flex-1 py-2 border border-dashed border-red-500 text-red-600 rounded-lg text-sm font-medium hover:bg-red-50 transition-colors flex items-center justify-center gap-2"
                        >
                            <span className="icon-receipt"></span> Redeem
                        </button>
                    </div>

                    <div className="pt-2 space-y-1 text-sm text-gray-600">
                        <div className="flex justify-between">
                            <span>Subtotal</span>
                            <span>{formatLKR(subtotal)}</span>
                        </div>
                        {cartLevelDiscount > 0 && (
                            <div className="flex justify-between text-green-600">
                                <span>Cart Offer ({cartPromoName})</span>
                                <span>-{formatLKR(cartLevelDiscount)}</span>
                            </div>
                        )}
                        <div className="flex justify-between text-lg font-bold text-gray-900 border-t border-gray-200 pt-2 mt-2">
                            <span>Total Payable</span>
                            <span className={finalTotal < 0 ? 'text-red-600' : 'text-[var(--primary)]'}>{formatLKR(finalTotal)}</span>
                        </div>
                    </div>
                    
                    <button 
                        className={`w-full py-3 rounded-lg font-bold text-white mt-2 flex items-center justify-center gap-2 ${cart.length > 0 && finalTotal >= 0 ? 'bg-[var(--primary)] hover:bg-[var(--primary-dark)]' : 'bg-gray-300 cursor-not-allowed'}`}
                        disabled={cart.length === 0 || finalTotal < 0}
                        onClick={handleCheckout}
                    >
                        <span className="icon-credit-card"></span> {finalTotal < 0 ? 'Refund Required' : 'Proceed to Payment'}
                    </button>
                </div>
            </div>

            {/* Credit Note Redemption Modal */}
            <Modal isOpen={showCreditModal} onClose={() => setShowCreditModal(false)} title="Redeem Credit Note">
                <form onSubmit={handleCreditNoteLookup} className="p-5">
                    <p className="text-sm text-gray-500 mb-4">Enter Credit Note ID (e.g. CN-1234) or scan the barcode on the return receipt.</p>
                    <div className="mb-4">
                        <label className="block text-sm font-bold text-gray-700 mb-1">Credit ID / Barcode</label>
                        <input 
                            ref={creditInputRef}
                            type="text" 
                            className="input-field text-lg uppercase font-mono" 
                            placeholder="CN-XXXX or Scan" 
                            value={creditSearch}
                            onChange={(e) => setCreditSearch(e.target.value)}
                        />
                    </div>
                    <button type="submit" className="btn btn-primary w-full">Apply Credit</button>
                </form>
            </Modal>

            {/* Promotion Selection Modal */}
            {showPromoModal && (
                <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-md overflow-hidden animate-fade-in">
                        <div className="p-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                            <h3 className="font-bold text-gray-900">Active Global Promotions</h3>
                            <button onClick={() => setShowPromoModal(false)}><span className="icon-x text-gray-400"></span></button>
                        </div>
                        <div className="p-4 space-y-2 max-h-[400px] overflow-y-auto">
                            {promotions.filter(p => p.isActive).map(promo => {
                                const isApplied = activePromotions.includes(promo.id);
                                return (
                                    <div key={promo.id} 
                                        onClick={() => togglePromotion(promo.id)}
                                        className={`p-3 rounded-lg border cursor-pointer flex items-center gap-3 transition-colors ${isApplied ? 'bg-emerald-50 border-emerald-500' : 'bg-white border-gray-200 hover:bg-gray-50'}`}
                                    >
                                        <div className={`w-5 h-5 rounded border flex items-center justify-center flex-shrink-0 ${isApplied ? 'bg-emerald-500 border-emerald-500' : 'border-gray-300'}`}>
                                            {isApplied && <span className="icon-check text-white text-xs"></span>}
                                        </div>
                                        <div>
                                            <div className="font-bold text-sm text-gray-900">{promo.name}</div>
                                            <div className="text-xs text-gray-500">{promo.description}</div>
                                            {promo.type === 'bogo' && <div className="text-[10px] text-blue-600 font-bold mt-1">Buy {promo.bogoConfig.buy} Get {promo.bogoConfig.get} Free</div>}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                        <div className="p-4 border-t border-gray-100 bg-gray-50 text-right">
                            <button onClick={() => setShowPromoModal(false)} className="btn btn-primary text-sm">Done</button>
                        </div>
                    </div>
                </div>
            )}

            {/* Invoice View Modal */}
            <Modal isOpen={!!viewInvoice} onClose={() => setViewInvoice(null)} title="Invoice Details">
                {viewInvoice && (
                    <div className="p-4 space-y-4">
                        <div className="bg-gray-50 p-4 rounded-xl border border-gray-200">
                            <div className="flex justify-between items-center mb-2">
                                <h4 className="font-bold text-lg text-gray-900">{viewInvoice.id}</h4>
                                <span className={`badge ${viewInvoice.status === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                                    {viewInvoice.status}
                                </span>
                            </div>
                            <div className="text-sm text-gray-600 space-y-1">
                                <p>Date: <span className="font-medium text-gray-900">{viewInvoice.date}</span></p>
                                <p>Customer: <span className="font-medium text-gray-900">{viewInvoice.customer || 'Guest'}</span></p>
                                <p>Cashier: <span className="font-medium text-gray-900">{viewInvoice.cashierId}</span></p>
                                <p>Payment: <span className="font-medium text-gray-900">{viewInvoice.payment}</span></p>
                            </div>
                        </div>

                        <div className="max-h-60 overflow-y-auto border rounded-lg">
                            <table className="w-full text-sm text-left">
                                <thead className="bg-gray-100 text-gray-600">
                                    <tr>
                                        <th className="p-2">Item</th>
                                        <th className="p-2 text-right">Price</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {viewInvoice.items && viewInvoice.items.length > 0 ? (
                                        viewInvoice.items.map((item, idx) => (
                                            <tr key={idx}>
                                                <td className="p-2">
                                                    <div className="font-medium">{item.name}</div>
                                                    <div className="text-xs text-gray-500">{item.variation?.size}</div>
                                                </td>
                                                <td className="p-2 text-right font-bold">{formatLKR(item.price)}</td>
                                            </tr>
                                        ))
                                    ) : (
                                        <tr><td colSpan="2" className="p-4 text-center text-gray-400">Items data unavailable for mock invoice</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>

                        <div className="flex justify-between items-center pt-2 border-t border-gray-100">
                            <span className="font-bold text-gray-600">Total Amount</span>
                            <span className="font-bold text-xl text-[var(--primary)]">{formatLKR(viewInvoice.total)}</span>
                        </div>

                        <button 
                            onClick={() => {
                                // Re-print logic
                                // Need to reconstruct cart-like items for generateReceipt
                                // Using the viewInvoice.items directly
                                generateReceipt(
                                    viewInvoice.id, 
                                    viewInvoice.items.map(i => ({...i, qty: 1, finalTotal: i.price, discount: 0, type: 'product'})), 
                                    viewInvoice.total, 
                                    0, 
                                    viewInvoice.customerId ? {name: viewInvoice.customer} : null, 
                                    viewInvoice.payment, 
                                    null,
                                    viewInvoice.cashierId
                                );
                                setTimeout(() => {
                                    if (window.setupPrintConfig) window.setupPrintConfig('receipt');
                                    window.print();
                                }, 500);
                            }} 
                            className="btn btn-secondary w-full"
                        >
                            <span className="icon-printer mr-2"></span> Re-Print Receipt
                        </button>
                    </div>
                )}
            </Modal>

            {/* Payment Modal */}
            {showPaymentModal && (
                <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4 backdrop-blur-sm">
                    <div className="bg-white rounded-2xl w-full max-w-md overflow-hidden shadow-2xl animate-fade-in">
                        <div className="p-6 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                            <h3 className="text-lg font-bold text-gray-900">{isCashPayment ? 'Cash Payment' : 'Select Payment Method'}</h3>
                            <button onClick={() => setShowPaymentModal(false)} className="text-gray-400 hover:text-gray-600"><span className="icon-x text-xl"></span></button>
                        </div>
                        <div className="p-6">
                            <div className="mb-8 text-center">
                                <p className="text-sm text-gray-500 uppercase tracking-wide">Total Amount</p>
                                <p className="text-4xl font-bold text-[var(--primary)]">{formatLKR(finalTotal)}</p>
                            </div>
                            {!isCashPayment ? (
                                <div className="space-y-3 max-h-60 overflow-y-auto pr-2">
                                    {paymentMethods.map(method => (
                                        <button 
                                            key={method.id} 
                                            disabled={isProcessing}
                                            onClick={() => method.id === 'cash' ? setIsCashPayment(true) : finalizeSale(method.id)} 
                                            className={`w-full py-3 rounded-lg border-2 font-bold transition-all flex items-center justify-center gap-2 ${isProcessing ? 'border-gray-100 bg-gray-50 text-gray-300 cursor-not-allowed' : 'border-gray-200 text-gray-700 hover:bg-emerald-50 hover:border-[var(--primary)] hover:text-[var(--primary)]'}`}
                                        >
                                            <span className={isProcessing ? 'icon-loader-circle animate-spin' : method.icon}></span> {isProcessing ? 'Processing...' : method.name}
                                        </button>
                                    ))}
                                </div>
                            ) : (
                                <div className="space-y-6 animate-fade-in">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-2">Received Cash Amount</label>
                                        <div className="relative">
                                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 font-bold">LKR</span>
                                            <input ref={cashInputRef} type="number" className="w-full pl-14 pr-4 py-3 rounded-xl border-2 border-gray-300 focus:border-[var(--primary)] focus:ring-0 text-xl font-bold text-gray-800 outline-none" placeholder="0.00" value={cashReceived} onChange={(e) => handleCashInput(e.target.value)} />
                                        </div>
                                    </div>
                                    <div className={`p-4 rounded-xl border ${changeDue >= 0 ? 'bg-green-50 border-green-100' : 'bg-red-50 border-red-100'}`}>
                                        <div className="flex justify-between items-center">
                                            <span className={`text-sm font-bold ${changeDue >= 0 ? 'text-green-700' : 'text-red-700'}`}>{changeDue >= 0 ? 'Balance / Change Due' : 'Shortage'}</span>
                                            <span className={`text-2xl font-bold ${changeDue >= 0 ? 'text-green-700' : 'text-red-700'}`}>{formatLKR(Math.abs(changeDue))}</span>
                                        </div>
                                    </div>
                                    <div className="flex gap-3">
                                        <button onClick={() => setIsCashPayment(false)} disabled={isProcessing} className="flex-1 py-3 rounded-lg border border-gray-300 font-bold text-gray-600 hover:bg-gray-50 disabled:opacity-50">Back</button>
                                        <button onClick={() => finalizeSale('cash')} disabled={changeDue < 0 || isProcessing} className="flex-[2] py-3 rounded-lg bg-[var(--primary)] text-white font-bold hover:bg-[var(--primary-dark)] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2">
                                            {isProcessing ? <><span className="icon-loader-circle animate-spin"></span> Processing...</> : 'Complete Sale'}
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}