<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS System</title>
    <script src="https://cdn.tailwindcss.com"></script>
   

    <style>
        /* Disable pull-to-refresh and overscroll */
        html {
            overscroll-behavior-y: none;
        }

        /* Hide scrollbar but keep functionality */
        .hide-scrollbar::-webkit-scrollbar {
            display: none;
        }

        .hide-scrollbar {
            -ms-overflow-style: none;
            scrollbar-width: none;
        }

        /* For iOS devices - smoother scrolling */
        .smooth-scroll {
            -webkit-overflow-scrolling: touch;
        }

        /* Prevent text selection */
        * {
            -webkit-user-select: none;
            user-select: none;
        }

        /* Allow text selection in inputs */
        input,
        textarea {
            -webkit-user-select: text;
            user-select: text;
        }

        /* Active state for buttons */
        .tab-active {
            @apply bg-blue-500 text-white;
        }
    </style>
   
</head>

<body class="bg-gray-100 h-screen overflow-hidden">
    <div id="loadingOverlay"
        class="fixed inset-0 bg-black bg-opacity-50 z-[9999] hidden flex items-center justify-center">
        <div class="bg-white p-6 rounded-lg shadow-xl flex flex-col items-center">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
            <p class="text-gray-700" id="loadingText">Đang tải dữ liệu...</p>
        </div>
    </div>
    <header class="bg-white shadow-sm p-3 h-16 fixed top-0 left-0 right-0 z-10">
        <div class="flex justify-between items-center h-full max-w-full mx-auto">
            <div class="flex items-center space-x-4">
                <!-- Logo/Title -->
                <div class="flex items-center space-x-3">
                    <h1 class="text-xl font-bold text-gray-800">POS System</h1>
                    <button id="syncButton" onclick="DataSyncManager.syncData()"
                        class="flex items-center space-x-1 px-3 py-1.5 bg-green-500 text-white text-sm rounded-lg hover:bg-green-600 transition-colors">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                        <span>Đồng bộ</span>
                    </button>
                </div>

                <!-- Barcode Section -->
                <div class="flex items-center">
                    <div class="relative">
                        <input type="text" id="barcodeInput" class="px-3 py-1.5 border rounded-lg w-56 text-sm"
                            placeholder="Quét mã sản phẩm..." autocomplete="off"
                            onkeydown="FocusManager.handleBarcodeInput(event)">
                    </div>
                </div>

                <!-- Shortcut Keys -->
                <div class="hidden lg:flex items-center gap-3 text-xs text-gray-600">
                    <div class="flex items-center">
                        <span class="bg-gray-100 px-2 py-0.5 rounded font-mono text-gray-700">F2</span>
                        <span class="ml-1">Tìm kiếm</span>
                    </div>
                    <div class="flex items-center">
                        <span class="bg-gray-100 px-2 py-0.5 rounded font-mono text-gray-700">ESC</span>
                        <span class="ml-1">Xóa giỏ</span>
                    </div>
                    <div class="flex items-center">
                        <span class="bg-gray-100 px-2 py-0.5 rounded font-mono text-gray-700">F4</span>
                        <span class="ml-1">Thanh toán</span>
                    </div>
                    <div class="flex items-center">
                        <span class="bg-gray-100 px-2 py-0.5 rounded font-mono text-gray-700">Ctrl+B</span>
                        <span class="ml-1">Quét mã</span>
                    </div>
                </div>

                <!-- Function Buttons -->
                <div class="flex items-center space-x-2">
                    <button id="customerDisplayBtn" onclick="CustomerDisplayManager.open()"
                        class="flex items-center space-x-1 px-3 py-1.5 bg-purple-500 text-white text-sm rounded-lg hover:bg-purple-600 transition-colors">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                        </svg>
                        <span>Màn hình phụ</span>
                    </button>

                    <button id="tableSelectionBtn" onclick="TableManager.openTableSelection()"
                        class="flex items-center space-x-1 px-3 py-1.5 bg-purple-500 text-white text-sm rounded-lg hover:bg-purple-600 transition-colors">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        <span>Chọn bàn</span>
                    </button>
                </div>
            </div>

            <!-- Search and Filters -->
            <div class="flex items-center gap-2">
                <input type="text" id="searchInput" placeholder="Tìm kiếm sản phẩm..."
                    class="px-3 py-1.5 border rounded-lg w-48 text-sm" oninput="FilterManager.filterProducts()">
                <select id="categoryFilter" class="px-3 py-1.5 border rounded-lg text-sm"
                    onchange="FilterManager.filterProducts()">
                    <option value="all">Tất cả danh mục</option>
                </select>
                <select id="priceFilter" class="px-3 py-1.5 border rounded-lg text-sm"
                    onchange="FilterManager.filterProducts()">
                    <option value="all">Tất cả giá</option>
                    <option value="0-20000">0đ - 20,000đ</option>
                    <option value="20000-50000">20,000đ - 50,000đ</option>
                    <option value="50000+">Trên 50,000đ</option>
                </select>
                <button onclick="FilterManager.resetFilters()"
                    class="flex items-center justify-center w-8 h-8 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                </button>
            </div>
        </div>
    </header>
    <!-- Modal Dialogs -->
    <div id="tableSelectionModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
        <div
            class="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-6 rounded-lg shadow-xl w-full max-w-4xl">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-2xl font-bold">Chọn bàn</h2>
                <div class="flex space-x-2">
                    <button onclick="TableTransferManager.openTransferModal()"
                        class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 flex items-center space-x-2"
                        id="transferTableBtn">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                        </svg>
                        <span>Chuyển bàn</span>
                    </button>
                    <button onclick="TableManager.closeTableSelection()"
                        class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600">
                        Đóng
                    </button>
                </div>
            </div>
            <div id="tableGrid" class="grid grid-cols-4 gap-4 mb-6">
                <!-- Tables will be dynamically inserted here -->
            </div>
            <div class="flex space-x-4">
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-green-100 rounded mr-2"></div>
                    <span>Bàn trống</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-yellow-100 rounded mr-2"></div>
                    <span>Đang có khách</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 bg-blue-100 rounded mr-2"></div>
                    <span>Bàn đang chọn</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="flex h-[calc(100vh-4rem)] mt-16">
        <!-- Product List Section (auto-expanding) -->
        <div class="flex-grow bg-gray-100 overflow-hidden">
            <div class="h-full overflow-y-auto p-4">
                <div id="productList" class="grid grid-cols-5 gap-4">
                    <!-- Products will be dynamically inserted here -->
                </div>
            </div>
        </div>

        <!-- Cart Section (fixed width) -->
        <!-- Cart Section (fixed width) -->
        <div class="w-1/3 bg-white shadow-lg flex flex-col h-[calc(100vh-5rem)]"> <!-- Add fixed height -->
            <!-- Cart Header -->
            <div class="p-4 border-b flex-shrink-0">
                <h2 class="text-xl font-semibold">Giỏ hàng</h2>
            </div>

            <!-- Cart Items (scrollable) -->
            <div id="cartItems" class="flex-1 overflow-y-auto p-4 space-y-4">
                <!-- Cart items will be dynamically inserted here -->
            </div>

            <!-- Fixed Cart Summary -->
            <div class="border-t bg-gray-50 p-4 space-y-3 flex-shrink-0">
                <!-- Subtotal -->
                <div class="flex justify-between items-center text-gray-600">
                    <span>Tạm tính:</span>
                    <span id="cartSubtotal" class="font-medium">0đ</span>
                </div>

                <!-- VAT -->
                <div class="flex justify-between items-center text-gray-600">
                    <span>VAT (10%):</span>
                    <span id="cartVat" class="font-medium">0đ</span>
                </div>

                <!-- Divider -->
                <div class="border-t border-gray-200 my-2"></div>

                <!-- Total -->
                <div class="flex justify-between items-center">
                    <span class="font-semibold text-lg">Tổng tiền:</span>
                    <span id="cartTotal" class="font-bold text-xl text-blue-600">0đ</span>
                </div>

                <!-- Checkout Button -->
                <button onclick="PaymentManager.openCheckoutModal()"
                    class="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center space-x-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                    </svg>
                    <span>Thanh toán</span>
                </button>
            </div>
        </div>
    </div>
    <script>
        // Table Transfer Manager
        const TableTransferManager = {
            // Mở modal chọn bàn để chuyển
            openTransferModal() {
                // Kiểm tra điều kiện chuyển bàn
                if (!AppState.selectedTableId) {
                    UIService.showNotification('Vui lòng chọn bàn trước khi chuyển!', 'error');
                    return;
                }
                if (AppState.cart.length === 0) {
                    UIService.showNotification('Không có món để chuyển!', 'error');
                    return;
                }

                const selectedTable = AppState.tables.find(t => t.IDBAN === AppState.selectedTableId);
                if (selectedTable['Tên bàn'] === 'Khách mua về') {
                    UIService.showNotification('Không thể chuyển từ bàn mang về!', 'error');
                    return;
                }

                const modalHtml = this.generateTransferModalHtml();
                document.body.insertAdjacentHTML('beforeend', modalHtml);

                // Render danh sách bàn có thể chuyển đến
                this.renderAvailableTables();
            },

            // Tạo HTML cho modal chuyển bàn
            generateTransferModalHtml() {
                const selectedTable = AppState.tables.find(t => t.IDBAN === AppState.selectedTableId);

                return `
            <div id="transferModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
                <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-2xl">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-2xl font-bold">Chuyển bàn</h2>
                        <button onclick="TableTransferManager.closeTransferModal()" 
                                class="text-gray-500 hover:text-gray-700">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>
                    
                    <div class="mb-4">
                        <p class="text-lg font-medium">Đang chuyển từ: ${selectedTable['Tên bàn']}</p>
                        <p class="text-gray-600">Tổng món: ${AppState.cart.length}</p>
                        <p class="text-gray-600">Tổng tiền: ${Utils.formatCurrency(Utils.calculateTotal(AppState.cart))}</p>
                    </div>

                    <div class="mb-4">
                        <h3 class="font-medium mb-2">Chọn bàn để chuyển đến:</h3>
                        <div id="availableTablesList" class="grid grid-cols-3 gap-4">
                            <!-- Available tables will be rendered here -->
                        </div>
                    </div>

                    <div class="flex justify-end gap-2 mt-4">
                        <button onclick="TableTransferManager.closeTransferModal()" 
                                class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600">
                            Hủy
                        </button>
                    </div>
                </div>
            </div>
        `;
            },

            // Render danh sách bàn có thể chuyển đến
            renderAvailableTables() {
                const tablesList = document.getElementById('availableTablesList');
                if (!tablesList) return;

                const availableTables = AppState.tables.filter(table =>
                    table.IDBAN !== AppState.selectedTableId && // Không phải bàn hiện tại
                    table['Tên bàn'] !== 'Khách mua về' && // Không phải bàn mang về
                    (!AppState.activeOrders.has(table.IDBAN) || // Không có đơn hàng
                        AppState.activeOrders.get(table.IDBAN).length === 0)
                );

                tablesList.innerHTML = availableTables.map(table => `
            <div onclick="TableTransferManager.transferToTable('${table.IDBAN}')"
                 class="p-4 bg-green-100 rounded-lg cursor-pointer hover:bg-green-200 transition-colors">
                <h4 class="font-medium">${table['Tên bàn']}</h4>
                <p class="text-sm text-gray-600">Sức chứa: ${table['Sức chứa tối đa']} người</p>
                <p class="text-sm text-gray-600">Trạng thái: ${table['Trạng thái']}</p>
            </div>
        `).join('');
            },

            // Xử lý chuyển bàn
            async transferToTable(targetTableId) {
                try {
                    UIService.showLoading('Đang chuyển bàn...');

                    const sourceTableId = AppState.selectedTableId;
                    const sourceTable = AppState.tables.find(t => t.IDBAN === sourceTableId);
                    const targetTable = AppState.tables.find(t => t.IDBAN === targetTableId);

                    // Cập nhật trạng thái bàn
                    if (sourceTable['Tên bàn'] !== 'Khách mua về') {
                        sourceTable['Trạng thái'] = 'Trống';
                    }
                    if (targetTable['Tên bàn'] !== 'Khách mua về') {
                        targetTable['Trạng thái'] = 'Đang sử dụng';
                    }

                    // Chuyển đơn hàng sang bàn mới
                    AppState.activeOrders.set(targetTableId, [...AppState.cart]);
                    AppState.activeOrders.delete(sourceTableId);

                    // Cập nhật bàn hiện tại và giỏ hàng
                    AppState.selectedTableId = targetTableId;
                    AppState.cart = AppState.activeOrders.get(targetTableId) || [];

                    // Cập nhật UI
                    CartManager.renderCart();
                    TableManager.updateTableButton(targetTable['Tên bàn']);
                    UIService.showNotification(`Đã chuyển từ ${sourceTable['Tên bàn']} sang ${targetTable['Tên bàn']}`);

                    // Đóng modal
                    this.closeTransferModal();
                    this.closeTableSelection();
                    CustomerDisplayManager.updateDisplay();
                } catch (error) {
                    console.error('Lỗi chuyển bàn:', error);
                    UIService.showNotification('Có lỗi xảy ra khi chuyển bàn!', 'error');
                } finally {
                    UIService.hideLoading();
                }
            },
            closeTableSelection() {
                document.getElementById('tableSelectionModal').classList.add('hidden');
            },

            // Đóng modal chuyển bàn
            closeTransferModal() {
                const modal = document.getElementById('transferModal');
                if (modal) {
                    modal.remove();
                }
            }
        };
        // Constants and Configurations
        const CONFIG = {
            appId: 'ab00cc33-e1ce-4e9c-80a4-35feded6205b',
            accessKey: 'V2-Qrb6D-bpPkv-CGv51-VvzZn-VZnXb-9ePlp-SvHIM-Gs8kJ',
            region: 'www',
            customerDisplayUrl: 'customer-display.html',
            timeouts: {
                notification: 2000,
                barcodeBuffer: 100
            }
        };

        // State Management
        const AppState = {
            allProducts: [],
            tables: [],
            cart: [],
            nhanvien : "",
            selectedTableId: null,
            activeOrders: new Map(),
            autoFocusEnabled: true,
            customerDisplay: null,
            barcodeBuffer: '',
            lastKeystrokeTime: Date.now()
        };
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }
        // Utilities
        const Utils = {
            formatCurrency(amount) {
                return new Intl.NumberFormat('vi-VN', {
                    style: 'currency',
                    currency: 'VND'
                }).format(amount);
            },

            generateId(prefix) {
                const timestamp = new Date().getTime();
                const random = Math.floor(Math.random() * 1000);
                return `${prefix}${timestamp}${random}`;
            },

            calculateTotal(items) {
                return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            },
            formatInputCurrency(input) {
                // Xóa tất cả ký tự không phải số
                let value = input.value.replace(/[^\d]/g, '');

                // Chuyển thành số
                let number = parseInt(value) || 0;

                // Format số theo định dạng tiền tệ Việt Nam
                let formattedValue = new Intl.NumberFormat('vi-VN', {
                    style: 'decimal',
                    maximumFractionDigits: 0
                }).format(number);

                // Cập nhật giá trị input
                input.value = formattedValue;

                // Lưu giá trị số thực vào data attribute
                input.dataset.value = number;

                return number;
            },

            // Hàm lấy giá trị số từ input đã format
            getNumericValue(input) {
                return parseInt(input.dataset.value) || 0;
            }
        };

        // API Service
        const ApiService = {
            async request(tableName, action, data) {
                const apiUrl = `https://${CONFIG.region}.appsheet.com/api/v2/apps/${CONFIG.appId}/tables/${tableName}/Action`;
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'ApplicationAccessKey': CONFIG.accessKey,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        Action: action,
                        Properties: {
                            Locale: "vi-VN",
                            Timezone: "Asia/Ho_Chi_Minh",
                        },
                        ...data
                    })
                });
                return response.json();
            },

            async fetchProducts() {
                return this.request('Sản phẩm', 'Find', {
                    Selector: "Filter(Sản phẩm, true)"
                });
            },

            async fetchTables() {
                return this.request('DSBAN', 'Find', {
                    Selector: "Filter(DSBAN, true)"
                });
            },

            async saveInvoice(invoice, details) {
                // API call to save invoice
                await this.request('HOADON', 'Add', { Rows: [invoice] });
                await this.request('HOADONDETAIL', 'Add', { Rows: details });
            }
        };

        // UI Service
        const UIService = {
            elements: {
                loadingOverlay: () => document.getElementById('loadingOverlay'),
                searchInput: () => document.getElementById('searchInput'),
                barcodeInput: () => document.getElementById('barcodeInput'),
                cartItems: () => document.getElementById('cartItems'),
                cartTotal: () => document.getElementById('cartTotal'),
                tableGrid: () => document.getElementById('tableGrid'),
                categoryFilter: () => document.getElementById('categoryFilter')
            },

            showLoading(message = 'Đang tải dữ liệu...') {
                const overlay = this.elements.loadingOverlay();
                const loadingText = document.getElementById('loadingText');
                loadingText.textContent = message;
                overlay.classList.remove('hidden');
                overlay.classList.add('flex');
            },

            hideLoading() {
                const overlay = this.elements.loadingOverlay();
                overlay.classList.add('hidden');
                overlay.classList.remove('flex');
            },

            showNotification(message, type = 'success') {
                let container = document.getElementById('notification-container');
                if (!container) {
                    container = document.createElement('div');
                    container.id = 'notification-container';
                    container.className = 'fixed bottom-4 left-4 flex flex-col gap-2 z-50';
                    document.body.appendChild(container);
                }

                const notification = document.createElement('div');
                notification.className = `
            flex items-center gap-2 px-6 py-3 rounded-lg shadow-lg 
            transform transition-all duration-300 -translate-x-full
            ${type === 'success' ? 'bg-green-500' : 'bg-red-500'} text-white
        `;

                notification.innerHTML = `
            <span>${type === 'success' ?
                        '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>' :
                        '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>'
                    }</span>
            <span>${message}</span>
        `;

                container.appendChild(notification);
                requestAnimationFrame(() => notification.style.transform = 'translateX(0)');

                setTimeout(() => {
                    notification.style.transform = 'translateX(-100%)';
                    notification.style.opacity = '0';
                    setTimeout(() => {
                        container.removeChild(notification);
                        if (container.children.length === 0) {
                            document.body.removeChild(container);
                        }
                    }, 300);
                }, CONFIG.timeouts.notification);
            }
        };

        // Table Manager
        const TableManager = {
            openTableSelection() {
                document.getElementById('tableSelectionModal').classList.remove('hidden');
                this.renderTables();
            },

            closeTableSelection() {
                document.getElementById('tableSelectionModal').classList.add('hidden');
            },

            renderTables() {
                const tableGrid = UIService.elements.tableGrid();
                tableGrid.innerHTML = AppState.tables.map(table => this.generateTableHtml(table)).join('');
            },

            generateTableHtml(table) {
                const hasOrder = AppState.activeOrders.has(table.IDBAN);
                const isCurrentTable = AppState.selectedTableId === table.IDBAN;
                const statusClass = this.getTableStatusClass(table, hasOrder);
                const orderTotal = hasOrder ? Utils.calculateTotal(AppState.activeOrders.get(table.IDBAN)) : 0;

                return `
            <div onclick="TableManager.selectTable('${table.IDBAN}')" 
                class="p-4 rounded-lg cursor-pointer border-2 ${statusClass} ${isCurrentTable ? 'ring-2 ring-blue-500' : ''}">
                <h3 class="font-bold">${table['Tên bàn']}</h3>
                <p class="text-sm">Sức chứa: ${table['Sức chứa tối đa']} người</p>
                ${this.generateTableStatusHtml(table, hasOrder, orderTotal)}
            </div>
        `;
            },

            getTableStatusClass(table, hasOrder) {
                if (table['Tên bàn'] === 'Khách mua về') {
                    return 'bg-gray-100 border-gray-200 hover:bg-gray-200';
                }
                return hasOrder || table['Trạng thái'] === 'Đang sử dụng' ?
                    'bg-yellow-100 border-yellow-200 hover:bg-yellow-200' :
                    'bg-green-100 border-green-200 hover:bg-green-200';
            },

            generateTableStatusHtml(table, hasOrder, orderTotal) {
                let html = '';
                if (table['Tên bàn'] !== 'Khách mua về') {
                    html += `<p class="text-sm font-medium ${hasOrder ? 'text-yellow-600' : ''}">${table['Trạng thái']}</p>`;
                }
                if (hasOrder) {
                    html += `
                <div class="mt-2 pt-2 border-t">
                    <p class="text-sm font-medium text-blue-600">
                        Đơn hiện tại: ${Utils.formatCurrency(orderTotal)}
                    </p>
                </div>
            `;
                }
                return html;
            },

            selectTable(tableId) {
                const table = AppState.tables.find(t => t.IDBAN === tableId);

                // Save current cart if exists
                if (AppState.selectedTableId && AppState.cart.length > 0) {
                    AppState.activeOrders.set(AppState.selectedTableId, [...AppState.cart]);
                }

                // Update selected table
                AppState.selectedTableId = tableId;
                AppState.cart = AppState.activeOrders.get(tableId) || [];

                if (table['Tên bàn'] !== 'Khách mua về' && table['Trạng thái'] === 'Trống') {
                    table['Trạng thái'] = 'Đang sử dụng';
                }

                // Update UI
                CartManager.renderCart();
                this.updateTableButton(table['Tên bàn']);
                UIService.showNotification(`Đã chuyển sang ${table['Tên bàn']}`);
                this.closeTableSelection();
            },

            updateTableButton(tableName) {
                const button = document.getElementById('tableSelectionBtn');
                button.innerHTML = `
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                    d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            <span>${tableName}</span>
        `;
            }
        };

        // Cart Manager
        const CartManager = {
            addToCart(productId) {
                // Check if table is selected
                if (!AppState.selectedTableId) {
                    UIService.showNotification('Vui lòng chọn bàn trước khi gọi món!', 'error');
                    TableManager.openTableSelection(); // Automatically open table selection
                    return;
                }

                const product = AppState.allProducts.find(p => p.IDSP === productId);
                if (!product) {
                    UIService.showNotification('Không tìm thấy sản phẩm!', 'error');
                    return;
                }

                const existingItem = AppState.cart.find(item => item.id === productId);
                if (existingItem) {
                    existingItem.quantity += 1;
                } else {
                    AppState.cart.push({
                        id: product.IDSP,
                        name: product['Tên sản phẩm'],
                        price: parseInt(product['Đơn giá']),
                        quantity: 1
                    });
                }

                this.updateCart();
                UIService.showNotification(`Đã thêm ${product['Tên sản phẩm']} vào giỏ hàng`);
            },

            removeFromCart(productId) {
                AppState.cart = AppState.cart.filter(item => item.id !== productId);
                this.updateCart();
                UIService.showNotification('Đã xóa sản phẩm khỏi giỏ hàng');
            },

            updateCart() {
                this.renderCart();
                this.updateCartSummary();
                if (AppState.customerDisplay && !AppState.customerDisplay.closed) {
                    CustomerDisplayManager.updateDisplay();
                }
            },
            updateCartSummary() {
                const subtotal = Utils.calculateTotal(AppState.cart);
                const vat = subtotal * 0.1;
                const total = subtotal + vat;

                // Update summary displays
                document.getElementById('cartSubtotal').textContent = Utils.formatCurrency(subtotal);
                document.getElementById('cartVat').textContent = Utils.formatCurrency(vat);
                document.getElementById('cartTotal').textContent = Utils.formatCurrency(total);

                // Update checkout button state
                const checkoutBtn = document.querySelector('button[onclick="PaymentManager.openCheckoutModal()"]');
                if (checkoutBtn) {
                    if (AppState.cart.length === 0) {
                        checkoutBtn.disabled = true;
                        checkoutBtn.classList.add('opacity-50', 'cursor-not-allowed');
                    } else {
                        checkoutBtn.disabled = false;
                        checkoutBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                    }
                }
            },
            renderCart() {
                const cartItems = UIService.elements.cartItems();
                cartItems.innerHTML = AppState.cart.map(this.generateCartItemHtml).join('');
                UIService.elements.cartTotal().textContent = Utils.formatCurrency(Utils.calculateTotal(AppState.cart));
            },

            generateCartItemHtml(item) {
                return `
            <div class="flex items-center justify-between bg-gray-50 p-3 rounded-lg">
                <div>
                    <h3 class="font-medium">${item.name}</h3>
                    <p class="text-sm text-gray-600">${Utils.formatCurrency(item.price)} x ${item.quantity}</p>
                </div>
                <div class="flex items-center space-x-2">
                    <button onclick="CartManager.adjustQuantity('${item.id}', -1)" 
                            class="w-8 h-8 flex items-center justify-center bg-gray-200 rounded-full hover:bg-gray-300">
                        -
                    </button>
                    <span class="w-8 text-center">${item.quantity}</span>
                    <button onclick="CartManager.adjustQuantity('${item.id}', 1)" 
                            class="w-8 h-8 flex items-center justify-center bg-gray-200 rounded-full hover:bg-gray-300">
                        +
                    </button>
                    <button onclick="CartManager.removeFromCart('${item.id}')"
                            class="w-8 h-8 flex items-center justify-center bg-red-500 text-white rounded-full hover:bg-red-600">
                        <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
            </div>
        `;
            },

            adjustQuantity(productId, amount) {
                const item = AppState.cart.find(item => item.id === productId);
                if (!item) return;

                item.quantity += amount;
                if (item.quantity <= 0) {
                    if (confirm('Bạn có muốn xóa sản phẩm này khỏi giỏ hàng?')) {
                        this.removeFromCart(productId);
                    } else {
                        item.quantity = 1;
                    }
                }
                this.updateCart();
            },

            clearCart() {
                if (AppState.cart.length === 0) return;

                if (confirm('Bạn có muốn xóa toàn bộ giỏ hàng?')) {
                    AppState.cart = [];
                    this.updateCart();
                    UIService.showNotification('Đã xóa toàn bộ giỏ hàng');
                }
            }
        };

        // Customer Display Manager
        const CustomerDisplayManager = {
            open() {
                if (AppState.customerDisplay && !AppState.customerDisplay.closed) {
                    AppState.customerDisplay.close();
                }

                const width = 800;
                const height = 600;
                const left = window.screen.width - width;
                AppState.customerDisplay = window.open(
                    CONFIG.customerDisplayUrl,
                    'CustomerDisplay',
                    `width=${width},height=${height},left=${left},top=0`
                );

                AppState.customerDisplay.onload = () => this.updateDisplay();
            },

            updateDisplay() {
                if (!AppState.customerDisplay || AppState.customerDisplay.closed) return;

                try {
                    const total = Utils.calculateTotal(AppState.cart);
                    // Lấy thông tin bàn hiện tại
                    const currentTable = AppState.tables.find(t => t.IDBAN === AppState.selectedTableId);
                    const tableInfo = currentTable ? {
                        id: currentTable.IDBAN,
                        name: currentTable['Tên bàn'],
                        capacity: currentTable['Sức chứa tối đa'],
                        status: currentTable['Trạng thái']
                    } : null;

                    AppState.customerDisplay.postMessage({
                        type: 'updateCart',
                        cart: AppState.cart,
                        totals: {
                            subtotal: total,
                            vat: total * 0.1,
                            discount: 0,
                            total: total * 1.1
                        },
                        tableInfo: tableInfo
                    }, window.location.origin);
                } catch (error) {
                    console.error('Lỗi khi cập nhật màn hình phụ:', error);
                }
            }
        };

        // Payment Manager
        const PaymentManager = {
            openCheckoutModal() {
                if (AppState.cart.length === 0) {
                    UIService.showNotification('Giỏ hàng trống!', 'error');
                    return;
                }
                if (!AppState.selectedTableId) {
                    UIService.showNotification('Vui lòng chọn bàn trước khi thanh toán!', 'error');
                    return;
                }

                const total = Utils.calculateTotal(AppState.cart);
                const vat = total * 0.1;
                const finalTotal = total + vat;
                const selectedTable = AppState.tables.find(t => t.IDBAN === AppState.selectedTableId);

                const modalHtml = this.generateCheckoutModalHtml(selectedTable, total, vat);
                document.body.insertAdjacentHTML('beforeend', modalHtml);

                // Thêm event listeners
                const discountInput = document.getElementById('discountInput');
                const paidAmountInput = document.getElementById('paidAmount');

                if (discountInput) {
                    discountInput.addEventListener('input', () => this.updateFinalTotal());
                }

                if (paidAmountInput) {
                    // Format giá trị ban đầu
                    Utils.formatInputCurrency(paidAmountInput);
                    paidAmountInput.addEventListener('input', () => {
                        Utils.formatInputCurrency(paidAmountInput);
                        this.updateChange();
                    });
                }
                // Tính toán ban đầu
                this.updateFinalTotal();
                this.updateChange();
            },
          
            generateCheckoutModalHtml(table, total, vat) {
                return `
            <div id="checkoutModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
                <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-2xl">
                    <h2 class="text-2xl font-bold mb-4">Thanh toán</h2>
                    
                    <!-- Basic Info -->
                    <div class="grid grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Bàn</label>
                            <input type="text" value="${table['Tên bàn']}" readonly 
                                class="mt-1 block w-full rounded-md border-gray-300 bg-gray-50">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Nhân viên</label>
                            <input type="text" id="employeeInput" value="${AppState.nhanvien}"  disabled
                                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Khách hàng</label>
                            <input type="text" id="customerInput" value="Khách lẻ" 
                                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
                        </div>
                    </div>

                    <!-- Payment Info -->
                    <div class="space-y-3">
                        <div class="flex justify-between">
                            <span>Tổng tiền hàng:</span>
                            <span>${Utils.formatCurrency(total)}</span>
                        </div>
                        <div class="flex justify-between">
                            <span>VAT (10%):</span>
                            <span>${Utils.formatCurrency(vat)}</span>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Giảm giá</label>
                            <input type="number" id="discountInput" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500" 
                                value="0">
                        </div>
                        <div class="flex justify-between font-bold text-lg">
                            <span>Tổng cộng:</span>
                            <span id="finalTotal">${Utils.formatCurrency(total + vat)}</span>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Khách trả</label>
                            <input type="text" 
                    value="${new Intl.NumberFormat('vi-VN').format(total + vat)}" 
                    id="paidAmount" 
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                    oninput="Utils.formatInputCurrency(this)"
                    onkeypress="return event.charCode >= 48 && event.charCode <= 57">    </div>
                        <div class="flex justify-between text-lg">
                            <span>Tiền thừa:</span>
                            <span id="changeAmount">0đ</span>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Ghi chú</label>
                            <textarea id="noteInput" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"></textarea>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="mt-6 flex justify-end space-x-3">
                        <button onclick="PaymentManager.closeCheckoutModal()" 
                                class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600">
                            Hủy
                        </button>
                        <button onclick="PaymentManager.processPayment()" 
                                class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                            Xác nhận thanh toán
                        </button>
                    </div>
                </div>
            </div>
        `;
            },

            closeCheckoutModal() {
                const modal = document.getElementById('checkoutModal');
                modal?.remove();
            },

            updateFinalTotal() {
                const total = Utils.calculateTotal(AppState.cart);
                const vat = total * 0.1;
                const discount = parseFloat(document.getElementById('discountInput').value) || 0;
                const finalTotal = total + vat - discount;

                // Format và hiển thị tổng cộng
                document.getElementById('finalTotal').textContent = Utils.formatCurrency(finalTotal);

                // Cập nhật ô khách trả nếu trống
                const paidAmountInput = document.getElementById('paidAmount');
                if (paidAmountInput.value === '') {
                    paidAmountInput.value = finalTotal;
                }

                // Cập nhật tiền thừa
                this.updateChange();
            },
            updateChange() {
                const finalTotalText = document.getElementById('finalTotal').textContent;
                const finalTotal = parseFloat(finalTotalText.replace(/[^\d]/g, ''));

                // Lấy giá trị số từ input đã format
                const paidAmountInput = document.getElementById('paidAmount');
                const paidAmount = Utils.getNumericValue(paidAmountInput);

                const change = paidAmount - finalTotal;
                document.getElementById('changeAmount').textContent = Utils.formatCurrency(Math.max(0, change));
            },
            async processPayment() {
                try {
                    UIService.showLoading('Đang xử lý thanh toán...');

                    // Kiểm tra giỏ hàng
                    if (!AppState.cart || AppState.cart.length === 0) {
                        throw new Error('EMPTY_CART');
                    }

                    // Kiểm tra và lấy các giá trị đầu vào
                    const employee = document.getElementById('employeeInput')?.value;
                    if (!employee?.trim()) {
                        throw new Error('INVALID_EMPLOYEE');
                    }

                    const customer = document.getElementById('customerInput')?.value?.trim() || 'Khách lẻ';

                    // Tính toán các giá trị thanh toán
                    const total = Utils.calculateTotal(AppState.cart);
                    if (total <= 0) {
                        throw new Error('INVALID_TOTAL');
                    }

                    const vat = total * 0.1;

                    const discount = parseFloat(document.getElementById('discountInput')?.value || '0');
                    if (isNaN(discount) || discount < 0) {
                        throw new Error('INVALID_DISCOUNT');
                    }

                    // Lấy giá trị số thực từ input đã format
                    const paidAmountInput = document.getElementById('paidAmount');
                    const paidAmount = Utils.getNumericValue(paidAmountInput);

                    if (isNaN(paidAmount) || paidAmount <= 0) {
                        throw new Error('INVALID_PAID_AMOUNT');
                    }

                    const finalAmount = total + vat - discount;
                    if (paidAmount < finalAmount) {
                        throw new Error('INSUFFICIENT_PAYMENT');
                    }

                    const change = paidAmount - finalAmount;

                    // Tạo đối tượng thanh toán
                    const paymentData = {
                        id: Utils.generateId('INV'),
                        tableId: AppState.selectedTableId,
                        employee,
                        customer,
                        date: new Date().toISOString(),
                        total,
                        vat,
                        discount,
                        paidAmount,
                        change,
                        note: document.getElementById('noteInput')?.value?.trim() || '',
                        items: [...AppState.cart] // Clone cart để tránh tham chiếu
                    };

                    // Xử lý thanh toán và lưu hóa đơn
                    await this.saveInvoice(paymentData);

                    // In hóa đơn
                    try {
                        await this.printReceipt(paymentData);
                    } catch (printError) {
                        console.warn('Không thể in hóa đơn:', printError);
                        UIService.showNotification('Thanh toán thành công nhưng không thể in hóa đơn', 'warning');
                    }

                    // Reset trạng thái
                    await this.resetTableState();
                    AppState.cart = [];
                    CartManager.renderCart();
                    this.closeCheckoutModal();

                    UIService.showNotification('Thanh toán thành công!', 'success');

                } catch (error) {
                    console.error('Lỗi thanh toán:', error);

                    // Xử lý các loại lỗi cụ thể
                    const errorMessages = {
                        'EMPTY_CART': 'Giỏ hàng trống!',
                        'INVALID_EMPLOYEE': 'Vui lòng chọn nhân viên thanh toán!',
                        'INVALID_TOTAL': 'Tổng tiền không hợp lệ!',
                        'INVALID_DISCOUNT': 'Giảm giá không hợp lệ!',
                        'INVALID_PAID_AMOUNT': 'Số tiền thanh toán không hợp lệ!',
                        'INSUFFICIENT_PAYMENT': 'Số tiền khách trả không đủ!',
                        'NETWORK_ERROR': 'Lỗi kết nối! Vui lòng kiểm tra lại.',
                        'DATABASE_ERROR': 'Lỗi lưu dữ liệu! Vui lòng thử lại.'
                    };

                    const message = errorMessages[error.message] || 'Có lỗi xảy ra khi thanh toán!';
                    UIService.showNotification(message, 'error');

                } finally {
                    UIService.hideLoading();
                }
            },
            async saveInvoice(paymentData) {
                const invoice = {
                    IDHOADON: paymentData.id,
                    IDBAN: paymentData.tableId,
                    "Nhân viên": paymentData.employee,
                    "Khách hàng": paymentData.customer,
                    "Tổng tiền": paymentData.total,
                    "VAT": paymentData.vat,
                    "Giảm giá": paymentData.discount,
                    "Khách trả": paymentData.paidAmount,
                    "Tiền thừa": paymentData.change,
                    "Ghi chú": paymentData.note,
                    "Trạng thái": "Đã thanh toán"
                };

                const invoiceDetails = paymentData.items.map(item => ({
                    IDHOADONDETAIL: `${paymentData.id}_${item.id}`,
                    IDHOADON: paymentData.id,
                    IDSP: item.id,

                    "Số lượng": item.quantity
                }));
                console.log(invoice);

                await ApiService.saveInvoice(invoice, invoiceDetails);
            },

            async resetTableState() {
                if (AppState.selectedTableId) {
                    // Clear active order
                    AppState.activeOrders.delete(AppState.selectedTableId);

                    // Reset table status
                    const selectedTable = AppState.tables.find(t => t.IDBAN === AppState.selectedTableId);
                    if (selectedTable && selectedTable['Tên bàn'] !== 'Khách mua về') {
                        selectedTable['Trạng thái'] = 'Trống';
                        // Update tables in database if needed
                        // await ApiService.updateTableStatus(selectedTable.IDBAN, 'Trống');
                    }

                    // Reset selected table
                    AppState.selectedTableId = null;
                    TableManager.updateTableButton('Chọn bàn');
                }
            },

            async printReceipt(paymentData) {
                const printWindow = window.open('', '', 'width=800,height=600');
                const receiptHtml = this.generateReceiptHtml(paymentData);

                printWindow.document.write(receiptHtml);
                printWindow.document.close();
                printWindow.focus();

                // Print after a small delay to ensure loading
                setTimeout(() => {
                    printWindow.print();
                    printWindow.close();
                }, 250);
            },

            generateReceiptHtml(paymentData) {
                return `
            <!DOCTYPE html>
            <html>
            <head>
                <title>Hóa đơn - ${paymentData.id}</title>
                <style>
                    /* Receipt styles */
                    body {
                        font-family: Verdana, sans-serif;
                        font-size: 12px;
                        line-height: 1.2;
                        margin: 0;
                        padding: 0;
                        display: flex;
                        justify-content: center;
                        background-color: #f0f0f0;
                    }

                    #content {
                        width: 80mm;
                        background-color: white;
                        padding: 5mm;
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    }

                    .header, .footer {
                        text-align: center;
                        margin: 3mm 0;
                    }

                    .invoice-details {
                        margin: 2mm 0;
                    }

                    table {
                        width: 100%;
                        border-collapse: collapse;
                        font-size: 10px;
                    }

                    th, td {
                        padding: 1mm;
                        text-align: left;
                        border-bottom: 0.5px solid #ddd;
                    }

                    .total {
                        text-align: right;
                        margin-top: 2mm;
                        font-weight: bold;
                    }

                    @media print {
                        body { margin: 0; padding: 0; }
                        #content { box-shadow: none; }
                    }
                </style>
            </head>
            <body>
                <div id="content">
                    <div class="header">
                        <div class="company-name"><strong>Goal COFFEE</strong></div>
                        <div><strong>Địa chỉ: Lâm Đồng</strong></div>
                        <div>SĐT: 0326132124</div>
                    </div>

                    <div style="text-align: center;">
                        <h2><strong>Hóa đơn bán hàng</strong></h2>
                        <div><strong>Số: ${paymentData.id}</strong></div>
                        <div><strong>Ngày: ${new Date(paymentData.date).toLocaleString()}</strong></div>
                    </div>

                    <div class="invoice-details">
                        <div>Khách hàng: ${paymentData.customer}</div>
                        <div>Nhân viên: ${paymentData.employee}</div>
                    </div>

                    <table>
                        <thead>
                            <tr>
                                <th>TÊN SP</th>
                                <th>SL</th>
                                <th>ĐƠN GIÁ</th>
                                <th>THÀNH TIỀN</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${paymentData.items.map(item => `
                                <tr>
                                    <td>${item.name}</td>
                                    <td>${item.quantity}</td>
                                    <td>${Utils.formatCurrency(item.price)}</td>
                                    <td style="text-align: right">
                                        ${Utils.formatCurrency(item.price * item.quantity)}
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>

                    <div class="total">
                        <div>Tổng tiền hàng: ${Utils.formatCurrency(paymentData.total)}</div>
                        <div>VAT (10%): ${Utils.formatCurrency(paymentData.vat)}</div>
                        <div>Giảm giá: ${Utils.formatCurrency(paymentData.discount)}</div>
                        <div class="total">
                            Tổng cộng: ${Utils.formatCurrency(paymentData.total + paymentData.vat - paymentData.discount)}
                        </div>
                        <div>Khách trả: ${Utils.formatCurrency(paymentData.paidAmount)}</div>
                        <div>Tiền thừa: ${Utils.formatCurrency(paymentData.change)}</div>
                    </div>

                    <div style="margin-top: 10px;">
                        <i>Ghi chú: ${paymentData.note || ''}</i>
                    </div>

                    <div class="footer">
                        <hr>
                        <i>Cảm ơn quý khách đã mua hàng!</i>
                        <p>Liên hệ Ninh Phước để được hỗ trợ: 0326132124</p>
                    </div>
                </div>
            </body>
            </html>
        `;
            }
        };

        // Event Handlers
        const EventHandlers = {
            setupEventListeners() {
                // Keyboard shortcuts
                document.addEventListener('keydown', this.handleKeyboardShortcuts);

                // Input focus management
                this.setupInputFocusHandlers();

                // Window events
                window.addEventListener('beforeunload', this.handleBeforeUnload);

                // Create barcode button
                this.createBarcodeButton();
            },

            handleKeyboardShortcuts(e) {
                switch (true) {
                    case e.key === 'F2': // Search
                        e.preventDefault();
                        FocusManager.toggleAutoFocus(false);
                        UIService.elements.searchInput().focus();
                        break;

                    case e.key === 'F4': // Quick checkout
                        e.preventDefault();
                        PaymentManager.openCheckoutModal();
                        break;

                    case e.key === 'Escape': // Clear cart
                        e.preventDefault();
                        CartManager.clearCart();
                        break;

                    case e.ctrlKey && e.key.toLowerCase() === 'b': // Barcode focus
                        e.preventDefault();
                        FocusManager.toggleAutoFocus(true);
                        UIService.elements.barcodeInput().focus();
                        break;

                    case e.key === 'F1': // Reset filters
                        e.preventDefault();
                        FilterManager.resetFilters();
                        break;

                    case e.key === 'F5': // Sync data
                        e.preventDefault();
                        DataSyncManager.syncData();
                        break;
                }
            },

            setupInputFocusHandlers() {
                const inputs = ['searchInput', 'categoryFilter', 'priceFilter'];

                inputs.forEach(inputId => {
                    const element = document.getElementById(inputId);
                    if (!element) return;

                    element.addEventListener('focus', () => {
                        FocusManager.toggleAutoFocus(false);
                    });

                    element.addEventListener('blur', (e) => {
                        const relatedTarget = e.relatedTarget;
                        if (!relatedTarget || !inputs.includes(relatedTarget.id)) {
                            setTimeout(() => FocusManager.toggleAutoFocus(true), 200);
                        }
                    });

                    element.addEventListener('click', (e) => {
                        e.stopPropagation();
                        FocusManager.toggleAutoFocus(false);
                    });
                });
            },

            handleBeforeUnload() {
                // Save state before closing
                const state = {
                    activeOrders: Array.from(AppState.activeOrders.entries()),
                    selectedTableId: AppState.selectedTableId,
                    tables: AppState.tables
                };
                localStorage.setItem('posState', JSON.stringify(state));
            },

            createBarcodeButton() {
                const barcodeInput = UIService.elements.barcodeInput();
                if (!barcodeInput) return;

                const button = document.createElement('button');
                button.id = 'barcodeButton';
                button.className = 'px-4 py-2 bg-blue-500 text-white rounded-lg ml-2';
                button.textContent = 'Quét mã';
                button.onclick = () => {
                    FocusManager.toggleAutoFocus(true);
                    barcodeInput.focus();
                };

                barcodeInput.parentNode.appendChild(button);
            }
        };

        // Focus Manager
        const FocusManager = {
            toggleAutoFocus(enable) {
                AppState.autoFocusEnabled = enable;
                if (enable) {
                    UIService.elements.barcodeInput()?.focus();
                }
            },

            handleBarcodeInput(event) {
                const currentTime = Date.now();
                const barcodeInput = UIService.elements.barcodeInput();

                if (currentTime - AppState.lastKeystrokeTime > CONFIG.timeouts.barcodeBuffer) {
                    AppState.barcodeBuffer = '';
                }

                AppState.lastKeystrokeTime = currentTime;

                if (event.key === 'Enter') {
                    event.preventDefault();
                    const barcode = barcodeInput.value.trim();
                    if (barcode) {
                        this.processBarcodeInput(barcode);
                        barcodeInput.value = '';
                    }
                    AppState.barcodeBuffer = '';
                }

                if (AppState.autoFocusEnabled) {
                    setTimeout(() => barcodeInput?.focus(), 100);
                }
            },

            processBarcodeInput(barcode) {
                const product = AppState.allProducts.find(p => p.IDSP === barcode);
                if (product) {
                    CartManager.addToCart(barcode);
                } else {
                    UIService.showNotification('Không tìm thấy sản phẩm với mã này!', 'error');
                }
            }
        };

        // Filter Manager
        const FilterManager = {
            filterProducts() {
                const searchTerm = UIService.elements.searchInput().value.toLowerCase();
                const category = UIService.elements.categoryFilter().value;
                const priceRange = document.getElementById('priceFilter').value;

                const filtered = AppState.allProducts.filter(product => {
                    const matchesSearch = product['Tên sản phẩm'].toLowerCase().includes(searchTerm);
                    const matchesCategory = category === 'all' || product['Loại sản phẩm'] === category;
                    const matchesPrice = this.checkPriceRange(product['Đơn giá'], priceRange);

                    return matchesSearch && matchesCategory && matchesPrice;
                });

                if (searchTerm || category !== 'all' || priceRange !== 'all') {
                    UIService.showNotification(`Tìm thấy ${filtered.length} sản phẩm`);
                }

                ProductRenderer.renderProducts(filtered);
            },

            checkPriceRange(price, range) {
                if (range === 'all') return true;

                const [min, max] = range.split('-').map(Number);
                price = parseInt(price);

                if (max) {
                    return price >= min && price < max;
                }
                return price >= min;
            },

            resetFilters() {
                UIService.elements.searchInput().value = '';
                UIService.elements.categoryFilter().value = 'all';
                document.getElementById('priceFilter').value = 'all';

                ProductRenderer.renderProducts(AppState.allProducts);
                UIService.showNotification('Đã đặt lại bộ lọc');
            }
        };

        // Data Sync Manager
        const DataSyncManager = {
            async syncData() {
                const syncButton = document.getElementById('syncButton');
                try {
                    syncButton.disabled = true;
                    syncButton.classList.add('opacity-50', 'cursor-not-allowed');

                    UIService.showLoading('Đang đồng bộ dữ liệu...');

                    const [products, tables] = await Promise.all([
                        ApiService.fetchProducts(),
                        ApiService.fetchTables()
                    ]);

                    AppState.allProducts = products;
                    AppState.tables = tables;

                    ProductRenderer.renderProducts(AppState.allProducts);
                    CategoryManager.populateCategories();
                    TableManager.renderTables();

                    UIService.showNotification('Đồng bộ dữ liệu thành công!');
                } catch (error) {
                    console.error('Lỗi đồng bộ:', error);
                    UIService.showNotification('Lỗi đồng bộ dữ liệu. Vui lòng thử lại!', 'error');
                } finally {
                    UIService.hideLoading();
                    syncButton.disabled = false;
                    syncButton.classList.remove('opacity-50', 'cursor-not-allowed');
                }
            }
        };

        // Product Renderer
        const ProductRenderer = {
            renderProducts(products) {
                const productList = document.getElementById('productList');
                const defaultImageUrl = 'https://dummyimage.com/400x400/eee/999.png&text=No+Image';

                productList.innerHTML = products.map(product => this.generateProductHtml(product, defaultImageUrl)).join('');
                this.addTextClampStyles();
            },

            generateProductHtml(product, defaultImageUrl) {
                return `
            <div class="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow cursor-pointer" 
                 onclick="CartManager.addToCart('${product.IDSP}')">
                <div class="mb-4">
                    <img src="${encodeURI(product['Hình ảnh'])}"
                         alt="${product['Tên sản phẩm']}"
                         onerror="this.onerror=null; this.src='${defaultImageUrl}'"
                         class="w-40 h-40 object-cover rounded-lg">
                </div>
                <h3 class="font-medium text-gray-900 mb-1 line-clamp-2">
                    ${product['Tên sản phẩm']}
                </h3>
                <p class="text-blue-600 font-semibold">
                    ${Utils.formatCurrency(parseInt(product['Đơn giá']))}
                </p>
            </div>
        `;
            },

            addTextClampStyles() {
                if (!document.getElementById('product-styles')) {
                    const style = document.createElement('style');
                    style.id = 'product-styles';
                    style.textContent = `
                .line-clamp-2 {
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                }
            `;
                    document.head.appendChild(style);
                }
            }
        };

        // Category Manager
        const CategoryManager = {
            populateCategories() {
                const categoryCounts = AppState.allProducts.reduce((acc, product) => {
                    const category = product['Loại sản phẩm'];
                    acc[category] = (acc[category] || 0) + 1;
                    return acc;
                }, {});

                const categories = Object.keys(categoryCounts).sort();
                const categoryFilter = UIService.elements.categoryFilter();

                // Clear existing options except the first one
                while (categoryFilter.children.length > 1) {
                    categoryFilter.removeChild(categoryFilter.lastChild);
                }

                categories.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category;
                    option.textContent = `${category} (${categoryCounts[category]})`;
                    categoryFilter.appendChild(option);
                });
            }
        };

        // Initialize Application
        async function initializeApp() {
            AppState.nhanvien =getUrlParameter('manv');
            if (AppState.nhanvien) {
            try {
               


                UIService.showLoading('Đang khởi tạo ứng dụng...');

                // Restore saved state if exists
                const savedState = localStorage.getItem('posState');
                if (savedState) {
                    const state = JSON.parse(savedState);
                    AppState.activeOrders = new Map(state.activeOrders);
                    AppState.selectedTableId = state.selectedTableId;
                    if (state.tables) AppState.tables = state.tables;
                }

                // Fetch initial data
                const [products, tables] = await Promise.all([
                    ApiService.fetchProducts(),
                    ApiService.fetchTables()
                ]);

                // Initialize state
                AppState.allProducts = products;
                if (!AppState.tables.length) AppState.tables = tables;

                // Initialize UI
                ProductRenderer.renderProducts(products);
                CategoryManager.populateCategories();
                TableManager.renderTables();

                // Setup event handlers
                EventHandlers.setupEventListeners();

                // Restore cart if there was a selected table
                if (AppState.selectedTableId) {
                    AppState.cart = AppState.activeOrders.get(AppState.selectedTableId) || [];
                    CartManager.renderCart();
                    const selectedTable = AppState.tables.find(t => t.IDBAN === AppState.selectedTableId);
                    if (selectedTable) {
                        TableManager.updateTableButton(selectedTable['Tên bàn']);
                    }
                }

                UIService.showNotification('Khởi tạo ứng dụng thành công!');
            } catch (error) {
                console.error('Lỗi khởi tạo:', error);
                UIService.showNotification('Không thể khởi tạo ứng dụng. Vui lòng thử lại!', 'error');
            } finally {
                UIService.hideLoading();
            }
        } else {
            UIService.showNotification('Không thể khởi tạo ứng dụng. Vui lòng thử lại!', 'error');
        }
    } 
        // Start the application
        initializeApp();
    </script>

</body>

</html>