// app.jsx
// Legacy: React/ReactDOM from libs/*. Web/Vite: web/src/main.jsx sets window.React / window.ReactDOM before importing this file.
const { useState, useEffect, useRef, useMemo } = React;

// Vite ESM bundle: components register on window; bare JSX tags need these in scope.
const Login = window.Login;
const Sidebar = window.Sidebar;
const ProductList = window.ProductList;
const Cart = window.Cart;
const PaymentModal = window.PaymentModal;
const SettingsModal = window.SettingsModal;
const MaterialModal = window.MaterialModal;
const AlertModal = window.AlertModal;
const ConfirmModal = window.ConfirmModal;

// Get api from window object
const api = typeof window !== 'undefined' && window.api ? window.api : null;

// Mock initial products
const initialProducts = [
    { id: 1, name: 'Талх', price: 5000, category: 'Хүнсний бүтээгдэхүүн' },
    { id: 2, name: 'Сүү', price: 3000, category: 'Хүнсний бүтээгдэхүүн' },
    { id: 3, name: 'Өндөг', price: 7000, category: 'Хүнсний бүтээгдэхүүн' },
    { id: 4, name: 'Тос', price: 12000, category: 'Хүнсний бүтээгдэхүүн' },
    { id: 5, name: 'Гурил', price: 8000, category: 'Хүнсний бүтээгдэхүүн' },
    { id: 6, name: 'Цай', price: 4000, category: 'Ундаа' },
    { id: 7, name: 'Кофе', price: 15000, category: 'Ундаа' },
    { id: 8, name: 'Juice', price: 6000, category: 'Ундаа' },
    { id: 9, name: 'Chips', price: 2000, category: 'Snacks' },
    { id: 10, name: 'Chocolate', price: 3000, category: 'Snacks' },
    { id: 11, name: 'Cookies', price: 4000, category: 'Snacks' },
    { id: 12, name: 'Candy', price: 1000, category: 'Snacks' },
];

