// Add custom (non-inventory) product to cart
function addCustomProductToCart() {
    const name = document.getElementById('customProductName').value.trim();
    const price = parseFloat(document.getElementById('customProductPrice').value);
    const qty = parseFloat(document.getElementById('customProductQty').value);
    if (!name) {
        alert('Enter product name');
        return;
    }
    if (isNaN(price) || price <= 0) {
        alert('Enter valid price');
        return;
    }
    if (isNaN(qty) || qty <= 0) {
        alert('Enter valid quantity');
        return;
    }
    // Use a unique negative id for custom products
    const customId = 'custom_' + Date.now() + '_' + Math.floor(Math.random()*10000);
    const cartKey = customId;
    cart.push({
        id: customId,
        cartKey: cartKey,
        name: name + ' (Custom)',
        price: price,
        priceType: 'Custom',
        quantity: qty,
        original_price: price,
        discounted_price: price,
        total: price * qty,
        stock: 999999 // No stock check for custom
    });
    updateCartDisplay();
    updateTotals();
    // Clear fields
    document.getElementById('customProductName').value = '';
    document.getElementById('customProductPrice').value = '';
    document.getElementById('customProductQty').value = 1;
}
// POS Terminal JavaScript
let cart = [];
let cartTotal = 0;
let currentHeldOrderId = null; // Track if current cart is from a resumed held order

// Add product to cart
function addToCart(product) {
    const productId = parseInt(product.id);
    const halfPrice = parseFloat(product.half_price) || 0;
    const fullPrice = parseFloat(product.price);

    // Detect if this addToCart call is from a barcode scan (set a flag before calling)
    if (window._barcodeScanInProgress) {
        addToCartWithPrice(product, fullPrice, 'Full Price');
        window._barcodeScanInProgress = false;
        return;
    }

    // Manual UI click: show modal if half price exists
    if (halfPrice > 0) {
        showPriceSelectionModal(product);
        return;
    }
    addToCartWithPrice(product, fullPrice, 'Full Price');
}

// Show price selection modal
function showPriceSelectionModal(product) {
    const modal = document.getElementById('priceSelectionModal');
    const productName = document.getElementById('modalProductName');
    const fullPriceBtn = document.getElementById('fullPriceBtn');
    const halfPriceBtn = document.getElementById('halfPriceBtn');
    
    productName.textContent = product.name;
    fullPriceBtn.textContent = `Full Price - Rs ${parseFloat(product.price).toFixed(2)}`;
    halfPriceBtn.textContent = `Half Price - Rs ${parseFloat(product.half_price).toFixed(2)}`;
    
    // Set click handlers
    fullPriceBtn.onclick = () => {
        addToCartWithPrice(product, parseFloat(product.price), 'Full Price');
        bootstrap.Modal.getInstance(modal).hide();
    };
    
    halfPriceBtn.onclick = () => {
        addToCartWithPrice(product, parseFloat(product.half_price), 'Half Price');
        bootstrap.Modal.getInstance(modal).hide();
    };
    
    new bootstrap.Modal(modal).show();
}

// Add product to cart with specific price
function addToCartWithPrice(product, selectedPrice, priceType) {
    const productId = parseInt(product.id);
    const cartKey = `${productId}_${priceType}`; // Unique key for same product with different prices
    
    const existingItem = cart.find(item => item.cartKey === cartKey);
    console.log('addToCartWithPrice called with:', product, selectedPrice, priceType);
    

    if (existingItem) {
        if (existingItem.quantity < product.stock) {
            existingItem.quantity++;
            existingItem.total = (existingItem.discounted_price ?? existingItem.price) * existingItem.quantity;
        } else {
            alert('Insufficient stock!');
            return;
        }
    } else {
        cart.push({
            id: productId,
            cartKey: cartKey,
            name: `${product.name} (${priceType})`,
            price: selectedPrice,
            priceType: priceType,
            quantity: 1,
            original_price: selectedPrice,
            discounted_price: selectedPrice, // default to no discount
            item_discount: 0,
            total: selectedPrice,
            stock: parseInt(product.stock)
        });
    }

    updateCartDisplay();
    updateTotals();
}

