// formatCurrency should be loaded before this file
const formatCurrency = typeof window !== 'undefined' ? window.formatCurrency : (typeof require !== 'undefined' ? require('../utils/formatCurrency.js').formatCurrency : null);
const formatDateMongolian = typeof window !== 'undefined' ? window.formatDateMongolian : (typeof require !== 'undefined' ? require('../utils/formatDate.js').formatDateMongolian : null);
const { useState, useEffect } = React;

function Sidebar({ 
    licenseWarning,
    currentOperator, 
    selectedCompany, 
    vatRate,
    currentMtId,
    currentSourceNo,
    barcodeInput, 
    onBarcodeChange, 
    onBarcodeScan,
    onInternalCodeSearch,
    internalCodeInput,
    onInternalCodeChange,
    internalCodeProduct,
    internalCodeQuantity,
    onInternalCodeQuantityChange,
    internalCodeModalOpen,
    onInternalCodeModalClose,
    onInternalCodeAddToCart,
    internalCodeLoading,
    productSearchList,
    productSearchLoading,
    onProductSearch,
    onProductSearchSelect,
    onProductSearchClose,
    cart, 
    calculateTotal, 
    calculateVATTotal,
    calculateCityTaxTotal,
    calculateTaxTotal,
    calculateDiscountTotal,
    calculateGrandTotal, 
    onLogout,
    onSettingsClick,
    onMaterialClick,
    onProductCatalogClick,
    onRefund,
    barcodeInputRef,
    showAlert,
    api,
    showConfirm,
    addToCart,
    setCart,
    onBeginNewPurchase,
    collapsed = false,
    onExpand,
    onCollapse
}) {
    const [refundModalOpen, setRefundModalOpen] = useState(false);
    const [refundId, setRefundId] = useState('');
    const [refundDate, setRefundDate] = useState('');
    const [receiptInfo, setReceiptInfo] = useState(null);
    const [loadingReceipt, setLoadingReceipt] = useState(false);
    const [sendingToTax, setSendingToTax] = useState(false);
    const [refundItems, setRefundItems] = useState([]);
    const [loadingRefundItems, setLoadingRefundItems] = useState(false);

    const handleSendToTaxSystem = async () => {
        if (!api || !api.sendToTaxSystem) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('API функц олдсонгүй');
            }
            return;
        }

        if (!selectedCompany) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Байгууллагын мэдээлэл олдсонгүй.');
            }
            return;
        }

        // b_clients.apiUrl талбарыг ашиглах
        const apiUrl = selectedCompany.apiUrl || selectedCompany.apiURL;
        if (!apiUrl || !apiUrl.trim()) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Татварын системийн URL (b_clients.apiUrl) тохируулаагүй байна. Тохиргоо хэсэгт API URL оруулна уу.');
            }
            return;
        }

        setSendingToTax(true);
        
        try {
            const result = await api.sendToTaxSystem(apiUrl.trim());

            if (result.success) {
                if (showAlert && typeof showAlert === 'function') {
                    showAlert(result.message || 'Татварын системд амжилттай илгээгдлээ');
                }
                // Line1 === Line2 үед алсын бааз рүү синк хийхгүй (давхар мэдээ үүсэхгүй)
                if (result.line1SameAsLine2) {
                    return;
                }
                // Line1 !== Line2 бол сүүлийн 3 хоногийн борлуулалтыг алсын сервер рүү синк
                if (api.getRemoteAllowed && api.syncAfterTax) {
                    try {
                        const allowedRes = await api.getRemoteAllowed();
                        if (allowedRes.success && allowedRes.allowed) {
                            await api.syncAfterTax();
                        }
                    } catch (e) {
                        console.warn('syncAfterTax:', e);
                    }
                }
            } else {
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Татварын системд илгээхэд алдаа гарлаа: ' + (result.error || 'Тодорхойгүй алдаа'));
                }
            }
        } catch (error) {
            console.error('Error sending to tax system:', error);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Татварын системд илгээхэд алдаа гарлаа: ' + (error.message || 'Тодорхойгүй алдаа'));
            }
        } finally {
            setSendingToTax(false);
        }
    };

    useEffect(() => {
        if (typeof window === 'undefined') return;
        window.openRefundModal = () => setRefundModalOpen(true);
        window.sendToTaxSystemGlobal = () => handleSendToTaxSystem();
        return () => {
            if (window.openRefundModal) delete window.openRefundModal;
            if (window.sendToTaxSystemGlobal) delete window.sendToTaxSystemGlobal;
        };
    }, [handleSendToTaxSystem]);

    const formatCurrencyTwoDecimals = (amount) => {
        if (amount === null || amount === undefined || amount === '') return amount;
        const numericAmount = Number(amount);
        if (Number.isNaN(numericAmount)) return amount;
        return numericAmount.toLocaleString('mn-MN', {
            style: 'decimal',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    };
    
    // Tax-system dates often come as "YYYY-MM-DD HH:MM:SS" (no timezone).
    // Using `new Date(value)` can shift time due to local timezone parsing.
    // Here we parse the string components and keep HH:MM:SS identical.
    const parseDateTimeParts = (value) => {
        if (value == null) return null;
        const s = String(value).trim();
        if (!s) return null;

        // Date-only: YYYY-MM-DD
        const d = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
        if (d) {
            return {
                date: `${d[1]}-${d[2]}-${d[3]}`,
                hh: '00',
                mm: '00',
                ss: '00'
            };
        }

        // DateTime: YYYY-MM-DD[T ]HH:MM[:SS] with optional timezone/millis suffix
        const dt = s.match(
            /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/
        );
        if (dt) {
            return {
                date: `${dt[1]}-${dt[2]}-${dt[3]}`,
                hh: dt[4],
                mm: dt[5],
                ss: dt[6] ?? '00'
            };
        }

        return null;
    };

    const formatDateTimeIso = (value) => {
        const parts = parseDateTimeParts(value);
        if (parts) {
            return `${parts.date} ${parts.hh}:${parts.mm}:${parts.ss}`;
        }
        // Fallback for unexpected formats
        if (!value) return '';
        const date = new Date(value);
        if (isNaN(date.getTime())) return value;
        const pad2 = (n) => String(n).padStart(2, '0');
        return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
    };
    const formatDateTimeLocal = (value) => {
        const parts = parseDateTimeParts(value);
        if (parts) {
            return `${parts.date}T${parts.hh}:${parts.mm}:${parts.ss}`;
        }
        // Fallback for unexpected formats
        if (!value) return '';
        const date = new Date(value);
        if (isNaN(date.getTime())) return value;
        const pad2 = (n) => String(n).padStart(2, '0');
        return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
    };

    const normalizeReceiptItems = (data) => {
        if (!data) return [];
        if (Array.isArray(data)) return data;
        if (Array.isArray(data.rows)) return data.rows;
        if (Array.isArray(data.items)) return data.items;
        if (data.receipt && Array.isArray(data.receipt.items)) return data.receipt.items;
        if (Array.isArray(data.receipts) && data.receipts[0]) {
            if (Array.isArray(data.receipts[0].items)) return data.receipts[0].items;
            if (data.receipts[0].receipt && Array.isArray(data.receipts[0].receipt.items)) {
                return data.receipts[0].receipt.items;
            }
        }
        return [];
    };

    const getRefundItemName = (row) => {
        return row?.m_name || row?.name || row?.itemName || row?.item_name || row?.title ||
            row?.goodsName || row?.productName || row?.mname || 'Бүтээгдэхүүн';
    };

    const getRefundItemQty = (row) => {
        const qty = parseFloat(row?.tcount || row?.quantity || row?.qty || row?.count || 0);
        return Number.isFinite(qty) ? qty : 0;
    };

    const getRefundItemAmountFromFields = (row) => {
        const amount = parseFloat(row?.totalAmount || row?.amount || row?.total || row?.sum || row?.lineTotal || 0);
        return Number.isFinite(amount) ? amount : 0;
    };

    const getRefundItemPrice = (row) => {
        const directPrice = parseFloat(row?.price_low || row?.price || row?.unitPrice || row?.unit_price || row?.priceUnit || 0);
        if (Number.isFinite(directPrice) && directPrice !== 0) return directPrice;
        const qty = getRefundItemQty(row);
        const amount = getRefundItemAmountFromFields(row);
        if (qty > 0 && amount > 0) {
            return amount / qty;
        }
        return 0;
    };

    const getRefundItemDiscount = (row) => {
        const discount = parseFloat(row?.discount || row?.discountAmount || row?.disc || row?.discountValue || 0);
        return Number.isFinite(discount) ? discount : 0;
    };

    const getRefundItemAmount = (row) => {
        const amountFromFields = getRefundItemAmountFromFields(row);
        if (amountFromFields > 0) return amountFromFields;
        const qty = getRefundItemQty(row);
        const price = getRefundItemPrice(row);
        return price * qty;
    };

    // Helper function to get yesterday's date/time in YYYY-MM-DDTHH:MM:SS format (datetime-local)
    const getYesterdayDateTimeLocal = () => {
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        const year = yesterday.getFullYear();
        const month = String(yesterday.getMonth() + 1).padStart(2, '0');
        const day = String(yesterday.getDate()).padStart(2, '0');
        const hours = String(yesterday.getHours()).padStart(2, '0');
        const minutes = String(yesterday.getMinutes()).padStart(2, '0');
        const seconds = String(yesterday.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
    };
    
    // Set yesterday's date/time when refund modal opens
    useEffect(() => {
        if (refundModalOpen) {
            setRefundDate(getYesterdayDateTimeLocal());
        }
    }, [refundModalOpen]);
    
    // Баримт хайх modal state болон логик - шилжүүлсэн SettingsModal-д
    
    // Fetch receipt information when searchReceiptCashcode changes (for cashcode search) - шилжүүлсэн SettingsModal-д
    /* useEffect(() => {
        const fetchSearchReceiptByCashcode = async () => {
            if (!searchReceiptCashcode || !searchReceiptCashcode.trim() || !selectedCompany || !currentOperator) {
                setSearchReceiptInfo(null);
                setFoundMtId(null);
                setSearchReceiptItems([]);
                return;
            }
            
            if (!api || !api.getExpenseGByCashcode) {
                setSearchReceiptInfo({ found: false, error: 'API функц олдсонгүй' });
                return;
            }
            
            setLoadingSearchReceipt(true);
            try {
                const cashcode = parseInt(searchReceiptCashcode.trim(), 10);
                const b_id = selectedCompany.b_id || selectedCompany.id;
                const opid = currentOperator.opid || currentOperator.op_id;
                
                if (isNaN(cashcode) || !b_id || !opid) {
                    setSearchReceiptInfo({ found: false, error: 'Зөв мэдээлэл оруулна уу' });
                    setLoadingSearchReceipt(false);
                    return;
                }
                
                // Сүүлийн хоногийн тоог ашиглах (default: 30 хоног)
                const days = parseInt(searchReceiptDays) || 30;
                // Sourceno байвал дамжуулах (cashcode болон sourceno хоёуланг нь ашиглан хайх)
                let sourceno = null;
                if (searchReceiptSourceno && searchReceiptSourceno.trim()) {
                    const parsedSourceno = parseInt(searchReceiptSourceno.trim(), 10);
                    if (!isNaN(parsedSourceno) && isFinite(parsedSourceno)) {
                        sourceno = parsedSourceno;
                    }
                }
                console.log('[fetchSearchReceiptByCashcode] Searching with:', { cashcode, sourceno, b_id, opid, days });
                const result = await api.getExpenseGByCashcode(cashcode, b_id, opid, days, sourceno);
                
                console.log('[fetchSearchReceiptByCashcode] API result:', result);
                
                if (result.success && result.data) {
                    const expenseG = result.data;
                    const mt_id = expenseG.mt_id;
                    console.log('[fetchSearchReceiptByCashcode] Found mt_id:', mt_id);
                    setFoundMtId(mt_id);
                    
                    // Баримтын барааны жагсаалтыг татах
                    if (api && api.getExpenseRows) {
                        try {
                            setLoadingReceiptItems(true);
                            const expenseResult = await api.getExpenseRows(mt_id);
                            if (expenseResult.success && expenseResult.data) {
                                let expenseRows = [];
                                if (expenseResult.data.rows) {
                                    expenseRows = expenseResult.data.rows;
                                } else if (Array.isArray(expenseResult.data)) {
                                    expenseRows = expenseResult.data;
                                }
                                setSearchReceiptItems(expenseRows);
                            } else {
                                setSearchReceiptItems([]);
                            }
                        } catch (error) {
                            console.error('[fetchSearchReceiptByCashcode] Error fetching receipt items:', error);
                            setSearchReceiptItems([]);
                        } finally {
                            setLoadingReceiptItems(false);
                        }
                    }
                    
                    // Check if receipt has ID in tax system
                    const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
                    if (apiURL) {
                        let baseUrl = apiURL.trim();
                        if (baseUrl.endsWith('/')) {
                            baseUrl = baseUrl.slice(0, -1);
                        }
                        const finalApiURL = `${baseUrl}/rest/receipt/${mt_id}`;
                        
                        try {
                            const response = await fetch(finalApiURL, {
                                method: 'GET',
                                headers: {
                                    'Accept': 'application/json'
                                }
                            });
                            
                            const responseText = await response.text();
                            
                            if (response.ok) {
                                let responseData = null;
                                try {
                                    responseData = JSON.parse(responseText);
                                } catch (e) {
                                    responseData = responseText;
                                }
                                
                                if (responseData && typeof responseData === 'object') {
                                    const receiptDate = responseData.date || responseData.receiptDate || responseData.createdAt || 
                                                      responseData.created_at || responseData.printedDate || responseData.printed_date ||
                                                      (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].date);
                                    
                                    // Check if receipt has ID
                                    const hasId = responseData.id || responseData.receiptId || (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].id);
                                    
                                    setSearchReceiptInfo({
                                        date: receiptDate,
                                        found: true,
                                        data: responseData,
                                        hasId: !!hasId,
                                        mt_id: mt_id
                                    });
                                } else {
                                    setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false });
                                }
                            } else {
                                // Receipt not found in tax system, but exists in database
                                setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false, notInTaxSystem: true });
                            }
                        } catch (error) {
                            console.error('[fetchSearchReceiptByCashcode] Error checking tax system:', error);
                            setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false, notInTaxSystem: true });
                        }
                    } else {
                        setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false });
                    }
                } else {
                    setSearchReceiptInfo({ found: false, error: 'Баримт олдсонгүй' });
                    setFoundMtId(null);
                    setSearchReceiptItems([]);
                }
            } catch (error) {
                console.error('[fetchSearchReceiptByCashcode] Error fetching receipt info:', error);
                setSearchReceiptInfo({ found: false, error: error.message || 'Баримтын мэдээлэл авах боломжгүй' });
                setFoundMtId(null);
            } finally {
                setLoadingSearchReceipt(false);
            }
        };
        
        if (searchMode === 'CASHCODE') {
            const timeoutId = setTimeout(() => {
                fetchSearchReceiptByCashcode();
            }, 500);
            
            return () => clearTimeout(timeoutId);
        }
    }, [searchReceiptCashcode, searchReceiptSourceno, searchReceiptDays, selectedCompany, currentOperator, searchMode, api]); */
    
    // Fetch receipt information when searchReceiptId changes (for ID search) - шилжүүлсэн SettingsModal-д
    /* useEffect(() => {
        const fetchSearchReceiptInfo = async () => {
            if (!searchReceiptId || !searchReceiptId.trim() || !selectedCompany) {
                setSearchReceiptInfo(null);
                return;
            }
            
            const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
            if (!apiURL) {
                setSearchReceiptInfo(null);
                return;
            }
            
            setLoadingSearchReceipt(true);
            try {
                let baseUrl = apiURL.trim();
                if (baseUrl.endsWith('/')) {
                    baseUrl = baseUrl.slice(0, -1);
                }
                const finalApiURL = `${baseUrl}/rest/receipt/${searchReceiptId.trim()}`;
                
                console.log('[fetchSearchReceiptInfo] Fetching receipt from:', finalApiURL);
                
                const response = await fetch(finalApiURL, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                
                const responseText = await response.text();
                console.log('[fetchSearchReceiptInfo] Response status:', response.status);
                console.log('[fetchSearchReceiptInfo] Response text:', responseText);
                
                if (response.ok) {
                    let responseData = null;
                    try {
                        responseData = JSON.parse(responseText);
                    } catch (e) {
                        console.error('[fetchSearchReceiptInfo] Failed to parse JSON:', e);
                        responseData = responseText;
                    }
                    
                    console.log('[fetchSearchReceiptInfo] Parsed response data:', responseData);
                    
                    if (responseData && typeof responseData === 'object') {
                        const receiptDate = responseData.date || responseData.receiptDate || responseData.createdAt || 
                                          responseData.created_at || responseData.printedDate || responseData.printed_date ||
                                          (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].date);
                        
                        // Check if receipt has ID
                        const hasId = responseData.id || responseData.receiptId || (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].id);
                        
                        setSearchReceiptInfo({
                            date: receiptDate,
                            found: true,
                            data: responseData,
                            hasId: !!hasId
                        });
                    } else {
                        setSearchReceiptInfo({ found: false, error: 'Баримтын мэдээлэл буруу форматтай байна' });
                    }
                } else {
                    if (response.status === 404) {
                        setSearchReceiptInfo({ found: false, error: 'Баримт олдсонгүй (404)' });
                    } else {
                        let errorMessage = 'Баримт олдсонгүй';
                        try {
                            const errorData = JSON.parse(responseText);
                            if (errorData && errorData.message) {
                                errorMessage = errorData.message;
                            }
                        } catch (e) {
                            errorMessage = response.statusText || `Алдаа: ${response.status}`;
                        }
                        setSearchReceiptInfo({ found: false, error: errorMessage });
                    }
                }
            } catch (error) {
                console.error('[fetchSearchReceiptInfo] Error fetching receipt info:', error);
                setSearchReceiptInfo({ found: false, error: error.message || 'Баримтын мэдээлэл авах боломжгүй' });
            } finally {
                setLoadingSearchReceipt(false);
            }
        };
        
        if (searchMode === 'ID') {
            const timeoutId = setTimeout(() => {
                fetchSearchReceiptInfo();
            }, 500);
            
            return () => clearTimeout(timeoutId);
        }
    }, [searchReceiptId, selectedCompany, searchMode]); */
    
    // Fetch receipt information when searchReceiptSourceno and searchReceiptOpid change (for sourceno search) - шилжүүлсэн SettingsModal-д
    /* useEffect(() => {
        const fetchSearchReceiptBySourceno = async () => {
            if (!searchReceiptSourceno || !searchReceiptSourceno.trim() || !searchReceiptOpid || !searchReceiptOpid.trim() || !selectedCompany) {
                setSearchReceiptInfo(null);
                setFoundMtId(null);
                setSearchReceiptItems([]);
                return;
            }
            
            if (!api || !api.getExpenseGBySourceno) {
                setSearchReceiptInfo({ found: false, error: 'API функц олдсонгүй' });
                return;
            }
            
            setLoadingSearchReceipt(true);
            try {
                const sourceno = parseInt(searchReceiptSourceno.trim(), 10);
                const opid = parseInt(searchReceiptOpid.trim(), 10);
                const b_id = selectedCompany.b_id || selectedCompany.id;
                
                if (isNaN(sourceno) || isNaN(opid) || !b_id) {
                    setSearchReceiptInfo({ found: false, error: 'Зөв мэдээлэл оруулна уу' });
                    setLoadingSearchReceipt(false);
                    return;
                }
                
                const days = parseInt(searchReceiptDays || '30', 10);
                const result = await api.getExpenseGBySourceno(sourceno, opid, b_id, days);
                
                if (result.success && result.data) {
                    const expenseG = result.data;
                    const mt_id = expenseG.mt_id;
                    setFoundMtId(mt_id);
                    
                    // Баримтын барааны жагсаалтыг татах
                    if (api && api.getExpenseRows) {
                        try {
                            setLoadingReceiptItems(true);
                            const expenseResult = await api.getExpenseRows(mt_id);
                            if (expenseResult.success && expenseResult.data) {
                                let expenseRows = [];
                                if (expenseResult.data.rows) {
                                    expenseRows = expenseResult.data.rows;
                                } else if (Array.isArray(expenseResult.data)) {
                                    expenseRows = expenseResult.data;
                                }
                                setSearchReceiptItems(expenseRows);
                            } else {
                                setSearchReceiptItems([]);
                            }
                        } catch (error) {
                            console.error('[fetchSearchReceiptBySourceno] Error fetching receipt items:', error);
                            setSearchReceiptItems([]);
                        } finally {
                            setLoadingReceiptItems(false);
                        }
                    }
                    
                    // Check if receipt has ID in tax system
                    const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
                    if (apiURL) {
                        let baseUrl = apiURL.trim();
                        if (baseUrl.endsWith('/')) {
                            baseUrl = baseUrl.slice(0, -1);
                        }
                        const finalApiURL = `${baseUrl}/rest/receipt/${mt_id}`;
                        
                        try {
                            const response = await fetch(finalApiURL, {
                                method: 'GET',
                                headers: {
                                    'Accept': 'application/json'
                                }
                            });
                            
                            const responseText = await response.text();
                            
                            if (response.ok) {
                                let responseData = null;
                                try {
                                    responseData = JSON.parse(responseText);
                                } catch (e) {
                                    responseData = responseText;
                                }
                                
                                if (responseData && typeof responseData === 'object') {
                                    const receiptDate = responseData.date || responseData.receiptDate || responseData.createdAt || 
                                                      responseData.created_at || responseData.printedDate || responseData.printed_date ||
                                                      (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].date);
                                    
                                    // Check if receipt has ID
                                    const hasId = responseData.id || responseData.receiptId || (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].id);
                                    
                                    setSearchReceiptInfo({
                                        date: receiptDate,
                                        found: true,
                                        data: responseData,
                                        hasId: !!hasId,
                                        mt_id: mt_id
                                    });
                                } else {
                                    setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false });
                                }
                            } else {
                                // Receipt not found in tax system, but exists in database
                                setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false, notInTaxSystem: true });
                            }
                        } catch (error) {
                            console.error('[fetchSearchReceiptBySourceno] Error checking tax system:', error);
                            setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false, notInTaxSystem: true });
                        }
                    } else {
                        setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false });
                    }
                } else {
                    setSearchReceiptInfo({ found: false, error: 'Баримт олдсонгүй' });
                    setFoundMtId(null);
                    setSearchReceiptItems([]);
                }
            } catch (error) {
                console.error('[fetchSearchReceiptBySourceno] Error fetching receipt info:', error);
                setSearchReceiptInfo({ found: false, error: error.message || 'Баримтын мэдээлэл авах боломжгүй' });
                setFoundMtId(null);
            } finally {
                setLoadingSearchReceipt(false);
            }
        };
        
        if (searchMode === 'SOURCENO') {
            const timeoutId = setTimeout(() => {
                fetchSearchReceiptBySourceno();
            }, 500);
            
            return () => clearTimeout(timeoutId);
        }
    }, [searchReceiptSourceno, searchReceiptOpid, searchReceiptDays, selectedCompany, searchMode, api]); */
    
    // Fetch receipt information when searchReceiptCashcode and searchReceiptOpid change (for cashcode and opid search) - шилжүүлсэн SettingsModal-д
    /* useEffect(() => {
        const fetchSearchReceiptByCashcodeAndOpid = async () => {
            if (!searchReceiptCashcode || !searchReceiptCashcode.trim() || !searchReceiptOpid || !searchReceiptOpid.trim() || !selectedCompany || !currentOperator) {
                setSearchReceiptInfo(null);
                setFoundMtId(null);
                setSearchReceiptItems([]);
                return;
            }
            
            if (!api || !api.getExpenseGByCashcodeAndOpid) {
                setSearchReceiptInfo({ found: false, error: 'API функц олдсонгүй' });
                return;
            }
            
            setLoadingSearchReceipt(true);
            try {
                const cashcode = parseInt(searchReceiptCashcode.trim(), 10);
                const opid = parseInt(searchReceiptOpid.trim(), 10);
                const b_id = selectedCompany.b_id || selectedCompany.id;
                
                if (isNaN(cashcode) || isNaN(opid) || !b_id) {
                    setSearchReceiptInfo({ found: false, error: 'Зөв мэдээлэл оруулна уу' });
                    setLoadingSearchReceipt(false);
                    return;
                }
                
                const days = 10; // Сүүлийн 10 хоног
                const result = await api.getExpenseGByCashcodeAndOpid(cashcode, opid, b_id, days);
                
                if (result.success && result.data) {
                    const expenseG = result.data;
                    const mt_id = expenseG.mt_id;
                    setFoundMtId(mt_id);
                    
                    // Баримтын барааны жагсаалтыг татах
                    if (api && api.getExpenseRows) {
                        try {
                            setLoadingReceiptItems(true);
                            const expenseResult = await api.getExpenseRows(mt_id);
                            if (expenseResult.success && expenseResult.data) {
                                let expenseRows = [];
                                if (expenseResult.data.rows) {
                                    expenseRows = expenseResult.data.rows;
                                } else if (Array.isArray(expenseResult.data)) {
                                    expenseRows = expenseResult.data;
                                }
                                setSearchReceiptItems(expenseRows);
                            } else {
                                setSearchReceiptItems([]);
                            }
                        } catch (error) {
                            console.error('[fetchSearchReceiptByCashcodeAndOpid] Error fetching receipt items:', error);
                            setSearchReceiptItems([]);
                        } finally {
                            setLoadingReceiptItems(false);
                        }
                    }
                    
                    // Check if receipt has ID in tax system
                    const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
                    if (apiURL) {
                        let baseUrl = apiURL.trim();
                        if (baseUrl.endsWith('/')) {
                            baseUrl = baseUrl.slice(0, -1);
                        }
                        const finalApiURL = `${baseUrl}/rest/receipt/${mt_id}`;
                        
                        try {
                            const response = await fetch(finalApiURL, {
                                method: 'GET',
                                headers: {
                                    'Accept': 'application/json'
                                }
                            });
                            
                            const responseText = await response.text();
                            
                            if (response.ok) {
                                let responseData = null;
                                try {
                                    responseData = JSON.parse(responseText);
                                } catch (e) {
                                    responseData = responseText;
                                }
                                
                                if (responseData && typeof responseData === 'object') {
                                    const receiptDate = responseData.date || responseData.receiptDate || responseData.createdAt || 
                                                      responseData.created_at || responseData.printedDate || responseData.printed_date ||
                                                      (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].date);
                                    
                                    // Check if receipt has ID
                                    const hasId = responseData.id || responseData.receiptId || (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].id);
                                    
                                    setSearchReceiptInfo({
                                        date: receiptDate,
                                        found: true,
                                        data: responseData,
                                        hasId: !!hasId,
                                        mt_id: mt_id
                                    });
                                } else {
                                    setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false });
                                }
                            } else {
                                // Receipt not found in tax system, but exists in database
                                setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false, notInTaxSystem: true });
                            }
                        } catch (error) {
                            console.error('[fetchSearchReceiptByCashcodeAndOpid] Error checking tax system:', error);
                            setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false, notInTaxSystem: true });
                        }
                    } else {
                        setSearchReceiptInfo({ found: true, mt_id: mt_id, hasId: false });
                    }
                } else {
                    setSearchReceiptInfo({ found: false, error: 'Баримт олдсонгүй' });
                    setFoundMtId(null);
                    setSearchReceiptItems([]);
                }
            } catch (error) {
                console.error('[fetchSearchReceiptByCashcodeAndOpid] Error fetching receipt info:', error);
                setSearchReceiptInfo({ found: false, error: error.message || 'Баримтын мэдээлэл авах боломжгүй' });
                setFoundMtId(null);
                setSearchReceiptItems([]);
            } finally {
                setLoadingSearchReceipt(false);
            }
        };
        
        if (searchMode === 'CASHCODE_OPID') {
            const timeoutId = setTimeout(() => {
                fetchSearchReceiptByCashcodeAndOpid();
            }, 500);
            
            return () => clearTimeout(timeoutId);
        }
    }, [searchReceiptCashcode, searchReceiptOpid, selectedCompany, currentOperator, searchMode, api]); */
    
    // Fetch receipt information function (called manually on Enter key press)
    const fetchReceiptInfo = async () => {
        if (!refundId || !refundId.trim() || !selectedCompany) {
            setReceiptInfo(null);
            setRefundItems([]);
            return;
        }
        
        const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
        const isResponseId = /^\d{33}$/.test(refundId.trim());
        if (!apiURL && !isResponseId) {
            setReceiptInfo(null);
            return;
        }
        
        setLoadingReceipt(true);
        try {
            if (isResponseId && api && api.getExpenseGByInspector) {
                const bId = selectedCompany.b_id || selectedCompany.id;
                const result = await api.getExpenseGByInspector(bId, refundId.trim());
                if (result.success && result.data) {
                    const expenseG = result.data;
                    const mtId = expenseG.mt_id || expenseG.mtId || null;
                    setReceiptInfo({
                        date: expenseG.adate,
                        receiptId: expenseG.inspector || refundId.trim(),
                        totalAmount: expenseG.totalAmount || expenseG.total || null,
                        totalVAT: expenseG.vat || null,
                        totalCityTax: expenseG.citytax || null,
                        found: true,
                        data: expenseG,
                        mt_id: mtId
                    });
                    setRefundDate(formatDateTimeLocal(expenseG.adate));

                        // If refundId is the tax-system receipt id, use the exact tax response date.
                        // (Some refund endpoints require id+date to match the tax system.)
                        if (apiURL) {
                            try {
                                let baseUrl = apiURL.trim();
                                if (baseUrl.endsWith('/')) baseUrl = baseUrl.slice(0, -1);
                                const finalApiURL = `${baseUrl}/rest/receipt/${refundId.trim()}`;
                                const taxReceiptResp = await fetch(finalApiURL, {
                                    method: 'GET',
                                    headers: { 'Accept': 'application/json' }
                                });
                                const taxReceiptText = await taxReceiptResp.text();
                                let taxReceiptData = null;
                                try {
                                    taxReceiptData = JSON.parse(taxReceiptText);
                                } catch (e) {
                                    taxReceiptData = null;
                                }
                                if (taxReceiptData && typeof taxReceiptData === 'object') {
                                    const taxReceiptDate = taxReceiptData.date ||
                                        taxReceiptData.receiptDate ||
                                        taxReceiptData.createdAt ||
                                        taxReceiptData.created_at ||
                                        taxReceiptData.printedDate ||
                                        taxReceiptData.printed_date ||
                                        (taxReceiptData.receipts && taxReceiptData.receipts[0] && taxReceiptData.receipts[0].date) ||
                                        null;
                                    if (taxReceiptDate) {
                                        setReceiptInfo(prev => ({
                                            ...(prev || {}),
                                            date: taxReceiptDate
                                        }));
                                        setRefundDate(formatDateTimeLocal(taxReceiptDate));
                                    }
                                }
                            } catch (e) {
                                // Fallback: keep expenseG.adate if tax lookup fails
                                console.warn('[fetchReceiptInfo] Could not fetch tax receipt date:', e?.message || e);
                            }
                        }

                    if (mtId && api && api.getExpenseRows) {
                        setLoadingRefundItems(true);
                        try {
                            const expenseResult = await api.getExpenseRows(mtId);
                            const rows = normalizeReceiptItems(expenseResult?.data);
                            setRefundItems(rows);
                        } catch (error) {
                            console.error('[fetchReceiptInfo] Error fetching refund items:', error);
                            setRefundItems([]);
                        } finally {
                            setLoadingRefundItems(false);
                        }
                    } else {
                        setRefundItems([]);
                    }
                } else {
                    setReceiptInfo({ found: false, error: 'Баримт олдсонгүй' });
                    setRefundItems([]);
                }
                return;
            }
            
            // Fallback: tax system lookup by receipt ID
            let baseUrl = apiURL.trim();
            if (baseUrl.endsWith('/')) {
                baseUrl = baseUrl.slice(0, -1);
            }
            const finalApiURL = `${baseUrl}/rest/receipt/${refundId.trim()}`;
            console.log('[fetchReceiptInfo] Fetching receipt from:', finalApiURL);
            
            const response = await fetch(finalApiURL, {
                method: 'GET',
                headers: { 'Accept': 'application/json' }
            });
            
            const responseText = await response.text();
            console.log('[fetchReceiptInfo] Response status:', response.status, response.statusText);
            console.log('[fetchReceiptInfo] Response text:', responseText);
            
            if (response.ok) {
                let responseData = null;
                try {
                    responseData = JSON.parse(responseText);
                } catch (e) {
                    console.error('[fetchReceiptInfo] Failed to parse JSON:', e);
                    responseData = responseText;
                }
                
                console.log('[fetchReceiptInfo] Parsed response data:', responseData);
                
                if (responseData && typeof responseData === 'object') {
                    const receiptDate = responseData.date || responseData.receiptDate || responseData.createdAt || 
                                      responseData.created_at || responseData.printedDate || responseData.printed_date ||
                                      (responseData.receipts && responseData.receipts[0] && responseData.receipts[0].date);
                    const receiptIdValue = responseData.id || refundId.trim();
                    const totalAmountValue = responseData.totalAmount || responseData.total || null;
                    const totalVatValue = responseData.totalVAT || responseData.vat || null;
                    const totalCityTaxValue = responseData.totalCityTax || responseData.cityTax || null;
                    
                    console.log('[fetchReceiptInfo] Extracted receipt date:', receiptDate);
                    
                    setReceiptInfo({
                        date: receiptDate,
                        receiptId: receiptIdValue,
                        totalAmount: totalAmountValue,
                        totalVAT: totalVatValue,
                        totalCityTax: totalCityTaxValue,
                        found: true,
                        data: responseData
                    });
                    const itemsFromResponse = normalizeReceiptItems(responseData);
                    setRefundItems(itemsFromResponse);
                    if (receiptDate) {
                        setRefundDate(formatDateTimeLocal(receiptDate));
                    }
                } else {
                    console.warn('[fetchReceiptInfo] Response data is not an object or is null');
                    setReceiptInfo({ found: false, error: 'Баримтын мэдээлэл буруу форматтай байна' });
                    setRefundItems([]);
                }
            } else {
                if (response.status === 404) {
                    console.warn('[fetchReceiptInfo] Receipt not found (404) - this may be normal, refund can still proceed');
                    setReceiptInfo({ found: false, error: 'Баримтын мэдээлэл олдсонгүй (404). Буцаалт хийх боломжтой.' });
                    setRefundItems([]);
                } else {
                    let errorMessage = 'Баримт олдсонгүй';
                    try {
                        const errorData = JSON.parse(responseText);
                        if (errorData && errorData.message) {
                            errorMessage = errorData.message;
                        }
                    } catch (e) {
                        errorMessage = response.statusText || `Алдаа: ${response.status}`;
                    }
                    console.error('[fetchReceiptInfo] Failed to fetch receipt:', response.status, errorMessage);
                    setReceiptInfo({ found: false, error: errorMessage });
                    setRefundItems([]);
                }
            }
        } catch (error) {
            console.error('[fetchReceiptInfo] Error fetching receipt info:', error);
            setReceiptInfo({ found: false, error: error.message || 'Баримтын мэдээлэл авах боломжгүй' });
            setRefundItems([]);
        } finally {
            setLoadingReceipt(false);
        }
    };

    const refundItemsTotal = refundItems.reduce((sum, row) => sum + getRefundItemAmount(row), 0);

    const iconBtn = (onClick, title, icon, disabled = false) => (
        <button
            type="button"
            onClick={onClick}
            disabled={disabled}
            title={title}
            style={{
                width: '36px',
                height: '36px',
                padding: 0,
                border: 'none',
                borderRadius: '6px',
                background: '#34495e',
                color: 'white',
                cursor: disabled ? 'not-allowed' : 'pointer',
                fontSize: '16px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                opacity: disabled ? 0.6 : 1
            }}
        >
            {icon}
        </button>
    );

    const collapsedStrip = (
        <>
            <button
                type="button"
                onClick={onExpand}
                title="Тэлэх"
                style={{
                    width: '36px',
                    height: '36px',
                    marginBottom: '8px',
                    padding: 0,
                    border: 'none',
                    borderRadius: '6px',
                    background: '#3498db',
                    color: 'white',
                    cursor: 'pointer',
                    fontSize: '14px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }}
            >
                ▶
            </button>
            {onSettingsClick && iconBtn(onSettingsClick, 'Тохиргоо', '⚙️')}
            {onProductCatalogClick && iconBtn(onProductCatalogClick, 'Лавлагаа', '📋')}
            {iconBtn(handleSendToTaxSystem, 'Татварт илгээх', sendingToTax ? '⏳' : '📤', sendingToTax)}
            {onRefund && iconBtn(() => setRefundModalOpen(true), 'Буцаалт', '🔄')}
            {onLogout && iconBtn(onLogout, 'Гарах', '⎋')}
        </>
    );

    return (
        <div className={"sidebar" + (collapsed ? " sidebar-collapsed" : "")}>
            {collapsed ? collapsedStrip : (
            <div className="sidebar-main-content">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px', gap: '8px' }}>
                <h1 style={{ margin: 0 }}>🛒 CSPOS</h1>
                {onCollapse && (
                    <button
                        type="button"
                        onClick={onCollapse}
                        title="Эвхэх"
                        style={{
                            width: '32px',
                            height: '32px',
                            padding: 0,
                            border: 'none',
                            borderRadius: '6px',
                            background: '#34495e',
                            color: 'white',
                            cursor: 'pointer',
                            fontSize: '14px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            flexShrink: 0
                        }}
                    >
                        ◀
                    </button>
                )}
            </div>
            {currentOperator && (
                <div style={{
                    background: '#34495e',
                    padding: '8px',
                    borderRadius: '6px',
                    marginBottom: '10px',
                    border: '1px solid #667eea'
                }}>
                    <div style={{ fontSize: '10px', color: '#bdc3c7', marginBottom: '3px' }}>
                        Нэвтэрсэн хэрэглэгч:
                    </div>
                    <div style={{ fontSize: '12px', fontWeight: 'bold', color: '#ecf0f1', marginBottom: '3px' }}>
                        {currentOperator.o_name || currentOperator.name || currentOperator.operator_name || 
                         currentOperator.opercode || currentOperator.operator_code || 
                         'Operator'}
                    </div>
                    {(currentOperator.opid || currentOperator.opercode) && (
                        <div style={{ fontSize: '9px', color: '#95a5a6', marginBottom: '3px' }}>
                            {currentOperator.opid && `opid: ${currentOperator.opid}`}
                            {currentOperator.opid && currentOperator.opercode && ' | '}
                            {currentOperator.opercode && `opercode: ${currentOperator.opercode}`}
                        </div>
                    )}
                    {currentOperator.dep_code && (
                        <div style={{ fontSize: '9px', color: '#95a5a6', marginBottom: '4px' }}>
                            Дэлгүүр: {currentOperator.dep_code}
                        </div>
                    )}
                    {licenseWarning && (
                        <div style={{
                            fontSize: '9px',
                            marginBottom: '4px',
                            padding: '4px 6px',
                            borderRadius: '4px',
                            background: licenseWarning.valid === false ? 'rgba(220, 53, 69, 0.2)' : licenseWarning.daysRemaining !== null && licenseWarning.daysRemaining <= 7 ? 'rgba(255, 193, 7, 0.2)' : 'rgba(46, 204, 113, 0.15)',
                            color: licenseWarning.valid === false ? '#f8d7da' : licenseWarning.daysRemaining !== null && licenseWarning.daysRemaining <= 7 ? '#ffc107' : '#2ecc71'
                        }}>
                            {licenseWarning.valid === false
                                ? 'Хүчинтэй хугацаа дууссан'
                                : licenseWarning.daysRemaining !== null
                                    ? `Дуусах хугацаа: ${licenseWarning.daysRemaining} хоног үлдлээ`
                                    : 'Хүчинтэй'}
                        </div>
                    )}
                    {currentMtId && currentMtId > 0 && (
                        <div style={{ marginBottom: '4px' }}>
                            <div style={{ fontSize: '9px', color: '#2ecc71', fontWeight: 'bold' }}>
                                mt_id: {currentMtId}
                            </div>
                            {cart && cart.length > 0 && (
                                <div
                                    style={{
                                        fontSize: '9px',
                                        color: '#f4d03f',
                                        marginTop: '2px',
                                        padding: '3px 6px',
                                        borderRadius: '4px',
                                        background: 'rgba(243, 156, 18, 0.2)',
                                        border: '1px solid rgba(243, 156, 18, 0.45)'
                                    }}
                                    title="Төлбөр төлөгдөх хүртэл энэ худалдан авалт дуусаагүй"
                                >
                                    Тооцоо хийгээгүй — хүлээгдэж байна
                                </div>
                            )}
                        </div>
                    )}
                    {currentSourceNo && currentSourceNo > 0 && (
                        <div style={{ fontSize: '9px', color: '#3498db', marginBottom: '4px', fontWeight: 'bold' }}>
                            Баримтын дугаар: {currentSourceNo}
                        </div>
                    )}
                    {selectedCompany && (
                        <>
                            <div style={{ fontSize: '10px', fontWeight: 'bold', color: '#ecf0f1', marginBottom: '4px' }}>
                                Байгууллага: {selectedCompany.b_name || selectedCompany.name || selectedCompany.client_name || selectedCompany.company_name || `ID: ${selectedCompany.b_id}`}
                            </div>
                            {selectedCompany.b_tax !== undefined && selectedCompany.b_tax !== null && (
                                <div style={{ fontSize: '9px', color: '#3498db', marginBottom: '2px' }}>
                                    НӨАТ код: {selectedCompany.b_tax}
                                </div>
                            )}
                            {vatRate !== undefined && vatRate !== null && vatRate > 0 && (
                                <div style={{ fontSize: '9px', color: '#3498db', marginBottom: '2px' }}>
                                    НӨАТ хувь: {vatRate}%
                                </div>
                            )}
                            {selectedCompany.b_citytax !== undefined && selectedCompany.b_citytax !== null && (
                                <div style={{ fontSize: '9px', color: '#9b59b6', marginBottom: '2px' }}>
                                    НХАТ хувь: {selectedCompany.b_citytax}%
                                </div>
                            )}
                            {(selectedCompany.b_wholesale_center === true || selectedCompany.b_wholesale_center === 1 || selectedCompany.b_wholesale_center === '1') && (
                                <div style={{ fontSize: '9px', color: '#1abc9c', marginBottom: '2px' }} title="Байгууллагын мэдээллээс (Тохиргоо)">
                                    Бөөний төв: Тийм (бөөний үнээр — НХАТ тооцохгүй)
                                </div>
                            )}
                            {selectedCompany.merchantTin && (
                                <div style={{ fontSize: '9px', color: '#f39c12', marginBottom: '2px' }}>
                                    Merchant TIN: {selectedCompany.merchantTin}
                                </div>
                            )}
                            {selectedCompany.regNo && (
                                <div style={{ fontSize: '9px', color: '#e67e22', marginBottom: '2px' }}>
                                    Reg No: {selectedCompany.regNo}
                                </div>
                            )}
                            {selectedCompany.companyName && (
                                <div style={{ fontSize: '9px', color: '#16a085', marginBottom: '2px' }}>
                                    Байгууллагын нэр: {selectedCompany.companyName}
                                </div>
                            )}
                            {(selectedCompany.apiURL || selectedCompany.apiUrl) && (
                                <div style={{ 
                                    fontSize: '9px', 
                                    color: '#2ecc71', 
                                    marginBottom: '4px', 
                                    wordBreak: 'break-all',
                                    fontWeight: 'bold',
                                    padding: '4px',
                                    background: '#1e3a2e',
                                    borderRadius: '3px',
                                    border: '1px solid #2ecc71'
                                }}>
                                    🌐 API URL: {selectedCompany.apiURL || selectedCompany.apiUrl}
                                </div>
                            )}
                        </>
                    )}
                    <div style={{ display: 'flex', gap: '4px', marginTop: '6px', flexWrap: 'wrap' }}>
                        <button
                            onClick={onSettingsClick}
                            style={{
                                flex: 1,
                                padding: '4px 8px',
                                background: '#3498db',
                                color: 'white',
                                border: 'none',
                                borderRadius: '4px',
                                cursor: 'pointer',
                                fontSize: '10px',
                                minWidth: '80px'
                            }}
                        >
                            ⚙️ Тохиргоо
                        </button>
                        {onProductCatalogClick && (
                            <button
                                onClick={onProductCatalogClick}
                                style={{
                                    flex: 1,
                                    padding: '4px 8px',
                                    background: '#27ae60',
                                    color: 'white',
                                    border: 'none',
                                    borderRadius: '4px',
                                    cursor: 'pointer',
                                    fontSize: '10px',
                                    minWidth: '80px'
                                }}
                            >
                                📋 Лавлагаа
                            </button>
                        )}
                        <button
                            onClick={handleSendToTaxSystem}
                            disabled={sendingToTax}
                            style={{
                                flex: 1,
                                padding: '4px 8px',
                                background: sendingToTax ? '#95a5a6' : '#e74c3c',
                                color: 'white',
                                border: 'none',
                                borderRadius: '4px',
                                cursor: sendingToTax ? 'not-allowed' : 'pointer',
                                fontSize: '10px',
                                minWidth: '80px',
                                opacity: sendingToTax ? 0.6 : 1
                            }}
                        >
                            {sendingToTax ? '⏳ Илгээж байна...' : '📤 Татварт илгээх'}
                        </button>
                        {onRefund && (
                            <button
                                onClick={() => setRefundModalOpen(true)}
                                style={{
                                    flex: 1,
                                    padding: '4px 8px',
                                    background: '#f39c12',
                                    color: 'white',
                                    border: 'none',
                                    borderRadius: '4px',
                                    cursor: 'pointer',
                                    fontSize: '10px',
                                    minWidth: '80px'
                                }}
                            >
                                🔄 Буцаалт
                            </button>
                        )}
                        <button
                            onClick={onLogout}
                            style={{
                                flex: 1,
                                padding: '4px 8px',
                                background: '#e74c3c',
                                color: 'white',
                                border: 'none',
                                borderRadius: '4px',
                                cursor: 'pointer',
                                fontSize: '10px',
                                minWidth: '80px'
                            }}
                        >
                            Гарах
                        </button>
                    </div>
                </div>
            )}
            <div style={{ marginBottom: '10px' }}>
                <label style={{ 
                    display: 'block', 
                    fontSize: '10px', 
                    color: '#bdc3c7', 
                    marginBottom: '3px' 
                }}>
                    Бараа хайх:
                </label>
                <div style={{ display: 'flex', gap: '4px' }}>
                    <input
                        type="text"
                        id="productSearchInput"
                        onKeyPress={(e) => {
                            if (e.key === 'Enter' && e.target.value) {
                                if (onProductSearch) onProductSearch(e.target.value);
                            }
                        }}
                        placeholder="Баркод эсвэл барааны нэр оруулах..."
                        style={{
                            flex: 1,
                            padding: '6px',
                            border: '1px solid #34495e',
                            borderRadius: '4px',
                            background: '#2c3e50',
                            color: 'white',
                            fontSize: '12px',
                            boxSizing: 'border-box'
                        }}
                    />
                    <button
                        onClick={() => {
                            const input = document.getElementById('productSearchInput');
                            if (input && input.value && onProductSearch) {
                                onProductSearch(input.value);
                            }
                        }}
                        style={{
                            padding: '6px 12px',
                            background: '#3498db',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontSize: '12px',
                            whiteSpace: 'nowrap'
                        }}
                    >
                        Хайх
                    </button>
                </div>
                {productSearchLoading && (
                    <div style={{ marginTop: '6px', fontSize: '11px', color: '#95a5a6' }}>Хайж байна...</div>
                )}
            </div>
            <div style={{ 
                marginBottom: '10px', 
                padding: '6px', 
                background: '#34495e', 
                borderRadius: '6px',
                border: '1px solid #667eea'
            }}>
                <div style={{ fontSize: '10px', color: '#bdc3c7', marginBottom: '3px' }}>
                    Сагс:
                </div>
                {cart.length > 0 && (
                    <div style={{ fontSize: '10px', color: '#f7dc6f', marginBottom: '4px', fontWeight: '600' }}>
                        Тооцоо хийгээгүй — хүлээгдэж байна
                    </div>
                )}
                <div style={{ fontSize: '13px', fontWeight: 'bold', color: '#ecf0f1' }}>
                    {cart.length} бүтээгдэхүүн
                </div>
                <div style={{ fontSize: '11px', color: '#bdc3c7', marginTop: '2px' }}>
                    Дүн: {formatCurrency(calculateTotal())}
                </div>
                {calculateVATTotal() > 0 && (
                    <div style={{ fontSize: '11px', color: '#3498db', marginTop: '2px' }}>
                        НӨАТ: {formatCurrencyTwoDecimals(calculateVATTotal())}
                    </div>
                )}
                {calculateCityTaxTotal() > 0 && (
                    <div style={{ fontSize: '11px', color: '#9b59b6', marginTop: '2px' }}>
                        НХАТ: {formatCurrency(calculateCityTaxTotal())}
                    </div>
                )}
                {calculateTaxTotal() > 0 && (
                    <div style={{ fontSize: '11px', color: '#f39c12', marginTop: '2px' }}>
                        Татвар (нийт): {formatCurrency(calculateTaxTotal())}
                    </div>
                )}
                {calculateDiscountTotal && calculateDiscountTotal() > 0 && (
                    <div style={{ fontSize: '11px', color: '#e74c3c', marginTop: '2px' }}>
                        Хөнгөлөлт: {formatCurrency(calculateDiscountTotal())}
                    </div>
                )}
                <div style={{ fontSize: '13px', fontWeight: 800, color: '#0d0d0d', marginTop: '4px', borderTop: '1px solid #667eea', paddingTop: '4px' }}>
                    Нийт: <span style={{ color: '#000000' }}>{formatCurrency(calculateGrandTotal())}</span>
                </div>
            </div>
            </div>
            )}

            {/* Refund Modal */}
            {refundModalOpen && onRefund && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div style={{
                        backgroundColor: 'white',
                        padding: '20px',
                        borderRadius: '8px',
                        minWidth: '400px',
                        maxWidth: '90%',
                        color: '#212529'
                    }}>
                        <h3 style={{ marginTop: 0, marginBottom: '16px' }}>НӨАТ-н баримт буцаах</h3>
                        <div style={{ marginBottom: '12px' }}>
                            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                Баримтын ID: *
                            </label>
                            <input
                                type="text"
                                value={refundId}
                                onChange={(e) => setRefundId(e.target.value)}
                                onKeyPress={(e) => {
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        fetchReceiptInfo();
                                    }
                                }}
                                placeholder="Баримтын ID оруулна уу (Enter дарахад хайлт хийгдэнэ)"
                                style={{
                                    width: '100%',
                                    padding: '8px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    fontSize: '14px',
                                    boxSizing: 'border-box'
                                }}
                                autoFocus
                            />
                        </div>
                        {refundId && refundId.trim() && (
                            <div style={{ 
                                marginBottom: '12px', 
                                padding: '10px', 
                                background: loadingReceipt ? '#f8f9fa' : (receiptInfo?.found ? '#e8f5e9' : '#fff3cd'),
                                borderRadius: '4px',
                                border: `1px solid ${loadingReceipt ? '#ced4da' : (receiptInfo?.found ? '#4caf50' : '#ffc107')}`
                            }}>
                                {loadingReceipt ? (
                                    <div style={{ fontSize: '13px', color: '#6c757d' }}>
                                        Баримтын мэдээлэл хайж байна...
                                    </div>
                                ) : receiptInfo?.found && receiptInfo?.date ? (
                                    <div>
                                        <div style={{ fontSize: '12px', color: '#495057', marginBottom: '4px', fontWeight: 'bold' }}>
                                            Хэвлэсэн огноо/цаг:
                                        </div>
                                        <div style={{ fontSize: '14px', color: '#2e7d32', fontWeight: 'bold' }}>
                                            {formatDateTimeIso(receiptInfo.date)}
                                        </div>
                                        {receiptInfo.receiptId && (
                                            <div style={{ marginTop: '6px', fontSize: '12px', color: '#495057' }}>
                                                Баримтын ID: <span style={{ fontWeight: 'bold' }}>{receiptInfo.receiptId}</span>
                                            </div>
                                        )}
                                        {receiptInfo.totalAmount !== null && receiptInfo.totalAmount !== undefined && (
                                            <div style={{ marginTop: '4px', fontSize: '12px', color: '#495057' }}>
                                                Нийт дүн: <span style={{ fontWeight: 'bold' }}>{formatCurrency ? formatCurrency(receiptInfo.totalAmount) : receiptInfo.totalAmount}</span>
                                            </div>
                                        )}
                                        {(receiptInfo.totalVAT !== null && receiptInfo.totalVAT !== undefined) && (
                                            <div style={{ marginTop: '4px', fontSize: '12px', color: '#495057' }}>
                                                НӨАТ: <span style={{ fontWeight: 'bold' }}>{formatCurrency ? formatCurrency(receiptInfo.totalVAT) : receiptInfo.totalVAT}</span>
                                            </div>
                                        )}
                                        {(receiptInfo.totalCityTax !== null && receiptInfo.totalCityTax !== undefined) && (
                                            <div style={{ marginTop: '4px', fontSize: '12px', color: '#495057' }}>
                                                НХАТ: <span style={{ fontWeight: 'bold' }}>{formatCurrency ? formatCurrency(receiptInfo.totalCityTax) : receiptInfo.totalCityTax}</span>
                                            </div>
                                        )}
                                    </div>
                                ) : receiptInfo?.found === false ? (
                                    <div style={{ fontSize: '13px', color: receiptInfo?.error?.includes('404') || receiptInfo?.error?.includes('Буцаалт хийх боломжтой') ? '#6c757d' : '#856404' }}>
                                        {receiptInfo?.error || 'Баримт олдсонгүй эсвэл мэдээлэл авах боломжгүй'}
                                    </div>
                                ) : null}
                            </div>
                        )}
                        {loadingRefundItems && (
                            <div style={{ textAlign: 'center', padding: '12px', color: '#6c757d', fontSize: '13px' }}>
                                Баримтын барааны мэдээлэл татаж байна...
                            </div>
                        )}
                        {!loadingRefundItems && refundItems.length > 0 && (
                            <div style={{ marginBottom: '16px' }}>
                                <h4 style={{ marginBottom: '8px', color: '#2e7d32', fontSize: '14px' }}>
                                    Буцаалтын барааны жагсаалт ({refundItems.length})
                                </h4>
                                <div style={{
                                    maxHeight: '240px',
                                    overflowY: 'auto',
                                    border: '1px solid #dee2e6',
                                    borderRadius: '4px'
                                }}>
                                    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '12px' }}>
                                        <thead style={{ position: 'sticky', top: 0, backgroundColor: '#f8f9fa', zIndex: 10 }}>
                                            <tr>
                                                <th style={{ padding: '6px', textAlign: 'left', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>№</th>
                                                <th style={{ padding: '6px', textAlign: 'left', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Бараа</th>
                                                <th style={{ padding: '6px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Тоо</th>
                                                <th style={{ padding: '6px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Үнэ</th>
                                                <th style={{ padding: '6px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Хөнгөлөлт</th>
                                                <th style={{ padding: '6px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Дүн</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {refundItems.map((row, index) => (
                                                <tr key={row.zid || row.id || index} style={{ borderBottom: '1px solid #dee2e6' }}>
                                                    <td style={{ padding: '6px' }}>{index + 1}</td>
                                                    <td style={{ padding: '6px' }}>{getRefundItemName(row)}</td>
                                                    <td style={{ padding: '6px', textAlign: 'right' }}>{getRefundItemQty(row)}</td>
                                                    <td style={{ padding: '6px', textAlign: 'right' }}>
                                                        {formatCurrency ? formatCurrency(getRefundItemPrice(row)) : getRefundItemPrice(row)}
                                                    </td>
                                                    <td style={{ padding: '6px', textAlign: 'right' }}>
                                                        {formatCurrency ? formatCurrency(getRefundItemDiscount(row)) : getRefundItemDiscount(row)}
                                                    </td>
                                                    <td style={{ padding: '6px', textAlign: 'right', fontWeight: 'bold' }}>
                                                        {formatCurrency ? formatCurrency(getRefundItemAmount(row)) : getRefundItemAmount(row)}
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                                <div style={{ marginTop: '8px', textAlign: 'right', fontSize: '13px', fontWeight: 'bold', color: '#2e7d32' }}>
                                    Нийт дүн: {formatCurrency ? formatCurrency(refundItemsTotal) : refundItemsTotal}
                                </div>
                            </div>
                        )}
                        <div style={{ marginBottom: '16px' }}>
                            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                Баримтын огноо/цаг (YYYY-MM-DD HH:MM:SS):
                            </label>
                            <input
                                type="datetime-local"
                                step="1"
                                value={refundDate}
                                onChange={(e) => setRefundDate(e.target.value)}
                                style={{
                                    width: '100%',
                                    padding: '8px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    fontSize: '14px',
                                    boxSizing: 'border-box'
                                }}
                            />
                            <small style={{ color: '#6c757d', fontSize: '12px' }}>
                                  огноогоо цаг мин секундээр оруулна уу, AM үдээс өмнө/PM үдээс хойш 
                            </small>
                            {refundDate && (
                                <div style={{ marginTop: '6px', fontSize: '12px', color: '#495057' }}>
                                    24 цагийн формат: {formatDateTimeIso(refundDate)}
                                </div>
                            )}
                        </div>
                        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
                            <button
                                onClick={() => {
                                    setRefundModalOpen(false);
                                    setRefundId('');
                                    setRefundDate('');
                                    setReceiptInfo(null);
                                    setRefundItems([]);
                                }}
                                style={{
                                    padding: '8px 16px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    backgroundColor: 'white',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                Цуцлах
                            </button>
                            <button
                                onClick={async () => {
                                    if (!refundId.trim()) {
                                        const message = 'Баримтын ID оруулах шаардлагатай!';
                                        if (showAlert && typeof showAlert === 'function') {
                                            showAlert(message);
                                        }
                                        return;
                                    }
                                    if (onRefund) {
                                        await onRefund(refundId.trim(), refundDate && refundDate.trim() ? refundDate.trim() : null);
                                        setRefundModalOpen(false);
                                        setRefundId('');
                                        setRefundDate('');
                                        setReceiptInfo(null);
                                        setRefundItems([]);
                                    } else {
                                        const message = 'Буцаалт хийх функц олдсонгүй!';
                                        if (showAlert && typeof showAlert === 'function') {
                                            showAlert(message);
                                        }
                                    }
                                }}
                                style={{
                                    padding: '8px 16px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: '#dc3545',
                                    color: 'white',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                Буцаалт хийх
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Баримт хайх Modal - шилжүүлсэн SettingsModal-д */}
            {/* {searchReceiptModalOpen && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div style={{
                        backgroundColor: 'white',
                        padding: '20px',
                        borderRadius: '8px',
                        minWidth: '400px',
                        maxWidth: '90%'
                    }}>
                        <h3 style={{ marginTop: 0, marginBottom: '16px' }}>Баримт хайх</h3>
                        <div style={{ marginBottom: '12px' }}>
                            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                Сүүлийн хоногийн тоо:
                            </label>
                            <input
                                type="number"
                                value={searchReceiptDays}
                                onChange={(e) => setSearchReceiptDays(e.target.value)}
                                placeholder="30"
                                min="1"
                                max="365"
                                style={{
                                    width: '100%',
                                    padding: '8px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    fontSize: '14px',
                                    boxSizing: 'border-box'
                                }}
                            />
                            <small style={{ color: '#6c757d', fontSize: '12px' }}>
                                Сүүлийн хэдэн хоногоос хайх (default: 30 хоног)
                            </small>
                        </div>
                        <div style={{ marginBottom: '12px', display: 'flex', gap: '8px' }}>
                            <button
                                onClick={() => {
                                    setSearchMode('ID');
                                    setSearchReceiptId('');
                                    setSearchReceiptCashcode('');
                                    setSearchReceiptSourceno('');
                                    setSearchReceiptOpid('');
                                    setSearchReceiptDays('30');
                                    setSearchReceiptInfo(null);
                                    setFoundMtId(null);
                                    setSearchReceiptItems([]);
                                }}
                                style={{
                                    flex: 1,
                                    padding: '6px 12px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: searchMode === 'ID' ? '#007bff' : '#e9ecef',
                                    color: searchMode === 'ID' ? 'white' : '#495057',
                                    cursor: 'pointer',
                                    fontSize: '13px',
                                    fontWeight: searchMode === 'ID' ? 'bold' : 'normal'
                                }}
                            >
                                ID-аар хайх
                            </button>
                            <button
                                onClick={() => {
                                    setSearchMode('CASHCODE');
                                    setSearchReceiptId('');
                                    setSearchReceiptCashcode('');
                                    setSearchReceiptSourceno('');
                                    setSearchReceiptOpid('');
                                    setSearchReceiptDays('30');
                                    setSearchReceiptInfo(null);
                                    setFoundMtId(null);
                                    setSearchReceiptItems([]);
                                }}
                                style={{
                                    flex: 1,
                                    padding: '6px 12px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: searchMode === 'CASHCODE' ? '#007bff' : '#e9ecef',
                                    color: searchMode === 'CASHCODE' ? 'white' : '#495057',
                                    cursor: 'pointer',
                                    fontSize: '13px',
                                    fontWeight: searchMode === 'CASHCODE' ? 'bold' : 'normal'
                                }}
                            >
                                Cashcode-оор хайх
                            </button>
                            <button
                                onClick={() => {
                                    setSearchMode('SOURCENO');
                                    setSearchReceiptId('');
                                    setSearchReceiptCashcode('');
                                    setSearchReceiptSourceno('');
                                    setSearchReceiptOpid('');
                                    setSearchReceiptDays('30');
                                    setSearchReceiptInfo(null);
                                    setFoundMtId(null);
                                    setSearchReceiptItems([]);
                                }}
                                style={{
                                    flex: 1,
                                    padding: '6px 12px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: searchMode === 'SOURCENO' ? '#007bff' : '#e9ecef',
                                    color: searchMode === 'SOURCENO' ? 'white' : '#495057',
                                    cursor: 'pointer',
                                    fontSize: '13px',
                                    fontWeight: searchMode === 'SOURCENO' ? 'bold' : 'normal'
                                }}
                            >
                                Sourceno-оор хайх
                            </button>
                            <button
                                onClick={() => {
                                    setSearchMode('CASHCODE_OPID');
                                    setSearchReceiptId('');
                                    setSearchReceiptCashcode('');
                                    setSearchReceiptSourceno('');
                                    setSearchReceiptOpid('');
                                    setSearchReceiptDays('30');
                                    setSearchReceiptInfo(null);
                                    setFoundMtId(null);
                                    setSearchReceiptItems([]);
                                }}
                                style={{
                                    flex: 1,
                                    padding: '6px 12px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: searchMode === 'CASHCODE_OPID' ? '#007bff' : '#e9ecef',
                                    color: searchMode === 'CASHCODE_OPID' ? 'white' : '#495057',
                                    cursor: 'pointer',
                                    fontSize: '13px',
                                    fontWeight: searchMode === 'CASHCODE_OPID' ? 'bold' : 'normal'
                                }}
                            >
                                Cashcode & Opid
                            </button>
                        </div>
                        {searchMode === 'ID' ? (
                            <div style={{ marginBottom: '12px' }}>
                                <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                    Баримтын ID:
                                </label>
                                <input
                                    type="text"
                                    value={searchReceiptId}
                                    onChange={(e) => setSearchReceiptId(e.target.value)}
                                    placeholder="Баримтын ID оруулна уу"
                                    style={{
                                        width: '100%',
                                        padding: '8px',
                                        border: '1px solid #ced4da',
                                        borderRadius: '4px',
                                        fontSize: '14px',
                                        boxSizing: 'border-box'
                                    }}
                                    autoFocus
                                />
                            </div>
                        ) : searchMode === 'CASHCODE_OPID' ? (
                            <>
                                <div style={{ marginBottom: '12px' }}>
                                    <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                        Cashcode:
                                    </label>
                                    <input
                                        type="number"
                                        value={searchReceiptCashcode}
                                        onChange={(e) => setSearchReceiptCashcode(e.target.value)}
                                        placeholder="Cashcode оруулна уу"
                                        style={{
                                            width: '100%',
                                            padding: '8px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                        autoFocus
                                    />
                                </div>
                                <div style={{ marginBottom: '12px' }}>
                                    <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                        Операторын ID (Opid):
                                    </label>
                                    <input
                                        type="number"
                                        value={searchReceiptOpid}
                                        onChange={(e) => setSearchReceiptOpid(e.target.value)}
                                        placeholder="Операторын ID оруулна уу"
                                        style={{
                                            width: '100%',
                                            padding: '8px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    />
                                </div>
                                <div style={{ marginBottom: '12px', fontSize: '12px', color: '#6c757d' }}>
                                    Сүүлийн 10 хоногоос хайна
                                </div>
                            </>
                        ) : searchMode === 'CASHCODE' ? (
                            <>
                                <div style={{ marginBottom: '12px' }}>
                                    <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                        Cashcode:
                                    </label>
                                    <input
                                        type="number"
                                        value={searchReceiptCashcode}
                                        onChange={(e) => setSearchReceiptCashcode(e.target.value)}
                                        placeholder="Cashcode оруулна уу"
                                        style={{
                                            width: '100%',
                                            padding: '8px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                        autoFocus
                                    />
                                </div>
                                <div style={{ marginBottom: '12px' }}>
                                    <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                        Баримтын дугаар (Sourceno):
                                    </label>
                                    <input
                                        type="number"
                                        value={searchReceiptSourceno}
                                        onChange={(e) => setSearchReceiptSourceno(e.target.value)}
                                        placeholder="Баримтын дугаар оруулна уу"
                                        style={{
                                            width: '100%',
                                            padding: '8px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    />
                                </div>
                            </>
                        ) : (
                            <>
                                <div style={{ marginBottom: '12px' }}>
                                    <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                        Баримтын дугаар (Sourceno):
                                    </label>
                                    <input
                                        type="number"
                                        value={searchReceiptSourceno}
                                        onChange={(e) => setSearchReceiptSourceno(e.target.value)}
                                        placeholder="Баримтын дугаар оруулна уу"
                                        style={{
                                            width: '100%',
                                            padding: '8px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                        autoFocus
                                    />
                                </div>
                                <div style={{ marginBottom: '12px' }}>
                                    <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                        Операторын ID (Opid):
                                    </label>
                                    <input
                                        type="number"
                                        value={searchReceiptOpid}
                                        onChange={(e) => setSearchReceiptOpid(e.target.value)}
                                        placeholder="Операторын ID оруулна уу"
                                        style={{
                                            width: '100%',
                                            padding: '8px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    />
                                </div>
                            </>
                        )}
                        {((searchMode === 'ID' && searchReceiptId && searchReceiptId.trim()) || 
                          (searchMode === 'CASHCODE' && searchReceiptCashcode && searchReceiptCashcode.trim()) ||
                          (searchMode === 'CASHCODE_OPID' && searchReceiptCashcode && searchReceiptCashcode.trim() && searchReceiptOpid && searchReceiptOpid.trim()) ||
                          (searchMode === 'SOURCENO' && searchReceiptSourceno && searchReceiptSourceno.trim() && searchReceiptOpid && searchReceiptOpid.trim())) && (
                            <div style={{ 
                                marginBottom: '12px', 
                                padding: '10px', 
                                background: loadingSearchReceipt ? '#f8f9fa' : (searchReceiptInfo?.found ? '#e8f5e9' : '#fff3cd'),
                                borderRadius: '4px',
                                border: `1px solid ${loadingSearchReceipt ? '#ced4da' : (searchReceiptInfo?.found ? '#4caf50' : '#ffc107')}`
                            }}>
                                {loadingSearchReceipt ? (
                                    <div style={{ fontSize: '13px', color: '#6c757d' }}>
                                        Баримтын мэдээлэл хайж байна...
                                    </div>
                                ) : searchReceiptInfo?.found ? (
                                    <div>
                                        {searchReceiptInfo.date && (
                                            <>
                                                <div style={{ fontSize: '12px', color: '#495057', marginBottom: '4px', fontWeight: 'bold' }}>
                                                    Хэвлэсэн огноо/цаг:
                                                </div>
                                                <div style={{ fontSize: '14px', color: '#2e7d32', fontWeight: 'bold' }}>
                                                    {formatDateMongolian ? formatDateMongolian(searchReceiptInfo.date) : searchReceiptInfo.date}
                                                </div>
                                            </>
                                        )}
                                        {searchReceiptInfo.data && (
                                            <div style={{ marginTop: '8px', fontSize: '12px', color: '#495057' }}>
                                                <div>Нийт дүн: {formatCurrency ? formatCurrency(searchReceiptInfo.data.totalAmount || searchReceiptInfo.data.total || 0) : (searchReceiptInfo.data.totalAmount || searchReceiptInfo.data.total || 0)}</div>
                                                {searchReceiptInfo.data.items && (
                                                    <div style={{ marginTop: '4px' }}>
                                                        Барааны тоо: {searchReceiptInfo.data.items.length}
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                        {foundMtId && (
                                            <div style={{ marginTop: '12px' }}>
                                                <button
                                                    onClick={async () => {
                                                        if (!foundMtId) {
                                                            if (showAlert) showAlert('Баримт олдсонгүй');
                                                            return;
                                                        }
                                                        
                                                        if (!api || !api.getExpenseRows) {
                                                            if (showAlert) showAlert('API функц олдсонгүй');
                                                            return;
                                                        }
                                                        
                                                        try {
                                                            if (showAlert) showAlert('Баримтын мэдээлэл татаж байна...');
                                                            
                                                            const expenseResult = await api.getExpenseRows(foundMtId);
                                                            
                                                            if (expenseResult.success && expenseResult.data) {
                                                                let expenseRows = [];
                                                                if (expenseResult.data.rows) {
                                                                    expenseRows = expenseResult.data.rows;
                                                                } else if (Array.isArray(expenseResult.data)) {
                                                                    expenseRows = expenseResult.data;
                                                                }
                                                                
                                                                if (expenseRows.length === 0) {
                                                                    if (showAlert) showAlert('Баримтанд бараа олдсонгүй');
                                                                    return;
                                                                }
                                                                
                                                                // Cart-д нэмэх
                                                                let addedCount = 0;
                                                                for (const row of expenseRows) {
                                                                    if (row.m_id) {
                                                                        const product = {
                                                                            m_id: row.m_id,
                                                                            name: row.m_name || row.name || 'Бүтээгдэхүүн',
                                                                            shortname: row.shortname || null,
                                                                            dotcode: row.dotcode || row.m_code || null,
                                                                            m_code: row.m_code || null,
                                                                            price_low: row.price_low || row.price || 0,
                                                                            quantity: parseFloat(row.tcount || row.quantity || 1),
                                                                            tcount: parseFloat(row.tcount || row.quantity || 1),
                                                                            vat: row.vat || 0,
                                                                            citytax: row.citytax || 0,
                                                                            discount: row.discount || 0,
                                                                            discper: row.discper || 0,
                                                                            nodiscount: row.nodiscount || 0,
                                                                            zid: row.zid || null,
                                                                            mt_id: foundMtId
                                                                        };
                                                                        
                                                                        if (addToCart && typeof addToCart === 'function') {
                                                                            await addToCart(product);
                                                                            addedCount++;
                                                                        }
                                                                    }
                                                                }
                                                                
                                                                if (addedCount > 0) {
                                                                    if (showAlert) showAlert(`${addedCount} бараа cart-д нэмэгдлээ`);
                                                                    setSearchReceiptModalOpen(false);
                                                                    setSearchReceiptId('');
                                                                    setSearchReceiptCashcode('');
                                                                    setSearchReceiptSourceno('');
                                                                    setSearchReceiptOpid('');
                                                                    setSearchReceiptInfo(null);
                                                                    setFoundMtId(null);
                                                                    setSearchMode('ID');
                                                                } else {
                                                                    if (showAlert) showAlert('Cart-д бараа нэмэхэд алдаа гарлаа');
                                                                }
                                                            } else {
                                                                if (showAlert) showAlert('Баримтын мэдээлэл авах боломжгүй');
                                                            }
                                                        } catch (error) {
                                                            console.error('Error loading receipt to cart:', error);
                                                            if (showAlert) showAlert(`Алдаа: ${error.message || 'Баримтын мэдээлэл авах боломжгүй'}`);
                                                        }
                                                    }}
                                                    style={{
                                                        padding: '8px 16px',
                                                        border: 'none',
                                                        borderRadius: '4px',
                                                        backgroundColor: '#28a745',
                                                        color: 'white',
                                                        cursor: 'pointer',
                                                        fontSize: '14px',
                                                        width: '100%'
                                                    }}
                                                >
                                                    Cart-д нэмэх
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                ) : searchReceiptInfo?.found === false ? (
                                    <div style={{ fontSize: '13px', color: '#856404' }}>
                                        {searchReceiptInfo?.error || 'Баримт олдсонгүй эсвэл мэдээлэл авах боломжгүй'}
                                    </div>
                                ) : null}
                            </div>
                        )}
                        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '12px' }}>
                            <button
                                onClick={async () => {
                                    // Хайх функц
                                    if (searchMode === 'ID' && searchReceiptId && searchReceiptId.trim()) {
                                        // ID-аар хайх нь автоматаар хийгддэг
                                        return;
                                    } else if (searchMode === 'CASHCODE' && searchReceiptCashcode && searchReceiptCashcode.trim() && searchReceiptSourceno && searchReceiptSourceno.trim()) {
                                        // Cashcode-оор хайх нь автоматаар хийгддэг
                                        return;
                                    } else if (searchMode === 'CASHCODE_OPID' && searchReceiptCashcode && searchReceiptCashcode.trim() && searchReceiptOpid && searchReceiptOpid.trim()) {
                                        // Cashcode & Opid-оор хайх нь автоматаар хийгддэг
                                        return;
                                    } else if (searchMode === 'SOURCENO' && searchReceiptSourceno && searchReceiptSourceno.trim() && searchReceiptOpid && searchReceiptOpid.trim()) {
                                        // Sourceno-оор хайх нь автоматаар хийгддэг
                                        return;
                                    } else {
                                        if (showAlert) showAlert('Хайх мэдээлэл оруулна уу');
                                    }
                                }}
                                style={{
                                    padding: '8px 16px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: '#007bff',
                                    color: 'white',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                Хайх
                            </button>
                            <button
                                onClick={() => {
                                    setSearchReceiptModalOpen(false);
                                    setSearchReceiptId('');
                                    setSearchReceiptCashcode('');
                                    setSearchReceiptSourceno('');
                                    setSearchReceiptOpid('');
                                    setSearchReceiptDays('30');
                                    setSearchReceiptInfo(null);
                                    setFoundMtId(null);
                                    setSearchReceiptItems([]);
                                    setSearchMode('ID');
                                }}
                                style={{
                                    padding: '8px 16px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    backgroundColor: 'white',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                Хаах
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Бараа сонгох цонх (тоо оруулах цонхтой адил) */}
            {productSearchList && productSearchList.length > 0 && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div style={{
                        backgroundColor: 'white',
                        padding: '20px',
                        borderRadius: '8px',
                        minWidth: '400px',
                        maxWidth: '90%',
                        maxHeight: '85vh',
                        overflow: 'hidden',
                        display: 'flex',
                        flexDirection: 'column'
                    }}>
                        <h3 style={{ marginTop: 0, marginBottom: '16px' }}>Бараа сонгох</h3>
                        <div style={{ marginBottom: '8px', fontSize: '14px', color: '#495057' }}>
                            Олдсон {productSearchList.length} бараа – нэгийг сонгоно уу:
                        </div>
                        <div style={{ flex: 1, overflowY: 'auto', marginBottom: '16px', border: '1px solid #dee2e6', borderRadius: '4px' }}>
                            {productSearchList.map(function (p) {
                                return (
                                    <div
                                        key={p.m_id}
                                        onClick={function () { if (onProductSearchSelect) onProductSearchSelect(p); }}
                                        style={{
                                            padding: '12px 14px',
                                            borderBottom: '1px solid #eee',
                                            cursor: 'pointer',
                                            display: 'flex',
                                            justifyContent: 'space-between',
                                            alignItems: 'center'
                                        }}
                                        onMouseEnter={function (e) { e.currentTarget.style.backgroundColor = '#f0f7ff'; }}
                                        onMouseLeave={function (e) { e.currentTarget.style.backgroundColor = 'white'; }}
                                    >
                                        <span style={{ fontWeight: 500, fontSize: '14px', color: '#2c3e50' }}>{p.m_name || p.shortname || '-'}</span>
                                        <span style={{ fontSize: '14px', color: '#27ae60', fontWeight: 'bold' }}>{formatCurrency ? formatCurrency(p.price_low || 0) : (p.price_low || 0)}</span>
                                    </div>
                                );
                            })}
                        </div>
                        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                            <button
                                onClick={onProductSearchClose}
                                style={{
                                    padding: '8px 16px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    backgroundColor: 'white',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                Хаах
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Internal Code Product Modal */}
            {internalCodeModalOpen && internalCodeProduct && onInternalCodeAddToCart && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div style={{
                        backgroundColor: 'white',
                        padding: '20px',
                        borderRadius: '8px',
                        minWidth: '400px',
                        maxWidth: '90%'
                    }}>
                        <h3 style={{ marginTop: 0, marginBottom: '16px' }}>Бараа нэмэх</h3>
                        
                        <div style={{ marginBottom: '12px' }}>
                            <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>Барааны нэр:</div>
                            <div style={{ fontSize: '14px', color: '#495057' }}>{internalCodeProduct.m_name || internalCodeProduct.shortname }</div>
                        </div>

                        {internalCodeProduct.dotcode && (
                            <div style={{ marginBottom: '12px' }}>
                                <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>Дотоод код:</div>
                                <div style={{ fontSize: '14px', color: '#495057' }}>{internalCodeProduct.dotcode}</div>
                            </div>
                        )}

                        {internalCodeProduct.barcode && (
                            <div style={{ marginBottom: '12px' }}>
                                <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>Баркод:</div>
                                <div style={{ fontSize: '14px', color: '#495057' }}>{internalCodeProduct.barcode}</div>
                            </div>
                        )}

                        <div style={{ marginBottom: '12px' }}>
                            <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>Үнэ:</div>
                            <div style={{ fontSize: '14px', color: '#495057', fontWeight: 'bold' }}>
                                {formatCurrency(internalCodeProduct.price_low || 0)}
                            </div>
                        </div>

                        <div style={{ marginBottom: '16px' }}>
                            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                Тоо хэмжээ: *
                            </label>
                            <input
                                type="number"
                                value={internalCodeQuantity !== '' && internalCodeQuantity !== null && internalCodeQuantity !== undefined ? internalCodeQuantity : '1'}
                                onChange={(e) => onInternalCodeQuantityChange(e.target.value)}
                                min="0.001"
                                step="0.001"
                                placeholder="1"
                                autoFocus
                                onKeyPress={(e) => {
                                    if (e.key === 'Enter') {
                                        onInternalCodeAddToCart();
                                    }
                                }}
                                onFocus={(e) => e.target.select()}
                                style={{
                                    width: '100%',
                                    padding: '8px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    fontSize: '16px',
                                    fontWeight: 'bold',
                                    boxSizing: 'border-box',
                                    textAlign: 'center'
                                }}
                            />
                        </div>

                        <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
                            <button
                                onClick={onInternalCodeModalClose}
                                style={{
                                    padding: '8px 16px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    backgroundColor: 'white',
                                    cursor: 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                Цуцлах
                            </button>
                            <button
                                onClick={onInternalCodeAddToCart}
                                disabled={internalCodeLoading || parseFloat(internalCodeQuantity || '1') <= 0}
                                style={{
                                    padding: '8px 16px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: internalCodeLoading || parseFloat(internalCodeQuantity || '1') <= 0 ? '#95a5a6' : '#27ae60',
                                    color: 'white',
                                    cursor: internalCodeLoading || parseFloat(internalCodeQuantity || '1') <= 0 ? 'not-allowed' : 'pointer',
                                    fontSize: '14px'
                                }}
                            >
                                {internalCodeLoading ? 'Нэмж байна...' : 'Сагсанд нэмэх'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

// Make available globally for browser
if (typeof window !== 'undefined') {
    window.Sidebar = Sidebar;
}

