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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mobile POS</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;
        }
        .loading-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    z-index: 60;
    background: linear-gradient(to right, #3b82f6, #60a5fa);
    animation: loading 1s infinite linear;
}

@keyframes loading {
    0% {
        transform: translateX(-100%);
    }
    100% {
        transform: translateX(100%);
    }
}
    </style>

</head>

<body class="bg-gray-100">
    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="loading-bar hidden"></div>

    <!-- Navigation Bar -->
    <div class="fixed top-0 inset-x-0 bg-white shadow-md z-40">
        <div class="flex items-center justify-between p-4">
            <div class="text-lg font-bold">Mobile POS</div>
            <div class="flex items-center space-x-2">
                <button id="syncButton" class="p-2 bg-green-500 text-white rounded-lg">
                    <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="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>
                <button id="cartButton" class="relative p-2 bg-blue-500 text-white rounded-lg">
                    <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="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
                    </svg>
                    <span id="cartCount"
                        class="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">0</span>
                </button>
            </div>
        </div>

        <!-- Table Selection -->
        <div id="tableSelection" class="px-4 py-2 flex items-center space-x-2 bg-gray-50">
            <button id="selectedTable" class="flex-1 px-4 py-2 bg-white border rounded-lg text-left">
                Chọn bàn...
            </button>
        </div>

        <!-- Search and Categories -->
        <div class="p-4 space-y-2">
            <div class="relative">
                <input type="text" id="searchInput" placeholder="Tìm kiếm sản phẩm..."
                    class="w-full pl-10 pr-4 py-2 border rounded-lg">
                <svg class="w-5 h-5 absolute left-3 top-2.5 text-gray-400" fill="none" stroke="currentColor"
                    viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
            </div>
            <div id="categoriesScroll" class="flex space-x-2 overflow-x-auto hide-scrollbar smooth-scroll">
                <button class="category-btn tab-active whitespace-nowrap px-4 py-2 rounded-lg" data-category="all">
                    Tất cả
                </button>
            </div>
        </div>
    </div>

    <!-- Main Content Area -->
    <main class="mt-[260px] mb-16 px-4"> <!-- Điều chỉnh mt-48 thành mt-[220px] -->
        <!-- Products Grid -->
        <div id="productGrid" class="grid grid-cols-2 gap-4">
            <!-- Products will be dynamically inserted here -->
        </div>
    </main>

    <!-- Bottom Navigation -->
    <div class="fixed bottom-0 inset-x-0 bg-white border-t z-40">
        <div class="flex justify-around p-2">
            <button class="flex-1 py-2 text-center tab-active" data-view="products">
                Sản phẩm
            </button>
            <button class="flex-1 py-2 text-center" data-view="tables">
                Bàn
            </button>
            <button class="flex-1 py-2 text-center" data-view="orders">
                Đơn hàng
            </button>
        </div>
    </div>

    <!-- Modal Templates -->
    <!-- Table Selection Modal -->
    <div id="tableModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
        <div class="fixed inset-x-0 bottom-0 bg-white rounded-t-xl max-h-[80vh] overflow-y-auto">
            <div class="sticky top-0 bg-white border-b p-4 flex justify-between items-center">
                <h3 class="text-lg font-bold">Chọn bàn</h3>
                <button onclick="TableManager.closeTableModal()" class="p-2">
                    <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 id="tableGrid" class="grid grid-cols-2 gap-4 p-4">
                <!-- Tables will be dynamically inserted here -->
            </div>
        </div>
    </div>

    <!-- Cart Modal -->
    <div id="cartModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
        <div class="fixed inset-x-0 bottom-0 bg-white rounded-t-xl max-h-[90vh] flex flex-col">
            <div class="sticky top-0 bg-white border-b p-4 flex justify-between items-center">
                <h3 class="text-lg font-bold">Giỏ hàng</h3>
                <button onclick="CartManager.closeCartModal()" class="p-2">
                    <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 id="cartItems" class="flex-1 overflow-y-auto p-4 space-y-4">
                <!-- Cart items will be dynamically inserted here -->
            </div>
            <div class="border-t bg-white p-4 space-y-4">
                <div class="flex justify-between items-center">
                    <span class="font-bold">Tổng cộng:</span>
                    <span id="cartTotal" class="text-xl font-bold text-blue-600">0đ</span>
                </div>
                <button onclick="PaymentManager.openCheckoutModal()"
                    class="w-full py-3 bg-blue-600 text-white rounded-lg font-bold">
                    Thanh toán
                </button>
            </div>
        </div>
    </div>

    <script>
        // Constants
        const CONFIG = {
            appId: 'ab00cc33-e1ce-4e9c-80a4-35feded6205b',
            accessKey: 'V2-Qrb6D-bpPkv-CGv51-VvzZn-VZnXb-9ePlp-SvHIM-Gs8kJ',
            region: 'www'
        };

        // State Management
        const AppState = {
            products: [],
            tables: [],
            cart: [],
            selectedTableId: null,
            activeOrders: new Map(),
            categories: new Set(),
            currentView: 'products'
        };

        // Utilities
        const Utils = {
            formatCurrency(amount) {
                return new Intl.NumberFormat('vi-VN', {
                    style: 'currency',
                    currency: 'VND'
                }).format(amount);
            },

            calculateTotal(items) {
                return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
            },

            showLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (!overlay) return;
        overlay.classList.remove('hidden');
    },

    hideLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (!overlay) return;
        overlay.classList.add('hidden');
    },

            showNotification(message, type = 'success') {
                // Create notification element
                const notification = document.createElement('div');
                notification.className = `fixed bottom-20 left-4 right-4 p-4 rounded-lg shadow-lg transform transition-all duration-300 ${type === 'success' ? 'bg-green-500' : 'bg-red-500'
                    } text-white`;
                notification.textContent = message;

                // Add to document
                document.body.appendChild(notification);

                // Remove after delay
                setTimeout(() => {
                    notification.style.opacity = '0';
                    setTimeout(() => notification.remove(), 300);
                }, 2000);
            }
        };

        // API Service
        const ApiService = {
            async request(tableName, action, data) {
                const apiUrl = `https://${CONFIG.region}.appsheet.com/api/v2/apps/${CONFIG.appId}/tables/${tableName}/Action`;

                try {
                    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
                        })
                    });

                    if (!response.ok) {
                        throw new Error(`API Error: ${response.status}`);
                    }

                    return response.json();
                } catch (error) {
                    console.error('API Request Error:', error);
                    throw error;
                }
            },

            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)"
                });
            }
        };

        // Product Manager
        const ProductManager = {
            async initialize() {
                try {
                    const products = await ApiService.fetchProducts();
                    AppState.products = products;

                    // Extract unique categories
                    products.forEach(product => {
                        if (product['Loại sản phẩm']) {
                            AppState.categories.add(product['Loại sản phẩm']);
                        }
                    });

                    // Add null checks
                    if (document.getElementById('categoriesScroll')) {
                        this.renderCategories();
                    }
                    if (document.getElementById('productGrid')) {
                        this.renderProducts(products);
                    }
                } catch (error) {
                    console.error('Error initializing products:', error);
                    Utils.showNotification('Không thể tải danh sách sản phẩm', 'error');
                }
            },


            renderCategories() {
                const container = document.getElementById('categoriesScroll');
                if (!container) return;

                container.innerHTML = `
                    <button class="category-btn tab-active whitespace-nowrap px-4 py-2 rounded-lg" data-category="all">
                        Tất cả
                    </button>
                    ${Array.from(AppState.categories).map(category => `
                        <button class="category-btn whitespace-nowrap px-4 py-2 rounded-lg" data-category="${category}">
                            ${category}
                        </button>
                    `).join('')}
                `;

                // Add event listeners
                container.querySelectorAll('.category-btn').forEach(btn => {
                    btn.addEventListener('click', () => {
                        // Update active state
                        container.querySelectorAll('.category-btn').forEach(b =>
                            b.classList.remove('tab-active'));
                        btn.classList.add('tab-active');

                        // Filter products
                        const category = btn.dataset.category;
                        const filtered = category === 'all'
                            ? AppState.products : AppState.products.filter(p => p['Loại sản phẩm'] === category);
                        this.renderProducts(filtered);
                    });
                });
            },

            renderProducts(products) {
                const grid = document.getElementById('productGrid');
                const defaultImage = 'https://dummyimage.com/200x200/eee/999.png&text=No+Image';

                grid.innerHTML = products.map(product => `
                    <div class="bg-white rounded-lg shadow overflow-hidden" 
                         onclick="ProductManager.addToCart('${product.IDSP}')">
                        <img src="${product['Hình ảnh']}"
                             onerror="this.src='${defaultImage}'"
                             alt="${product['Tên sản phẩm']}"
                             class="w-full h-32 object-cover">
                        <div class="p-3">
                            <h3 class="font-medium text-sm line-clamp-2">${product['Tên sản phẩm']}</h3>
                            <p class="text-blue-600 font-bold mt-1">
                                ${Utils.formatCurrency(parseInt(product['Đơn giá']))}
                            </p>
                        </div>
                    </div>
                `).join('');
            },

            addToCart(productId) {
                if (!AppState.selectedTableId) {
                    Utils.showNotification('Vui lòng chọn bàn trước', 'error');
                    TableManager.openTableModal();
                    return;
                }

                const product = AppState.products.find(p => p.IDSP === productId);
                if (!product) 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
                    });
                }

                CartManager.updateCart();
                Utils.showNotification(`Đã thêm ${product['Tên sản phẩm']}`);
            },

            setupSearch() {
                const searchInput = document.getElementById('searchInput');
                if (!searchInput) return;
                searchInput.addEventListener('input', (e) => {
                    const term = e.target.value.toLowerCase();
                    const filtered = AppState.products.filter(product =>
                        product['Tên sản phẩm'].toLowerCase().includes(term)
                    );
                    this.renderProducts(filtered);
                });
            }
        };

        // Cart Manager
        const CartManager = {
            openCartModal() {
                document.getElementById('cartModal').classList.remove('hidden');
            },

            closeCartModal() {
                document.getElementById('cartModal').classList.add('hidden');
            },

            updateCart() {
                // Update cart count
                const cartCount = document.getElementById('cartCount');
                const cartItems = document.getElementById('cartItems');
                const cartTotal = document.getElementById('cartTotal');

                document.getElementById('cartCount').textContent = AppState.cart.reduce(
                    (sum, item) => sum + item.quantity, 0
                );

                // Update cart items
                document.getElementById('cartItems').innerHTML = AppState.cart.map(item => `
                    <div class="flex items-center justify-between bg-gray-50 p-3 rounded-lg">
                        <div class="flex-1">
                            <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">
                                -
                            </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">
                                +
                            </button>
                            <button onclick="CartManager.removeItem('${item.id}')"
                                    class="w-8 h-8 flex items-center justify-center bg-red-500 text-white rounded-full">
                                ×
                            </button>
                        </div>
                    </div>
                `).join('');

                // Update total
                const total = Utils.calculateTotal(AppState.cart);
                document.getElementById('cartTotal').textContent = Utils.formatCurrency(total);
            },

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

                item.quantity += amount;
                if (item.quantity <= 0) {
                    this.removeItem(itemId);
                } else {
                    this.updateCart();
                }
            },

            removeItem(itemId) {
                AppState.cart = AppState.cart.filter(item => item.id !== itemId);
                this.updateCart();
            },

            clearCart() {
                AppState.cart = [];
                this.updateCart();
                this.closeCartModal();
            }
        };

        // Table Manager
        const TableManager = {
            async initialize() {
                try {
                    const tables = await ApiService.fetchTables();
                    AppState.tables = tables;

                    const selectedTableBtn = document.getElementById('selectedTable');
                    if (selectedTableBtn) {
                        selectedTableBtn.addEventListener('click', () => {
                            this.openTableModal();
                        });
                    }

                    this.renderTables();
                } catch (error) {
                    console.error('Error initializing tables:', error);
                    Utils.showNotification('Không thể tải danh sách bàn', 'error');
                }
            },

            openTableModal() {
                document.getElementById('tableModal').classList.remove('hidden');
            },

            closeTableModal() {
                document.getElementById('tableModal').classList.add('hidden');
            },

            renderTables() {
                const grid = document.getElementById('tableGrid');
                if (!grid) return;
                grid.innerHTML = AppState.tables.map(table => `
                    <div onclick="TableManager.selectTable('${table.IDBAN}')"
                         class="p-4 rounded-lg cursor-pointer ${this.getTableStatusClass(table)}">
                        <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>
                        <p class="text-sm font-medium">${table['Trạng thái']}</p>
                    </div>
                `).join('');
            },

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

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

                // 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) || [];

                // Update table status
                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
                document.getElementById('selectedTable').textContent = table['Tên bàn'];
                CartManager.updateCart();
                this.closeTableModal();
                Utils.showNotification(`Đã chọn ${table['Tên bàn']}`);
            }
        };

        const PaymentManager = {
            openCheckoutModal() {
                // Create modal if it doesn't exist
                let modal = document.getElementById('checkoutModal');
                if (!modal) {
                    modal = document.createElement('div');
                    modal.id = 'checkoutModal';
                    modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 hidden';
                    modal.innerHTML = `
                <div class="fixed inset-x-0 bottom-0 bg-white rounded-t-xl max-h-[90vh] flex flex-col">
                    <div class="sticky top-0 bg-white border-b p-4 flex justify-between items-center">
                        <h3 class="text-lg font-bold">Thanh toán</h3>
                        <button onclick="PaymentManager.closeCheckoutModal()" class="p-2">
                            <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="flex-1 overflow-y-auto p-4 space-y-4">
                        <div class="space-y-4">
                            <div>
                                <div class="flex justify-between items-center mb-2">
                                    <span class="text-gray-600">Tổng tiền hàng:</span>
                                    <span id="checkoutSubtotal" class="font-medium"></span>
                                </div>
                                <div class="flex justify-between items-center mb-2">
                                    <span class="text-gray-600">VAT (10%):</span>
                                    <span id="checkoutVat" class="font-medium"></span>
                                </div>
                                <div class="flex justify-between items-center text-lg font-bold">
                                    <span>Tổng cộng:</span>
                                    <span id="checkoutTotal" class="text-blue-600"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="border-t bg-white p-4">
                        <button onclick="PaymentManager.processPayment()" 
                                class="w-full py-3 bg-blue-600 text-white rounded-lg font-bold">
                            Xác nhận thanh toán
                        </button>
                    </div>
                </div>
            `;
                    document.body.appendChild(modal);
                }

                // Update amounts
                const subtotal = Utils.calculateTotal(AppState.cart);
                const vat = subtotal * 0.1;
                const total = subtotal + vat;

                document.getElementById('checkoutSubtotal').textContent = Utils.formatCurrency(subtotal);
                document.getElementById('checkoutVat').textContent = Utils.formatCurrency(vat);
                document.getElementById('checkoutTotal').textContent = Utils.formatCurrency(total);

                // Show modal
                modal.classList.remove('hidden');
            },

            closeCheckoutModal() {
                const modal = document.getElementById('checkoutModal');
                if (modal) {
                    modal.classList.add('hidden');
                }
            },

            async processPayment() {
                try {
                    if (!AppState.selectedTableId || AppState.cart.length === 0) {
                        Utils.showNotification('Không có đơn hàng để thanh toán', 'error');
                        return;
                    }

                    Utils.showLoading('Đang xử lý thanh toán...');

                    // Generate invoice ID
                    const invoiceId = `INV${Date.now()}`;

                    const total = Utils.calculateTotal(AppState.cart);
                    const vat = total * 0.1;

                    // Create invoice object
                    const invoice = {
                        IDHOADON: invoiceId,
                        IDBAN: AppState.selectedTableId,
                        "Ngày": new Date().toISOString(),
                        "Tổng tiền": total,
                        "VAT": vat,
                        "Trạng thái": "Đã thanh toán",
                        "Nhân viên": "Ninh Văn Phước",
                        "Khách hàng": "Khách hàng",
                        "Khách trả": total + vat,
                        "Tiền thừa": 0,
                        "Trạng thái sự dụng bàn": "Đã trả bàn"
                    };

                    // Create invoice details
                    const invoiceDetails = AppState.cart.map(item => ({
                        IDHOADONDETAIL: `${invoiceId}_${item.id}`,
                        IDHOADON: invoiceId,
                        IDSP: item.id,

                        "Số lượng": item.quantity
                    }));

                    // Save invoice to system
                    await ApiService.request('HOADON', 'Add', {
                        Rows: [invoice]
                    });

                    // Save invoice details to system
                    await ApiService.request('HOADONDETAIL', 'Add', {
                        Rows: invoiceDetails
                    });

                    // Clear current table's cart
                    if (AppState.selectedTableId) {
                        AppState.activeOrders.delete(AppState.selectedTableId);
                        AppState.selectedTableId = null;
                        document.getElementById('selectedTable').textContent = 'Chọn bàn...';
                    }

                    // Clear cart and update UI
                    CartManager.clearCart();
                    this.closeCheckoutModal();
                    Utils.showNotification('Thanh toán thành công!');

                } catch (error) {
                    console.error('Payment error:', error);
                    Utils.showNotification('Lỗi thanh toán', 'error');
                } finally {
                    Utils.hideLoading();
                }
            }
        };

        // Initialize App
        async function initializeApp() {
            try {
                Utils.showLoading('Đang khởi tạo ứng dụng...');

                // Setup event listeners
                document.getElementById('cartButton').addEventListener('click', CartManager.openCartModal);
                document.getElementById('syncButton').addEventListener('click', async () => {
                    try {
                        Utils.showLoading('Đang đồng bộ...');
                        await Promise.all([
                            ProductManager.initialize(),
                            TableManager.initialize()
                        ]);
                        Utils.showNotification('Đồng bộ thành công!');
                    } catch (error) {
                        Utils.showNotification('Lỗi đồng bộ dữ liệu', 'error');
                    } finally {
                        Utils.hideLoading();
                    }
                });

                // Initialize managers
                await Promise.all([
                    ProductManager.initialize(),
                    TableManager.initialize()
                ]);

                ProductManager.setupSearch();

                Utils.showNotification('Khởi tạo ứng dụng thành công!');
            } catch (error) {
                console.error('Initialization error:', error);
                Utils.showNotification('Lỗi khởi tạo ứng dụng', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // Start the application
        initializeApp();
    </script>
</body>

</html>