// Remove item from cart
function removeFromCart(cartKey) {
    console.log('Removing cart item:', cartKey); // Debug log
    console.log('Cart before removal:', cart.map(item => ({ cartKey: item.cartKey || item.id }))); // Debug log

    // Handle both old format (productId) and new format (cartKey)
    if (typeof cartKey === 'string' && cartKey.includes('_')) {
        cart = cart.filter(item => item.cartKey !== cartKey);
    } else {
        // Fallback for old format
        const numericProductId = parseInt(cartKey);
        cart = cart.filter(item => parseInt(item.id) !== numericProductId);
    }

    updateCartDisplay();
    updateTotals();
    console.log('Cart after removal:', cart); // Debug log
}

// Update quantity
function updateQuantity(cartKey, change) {
    let item;
    
    // Handle both old format (productId) and new format (cartKey)
    if (typeof cartKey === 'string' && cartKey.includes('_')) {
        item = cart.find(item => item.cartKey === cartKey);
    } else {
        const numericProductId = parseInt(cartKey);
        item = cart.find(item => parseInt(item.id) === numericProductId && !item.cartKey);
    }
    
    if (item) {
        const newQty = item.quantity + change;
        if (newQty <= 0) {
            removeFromCart(item.cartKey || item.id);
        } else if (newQty <= item.stock) {
            item.quantity = newQty;
            item.total = item.quantity * item.price;
            updateCartDisplay();
            updateTotals();
        } else {
            alert('Insufficient stock!');
        }
    }
}