function App() {
    const [products, setProducts] = useState(initialProducts);
    const [cart, setCart] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [selectedCompany, setSelectedCompany] = useState(null); // b_clients-аас авсан мэдээлэл
    const [vatRate, setVatRate] = useState(0);
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [currentOperator, setCurrentOperator] = useState(null);
    const [loginUsername, setLoginUsername] = useState('');
    const [loginPassword, setLoginPassword] = useState('');
    const [loginError, setLoginError] = useState('');
    const [isLoggingIn, setIsLoggingIn] = useState(false);
    const [barcodeInput, setBarcodeInput] = useState('');
    const [regNoSearchResult, setRegNoSearchResult] = useState(null);
    const [currentMtId, setCurrentMtId] = useState(null);
    const [currentSourceNo, setCurrentSourceNo] = useState(null);
    const [cartSummary, setCartSummary] = useState({ totalvat: 0, totalsum: 0, discount: 0, totalcitytax: 0, vat: 0, citytax: 0 });
    const [isPaymentModalOpen, setIsPaymentModalOpen] = useState(false);
    const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
    const [isMaterialModalOpen, setIsMaterialModalOpen] = useState(false);
    const [isProductCatalogModalOpen, setIsProductCatalogModalOpen] = useState(false);
    const [isReceiptSearchModalOpen, setIsReceiptSearchModalOpen] = useState(false);
    const [isReportsModalOpen, setIsReportsModalOpen] = useState(false);
    const [isBannerOpen, setIsBannerOpen] = useState(false);
    const [materials, setMaterials] = useState([]);
    const [alertModal, setAlertModal] = useState({ isOpen: false, message: '' }); // AlertModal state
    const [confirmModal, setConfirmModal] = useState({ isOpen: false, message: '', onConfirm: null, onCancel: null }); // ConfirmModal state
    const [currentDiscountCard, setCurrentDiscountCard] = useState(null); // Хөнгөлөлтийн картын мэдээлэл
    const [licenseWarning, setLicenseWarning] = useState(null); // Лицензийн анхааруулга
    const [selectedCartItemId, setSelectedCartItemId] = useState(null); // Сонгогдсон картын мөрийн ID
    const [quantityInputModal, setQuantityInputModal] = useState({ isOpen: false, itemId: null, currentQuantity: 0, dotcode: null }); // Тоо оруулах modal
    const [lastSelectedProduct, setLastSelectedProduct] = useState(null); // Сүүлийн сонгосон барааны мэдээлэл
    const [addQuantityModal, setAddQuantityModal] = useState({ isOpen: false, quantity: '' }); // F8-аар тоо нэмэх modal
    const [hooksLoaded, setHooksLoaded] = useState(false); // Hooks ачаалагдсан эсэх
    const [sidebarCollapsed, setSidebarCollapsed] = useState(false); // Жижиг дэлгэцэнд зүүн панелыг шахаж жижигрүүлэх
    const [isSmallScreen, setIsSmallScreen] = useState(typeof window !== 'undefined' ? window.innerWidth < 992 : false);
    const [isMobileScreen, setIsMobileScreen] = useState(typeof window !== 'undefined' ? window.innerWidth <= 640 : false);
    const [mobileTab, setMobileTab] = useState('products'); // Mobile tab: 'products' | 'cart'
    const barcodeInputRef = useRef(null); // Баркод input-ийн ref (alert-ийн дараа focus буцаах)
    const paymentHookRef = useRef(null);

    // Check if hooks are loaded
    useEffect(() => {
        const checkHooks = () => {
            const hasHooks = typeof window !== 'undefined' && 
                typeof window.usePayment === 'function' &&
                typeof window.useCart === 'function' &&
                typeof window.useAuth === 'function' &&
                typeof window.useSettings === 'function';
            
            if (hasHooks) {
                console.log('All hooks are loaded');
                setHooksLoaded(true);
            } else {
                console.log('Waiting for hooks to load...', {
                    usePayment: typeof window !== 'undefined' ? typeof window.usePayment : 'window undefined',
                    useCart: typeof window !== 'undefined' ? typeof window.useCart : 'window undefined',
                    useAuth: typeof window !== 'undefined' ? typeof window.useAuth : 'window undefined',
                    useSettings: typeof window !== 'undefined' ? typeof window.useSettings : 'window undefined'
                });
                setTimeout(checkHooks, 50);
            }
        };
        checkHooks();
    }, [isLoggedIn]);

    // Initialize hooks
    const createNewTransactionHeaderWrapper = async (operatorOverride = null, clientOverride = null) => {
        const transactionHelpers = typeof window !== 'undefined' ? window.transactionHelpers : null;
        if (!transactionHelpers) {
            console.error('Transaction helpers not available');
            return null;
        }
        // Use override values if provided, otherwise use state values
        const operator = operatorOverride || currentOperator;
        const client = clientOverride || selectedCompany;
        return await transactionHelpers.createNewTransactionHeader(
            api,
            operator,
            client,
            setCurrentMtId,
            setCurrentSourceNo
        );
    };

    // AlertModal-г нээх функц (useCart hook-д дамжуулах)
    const showAlert = (message) => {
        setAlertModal({ isOpen: true, message });
    };

    // Initialize cart hook
    const cartHook = typeof window !== 'undefined' && window.useCart ? window.useCart(
        cart,
        setCart,
        api,
        selectedCompany,
        currentOperator,
        vatRate,
        currentDiscountCard,
        currentMtId,
        setCurrentMtId,
        createNewTransactionHeaderWrapper,
        showAlert
    ) : null;

    const addToCartBase = cartHook?.addToCart || (async () => {});
    // Wrapper функц: addToCart дуудагдах үед сүүлийн сонгосон барааны мэдээллийг хадгалах
    const addToCart = async (product) => {
        // Сүүлийн сонгосон барааны мэдээллийг хадгалах
        if (product && product.m_id) {
            setLastSelectedProduct(product);
        }
        return await addToCartBase(product);
    };
    const updateQuantityBase = cartHook?.updateQuantity || (async () => {});
    const updateDiscountBase = cartHook?.updateDiscount || (async () => {});
    const updateDiscountAmountBase = cartHook?.updateDiscountAmount || (async () => {});
    const removeFromCartBase = cartHook?.removeFromCart || (async () => {});
    
    // AlertModal-г хаах функц (баркод input-д focus буцаах)
    const handleAlertClose = () => {
        setAlertModal({ isOpen: false, message: '' });
        // Modal хаагдах үед баркод input-д focus буцаах
        setTimeout(() => {
            if (barcodeInputRef.current) {
                barcodeInputRef.current.focus();
            }
        }, 100);
    };
    
    // ConfirmModal-г нээх функц (useAuth hook-д дамжуулах)
    const showConfirm = (message, onConfirm) => {
        setConfirmModal({ isOpen: true, message, onConfirm, onCancel: null });
    };
    
    // F5 товч дарахад "Төлбөр төлөх" товчин дээр дарсантай адил үйлдэл хийх (бүх газраас)
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F5 товч дарахад (keyCode 116 эсвэл key === 'F5')
            if (e.keyCode === 116 || e.key === 'F5') {
                e.preventDefault(); // Browser refresh-ийг зогсоох
                
                const hook = paymentHookRef.current;
                // Check if paymentHook and handleCheckout are available
                if (!usePaymentAvailable || !hook || !hook.handleCheckout) {
                    console.error('F5 pressed but handleCheckout not available');
                    console.error('paymentHook:', hook);
                    showAlert('Төлбөр төлөх функц ажиллахгүй байна. Системийн алдаа.');
                    return;
                }
                
                // "Төлбөр төлөх" товчин дээр дарсантай адил үйлдэл - handleCheckout() дуудах
                // handleCheckout() нь сагс хоосон эсэхийг шалгаж, зөвхөн сагс хоосон биш байвал төлбөр хийх цонх нээдэг
                if (hook.handleCheckout && typeof hook.handleCheckout === 'function') {
                    hook.handleCheckout();
                }
            }
        };
        
        window.addEventListener('keydown', handleKeyDown);
        
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, [usePaymentAvailable, showAlert]);

    // Жижиг дэлгэц шалгах: 992px-аас бага бол зүүн панелыг автоматаар нуух (autohide)
    useEffect(() => {
        if (typeof window === 'undefined') return;
        const onResize = () => {
            const small = window.innerWidth < 992;
            const mobile = window.innerWidth <= 640;
            setIsSmallScreen(small);
            setSidebarCollapsed(small);
            setIsMobileScreen(mobile);
        };
        onResize();
        window.addEventListener('resize', onResize);
        return () => window.removeEventListener('resize', onResize);
    }, []);

    // F3 товч дарахад dotcode (дотоод код) input руу шилжих (sidebar эсвэл compact header)
    useEffect(() => {
        const handleKeyDown = (e) => {
            if (e.keyCode === 114 || e.key === 'F3') {
                e.preventDefault();
                const el = document.getElementById('internalCodeInput') || document.getElementById('internalCodeInputCart');
                if (el) {
                    el.focus();
                    el.select();
                }
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, []);
    
    // F4 товч дарахад barcode input руу шилжих (бүх газраас)
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F4 товч дарахад (keyCode 115 эсвэл key === 'F4')
            if (e.keyCode === 115 || e.key === 'F4') {
                e.preventDefault();
                if (barcodeInputRef.current) {
                    barcodeInputRef.current.focus();
                    barcodeInputRef.current.select(); // Текст сонгож байрлуулах
                }
            }
        };
        
        window.addEventListener('keydown', handleKeyDown);
        
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, []);

    // F1 товч дарахад барааны лавлагааны цонх нээх (баркод input-д focus байвал)
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F1 товч дарахад (keyCode 112 эсвэл key === 'F1')
            if (e.keyCode === 112 || e.key === 'F1') {
                const activeElement = document.activeElement;
                const isBarcodeInput = activeElement === barcodeInputRef.current;
                
                // Баркод input-д focus байвал барааны лавлагааны цонх нээх
                if (isBarcodeInput) {
                    e.preventDefault();
                    setIsProductCatalogModalOpen(true);
                }
            }
        };
        
        window.addEventListener('keydown', handleKeyDown);
        
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, []);

    // F2 товч дарахад буцаалтын цонх нээх
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F2 товч дарахад (keyCode 113 эсвэл key === 'F2')
            if (e.keyCode === 113 || e.key === 'F2') {
                e.preventDefault();
                if (typeof window !== 'undefined' && typeof window.openRefundModal === 'function') {
                    window.openRefundModal();
                }
            }
        };

        window.addEventListener('keydown', handleKeyDown);

        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, []);

    // F7 товч дарахад хөнгөлөлтийн картын input руу focus хийх (бүх газраас)
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F7 товч дарахад (keyCode 118 эсвэл key === 'F7')
            if (e.keyCode === 118 || e.key === 'F7') {
                e.preventDefault();
                const discountCardInput = document.getElementById('discountCardInput');
                if (discountCardInput) {
                    discountCardInput.focus();
                    discountCardInput.select(); // Текст сонгож байрлуулах
                }
            }
        };
        
        window.addEventListener('keydown', handleKeyDown);
        
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, []);

    // F8 товч дарахад сүүлийн сонгосон бараан дээр тоо нэмэх цонх гаргах
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F8 товч дарахад (keyCode 119 эсвэл key === 'F8')
            if (e.keyCode === 119 || e.key === 'F8') {
                e.preventDefault();
                // Сүүлийн сонгосон бараа байгаа эсэхийг шалгах
                if (lastSelectedProduct && lastSelectedProduct.m_id) {
                    setAddQuantityModal({ isOpen: true, quantity: '' });
                } else {
                    showAlert('Сүүлийн сонгосон бараа байхгүй байна. Эхлээд бараа нэмнэ үү.');
                }
            }
        };
        
        window.addEventListener('keydown', handleKeyDown);
        
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, [lastSelectedProduct, showAlert]);

    // F10 товч дарахад төлбөр хийх цонх нээгдээд байгууллага radio button сонгогдоод regNoInput selected
    const [f10Pressed, setF10Pressed] = React.useState(false);
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F10 товч дарахад (keyCode 121 эсвэл key === 'F10')
            if (e.keyCode === 121 || e.key === 'F10') {
                e.preventDefault(); // Browser refresh-ийг зогсоох
                e.stopPropagation(); // Бусад event listener-ууд руу дамжихгүй байх
                
                const hook = paymentHookRef.current;
                // Check if paymentHook and handleCheckout are available
                if (!usePaymentAvailable || !hook || !hook.handleCheckout) {
                    console.error('F10 pressed but handleCheckout not available');
                    console.error('paymentHook:', hook);
                    showAlert('Төлбөр төлөх функц ажиллахгүй байна. Системийн алдаа.');
                    return;
                }
                
                // "Төлбөр төлөх" товчин дээр дарсантай адил үйлдэл - handleCheckout() дуудах
                // handleCheckout() нь сагс хоосон эсэхийг шалгаж, зөвхөн сагс хоосон биш байвал төлбөр хийх цонх нээдэг
                if (hook.handleCheckout && typeof hook.handleCheckout === 'function') {
                    hook.handleCheckout();
                    // F10 даралтыг тэмдэглэх
                    setF10Pressed(true);
                    // Товчлуур даралтын тэмдэглэлийг цэвэрлэх (modal нээгдсэний дараа)
                    setTimeout(() => {
                        setF10Pressed(false);
                    }, 500);
                }
            }
        };
        
        window.addEventListener('keydown', handleKeyDown, true); // capture phase-д ажиллах
        
        return () => {
            window.removeEventListener('keydown', handleKeyDown, true);
        };
    }, [usePaymentAvailable, showAlert]);

    // F12 товч дарахад татварт илгээх
    useEffect(() => {
        const handleKeyDown = (e) => {
            // F12 товч дарахад (keyCode 123 эсвэл key === 'F12')
            if (e.keyCode === 123 || e.key === 'F12') {
                e.preventDefault();
                if (typeof window !== 'undefined' && typeof window.sendToTaxSystemGlobal === 'function') {
                    window.sendToTaxSystemGlobal();
                }
            }
        };

        window.addEventListener('keydown', handleKeyDown);

        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, []);

    // Payment modal хаагдах үед f10Pressed state-ийг reset хийх
    useEffect(() => {
        if (!isPaymentModalOpen && f10Pressed) {
            setF10Pressed(false);
        }
    }, [isPaymentModalOpen, f10Pressed]);

    // Global function for main process to use (window close event)
    useEffect(() => {
        if (typeof window !== 'undefined') {
            window.showConfirmGlobal = (message, onConfirm, onCancel) => {
                setConfirmModal({ 
                    isOpen: true, 
                    message, 
                    onConfirm: () => {
                        setConfirmModal({ isOpen: false, message: '', onConfirm: null, onCancel: null });
                        if (onConfirm) onConfirm();
                    },
                    onCancel: () => {
                        setConfirmModal({ isOpen: false, message: '', onConfirm: null, onCancel: null });
                        if (onCancel) onCancel();
                    }
                });
            };
        }
        return () => {
            if (typeof window !== 'undefined') {
                delete window.showConfirmGlobal;
            }
        };
    }, []);
    
    // Update global cart and mtId state for window close event
    useEffect(() => {
        if (typeof window !== 'undefined') {
            window.__cartState = cart;
            window.__currentMtId = currentMtId;
        }
    }, [cart, currentMtId]);

    // Expose function to open ReceiptSearchModal
    useEffect(() => {
        if (typeof window !== 'undefined') {
            window.onOpenReceiptSearch = () => {
                setIsReceiptSearchModalOpen(true);
            };
        }
        return () => {
            if (typeof window !== 'undefined') {
                delete window.onOpenReceiptSearch;
            }
        };
    }, [setIsReceiptSearchModalOpen]);

    // ConfirmModal-г баталгаажуулах функц
    const handleConfirmConfirm = () => {
        if (confirmModal.onConfirm && typeof confirmModal.onConfirm === 'function') {
            confirmModal.onConfirm();
        }
        setConfirmModal({ isOpen: false, message: '', onConfirm: null });
        // Modal хаагдах үед баркод input-д focus буцаах
        setTimeout(() => {
            if (barcodeInputRef.current) {
                barcodeInputRef.current.focus();
            }
        }, 100);
    };
    
    // ConfirmModal-г цуцлах функц
    const handleConfirmCancel = () => {
        if (confirmModal.onCancel && typeof confirmModal.onCancel === 'function') {
            confirmModal.onCancel();
        } else {
            setConfirmModal({ isOpen: false, message: '', onConfirm: null, onCancel: null });
        }
        // Modal хаагдах үед баркод input-д focus буцаах
        setTimeout(() => {
            if (barcodeInputRef.current) {
                barcodeInputRef.current.focus();
            }
        }, 100);
    };
    
    // Wrapper функц: AlertModal ашиглах
    const updateQuantity = async (id, change) => {
        const itemToUpdate = cart.find(item => item.id === id);
        if (!itemToUpdate) return;
        
        const newQuantity = itemToUpdate.quantity + change;
        
        // Хэрэв тоо 0-ээс бага бол removeFromCart-г дуудах (delete permission check байгаа)
        if (newQuantity <= 0) {
            await removeFromCartBase(id);
            return;
        }
        
        // Бусад тохиолдолд ердийн updateQuantity-г дуудах
        await updateQuantityBase(id, change);
    };
    
    const removeFromCart = async (id) => {
        await removeFromCartBase(id);
    };

    // Handle barcode scan with quantity input for kg/m units
    const handleBarcodeQuantityInput = (product) => {
        setInternalCodeProduct(product);
        setInternalCodeQuantity('1');
        setInternalCodeModalOpen(true);
    };

    // Initialize barcode hook
    const barcodeHook = typeof window !== 'undefined' && window.useBarcode ? window.useBarcode(
        api,
        selectedCompany,
        currentOperator,
        barcodeInput,
        setBarcodeInput,
        addToCart,
        showAlert,
        handleBarcodeQuantityInput
    ) : null;

    const handleBarcodeScan = barcodeHook?.handleBarcodeScan || (async () => {});

    // Handle internal code search with quantity input
    const [internalCodeInput, setInternalCodeInput] = useState('');
    const [internalCodeProduct, setInternalCodeProduct] = useState(null);
    const [internalCodeQuantity, setInternalCodeQuantity] = useState('1');
    const [internalCodeModalOpen, setInternalCodeModalOpen] = useState(false);
    const [internalCodeLoading, setInternalCodeLoading] = useState(false);

    const handleInternalCodeSearch = async (code) => {
        if (!code || !code.trim()) {
            setInternalCodeProduct(null);
            return;
        }

        if (!api || !selectedCompany) {
            showAlert('API эсвэл байгууллага сонгоогүй байна!');
            return;
        }

        setInternalCodeLoading(true);
        try {
            const b_id = selectedCompany.b_id || currentOperator?.b_id || 0;
            const result = await api.getProductByInternalCode(code.trim(), b_id);

            if (result.success && result.data) {
                setInternalCodeProduct(result.data);
                setInternalCodeQuantity('1');
                setInternalCodeModalOpen(true);
            } else {
                showAlert('Дотоод код олдсонгүй: ' + code.trim());
                setInternalCodeProduct(null);
                // Дотоод код олдохгүй бол barcodeInput focus хийх
                setTimeout(() => {
                    if (barcodeInputRef.current) {
                        barcodeInputRef.current.focus();
                        barcodeInputRef.current.select();
                    }
                }, 100);
            }
        } catch (error) {
            console.error('Error searching by internal code:', error);
            showAlert('Дотоод код хайхад алдаа гарлаа: ' + error.message);
            setInternalCodeProduct(null);
            // Алдаа гарвал barcodeInput focus хийх
            setTimeout(() => {
                if (barcodeInputRef.current) {
                    barcodeInputRef.current.focus();
                    barcodeInputRef.current.select();
                }
            }, 100);
        } finally {
            setInternalCodeLoading(false);
        }
    };

    const handleInternalCodeAddToCart = async () => {
        if (!internalCodeProduct) return;
        if (internalCodeLoading) return; // Давхар нэмэхээс сэргийлэх

        const quantity = Math.round((parseFloat(internalCodeQuantity) || 1) * 1000) / 1000; // 3 орон бутархай хадгалах
        if (quantity <= 0) {
            showAlert('Тоо хэмжээ 0-ээс их байх ёстой!');
            return;
        }

        // Loading эхлүүлэх
        setInternalCodeLoading(true);

        try {
            // Add product to cart with specified quantity
            // Ensure name is set from m_name (for cart display)
            const productToAdd = {
                ...internalCodeProduct,
                name: internalCodeProduct.m_name || internalCodeProduct.name || 'Бүтээгдэхүүн',
                tcount: quantity,
                quantity: quantity
            };

            await addToCart(productToAdd);
            
            // Reset and close (амжилттай нэмсний дараа)
            setInternalCodeProduct(null);
            setInternalCodeQuantity('1');
            setInternalCodeInput('');
            setInternalCodeModalOpen(false);
            
            // Дотоод кодоор уншуулсны дараа barcodeInput focus хийх
            setTimeout(() => {
                if (barcodeInputRef.current) {
                    barcodeInputRef.current.focus();
                    barcodeInputRef.current.select();
                }
            }, 100);
        } catch (error) {
            console.error('Error adding product to cart:', error);
            showAlert('Бараа нэмэхэд алдаа гарлаа: ' + error.message);
        } finally {
            setInternalCodeLoading(false);
        }
    };

    // Handle regNo search
    const handleRegNoSearch = async (regNo) => {
        if (!regNo || !regNo.trim()) {
            setRegNoSearchResult(null);
            return;
        }
        
        const regNoTrimmed = regNo.trim();
        console.log('Searching for company with regNo:', regNoTrimmed);
        setRegNoSearchResult({ loading: true });
        
        try {
            // Step 0: Эхлээд өөрийн серверээс хайх
            if (api && api.getClientByCregister) {
                try {
                    const localResult = await api.getClientByCregister(regNoTrimmed);
                    if (localResult && localResult.success && localResult.data) {
                        const client = localResult.data;
                        const localVatPayer = client.vatPayer ?? client.vatpayer ?? null;
                        const localCityPayer = client.cityPayer ?? client.citypayer ?? client.citytaxpayer ?? null;
                        const localCompanyInfo = {
                            regNo: regNoTrimmed,
                            companyName: client.cname || '',
                            customerTin: client.merchantTin || null,
                            vatPayer: localVatPayer !== null ? !!localVatPayer : undefined,
                            cityPayer: localCityPayer !== null ? !!localCityPayer : undefined,
                            success: true,
                            fromLocal: true
                        };
                        setRegNoSearchResult(localCompanyInfo);
                        // Хэрэв merchantTin байхгүй бол татвараас хайж update хийх
                        if (!client.merchantTin) {
                            setRegNoSearchResult({ ...localCompanyInfo, loading: true });
                        } else {
                            return;
                        }
                    }
                } catch (localError) {
                    console.error('Error checking local database for company info:', localError);
                }
            }

            // Step 1: Эхлээд getTinInfo-аас regNo-оос Tin авах
            const taxInfoBaseUrl = ((selectedCompany?.taxUrl || 'https://api.ebarimt.mn') + '').replace(/\/+$/, '');
            const tinInfoUrl = `${taxInfoBaseUrl}/api/info/check/getTinInfo?regNo=${encodeURIComponent(regNoTrimmed)}`;
            console.log('Fetching TIN from URL:', tinInfoUrl);
            
            const tinInfoResponse = await fetch(tinInfoUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });
            
            const tinInfoText = await tinInfoResponse.text();
            console.log('TIN Info response text:', tinInfoText);
            console.log('TIN Info response status:', tinInfoResponse.status, tinInfoResponse.statusText);
            
            let tin = null;
            let tinInfoData = null;
            
            try {
                tinInfoData = JSON.parse(tinInfoText);
            } catch (parseError) {
                console.error('Error parsing TIN Info JSON:', parseError);
                setRegNoSearchResult({
                    regNo: regNoTrimmed,
                    companyName: 'Олдсонгүй',
                    customerTin: null,
                    success: false,
                    error: `API хариу буруу форматтай: ${tinInfoText.substring(0, 100)}`
                });
                return;
            }
            
            console.log('TIN Info parsed data:', tinInfoData);
            
            if (tinInfoResponse.ok) {
                // Check different possible response formats
                if (tinInfoData.status === 200 && tinInfoData.data) {
                    tin = tinInfoData.data.toString();
                    console.log('Got TIN from getTinInfo:', tin);
                } else if (tinInfoData.data && typeof tinInfoData.data === 'string') {
                    // Sometimes data is directly a string
                    tin = tinInfoData.data.toString();
                    console.log('Got TIN (string format):', tin);
                } else if (tinInfoData.tin) {
                    // Alternative format
                    tin = tinInfoData.tin.toString();
                    console.log('Got TIN (alternative format):', tin);
                } else {
                    console.warn('TIN not found in response:', tinInfoData);
                    setRegNoSearchResult({
                        regNo: regNoTrimmed,
                        companyName: 'Олдсонгүй',
                        customerTin: null,
                        success: false,
                        error: tinInfoData.msg || tinInfoData.message || 'TIN олдсонгүй. Response: ' + JSON.stringify(tinInfoData)
                    });
                    return;
                }
                
                if (!tin || tin.trim() === '') {
                    setRegNoSearchResult({
                        regNo: regNoTrimmed,
                        companyName: 'Олдсонгүй',
                        customerTin: null,
                        success: false,
                        error: 'TIN хоосон байна'
                    });
                    return;
                }
                
                // Step 2: Tin-р худалдан авагчийн мэдээлэл хайж нэр болон бусад зүйлсийг олох
                console.log('Step 2: Getting customer info from getInfo for TIN:', tin);
                const companyInfoUrl = `${taxInfoBaseUrl}/api/info/check/getInfo?tin=${encodeURIComponent(tin)}`;
                console.log('Fetching company info from URL:', companyInfoUrl);
                
                const companyInfoResponse = await fetch(companyInfoUrl, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                
                const companyInfoText = await companyInfoResponse.text();
                console.log('Company Info response text:', companyInfoText);
                console.log('Company Info response status:', companyInfoResponse.status, companyInfoResponse.statusText);
                
                let companyInfoData = null;
                try {
                    companyInfoData = JSON.parse(companyInfoText);
                } catch (parseError) {
                    console.error('Error parsing Company Info JSON:', parseError);
                    setRegNoSearchResult({
                        regNo: regNoTrimmed,
                        companyName: 'Олдсонгүй',
                        customerTin: tin,
                        success: false,
                        error: `API хариу буруу форматтай: ${companyInfoText.substring(0, 100)}`
                    });
                    return;
                }
                
                console.log('Company Info parsed data:', companyInfoData);
                
                if (companyInfoResponse.ok) {
                    // Check different possible response formats
                    if (companyInfoData.status === 200 && companyInfoData.data && companyInfoData.data.found) {
                        const updatedInfo = {
                            regNo: regNoTrimmed,
                            companyName: companyInfoData.data.name || '',
                            customerTin: tin,
                            vatPayer: companyInfoData.data.vatPayer || false,
                            cityPayer: companyInfoData.data.cityPayer || false,
                            freeProject: companyInfoData.data.freeProject || false,
                            success: true
                        };
                        setRegNoSearchResult(updatedInfo);
                        if (api && api.updateClientRegNoAndCompanyInfo) {
                            try {
                                await api.updateClientRegNoAndCompanyInfo(null, {
                                    regNo: regNoTrimmed,
                                    companyName: updatedInfo.companyName,
                                    customerTin: updatedInfo.customerTin,
                                    vatPayer: updatedInfo.vatPayer,
                                    cityPayer: updatedInfo.cityPayer
                                });
                            } catch (updateError) {
                                console.error('Error updating local company info from tax system:', updateError);
                            }
                        }
                    } else if (companyInfoData.data && companyInfoData.data.name) {
                        // Alternative format - data exists but found might be missing
                        const updatedInfo = {
                            regNo: regNoTrimmed,
                            companyName: companyInfoData.data.name || '',
                            customerTin: tin,
                            vatPayer: companyInfoData.data.vatPayer || false,
                            cityPayer: companyInfoData.data.cityPayer || false,
                            freeProject: companyInfoData.data.freeProject || false,
                            success: true
                        };
                        setRegNoSearchResult(updatedInfo);
                        if (api && api.updateClientRegNoAndCompanyInfo) {
                            try {
                                await api.updateClientRegNoAndCompanyInfo(null, {
                                    regNo: regNoTrimmed,
                                    companyName: updatedInfo.companyName,
                                    customerTin: updatedInfo.customerTin,
                                    vatPayer: updatedInfo.vatPayer,
                                    cityPayer: updatedInfo.cityPayer
                                });
                            } catch (updateError) {
                                console.error('Error updating local company info from tax system:', updateError);
                            }
                        }
                    } else {
                        setRegNoSearchResult({
                            regNo: regNoTrimmed,
                            companyName: 'Олдсонгүй',
                            customerTin: tin,
                            success: false,
                            error: companyInfoData.msg || companyInfoData.message || 'Байгууллагын мэдээлэл олдсонгүй. Response: ' + JSON.stringify(companyInfoData)
                        });
                    }
                } else {
                    setRegNoSearchResult({
                        regNo: regNoTrimmed,
                        companyName: 'Олдсонгүй',
                        customerTin: tin,
                        success: false,
                        error: `HTTP ${companyInfoResponse.status}: ${companyInfoResponse.statusText}. Response: ${companyInfoText.substring(0, 200)}`
                    });
                }
            } else {
                setRegNoSearchResult({
                    regNo: regNoTrimmed,
                    companyName: 'Олдсонгүй',
                    customerTin: null,
                    success: false,
                    error: `HTTP ${tinInfoResponse.status}: ${tinInfoResponse.statusText}. Response: ${tinInfoText.substring(0, 200)}`
                });
            }
        } catch (error) {
            console.error('Error searching for company:', error);
            setRegNoSearchResult({
                regNo: regNoTrimmed,
                companyName: 'Олдсонгүй',
                customerTin: null,
                success: false,
                error: error.message || 'Сүлжээний алдаа гарлаа. Интернэт холболт шалгана уу.'
            });
        }
    };

    // Handle barcode input - зөвхөн Enter дарахад хайлт хийх (автоматаар хайхгүй)

    // Initialize discount hook
    const discountHook = typeof window !== 'undefined' && window.useDiscount ? window.useDiscount(
        api,
        cart,
        setCart,
        selectedCompany,
        vatRate,
        showAlert,
        setCurrentDiscountCard
    ) : null;

    const handleDiscountCardScan = discountHook?.handleDiscountCardScan || (async () => {});

    // Татварын бодолт хийх функцүүд - utils/taxCalculator.js-аас авна
    // Эдгээр функцүүдийг hooks-оос өмнө тодорхойлох хэрэгтэй
    const taxCalculator = typeof window !== 'undefined' ? window.taxCalculator : null;
    
    // Hooks болон татварын модуль бэлэн болох хүртэл 0 — ачааллын үеэр дутуу өгөгдлөөр тооцоо хийхгүй
    const calculateTotal = () => {
        if (!hooksLoaded || !taxCalculator) return 0;
        return taxCalculator.calculateTotal(cart);
    };

    const calculateVATTotal = () => {
        if (!hooksLoaded || !taxCalculator) return 0;
        return taxCalculator.calculateVATTotal(cart);
    };

    const calculateCityTaxTotal = () => {
        if (!hooksLoaded || !taxCalculator) return 0;
        return taxCalculator.calculateCityTaxTotal(cart);
    };

    const calculateTaxTotal = () => {
        if (!hooksLoaded || !taxCalculator) return 0;
        return taxCalculator.calculateTaxTotal(cart);
    };

    const calculateDiscountTotal = () => {
        if (!hooksLoaded || !taxCalculator) return 0;
        return taxCalculator.calculateDiscountTotal(cart);
    };

    const calculateGrandTotal = () => {
        if (!hooksLoaded || !taxCalculator) return 0;
        return taxCalculator.calculateGrandTotal(cart);
    };

    // Format currency function - must be defined before usePayment hook (without MNT symbol)
    const formatCurrency = (amount) => {
        return new Intl.NumberFormat('mn-MN', {
            style: 'decimal',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
        }).format(amount);
    };

    // Initialize payment hook - only if hooks are loaded
    const usePaymentAvailable = typeof window !== 'undefined' && typeof window.usePayment === 'function';
    
    // Use useMemo to ensure hook re-initializes when dependencies change
    const paymentHook = useMemo(() => {
        if (!usePaymentAvailable) {
            return null;
        }
        try {
            const hook = window.usePayment(
                api,
                cart,
                setCart,
                currentOperator,
                selectedCompany, // selectedCompany-г selectedClient гэж usePayment-д дамжуулна
                currentMtId,
                currentSourceNo,
                setCurrentMtId,
                setCurrentSourceNo,
                setIsPaymentModalOpen,
                createNewTransactionHeaderWrapper,
                calculateTotal,
                calculateVATTotal,
                calculateCityTaxTotal,
                calculateTaxTotal,
                calculateGrandTotal,
                formatCurrency,
                showAlert,
                currentDiscountCard, // Хөнгөлөлтийн картын мэдээлэл
                setCurrentDiscountCard, // Хөнгөлөлтийн картыг цэвэрлэх функц
                setSelectedCompany, // Байгууллагын мэдээллийг цэвэрлэх функц
                barcodeInputRef // Баркод input-ийн ref (төлбөр хийсний дараа focus хийх)
            );
            console.log('Payment hook initialized successfully');
            return hook;
        } catch (err) {
            console.error('Error calling window.usePayment:', err);
            return null;
        }
    }, [usePaymentAvailable, api, cart, currentOperator, selectedCompany, currentMtId, currentSourceNo, currentDiscountCard, hooksLoaded]);

    useEffect(() => {
        paymentHookRef.current = paymentHook;
    }, [paymentHook]);

    const handleCheckout = paymentHook?.handleCheckout || (() => {
        if (!usePaymentAvailable) {
            showAlert('Төлбөр төлөх модуль ачаалагдаагүй байна.');
            return;
        }
        // If paymentHook is null or handleCheckout is missing
        if (!paymentHook) {
            console.error('handleCheckout not available: paymentHook is null');
            console.error('hooksLoaded:', hooksLoaded);
            console.error('window.usePayment:', typeof window !== 'undefined' ? (window.usePayment ? 'exists' : 'NOT FOUND') : 'window undefined');
            showAlert('Төлбөр төлөх функц ажиллахгүй байна. Системийн алдаа.');
            return;
        }
        // If paymentHook exists but handleCheckout is missing
        console.error('handleCheckout not available from paymentHook');
        console.error('paymentHook:', paymentHook);
        showAlert('Төлбөр төлөх функц ажиллахгүй байна. Системийн алдаа.');
    });
    const handlePaymentConfirm = paymentHook?.handlePaymentConfirm || (async () => {});
    const handlePaymentCancelBase = paymentHook?.handlePaymentCancel || (() => {});
    const handlePaymentCancel = () => {
        handlePaymentCancelBase();
        // F10 даралтын тэмдэглэлийг цэвэрлэх
        setF10Pressed(false);
        // Modal хаагдах үед barcode input-д focus хийх
        setTimeout(() => {
            if (barcodeInputRef.current) {
                barcodeInputRef.current.focus();
                barcodeInputRef.current.select();
            }
        }, 100);
    };
    const handleRefund = paymentHook?.handleRefund || (async (receiptId, receiptDate) => {
        console.error('handleRefund not available from paymentHook');
        console.error('hooksLoaded:', hooksLoaded);
        console.error('window.usePayment:', typeof window !== 'undefined' ? (window.usePayment ? 'exists' : 'NOT FOUND') : 'window undefined');
        console.error('paymentHook:', paymentHook);
        showAlert('Буцаалт хийх функц ажиллахгүй байна. Системийн алдаа.');
    });

    // Initialize auth hook
    const authHook = typeof window !== 'undefined' && window.useAuth ? window.useAuth(
        api,
        setCurrentOperator,
        setSelectedCompany,
        setVatRate,
        setProducts,
        setCart,
        setCurrentMtId,
        setCurrentSourceNo,
        setCurrentDiscountCard,
        setIsLoggedIn,
        setLoginError,
        setIsLoggingIn,
        createNewTransactionHeaderWrapper,
        showAlert,
        showConfirm
    ) : null;

    const handleLogin = authHook?.handleLogin || (async () => {});
    const handleLogout = authHook?.handleLogout || (() => {});

    // Initialize settings hook
    const settingsHook = typeof window !== 'undefined' && window.useSettings ? window.useSettings(
        api,
        selectedCompany,
        setSelectedCompany,
        setVatRate,
        setIsSettingsModalOpen,
        showAlert
    ) : null;

    const handleSaveSettings = settingsHook?.handleSaveSettings || (async () => {});

    // REMOVED: Old addToCart, updateQuantity, removeFromCart, handleDiscountCardScan, 
    // handleLogin, handleLogout, handleSaveSettings, handleCheckout, handlePaymentConfirm, 
    // handlePaymentCancel, createNewTransactionHeader functions - now using hooks

    // data.txt дээрх программ хаах хугацааг шалгах — эхлэлтэд маш хойшлуулна
    useEffect(() => {
        if (!api) return;
        const baseUrl = selectedCompany?.apiURL || selectedCompany?.apiUrl || '';
        const checkLicense = async () => {
            try {
                const bId = (typeof localStorage !== 'undefined' && localStorage.getItem) ? localStorage.getItem('b_id') : undefined;
                const result = await api.checkLicenseExpiration(baseUrl || undefined, bId);
                if (result.success && result.data) {
                    setLicenseWarning(result.data);
                }
            } catch (err) {
                console.error('Лиценз шалгахад алдаа:', err);
            }
        };
        const initialDelay = setTimeout(checkLicense, 2000);
        const interval = setInterval(checkLicense, 5 * 60 * 1000);
        return () => {
            clearTimeout(initialDelay);
            clearInterval(interval);
        };
    }, [api, isLoggedIn, selectedCompany?.apiURL, selectedCompany?.apiUrl]);

    // Create transaction header when logged in and operator/client are available
    // ТАЙЛБАР: m_addPOSG2 ашиглахгүй тул энэ useEffect-ийг идэвхгүй болгосон
    // useEffect(() => {
    //     if (isLoggedIn && currentOperator && selectedClient && !currentMtId) {
    //         console.log('POS page opened, creating transaction header...');
    //         createNewTransactionHeader().then(headerResult => {
    //             if (headerResult) {
    //                 console.log('Transaction header created on POS page open:', headerResult);
    //             } else {
    //                 console.warn('Failed to create transaction header on POS page open');
    //             }
    //         }).catch(err => {
    //             console.error('Error creating transaction header on POS page open:', err);
    //         });
    //     }
    // }, [isLoggedIn, currentOperator, selectedClient, currentMtId]);

    // Auto-login for testing (remove in production)
    useEffect(() => {
        // Disabled: test auto-login interferes with tenant/manual login flow
        return;
        if (!isLoggedIn && !isLoggingIn) {
            const autoLogin = async () => {
                console.log('Auto-login starting...');
                const username = 'bataa';
                const password = 'bataa';
                
                try {
                    const result = await api.loginOperator(username, password);
                    if (result.success) {
                        const operator = result.data;
                        
                        // Validate operator data before setting
                        if (!operator) {
                            console.error('Operator data is null or undefined');
                            return;
                        }
                        
                        // Check if setCurrentOperator is available
                        if (!setCurrentOperator || typeof setCurrentOperator !== 'function') {
                            console.error('setCurrentOperator is not available or not a function');
                            return;
                        }
                        
                        try {
                            setCurrentOperator(operator);
                            console.log('Auto-login: Operator set successfully:', operator);
                        } catch (setError) {
                            console.error('Error setting operator in auto-login:', setError);
                            return;
                        }
                        
                        // b_id болон dep_code-г localStorage-д хадгалах
                        if (operator.b_id) {
                            try {
                                localStorage.setItem('b_id', operator.b_id.toString());
                                console.log('Saved b_id to localStorage:', operator.b_id);
                            } catch (storageError) {
                                console.error('Error saving b_id to localStorage:', storageError);
                            }
                        }
                        
                        const depCode = operator.dep_code || operator.dep_id?.toString() || operator.dep_id;
                        if (depCode) {
                            try {
                                localStorage.setItem('dep_code', depCode.toString());
                                console.log('Saved dep_code to localStorage:', depCode);
                            } catch (storageError) {
                                console.error('Error saving dep_code to localStorage:', storageError);
                            }
                        }
                        
                        let clientData = null;
                        if (operator.b_id) {
                            try {
                                const clientResult = await api.getClientById(operator.b_id);
                                if (clientResult.success && clientResult.data) {
                                    clientData = clientResult.data;
                                    
                                    // Login хийхэд getTinInfo/getInfo API call хийхгүй
                                    // Зөвхөн payment хийхэд (B2B баримт үед) хэрэгтэй
                                    
                                    setSelectedCompany(clientData);
                                    
                                    try {
                                        console.log(`Loading VAT rate for b_id: ${operator.b_id}`);
                                        const taxRateResult = await api.getTaxRate(operator.b_id, 2);
                                        console.log('VAT rate result:', taxRateResult);
                                        if (taxRateResult.success) {
                                            const rate = taxRateResult.data || 0;
                                            console.log(`Setting VAT rate to: ${rate}`);
                                            setVatRate(rate);
                                        }
                                    } catch (err) {
                                        console.error('Error loading VAT rate:', err);
                                    }
                                }
                            } catch (err) {
                                console.error('Error loading client:', err);
                            }
                        }
                        
                        // Барааны жагсаалтыг эхлэхэд татахгүй — жагсаалт руу орох эсвэл хуудас эргүүлэхэд MaterialModal өөрөө getProductsPaginated дуудана
                        
                        // Create transaction header after login (only if both operator and company are set)
                        // Wait a bit to ensure selectedCompany is set and state is updated
                        if (selectedCompany && operator) {
                            // Use setTimeout to ensure state is updated before creating transaction header
                            // Pass operator and selectedCompany directly to avoid closure issues
                            const operatorData = operator;
                            const companyData = selectedCompany;
                            setTimeout(function() {
                                var asyncFunc = async function() {
                                    try {
                                        // Pass operator and companyData directly to the wrapper to avoid state timing issues
                                        const headerResult = await createNewTransactionHeader(operatorData, companyData);
                        if (headerResult) {
                            console.log('Transaction header created on auto-login:', headerResult);
                                        } else {
                                            console.warn('Failed to create transaction header on auto-login - this is not critical');
                                            console.warn('Operator data:', operatorData);
                                            console.warn('Company data:', companyData);
                                        }
                                    } catch (headerError) {
                                        console.error('Error creating transaction header on auto-login:', headerError);
                                        // Don't block login if transaction header creation fails
                                    }
                                };
                                asyncFunc();
                            }, 200); // Increased delay to ensure state is fully updated
                        } else {
                            console.warn('Company or operator not selected, skipping transaction header creation on auto-login');
                            console.warn('selectedCompany:', !!selectedCompany, 'operator:', !!operator);
                        }
                        
                        setIsLoggedIn(true);
                    }
                } catch (err) {
                    console.error('Auto-login error:', err);
                }
            };
            const timer = setTimeout(() => {
                autoLogin();
            }, 1000);
            return () => clearTimeout(timer);
        }
    }, [isLoggedIn, isLoggingIn]);

    // Show login screen if not logged in
    if (!isLoggedIn) {
        return (
            <Login 
                onLogin={handleLogin}
                isLoggingIn={isLoggingIn}
                loginError={loginError}
            />
        );
    }

    return (
        <div className="app-container">
            {/* data.txt дээрх программ хаах хугацаа: анхааруулга эсвэл блок */}
            {licenseWarning && licenseWarning.message && (
                <>
                    <div style={{
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0,
                        background: licenseWarning.valid ? '#fff3cd' : '#f8d7da',
                        color: licenseWarning.valid ? '#856404' : '#721c24',
                        padding: '10px 20px',
                        textAlign: 'center',
                        fontWeight: 'bold',
                        zIndex: 9999,
                        borderBottom: `2px solid ${licenseWarning.valid ? '#ffc107' : '#dc3545'}`,
                        boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
                    }}>
                        {licenseWarning.message}
                        {licenseWarning.daysRemaining !== null && licenseWarning.valid && (
                            <span style={{ marginLeft: '10px', fontSize: '0.9em' }}>
                                ({licenseWarning.daysRemaining} хоног үлдлээ)
                            </span>
                        )}
                    </div>
                    {/* Хугацаа дууссан үед бүх үйлдлийг блоклох */}
                    {licenseWarning.valid === false && (
                        <div style={{
                            position: 'fixed',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            background: 'rgba(0,0,0,0.7)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            zIndex: 10000
                        }}>
                            <div style={{
                                background: '#fff',
                                padding: '32px',
                                borderRadius: '8px',
                                textAlign: 'center',
                                maxWidth: '400px',
                                boxShadow: '0 4px 20px rgba(0,0,0,0.3)'
                            }}>
                                <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#721c24', marginBottom: '12px' }}>
                                    Программын хүчинтэй хугацаа дууссан
                                </div>
                                <div style={{ color: '#333', marginBottom: '16px' }}>
                                    Программ ашиглах боломжгүй. Холбоо барих эсвэл data.txt шинэчлэх хэрэгтэй.
                                </div>
                            </div>
                        </div>
                    )}
                </>
            )}
            {(!isMobileScreen || mobileTab === 'products') && <Sidebar
                collapsed={!isMobileScreen && isSmallScreen && sidebarCollapsed}
                onExpand={() => setSidebarCollapsed(false)}
                onCollapse={isMobileScreen ? () => setMobileTab('cart') : (isSmallScreen ? () => setSidebarCollapsed(true) : undefined)}
                licenseWarning={licenseWarning}
                currentOperator={currentOperator}
                selectedCompany={selectedCompany}
                vatRate={vatRate}
                currentMtId={currentMtId}
                currentSourceNo={currentSourceNo}
                barcodeInput={barcodeInput}
                onBarcodeChange={setBarcodeInput}
                onBarcodeScan={handleBarcodeScan}
                onRegNoSearch={handleRegNoSearch}
                regNoSearchResult={regNoSearchResult}
                onInternalCodeSearch={handleInternalCodeSearch}
                internalCodeInput={internalCodeInput}
                onInternalCodeChange={setInternalCodeInput}
                internalCodeProduct={internalCodeProduct}
                internalCodeQuantity={internalCodeQuantity}
                onInternalCodeQuantityChange={setInternalCodeQuantity}
                internalCodeModalOpen={internalCodeModalOpen}
                onInternalCodeModalClose={() => {
                    setInternalCodeModalOpen(false);
                    setInternalCodeProduct(null);
                    setInternalCodeQuantity('1');
                    // Modal хаагдах үед barcodeInput focus хийх
                    setTimeout(() => {
                        if (barcodeInputRef.current) {
                            barcodeInputRef.current.focus();
                            barcodeInputRef.current.select();
                        }
                    }, 100);
                }}
                onInternalCodeAddToCart={handleInternalCodeAddToCart}
                internalCodeLoading={internalCodeLoading}
                cart={cart}
                calculateTotal={calculateTotal}
                calculateVATTotal={calculateVATTotal}
                calculateCityTaxTotal={calculateCityTaxTotal}
                calculateTaxTotal={calculateTaxTotal}
                calculateDiscountTotal={calculateDiscountTotal}
                calculateGrandTotal={calculateGrandTotal}
                onLogout={handleLogout}
                onSettingsClick={() => setIsSettingsModalOpen(true)}
                onReportsClick={() => setIsReportsModalOpen(true)}
                onBannerClick={() => setIsBannerOpen(true)}
                onProductCatalogClick={() => setIsProductCatalogModalOpen(true)}
                onMaterialClick={() => {
                    setIsMaterialModalOpen(true);
                }}
                onRefund={handleRefund}
                barcodeInputRef={barcodeInputRef}
                showAlert={showAlert}
                api={api}
                showConfirm={showConfirm}
                addToCart={addToCart}
                setCart={setCart}
            />}

            <div className="main-content" style={{ display: 'none' }}>
                <div className="header">
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                        <h2>Борлуулалтын систем</h2>
                        {currentOperator && (
                            <div style={{ fontSize: '11px', color: '#7f8c8d' }}>
                                {currentOperator.dep_code && `Дэлгүүр: ${currentOperator.dep_code}`}
                            </div>
                        )}
                    </div>
                    <input
                        type="text"
                        className="search-bar"
                        placeholder="Бүтээгдэхүүн хайх..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </div>

                <div style={{ display: 'none' }}>
                <ProductList
                    products={products}
                    searchTerm={searchTerm}
                    onAddToCart={addToCart}
                />
                </div>
            </div>

            {(!isMobileScreen || mobileTab === 'cart') && <Cart
                cart={cart}
                onUpdateQuantity={updateQuantity}
                onUpdateDiscount={updateDiscountBase}
                onUpdateDiscountAmount={updateDiscountAmountBase}
                onRemoveItem={removeFromCart}
                onDiscountCardScan={handleDiscountCardScan}
                onCheckout={handleCheckout}
                calculateTotal={calculateTotal}
                calculateVATTotal={calculateVATTotal}
                calculateCityTaxTotal={calculateCityTaxTotal}
                calculateTaxTotal={calculateTaxTotal}
                calculateDiscountTotal={calculateDiscountTotal}
                calculateGrandTotal={calculateGrandTotal}
                cartSummary={cartSummary}
                showAlert={showAlert}
                barcodeInputRef={barcodeInputRef}
                barcodeInput={barcodeInput}
                onBarcodeChange={setBarcodeInput}
                onBarcodeScan={handleBarcodeScan}
                internalCodeInput={internalCodeInput}
                onInternalCodeChange={setInternalCodeInput}
                onInternalCodeSearch={handleInternalCodeSearch}
                selectedItemId={selectedCartItemId}
                onItemSelect={setSelectedCartItemId}
                onQuantityInputRequest={(itemId, currentQuantity, dotcode) => {
                    setQuantityInputModal({
                        isOpen: true,
                        itemId: itemId,
                        currentQuantity: currentQuantity,
                        dotcode: dotcode
                    });
                }}
                currentDiscountCard={currentDiscountCard}
                onProductCatalogClick={() => setIsProductCatalogModalOpen(true)}
            />}

            {window.OrderMaterialsRightPanel && (
                <window.OrderMaterialsRightPanel
                    selectedCompany={selectedCompany}
                    api={api}
                    showAlert={showAlert}
                    cart={cart}
                    addToCart={addToCart}
                    removeFromCart={removeFromCart}
                />
            )}

            <PaymentModal
                isOpen={isPaymentModalOpen}
                onClose={handlePaymentCancel}
                onConfirm={handlePaymentConfirm}
                calculateTotal={calculateTotal}
                calculateVATTotal={calculateVATTotal}
                calculateCityTaxTotal={calculateCityTaxTotal}
                calculateGrandTotal={calculateGrandTotal}
                showAlert={showAlert}
                showConfirm={showConfirm}
                selectedCompany={selectedCompany}
                currentOperator={currentOperator}
                currentMtId={currentMtId}
                createNewTransactionHeader={createNewTransactionHeaderWrapper}
                f10Pressed={f10Pressed}
            />

            <SettingsModal
                isOpen={isSettingsModalOpen}
                onClose={() => setIsSettingsModalOpen(false)}
                onSave={handleSaveSettings}
                selectedCompany={selectedCompany}
                currentOperator={currentOperator}
                showAlert={showAlert}
                onMaterialClick={() => setIsMaterialModalOpen(true)}
                api={api}
                addToCart={addToCart}
                setCart={setCart}
            />

            {window.ReportsModal && (
                <window.ReportsModal
                    isOpen={isReportsModalOpen}
                    onClose={() => setIsReportsModalOpen(false)}
                    selectedCompany={selectedCompany}
                    currentOperator={currentOperator}
                    showAlert={showAlert}
                    api={api}
                    onOpenReceiptSearch={() => { setIsReportsModalOpen(false); setIsReceiptSearchModalOpen(true); }}
                />
            )}

            {window.BannerPanel && (
                <window.BannerPanel
                    isOpen={isBannerOpen}
                    onClose={() => setIsBannerOpen(false)}
                    orderBaseUrl={selectedCompany?.bannerUrl || 'http://208.91.198.196'}
                    apiUrl={selectedCompany?.bannerApiUrl || null}
                />
            )}

            {window.ReceiptSearchModal && (
                <window.ReceiptSearchModal
                    isOpen={isReceiptSearchModalOpen}
                    onClose={() => setIsReceiptSearchModalOpen(false)}
                    selectedCompany={selectedCompany}
                    currentOperator={currentOperator}
                    showAlert={showAlert}
                    api={api}
                    addToCart={addToCart}
                    cart={cart}
                    setIsPaymentModalOpen={setIsPaymentModalOpen}
                    handleCheckout={handleCheckout}
                    onRefund={handleRefund}
            />
            )}

            <MaterialModal
                isOpen={isMaterialModalOpen}
                onClose={() => setIsMaterialModalOpen(false)}
                onRefresh={async () => {
                    // MaterialModal now handles its own pagination, so refresh is handled internally
                }}
                selectedCompany={selectedCompany}
                api={api}
                showAlert={showAlert}
                showConfirm={showConfirm}
            />

            {window.ProductCatalogModal && (
                <window.ProductCatalogModal
                    isOpen={isProductCatalogModalOpen}
                    onClose={() => setIsProductCatalogModalOpen(false)}
                    selectedCompany={selectedCompany}
                    currentOperator={currentOperator}
                    showAlert={showAlert}
                />
            )}
            
            {/* F8-аар тоо нэмэх modal - body руу portal (жижиг дэлгэц дээр гарна) */}
            {addQuantityModal.isOpen && typeof document !== 'undefined' && document.body && ReactDOM.createPortal(
                <div className="modal-overlay" onClick={() => setAddQuantityModal({ isOpen: false, quantity: '' })}>
                    <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '400px' }}>
                        <div className="modal-header">
                            <h2>Тоо нэмэх</h2>
                            <button className="modal-close" onClick={() => setAddQuantityModal({ isOpen: false, quantity: '' })}>×</button>
                        </div>
                        <div className="modal-body">
                            {lastSelectedProduct && (
                                <div className="form-group" style={{ marginBottom: '12px' }}>
                                    <label style={{ fontWeight: 'bold', marginBottom: '4px' }}>Бараа:</label>
                                    <div style={{ fontSize: '14px', color: '#495057', padding: '6px', backgroundColor: '#f8f9fa', borderRadius: '4px' }}>
                                        {lastSelectedProduct.m_name || lastSelectedProduct.name || 'Бүтээгдэхүүн'}
                                    </div>
                                </div>
                            )}
                            <div className="form-group">
                                <label>Нэмэх тоо хэмжээ:</label>
                                <input
                                    type="number"
                                    className="form-input"
                                    value={addQuantityModal.quantity}
                                    onChange={(e) => {
                                        setAddQuantityModal(prev => ({ ...prev, quantity: e.target.value }));
                                    }}
                                    min="0.001"
                                    step="0.001"
                                    autoFocus
                                    onKeyPress={async (e) => {
                                        if (e.key === 'Enter') {
                                            const quantity = parseFloat(addQuantityModal.quantity);
                                            if (!isNaN(quantity) && quantity > 0) {
                                                if (lastSelectedProduct && lastSelectedProduct.m_id) {
                                                    try {
                                                        const productToAdd = {
                                                            ...lastSelectedProduct,
                                                            name: lastSelectedProduct.m_name || lastSelectedProduct.name || 'Бүтээгдэхүүн',
                                                            tcount: quantity,
                                                            quantity: quantity
                                                        };
                                                        await addToCart(productToAdd);
                                                        setAddQuantityModal({ isOpen: false, quantity: '' });
                                                        setTimeout(() => {
                                                            if (barcodeInputRef.current) {
                                                                barcodeInputRef.current.focus();
                                                            }
                                                        }, 100);
                                                    } catch (error) {
                                                        console.error('Error adding product to cart:', error);
                                                        showAlert('Бараа нэмэхэд алдаа гарлаа: ' + (error.message || error));
                                                    }
                                                }
                                            } else {
                                                showAlert('Тоо хэмжээ 0-ээс их байх ёстой!');
                                            }
                                        }
                                    }}
                                />
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button
                                className="btn btn-secondary"
                                onClick={() => setAddQuantityModal({ isOpen: false, quantity: '' })}
                            >
                                Цуцлах
                            </button>
                            <button
                                className="btn btn-primary"
                                onClick={async () => {
                                    const quantity = parseFloat(addQuantityModal.quantity);
                                    if (!isNaN(quantity) && quantity > 0) {
                                        if (lastSelectedProduct && lastSelectedProduct.m_id) {
                                            try {
                                                const productToAdd = {
                                                    ...lastSelectedProduct,
                                                    name: lastSelectedProduct.m_name || lastSelectedProduct.name || 'Бүтээгдэхүүн',
                                                    tcount: quantity,
                                                    quantity: quantity
                                                };
                                                await addToCart(productToAdd);
                                                setAddQuantityModal({ isOpen: false, quantity: '' });
                                                setTimeout(() => {
                                                    if (barcodeInputRef.current) {
                                                        barcodeInputRef.current.focus();
                                                    }
                                                }, 100);
                                            } catch (error) {
                                                console.error('Error adding product to cart:', error);
                                                showAlert('Бараа нэмэхэд алдаа гарлаа: ' + (error.message || error));
                                            }
                                        }
                                    } else {
                                        showAlert('Тоо хэмжээ 0-ээс их байх ёстой!');
                                    }
                                }}
                            >
                                Нэмэх
                            </button>
                        </div>
                    </div>
                </div>,
                document.body
            )}

            {/* Тоо оруулах modal - body руу portal (жижиг дэлгэц дээр гарна) */}
            {quantityInputModal.isOpen && typeof document !== 'undefined' && document.body && ReactDOM.createPortal(
                <div className="modal-overlay" onClick={() => setQuantityInputModal({ isOpen: false, itemId: null, currentQuantity: 0, dotcode: null })}>
                    <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '400px' }}>
                        <div className="modal-header">
                            <h2>Тоо хэмжээ оруулах</h2>
                            <button className="modal-close" onClick={() => setQuantityInputModal({ isOpen: false, itemId: null, currentQuantity: 0, dotcode: null })}>×</button>
                        </div>
                        <div className="modal-body">
                            {quantityInputModal.dotcode && (
                                <div className="form-group" style={{ marginBottom: '12px' }}>
                                    <label style={{ fontWeight: 'bold', marginBottom: '4px' }}>Дотоод код:</label>
                                    <div style={{ fontSize: '14px', color: '#495057', padding: '6px', backgroundColor: '#f8f9fa', borderRadius: '4px' }}>
                                        {quantityInputModal.dotcode}
                                    </div>
                                </div>
                            )}
                            <div className="form-group">
                                <label>Тоо хэмжээ:</label>
                                <input
                                    type="number"
                                    className="form-input"
                                    value={quantityInputModal.inputValue !== undefined ? quantityInputModal.inputValue : quantityInputModal.currentQuantity}
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        setQuantityInputModal(prev => ({ ...prev, inputValue: value }));
                                    }}
                                    min="0"
                                    step="0.001"
                                    autoFocus
                                    onKeyPress={(e) => {
                                        if (e.key === 'Enter') {
                                            const inputValue = parseFloat(quantityInputModal.inputValue !== undefined ? quantityInputModal.inputValue : quantityInputModal.currentQuantity);
                                            if (!isNaN(inputValue) && inputValue > 0) {
                                                const selectedItem = cart.find(item => item.id === quantityInputModal.itemId);
                                                if (selectedItem) {
                                                    const currentValue = parseFloat(selectedItem.quantity || selectedItem.tcount || 1);
                                                    const change = inputValue - currentValue;
                                                    if (change !== 0) {
                                                        updateQuantity(quantityInputModal.itemId, change);
                                                    }
                                                }
                                                setQuantityInputModal({ isOpen: false, itemId: null, currentQuantity: 0, dotcode: null });
                                                setTimeout(() => {
                                                    if (barcodeInputRef.current) {
                                                        barcodeInputRef.current.focus();
                                                    }
                                                }, 100);
                                            }
                                        }
                                    }}
                                />
                            </div>
                            <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '20px' }}>
                                <button
                                    className="btn btn-secondary"
                                    onClick={() => setQuantityInputModal({ isOpen: false, itemId: null, currentQuantity: 0, dotcode: null })}
                                >
                                    Цуцлах
                                </button>
                                <button
                                    className="btn btn-primary"
                                    onClick={() => {
                                        const inputValue = parseFloat(quantityInputModal.inputValue !== undefined ? quantityInputModal.inputValue : quantityInputModal.currentQuantity);
                                        if (!isNaN(inputValue) && inputValue > 0) {
                                            const selectedItem = cart.find(item => item.id === quantityInputModal.itemId);
                                            if (selectedItem) {
                                                const currentValue = parseFloat(selectedItem.quantity || selectedItem.tcount || 1);
                                                const change = inputValue - currentValue;
                                                if (change !== 0) {
                                                    updateQuantity(quantityInputModal.itemId, change);
                                                }
                                            }
                                            setQuantityInputModal({ isOpen: false, itemId: null, currentQuantity: 0, dotcode: null });
                                            setTimeout(() => {
                                                if (barcodeInputRef.current) {
                                                    barcodeInputRef.current.focus();
                                                }
                                            }, 100);
                                        } else {
                                            showAlert('Зөв тоо оруулна уу');
                                        }
                                    }}
                                >
                                    Хадгалах
                                </button>
                            </div>
                        </div>
                    </div>
                </div>,
                document.body
            )}
            
            <AlertModal
                isOpen={alertModal.isOpen}
                message={alertModal.message}
                onClose={handleAlertClose}
            />

            <ConfirmModal
                isOpen={confirmModal.isOpen}
                message={confirmModal.message}
                onConfirm={handleConfirmConfirm}
                onCancel={handleConfirmCancel}
            />

            {isMobileScreen && (
                <div className="mobile-bottom-nav">
                    <button
                        className={`mobile-nav-btn${mobileTab === 'products' ? ' active' : ''}`}
                        onClick={() => setMobileTab('products')}
                    >
                        <span className="mobile-nav-btn-icon">🛍️</span>
                        <span>Бараа</span>
                    </button>
                    <button
                        className={`mobile-nav-btn${mobileTab === 'cart' ? ' active' : ''}`}
                        onClick={() => setMobileTab('cart')}
                        style={{ position: 'relative' }}
                    >
                        <span className="mobile-nav-btn-icon">🛒</span>
                        <span>Сагс</span>
                        {cart.length > 0 && (
                            <span className="mobile-nav-badge">{cart.length}</span>
                        )}
                    </button>
                </div>
            )}
        </div>
    );
}