// Update cart display
function updateCartDisplay() {
    const cartItems = document.getElementById('cartItems');

    if (cart.length === 0) {
        cartItems.innerHTML = `
            <div class="text-center text-muted py-5">
                <i class="fas fa-shopping-cart fa-3x"></i>
                <p>Cart is empty</p>
            </div>
        `;
        return;
    }



    cartItems.innerHTML = cart.map(item => {
        const itemKey = item.cartKey || item.id;
        return `
        <div class="cart-item">
            <div class="d-flex justify-content-between align-items-center">
                <div class="flex-grow-1">
                    <h6 class="mb-1">${item.name}</h6>
                    <small class="text-muted">Original: Rs ${item.original_price.toFixed(2)} each</small><br>
                    <small class="text-muted">Discount: <input type="number" min="0" max="${item.original_price}" step="0.01" value="${item.item_discount}" data-cart-key="${itemKey}" class="item-discount-input" style="width:60px;display:inline-block;"> </small><br>
                    <small class="text-muted">Unit Price: <input type="number" min="0.01" step="0.01" value="${item.discounted_price.toFixed(2)}" data-cart-key="${itemKey}" class="item-price-input" style="width:90px;display:inline-block;"> <button type="button" class="btn btn-link btn-sm p-0 ms-1 item-price-reset" data-cart-key="${itemKey}">Reset</button></small><br>
                    <small class="text-success">Now: Rs <span class="item-discounted-price">${item.discounted_price.toFixed(2)}</span> each</small>
                    ${item.priceType ? `<br><small class="badge bg-info">${item.priceType}</small>` : ''}
                </div>
                <button class="btn btn-sm btn-danger delete-btn" data-cart-key="${itemKey}" type="button">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
            <div class="d-flex justify-content-between align-items-center mt-2">
                <div class="btn-group" role="group">
                    <button class="btn btn-outline-secondary qty-btn" onclick="updateQuantity('${itemKey}', -1)" type="button">-</button>
                    <input type="text" class="form-control d-inline-block text-center item-qty-input" style="width:60px;display:inline-block;" value="${item.quantity}" data-cart-key="${itemKey}">
                    <button class="btn btn-outline-secondary qty-btn" onclick="updateQuantity('${itemKey}', 1)" type="button">+</button>
                </div>
                <strong>Rs ${item.total.toFixed(2)}</strong>
            </div>
        </div>
    `;
    }).join('');

    // Add event listeners for per-item discount changes
    // Discount input handler: only update price/total fields, not quantity or cart
    cartItems.querySelectorAll('.item-discount-input').forEach(input => {
        input.onchange = null;
        input.addEventListener('change', function(e) {
            const cartKey = this.getAttribute('data-cart-key');
            let discount = parseFloat(this.value) || 0;
            let item = cart.find(i => (i.cartKey || i.id) == cartKey);
            if (item) {
                if (discount < 0) discount = 0;
                if (discount >= item.original_price) {
                    discount = item.original_price - 0.01;
                    alert('Discount cannot be equal to or greater than the original price.');
                }
                item.item_discount = discount;
                item.discounted_price = item.original_price - discount;
                item.price = item.discounted_price; // keep unit price in sync for processing
                item.total = item.discounted_price * item.quantity;
                // Only update the price and total fields in the DOM
                const cartItemDiv = input.closest('.cart-item');
                const priceSpan = cartItemDiv.querySelector('.item-discounted-price');
                if (priceSpan) priceSpan.textContent = item.discounted_price.toFixed(2);
                const priceInput = cartItemDiv.querySelector('.item-price-input');
                if (priceInput) priceInput.value = item.discounted_price.toFixed(2);
                const totalStrong = cartItemDiv.querySelector('strong');
                if (totalStrong) totalStrong.textContent = `Rs ${item.total.toFixed(2)}`;
                this.value = discount.toFixed(2);
                updateTotals();
            }
        });
    });

    // Unit price change handler: directly set per-item unit price and derive discount
    cartItems.querySelectorAll('.item-price-input').forEach(input => {
        input.onchange = null;
        input.addEventListener('change', function() {
            const cartKey = this.getAttribute('data-cart-key');
            const newPrice = parseFloat(this.value);
            const item = cart.find(i => (i.cartKey || i.id) == cartKey);
            if (!item) return;
            if (isNaN(newPrice) || newPrice <= 0) {
                alert('Enter a valid unit price.');
                this.value = item.discounted_price.toFixed(2);
                return;
            }
            item.price = newPrice;
            item.discounted_price = newPrice;
            item.item_discount = Math.max(0, item.original_price - newPrice);
            item.total = newPrice * item.quantity;
            const cartItemDiv = input.closest('.cart-item');
            const discInput = cartItemDiv.querySelector('.item-discount-input');
            if (discInput) discInput.value = item.item_discount.toFixed(2);
            const priceSpan = cartItemDiv.querySelector('.item-discounted-price');
            if (priceSpan) priceSpan.textContent = item.discounted_price.toFixed(2);
            const totalStrong = cartItemDiv.querySelector('strong');
            if (totalStrong) totalStrong.textContent = `Rs ${item.total.toFixed(2)}`;
            updateTotals();
        });
    });

    // Reset price to original handler
    cartItems.querySelectorAll('.item-price-reset').forEach(btn => {
        btn.onclick = function() {
            const cartKey = this.getAttribute('data-cart-key');
            const item = cart.find(i => (i.cartKey || i.id) == cartKey);
            if (!item) return;
            item.price = item.original_price;
            item.discounted_price = item.original_price;
            item.item_discount = 0;
            item.total = item.discounted_price * item.quantity;
            const cartItemDiv = this.closest('.cart-item');
            const discInput = cartItemDiv.querySelector('.item-discount-input');
            if (discInput) discInput.value = '0.00';
            const priceInput = cartItemDiv.querySelector('.item-price-input');
            if (priceInput) priceInput.value = item.original_price.toFixed(2);
            const priceSpan = cartItemDiv.querySelector('.item-discounted-price');
            if (priceSpan) priceSpan.textContent = item.original_price.toFixed(2);
            const totalStrong = cartItemDiv.querySelector('strong');
            if (totalStrong) totalStrong.textContent = `Rs ${item.total.toFixed(2)}`;
            updateTotals();
        };
    });

    // Quantity input handler: only update quantity, price, and total fields
    cartItems.querySelectorAll('.item-qty-input').forEach(input => {
        input.onchange = null;
        input.addEventListener('change', function(e) {
            const cartKey = this.getAttribute('data-cart-key');
            let value = this.value.trim();
            if (value.includes('/')) {
                const parts = value.split('/');
                if (parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1]) && parseFloat(parts[1]) !== 0) {
                    value = parseFloat(parts[0]) / parseFloat(parts[1]);
                } else {
                    alert('Invalid fraction. Use format like 4/3.');
                    this.value = '';
                    return;
                }
            } else {
                value = parseFloat(value);
            }
            if (isNaN(value) || value <= 0) {
                alert('Invalid quantity.');
                this.value = '';
                return;
            }
            let item = cart.find(i => (i.cartKey || i.id) == cartKey);
            if (item) {
                if (value > item.stock) {
                    alert('Insufficient stock!');
                    this.value = item.stock;
                    value = item.stock;
                }
                item.quantity = value;
                item.total = item.discounted_price * item.quantity;
                // Only update the total field in the DOM
                const cartItemDiv = input.closest('.cart-item');
                const totalStrong = cartItemDiv.querySelector('strong');
                if (totalStrong) totalStrong.textContent = `Rs ${item.total.toFixed(2)}`;
                updateTotals();
            }
        });
    });

    // Use event delegation for delete buttons
    cartItems.querySelectorAll('.delete-btn').forEach(btn => {
        btn.onclick = function() {
            const cartKey = this.getAttribute('data-cart-key');
            console.log('Delete button clicked for cart key:', cartKey);
            removeFromCart(cartKey);
        };
    });
}

// Update totals
function updateTotals() {
    // Subtotal is sum of original prices (before per-item discount)
    const subtotal = cart.reduce((sum, item) => sum + (item.original_price * item.quantity), 0);
    // Total per-item discount
    const totalItemDiscount = cart.reduce((sum, item) => sum + (item.item_discount * item.quantity), 0);
    // Discount field (global discount)
    let discountRaw = document.getElementById('discount').value.trim();
    let discountAmount = 0;
    if (discountRaw.endsWith('%')) {
        let percent = parseFloat(discountRaw.replace('%','')) || 0;
        discountAmount = (subtotal - totalItemDiscount) * (percent / 100);
    } else {
        discountAmount = parseFloat(discountRaw) || 0;
    }
    // Final total
    const total = subtotal - totalItemDiscount - discountAmount;

    const subtotalElem = document.getElementById('subtotal');
    const totalElem = document.getElementById('total');
    const discountElem = document.getElementById('totalItemDiscount');
    if (subtotalElem) subtotalElem.textContent = `Rs ${subtotal.toFixed(2)}`;
    if (totalElem) totalElem.textContent = `Rs ${total.toFixed(2)}`;
    if (discountElem) discountElem.textContent = `Rs ${totalItemDiscount.toFixed(2)}`;

    cartTotal = total;
}

// Process payment
async function processPayment() {
    if (cart.length === 0) {
        alert('Cart is empty!');
        return;
    }

    const customerId = document.getElementById('customerSelect').value;
    const customerPhone = document.getElementById('customerPhone').value.trim();
    const paymentMethod = document.querySelector('input[name="paymentMethod"]:checked').value;
    const discount = document.getElementById('discount').value.trim();
    const paidAmountInput = document.getElementById('paidAmount');
    const paidAmount = parseFloat(paidAmountInput ? paidAmountInput.value : 0);

    if (paidAmountInput && paidAmountInput.value.trim() === '') {
        paidAmountInput.focus();
        alert('Please enter the amount paid by the customer.');
        return;
    }

    const salesOfficerSelect = document.getElementById('salesOfficerSelect');
    const salesOfficerId = salesOfficerSelect && salesOfficerSelect.value ? parseInt(salesOfficerSelect.value) : null;
    
    const saleData = {
        customer_id: customerId || null,
        customer_phone: customerPhone || null,
        payment_method: paymentMethod,
        discount: discount,
        sales_officer_id: salesOfficerId,
        items: cart,
        total: cartTotal,
        paid_amount: paidAmount,
        held_order_id: currentHeldOrderId // Include held order reference if resuming from held order
    };
    
    // Add voucher details if payment method is voucher
    if (paymentMethod === 'voucher') {
        saleData.voucher_value = parseFloat(document.getElementById('voucherValue').value) || 0;
        saleData.secondary_payment_method = document.getElementById('secondaryPaymentMethod').value || null;
        saleData.secondary_amount = parseFloat(document.getElementById('secondaryAmount').value) || 0;
    }

    try {
        const response = await fetch('process_sale.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(saleData)
        });
        const result = await response.json();

        if (result.success) {
            alert('Sale completed successfully!');
            printReceipt(result.sale_id);
            clearCart();
            currentHeldOrderId = null; // Reset held order ID after successful sale
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error processing sale: ' + error.message);
    }
}

// Clear cart
function clearCart() {
    cart = [];
    currentHeldOrderId = null; // Reset held order ID when clearing cart
    
    // Hide held order indicator
    const indicator = document.getElementById('heldOrderIndicator');
    if (indicator) {
        indicator.style.display = 'none';
    }
    
    updateCartDisplay();
    updateTotals();
    document.getElementById('customerSelect').value = '';
    document.getElementById('customerName').value = '';
    document.getElementById('customerPhone').value = '';
    document.getElementById('tableNumber').value = '';
    document.getElementById('discount').value = '0';
    document.getElementById('paidAmount').value = '';
    document.getElementById('remainingAmountDisplay').textContent = '';
}