// Render the app
ReactDOM.render(<App />, document.getElementById('root'));

// Expose function for main process to check cart before closing
if (typeof window !== 'undefined') {
    // Global variables to store cart and mtId state
    window.__cartState = [];
    window.__currentMtId = null;
    
    window.checkCartBeforeClose = async () => {
        // Check cart from global state
        const cart = window.__cartState || [];
        const currentMtId = window.__currentMtId;
        const hasItems = cart && cart.length > 0;
        const hasUnprocessedTransaction = currentMtId && currentMtId !== 0 && hasItems;
        
        return { 
            hasItems: hasItems,
            hasUnprocessedTransaction: hasUnprocessedTransaction,
            cartCount: cart ? cart.length : 0,
            currentMtId: currentMtId
        };
    };
    
    // Expose function for main process to show confirm dialog before closing window
    window.showConfirmBeforeClose = async (message) => {
        return new Promise((resolve) => {
            // Use a global variable to store the resolve function
            if (!window.__confirmBeforeCloseResolve) {
                window.__confirmBeforeCloseResolve = null;
            }
            
            // Set the resolve function
            window.__confirmBeforeCloseResolve = resolve;
            
            // Trigger the confirm modal
            if (typeof window.showConfirmGlobal === 'function') {
                window.showConfirmGlobal(message, () => {
                    if (window.__confirmBeforeCloseResolve) {
                        window.__confirmBeforeCloseResolve(true);
                        window.__confirmBeforeCloseResolve = null;
                    }
                }, () => {
                    if (window.__confirmBeforeCloseResolve) {
                        window.__confirmBeforeCloseResolve(false);
                        window.__confirmBeforeCloseResolve = null;
                    }
                });
            } else {
                // Fallback to native confirm
                const result = confirm(message);
                resolve(result);
            }
        });
    };
}