// Print receipt
function printReceipt(saleId) {
    window.open(`receipt.php?id=${saleId}`, '_blank', 'width=800,height=600');
}

// Barcode scanner functionality
let lastScannedBarcode = '';
let lastScanTime = 0;
// Remove any existing event listeners by replacing the element (safe for single-page apps)
const barcodeInput = document.getElementById('barcodeInput');
if (barcodeInput) {
    const newBarcodeInput = barcodeInput.cloneNode(true);
    barcodeInput.parentNode.replaceChild(newBarcodeInput, barcodeInput);
    newBarcodeInput.addEventListener('keydown', async function(e) {
        if (e.key === 'Enter') {
            // Split input on whitespace and process all barcodes
            const input = this.value.trim();
            const barcodes = input.split(/\s+/).filter(b => b);
            this.value = '';
            for (let raw of barcodes) {
                // Sanitize barcode to remove any hidden control/unicode space characters
                const barcode = (raw + '')
                    .replace(/[\u00A0\u1680\u2000-\u200D\u202F\u205F\u3000]/g, '') // unicode spaces
                    .replace(/[\u0000-\u001F\u007F]/g, '') // control chars
                    .trim();
                const barcodeAlnum = barcode.replace(/[^A-Za-z0-9]/g, '');
                const now = Date.now();
                console.log('[DEBUG] Barcode event fired:', barcode, now);
                if (barcode) {
                    // Debounce: ignore if same barcode scanned within 1 second
                    if (barcode === lastScannedBarcode && (now - lastScanTime) < 1000) {
                        console.log('[DEBUG] Debounced duplicate barcode:', barcode);
                        continue;
                    }
                    lastScannedBarcode = barcode;
                    lastScanTime = now;
                    try {
                        // Fast path: resolve from preloaded map (no network)
                        let localList = (window.PRODUCTS_BY_BARCODE && window.PRODUCTS_BY_BARCODE[barcode]) || null;
                        if ((!localList || localList.length === 0) && barcodeAlnum) {
                            localList = window.PRODUCTS_BY_BARCODE && window.PRODUCTS_BY_BARCODE[barcodeAlnum];
                        }
                        if (localList && localList.length > 0) {
                            if (localList.length === 1) {
                                window._barcodeScanInProgress = true;
                                addToCart(localList[0]);
                            } else {
                                showProductSelectionModal(localList);
                            }
                            continue; // next barcode
                        }

                        // Fallback: call server API; robust JSON parse
                        const response = await fetch(`get_product.php?barcode=${encodeURIComponent(barcode)}`);
                        const raw = await response.text();
                        let product;
                        try {
                            product = raw ? JSON.parse(raw) : { success: false, message: 'Empty response' };
                        } catch(parseErr) {
                            console.error('Invalid JSON from get_product.php:', raw);
                            throw new Error('Server returned invalid response');
                        }
                        if (product.success && product.multiple && Array.isArray(product.data)) {
                            // Multiple products found for barcode: show selection modal
                            showProductSelectionModal(product.data);
                        } else if (product.success) {
                            // Single product found
                            window._barcodeScanInProgress = true;
                            addToCart(product.data);
                        } else {
                            alert('Product not found!');
                        }
// Modal for selecting among multiple products with the same barcode
function showProductSelectionModal(products) {
    // Remove any existing modal
    let oldModal = document.getElementById('barcodeProductSelectModal');
    if (oldModal) oldModal.remove();

    let modal = document.createElement('div');
    modal.id = 'barcodeProductSelectModal';
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.4)';
    modal.style.zIndex = '99999';
    modal.innerHTML = `
        <div style="background:#fff;max-width:500px;margin:80px auto;padding:24px;border-radius:8px;box-shadow:0 2px 12px #0002;position:relative;">
            <h5>Select Product/Price Batch</h5>
            <table class="table table-bordered table-sm mb-3">
                <thead><tr><th>Name</th><th>Price</th><th>Stock</th><th></th></tr></thead>
                <tbody>
                    ${products.map((p, i) => `
                        <tr>
                            <td>${p.name}</td>
                            <td>Rs ${parseFloat(p.price).toFixed(2)}</td>
                            <td>${p.stock}</td>
                            <td><button class="btn btn-primary btn-sm" onclick="window.selectBarcodeProduct(${i})">Select</button></td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
            <button class="btn btn-secondary" onclick="document.getElementById('barcodeProductSelectModal').remove()">Cancel</button>
        </div>
    `;
    document.body.appendChild(modal);
    // Expose selection function
    window.selectBarcodeProduct = function(idx) {
        addToCart(products[idx]);
        modal.remove();
    };
}
                    } catch (error) {
                        alert('Error searching product: ' + error.message);
                    }
                }
            }
        }
    });

    // Autocomplete suggestions for brand/product name typing
    // Debounce helper
    let suggestTimer = null;
    const suggestionsBox = document.getElementById('brandSuggestions');

    function hideSuggestions() {
        if (suggestionsBox) {
            suggestionsBox.style.display = 'none';
            suggestionsBox.innerHTML = '';
        }
    }

    function renderSuggestions(items) {
        if (!suggestionsBox) return;
        if (!items || items.length === 0) {
            hideSuggestions();
            return;
        }
        suggestionsBox.innerHTML = items.map(s => `
            <button type="button" class="list-group-item list-group-item-action suggestion-item" data-name="${s.name.replace(/"/g,'&quot;')}">
                <div class="d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-tag text-secondary me-2"></i>${s.name}</span>
                    ${typeof s.count === 'number' ? `<small class="text-muted">${s.count}</small>` : ''}
                </div>
            </button>
        `).join('');
        suggestionsBox.style.display = '';

        // Attach click handlers
        suggestionsBox.querySelectorAll('.suggestion-item').forEach(btn => {
            btn.addEventListener('click', () => {
                const name = btn.getAttribute('data-name');
                newBarcodeInput.value = name;
                filterProductsByName(name);
                hideSuggestions();
                newBarcodeInput.focus();
            });
        });
    }

    function filterProductsByName(term) {
        const lower = term.toLowerCase();
        document.querySelectorAll('.product-item').forEach(item => {
            const titleEl = item.querySelector('.card-title');
            const nameText = titleEl ? titleEl.textContent.trim().toLowerCase() : '';
            // Show items containing the name substring
            item.style.display = nameText.includes(lower) ? '' : 'none';
        });
    }

    function showAllProducts() {
        document.querySelectorAll('.product-item').forEach(item => {
            item.style.display = '';
        });
    }

    newBarcodeInput.addEventListener('input', function(e) {
        const q = this.value.trim();

        // Live filter grid by product name as user types
        if (q.length >= 1 && !/^\d+$/.test(q)) {
            filterProductsByName(q);
        } else if (q.length === 0) {
            showAllProducts();
        }

        // If user clears or types only digits (likely a barcode), hide suggestions and stop
        if (q.length < 2 || /^\d+$/.test(q)) { hideSuggestions(); return; }

        if (suggestTimer) clearTimeout(suggestTimer);
        suggestTimer = setTimeout(async () => {
            try {
                const res = await fetch(`search_brand.php?q=${encodeURIComponent(q)}`);
                const data = await res.json();
                if (data && data.success) {
                    renderSuggestions(data.suggestions || []);
                } else {
                    hideSuggestions();
                }
            } catch (err) {
                hideSuggestions();
            }
        }, 200);
    });

    // Hide suggestions when clicking outside or pressing Escape
    document.addEventListener('click', (evt) => {
        if (!suggestionsBox) return;
        const target = evt.target;
        if (target.id === 'barcodeInput' || suggestionsBox.contains(target)) return;
        hideSuggestions();
    });
    newBarcodeInput.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') hideSuggestions();
    });
}

// Category filter
document.querySelectorAll('.category-filter').forEach(button => {
    button.addEventListener('click', function() {
        const category = this.dataset.category;

        // Update button states
        document.querySelectorAll('.category-filter').forEach(btn => btn.classList.remove('active'));
        this.classList.add('active');

        // Filter products
        document.querySelectorAll('.product-item').forEach(item => {
            if (category === 'all' || item.dataset.category === category) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });
});

// Set initial state
document.querySelector('.category-filter[data-category="all"]').classList.add('active');