// Receipt Search Modal Component
const { useState, useEffect } = React;

// formatCurrency and formatDateMongolian 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);

function operatorCanReturnTaxReceipt(operator) {
    if (!operator) return false;
    const v = operator.is_admin ?? operator.isAdmin;
    return v === true || v === 1 || v === '1';
}

function ReceiptSearchModal({ 
    isOpen, 
    onClose,
    selectedCompany,
    currentOperator,
    showAlert,
    api,
    addToCart,
    cart,
    setIsPaymentModalOpen,
    handleCheckout,
    onRefund
}) {
    // Keep HH:MM:SS exactly as in tax-system response (avoid timezone shifting).
    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 [searchReceiptId, setSearchReceiptId] = useState('');
    const [searchReceiptCashcode, setSearchReceiptCashcode] = useState('');
    const [searchReceiptSourceno, setSearchReceiptSourceno] = useState('');
    const [searchReceiptOpid, setSearchReceiptOpid] = useState('');
    const [searchReceiptDays, setSearchReceiptDays] = useState('30');
    const [searchMode, setSearchMode] = useState('ID');
    const [loadingSearchReceipt, setLoadingSearchReceipt] = useState(false);
    const [receiptHeader, setReceiptHeader] = useState(null); // a_expenseG мэдээлэл
    const [receiptList, setReceiptList] = useState([]); // a_expenseG жагсаалт (олон баримт)
    const [receiptDetails, setReceiptDetails] = useState([]); // a_expense мэдээлэл
    const [loadingDetails, setLoadingDetails] = useState(false);
    const [foundMtId, setFoundMtId] = useState(null);
    const [receiptTaxData, setReceiptTaxData] = useState(null); // Татварын системээс ирсэн receipt мэдээлэл (lottery number зэрэг)
    const [isPrinting, setIsPrinting] = useState(false);
    const [isResendingToTax, setIsResendingToTax] = useState(false);
    const [isReturningReceipt, setIsReturningReceipt] = useState(false);
    const [phoneNumber, setPhoneNumber] = useState(''); // Утасны дугаар оруулах талбар
    const [testMessage, setTestMessage] = useState(''); // Тест мессеж оруулах талбар
    const [isSendingTestSMS, setIsSendingTestSMS] = useState(false); // Тест SMS илгээж байгаа эсэх
    const [dailyReportLoading, setDailyReportLoading] = useState(false);
    const [dailyReportError, setDailyReportError] = useState('');
    const [dailyReportSummary, setDailyReportSummary] = useState(null);
    const [selectedReportType, setSelectedReportType] = useState('DAILY_CASHCODE');
    
    const hasInspector = receiptHeader?.inspector !== undefined &&
        receiptHeader?.inspector !== null &&
        String(receiptHeader.inspector).trim() !== '';
    const getRefundReceiptId = () => {
        return (
            receiptTaxData?.id ||
            receiptTaxData?.receiptId ||
            receiptTaxData?.receipt_id ||
            receiptHeader?.inspector ||
            null
        );
    };

    const getReceiptItemQty = (row) => {
        return row?.tcount ?? row?.quantity ?? row?.qty ?? 0;
    };

    const getReceiptItemPrice = (row) => {
        return row?.price_low ?? row?.price ?? row?.unitPrice ?? row?.unit_price ?? 0;
    };

    const getReceiptItemAmount = (row) => {
        return row?.totalAmount ?? row?.amount ?? row?.total ?? row?.sum ?? row?.lineTotal ?? 0;
    };
    
    const getReceiptItemDiscount = (row) => {
        const discountValue = row?.discount;
        if (discountValue !== undefined && discountValue !== null && !isNaN(discountValue)) {
            return parseFloat(discountValue) || 0;
        }
        const discper = parseFloat(row?.discper || row?.dispercent || 0) || 0;
        if (discper > 0) {
            const qty = getReceiptItemQty(row);
            const price = getReceiptItemPrice(row);
            return (price * discper / 100) * qty;
        }
        return 0;
    };

    const getExpenseRowTotals = (row) => {
        const vat = parseFloat(row?.vat ?? row?.totalvat ?? row?.totalVat ?? 0) || 0;
        const cityTax = parseFloat(row?.citytax ?? row?.totalCityTax ?? row?.cityTax ?? 0) || 0;
        const discount = parseFloat(row?.discount ?? 0) || 0;
        const totalLow = parseFloat(row?.total_low ?? row?.totalLow ?? row?.total_low_amount ?? 0) || 0;
        let totalSum = parseFloat(row?.totalsum ?? row?.totalSum ?? row?.total_sum ?? 0) || 0;
        if (!totalSum && totalLow) {
            totalSum = totalLow;
        }
        return { totalSum, totalLow, vat, cityTax, discount };
    };

    // Reset when modal closes
    useEffect(() => {
        if (!isOpen) {
            setSearchReceiptId('');
            setSearchReceiptCashcode('');
            setSearchReceiptSourceno('');
            setSearchReceiptOpid('');
            setSearchReceiptDays('30');
            setSearchMode('ID');
            setReceiptHeader(null);
            setReceiptList([]);
            setReceiptDetails([]);
            setFoundMtId(null);
            setPhoneNumber(''); // Утасны дугаарыг reset хийх
            setTestMessage(''); // Тест мессежийг reset хийх
            setDailyReportLoading(false);
            setDailyReportError('');
            setDailyReportSummary(null);
            setSelectedReportType('DAILY_CASHCODE');
        }
    }, [isOpen]);

    const reportOptions = [
        { value: 'DAILY_CASHCODE', label: 'Өдрийн тайлан (cashcode)', enabled: selectedCompany?.reportDailyCashcode ?? selectedCompany?.report_daily_cashcode ?? true },
        { value: 'DAILY_PAYMENT', label: 'Өдрийн тайлан (Төлбөрийн төрлөөр)', enabled: selectedCompany?.reportDailyPayment ?? selectedCompany?.report_daily_payment ?? true },
        { value: 'DAILY_TAX', label: 'Өдрийн тайлан (Татвар)', enabled: selectedCompany?.reportDailyTax ?? selectedCompany?.report_daily_tax ?? true },
        { value: 'SUMMARY', label: 'Хураангуй тайлан', enabled: selectedCompany?.reportSummary ?? selectedCompany?.report_summary ?? true }
    ].filter(option => option.enabled);

    useEffect(() => {
        if (!reportOptions.length) {
            setSelectedReportType('');
            return;
        }
        if (!reportOptions.find(option => option.value === selectedReportType)) {
            setSelectedReportType(reportOptions[0].value);
        }
    }, [reportOptions.length, selectedReportType]);
    
    const calculateDailyReport = async () => {
        if (!api || !api.getExpenseGListByCashcode || !api.getExpenseRows) {
            if (showAlert) showAlert('Тайлангийн API функц олдсонгүй.');
            return;
        }
        if (!selectedCompany || !currentOperator) {
            if (showAlert) showAlert('Байгууллага эсвэл операторын мэдээлэл дутуу байна.');
            return;
        }
        setDailyReportLoading(true);
        setDailyReportError('');
        setDailyReportSummary(null);
        try {
            let cashcode = null;
            if (searchReceiptCashcode && searchReceiptCashcode.trim()) {
                const parsed = parseInt(searchReceiptCashcode.trim(), 10);
                if (!isNaN(parsed) && isFinite(parsed)) {
                    cashcode = parsed;
                }
            }
            if (!cashcode && api.getCashCode) {
                const cashcodeResult = await api.getCashCode();
                if (cashcodeResult?.success) {
                    const value = cashcodeResult.data !== undefined && cashcodeResult.data !== null ? cashcodeResult.data : null;
                    cashcode = value !== null ? parseInt(value, 10) : null;
                }
            }
            if (!cashcode || isNaN(cashcode)) {
                throw new Error('Cashcode олдсонгүй.');
            }
            const b_id = selectedCompany.b_id || selectedCompany.id;
            const opid = currentOperator.opid || currentOperator.op_id;
            if (!b_id || !opid) {
                throw new Error('B_id эсвэл opid олдсонгүй.');
            }
            const listResult = await api.getExpenseGListByCashcode(cashcode, b_id, opid, 1, null, 2000);
            if (!listResult?.success || !Array.isArray(listResult.data)) {
                throw new Error(listResult?.error || 'Өдрийн баримтын жагсаалт олдсонгүй.');
            }
            const today = new Date();
            const start = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0);
            const end = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999);
            const todaysReceipts = listResult.data.filter(row => {
                const adate = row?.adate ? new Date(row.adate) : null;
                return adate && adate >= start && adate <= end;
            });
            
            let totalAfterDiscount = 0;
            let totalDiscount = 0;
            let totalVAT = 0;
            let totalCityTax = 0;
            let totalCash = 0;
            let totalBank = 0;
            let totalOther = 0;
            for (const receipt of todaysReceipts) {
                const cashValue = receipt.cash1 ?? receipt.cash ?? 0;
                const bankValue = receipt.bank1 ?? receipt.bank ?? 0;
                totalCash += parseFloat(cashValue) || 0;
                totalBank += parseFloat(bankValue) || 0;
            }
            if (api.getExpenseRowsBatch && todaysReceipts.length > 0) {
                const mtIds = todaysReceipts.map(r => r.mt_id).filter(Boolean);
                const batchResult = await api.getExpenseRowsBatch(mtIds);
                const rowsByMtId = batchResult?.success ? (batchResult.data || {}) : {};
                for (const receipt of todaysReceipts) {
                    const mtId = receipt.mt_id;
                    const rows = mtId != null ? (rowsByMtId[mtId] || []) : [];
                    let receiptTotal = 0;
                    rows.forEach((row) => {
                        const rowTotals = getExpenseRowTotals(row);
                        receiptTotal += rowTotals.totalSum;
                        totalDiscount += rowTotals.discount;
                        totalVAT += rowTotals.vat;
                        totalCityTax += rowTotals.cityTax;
                    });
                    totalAfterDiscount += receiptTotal;
                }
            } else {
                const BATCH_SIZE = 25;
                for (let i = 0; i < todaysReceipts.length; i += BATCH_SIZE) {
                    const chunk = todaysReceipts.slice(i, i + BATCH_SIZE);
                    const rowResults = await Promise.all(
                        chunk.map((receipt) => {
                            const mtId = receipt.mt_id;
                            if (!mtId) return Promise.resolve(null);
                            return api.getExpenseRows(mtId).then((rowsResult) => ({ rowsResult })).catch(() => ({ rowsResult: null }));
                        })
                    );
                    for (const item of rowResults) {
                        if (!item || !item.rowsResult) continue;
                        const rows = item.rowsResult?.data?.rows || item.rowsResult?.data || [];
                        let receiptTotal = 0;
                        if (Array.isArray(rows)) {
                            rows.forEach((row) => {
                                const rowTotals = getExpenseRowTotals(row);
                                receiptTotal += rowTotals.totalSum;
                                totalDiscount += rowTotals.discount;
                                totalVAT += rowTotals.vat;
                                totalCityTax += rowTotals.cityTax;
                            });
                        }
                        totalAfterDiscount += receiptTotal;
                    }
                }
            }
            if (totalCash + totalBank <= totalAfterDiscount) {
                totalOther = totalAfterDiscount - (totalCash + totalBank);
            }
            const totalBeforeDiscount = totalAfterDiscount + totalDiscount;
            
            setDailyReportSummary({
                cashcode,
                totalAfterDiscount,
                totalDiscount,
                totalBeforeDiscount,
                totalVAT,
                totalCityTax,
                totalCash,
                totalBank,
                totalOther,
                count: todaysReceipts.length
            });
        } catch (err) {
            const message = err?.message || 'Өдрийн тайлан тооцоолоход алдаа гарлаа.';
            setDailyReportError(message);
            if (showAlert) showAlert(message);
        } finally {
            setDailyReportLoading(false);
        }
    };

    const printDailyReport = async () => {
        if (!dailyReportSummary) {
            if (showAlert) showAlert('Өдрийн тайлан тооцоолоогүй байна.');
            return;
        }
        if (!api || !api.silentPrintHtml) {
            if (showAlert) showAlert('Хэвлэх функц олдсонгүй.');
            return;
        }
        let receiptWidth = 58;
        if (api.getReceiptWidth) {
            try {
                const widthResult = await api.getReceiptWidth();
                if (widthResult && widthResult.success && widthResult.data != null) {
                    const w = parseInt(widthResult.data, 10);
                    receiptWidth = (!isNaN(w) && w >= 76) ? 80 : 58;
                }
            } catch (widthErr) {
                console.error('Error getting receipt width for report:', widthErr);
            }
        }
        const is58 = receiptWidth < 76;
        const paperWidthMm = is58 ? 58 : 80;
        const fontSizePx = is58 ? 10 : 12;
        const paddingPx = is58 ? 4 : 8;
        const now = new Date();
        const dateStr = now.toISOString().split('T')[0];
        const formatAmount = (val) => formatCurrency ? formatCurrency(val) : String(val);
        let reportTitle = 'Өдрийн тайлан';
        let bodyHtml = `
                <div class="row"><span class="label">Огноо:</span><span class="value">${dateStr}</span></div>
                <div class="row"><span class="label">Cashcode:</span><span class="value">${dailyReportSummary.cashcode}</span></div>
                <div class="row"><span class="label">Баримтын тоо:</span><span class="value">${dailyReportSummary.count}</span></div>
                <div class="divider"></div>
        `;
        if (selectedReportType === 'DAILY_PAYMENT') {
            reportTitle = 'Өдрийн тайлан (Төлбөрийн төрлөөр)';
            bodyHtml += `
                <div class="row"><span class="label">Бэлэн:</span><span class="value">${formatAmount(dailyReportSummary.totalCash)}</span></div>
                <div class="row"><span class="label">Карт:</span><span class="value">${formatAmount(dailyReportSummary.totalBank)}</span></div>
                <div class="row"><span class="label">Бусад:</span><span class="value">${formatAmount(dailyReportSummary.totalOther)}</span></div>
                <div class="divider"></div>
                <div class="row total"><span>Нийт дүн:</span><span>${formatAmount(dailyReportSummary.totalAfterDiscount)}</span></div>
            `;
        } else if (selectedReportType === 'DAILY_TAX') {
            reportTitle = 'Өдрийн тайлан (Татвар)';
            bodyHtml += `
                <div class="row"><span class="label">НӨАТ:</span><span class="value">${formatAmount(dailyReportSummary.totalVAT)}</span></div>
                <div class="row"><span class="label">НХАТ:</span><span class="value">${formatAmount(dailyReportSummary.totalCityTax)}</span></div>
                <div class="divider"></div>
                <div class="row total"><span>Нийт дүн:</span><span>${formatAmount(dailyReportSummary.totalAfterDiscount)}</span></div>
            `;
        } else if (selectedReportType === 'SUMMARY') {
            reportTitle = 'Хураангуй тайлан';
            bodyHtml += `
                <div class="row"><span class="label">Баримтын тоо:</span><span class="value">${dailyReportSummary.count}</span></div>
                <div class="divider"></div>
                <div class="row"><span class="label">Нийт дүн:</span><span class="value">${formatAmount(dailyReportSummary.totalAfterDiscount)}</span></div>
                <div class="row"><span class="label">Хөнгөлөлтийн дүн:</span><span class="value">${formatAmount(dailyReportSummary.totalDiscount)}</span></div>
                <div class="row"><span class="label">Хөнгөлөлт нэмсэн нийт дүн:</span><span class="value">${formatAmount(dailyReportSummary.totalBeforeDiscount)}</span></div>
                <div class="divider"></div>
                <div class="row"><span class="label">НӨАТ:</span><span class="value">${formatAmount(dailyReportSummary.totalVAT)}</span></div>
                <div class="row"><span class="label">НХАТ:</span><span class="value">${formatAmount(dailyReportSummary.totalCityTax)}</span></div>
                <div class="divider"></div>
                <div class="row"><span class="label">Бэлэн:</span><span class="value">${formatAmount(dailyReportSummary.totalCash)}</span></div>
                <div class="row"><span class="label">Карт:</span><span class="value">${formatAmount(dailyReportSummary.totalBank)}</span></div>
                <div class="row"><span class="label">Бусад:</span><span class="value">${formatAmount(dailyReportSummary.totalOther)}</span></div>
            `;
        } else {
            reportTitle = 'Өдрийн тайлан (Cashcode)';
            bodyHtml += `
                <div class="row"><span class="label">Нийт дүн:</span><span class="value">${formatAmount(dailyReportSummary.totalAfterDiscount)}</span></div>
                <div class="row"><span class="label">Хөнгөлөлтийн дүн:</span><span class="value">${formatAmount(dailyReportSummary.totalDiscount)}</span></div>
                <div class="divider"></div>
                <div class="row total"><span>Хөнгөлөлт нэмсэн нийт дүн:</span><span>${formatAmount(dailyReportSummary.totalBeforeDiscount)}</span></div>
            `;
        }
        const html = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8" />
                <style>
                    body { font-family: Arial, sans-serif; font-size: ${fontSizePx}px; margin: 0; padding: ${paddingPx}px; max-width: ${paperWidthMm}mm; box-sizing: border-box; }
                    h3 { margin: 0 0 ${paddingPx}px 0; text-align: center; font-size: ${fontSizePx + 1}px; }
                    .row { display: flex; justify-content: space-between; margin: 3px 0; }
                    .label { color: #555; }
                    .value { font-weight: bold; }
                    .total { font-size: ${fontSizePx + 1}px; font-weight: bold; }
                    .divider { border-top: 1px dashed #000; margin: 6px 0; }
                </style>
            </head>
            <body>
                <h3>${reportTitle}</h3>
                ${bodyHtml}
            </body>
            </html>
        `;
        await api.silentPrintHtml(html, receiptWidth);
    };

    const handleReportPrint = async () => {
        if (!dailyReportSummary) {
            await calculateDailyReport();
        }
        if (!selectedReportType) {
            if (showAlert) showAlert('Тайлан сонгоогүй байна.');
            return;
        }
        await printDailyReport();
    };

    const selectReceiptFromList = async (expenseG) => {
        if (!expenseG) return;
        const mt_id = expenseG.mt_id;
        setFoundMtId(mt_id);
        setReceiptHeader(expenseG);
        if (api && api.getExpenseRows) {
            await fetchReceiptDetails(mt_id);
        }
        setReceiptTaxData(null);
    };

    // Fetch receipt information when searchReceiptCashcode changes (for cashcode search)
    useEffect(() => {
        const fetchSearchReceiptByCashcode = async () => {
            if (!searchReceiptCashcode || !searchReceiptCashcode.trim() || !selectedCompany || !currentOperator) {
                setReceiptHeader(null);
                setReceiptDetails([]);
                setFoundMtId(null);
                return;
            }
            
            if (!api || (!api.getExpenseGListByCashcode && !api.getExpenseGByCashcode)) {
                if (showAlert) {
                    showAlert('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) {
                    setLoadingSearchReceipt(false);
                    if (showAlert) {
                        if (isNaN(cashcode)) {
                            showAlert('Cashcode буруу байна. Тоо оруулна уу.');
                        } else if (!b_id) {
                            showAlert('Байгууллагын мэдээлэл олдсонгүй.');
                        } else if (!opid) {
                            showAlert('Операторын мэдээлэл олдсонгүй.');
                        }
                    }
                    return;
                }
                
                const days = parseInt(searchReceiptDays) || 30;
                let sourceno = null;
                if (searchReceiptSourceno && searchReceiptSourceno.trim()) {
                    const parsedSourceno = parseInt(searchReceiptSourceno.trim(), 10);
                    if (!isNaN(parsedSourceno) && isFinite(parsedSourceno)) {
                        sourceno = parsedSourceno;
                    }
                }
                
                let listResult = null;
                if (api.getExpenseGListByCashcode) {
                    listResult = await api.getExpenseGListByCashcode(cashcode, b_id, opid, days, sourceno, 50);
                }
                
                if (listResult && listResult.success && Array.isArray(listResult.data)) {
                    const list = listResult.data;
                    setReceiptList(list);
                    
                    if (list.length > 0) {
                        await selectReceiptFromList(list[0]);
                    } else {
                        setReceiptHeader(null);
                        setReceiptDetails([]);
                        setFoundMtId(null);
                        if (showAlert) {
                            showAlert('Баримт олдсонгүй');
                        }
                    }
                } else {
                    const result = await api.getExpenseGByCashcode(cashcode, b_id, opid, days, sourceno);
                    
                    if (result.success && result.data) {
                        const expenseG = result.data;
                        setReceiptList([expenseG]);
                        await selectReceiptFromList(expenseG);
                    } else {
                        setReceiptHeader(null);
                        setReceiptDetails([]);
                        setFoundMtId(null);
                        setReceiptList([]);
                        if (showAlert && result && result.error) {
                            showAlert(`Баримт олдсонгүй: ${result.error}`);
                        }
                    }
                }
            } catch (error) {
                console.error('[fetchSearchReceiptByCashcode] Error:', error);
                setReceiptHeader(null);
                setReceiptList([]);
                setReceiptDetails([]);
                setFoundMtId(null);
                if (showAlert) {
                    showAlert(`Хайлтын алдаа: ${error.message || error.toString()}`);
                }
            } finally {
                setLoadingSearchReceipt(false);
            }
        };
        
        if (searchMode === 'CASHCODE' && isOpen) {
            const timeoutId = setTimeout(() => {
                fetchSearchReceiptByCashcode();
            }, 500);
            
            return () => clearTimeout(timeoutId);
        }
    }, [searchReceiptCashcode, searchReceiptSourceno, searchReceiptDays, selectedCompany, currentOperator, searchMode, api, isOpen]);
    
    // Fetch receipt information when searchReceiptId changes (for ID search)
    useEffect(() => {
        const fetchSearchReceiptInfo = async () => {
            if (!searchReceiptId || !searchReceiptId.trim() || !selectedCompany) {
                setReceiptHeader(null);
                setReceiptList([]);
                setReceiptDetails([]);
                return;
            }
            
            const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
            const isInspectorId = /^\d{33}$/.test(searchReceiptId.trim());
            if (!apiURL && !(isInspectorId && api && api.getExpenseGByInspector)) {
                setReceiptHeader(null);
                setReceiptList([]);
                setReceiptDetails([]);
                return;
            }
            
            setLoadingSearchReceipt(true);
            try {
                if (isInspectorId && api && api.getExpenseGByInspector) {
                    const bId = selectedCompany.b_id || selectedCompany.id;
                    const result = await api.getExpenseGByInspector(bId, searchReceiptId.trim());
                    if (result && result.success && result.data) {
                        const expenseG = result.data;
                        const mt_id = expenseG.mt_id || expenseG.mtId || null;
                        setReceiptHeader(expenseG);
                        setReceiptList([]);
                        setFoundMtId(mt_id);
                        if (mt_id) {
                            await fetchReceiptDetails(mt_id);
                        } else {
                            setReceiptDetails([]);
                        }
                        setReceiptTaxData(null);
                    } else {
                        setReceiptHeader(null);
                        setReceiptList([]);
                        setReceiptDetails([]);
                    }
                    return;
                }

                let baseUrl = apiURL.trim();
                if (baseUrl.endsWith('/')) {
                    baseUrl = baseUrl.slice(0, -1);
                }
                const finalApiURL = `${baseUrl}/rest/receipt/${searchReceiptId.trim()}`;
                
                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 (typeof window !== 'undefined' && typeof window.storeLastTaxReceiptResponse === 'function') {
                        window.storeLastTaxReceiptResponse({
                            source: 'receipt_get',
                            url: finalApiURL,
                            httpStatus: response.status,
                            httpStatusText: response.statusText,
                            receiptId: searchReceiptId.trim(),
                            ok: true,
                            body: responseData,
                            rawText: typeof responseData !== 'object' || responseData === null ? responseText : undefined
                        });
                    }
                    
                    if (responseData && typeof responseData === 'object') {
                        // Try to get mt_id from response or search by ID
                        const receiptId = responseData.id || searchReceiptId.trim();
                        // For now, we'll just show the tax system data
                        // In a real scenario, we might need to search the database by this ID
                        setReceiptHeader({ 
                            receiptId: receiptId,
                            date: responseData.date || responseData.receiptDate,
                            totalAmount: responseData.totalAmount || responseData.total,
                            fromTaxSystem: true,
                            data: responseData
                        });
                        setReceiptList([]);
                        setReceiptDetails(responseData.items || []);
                    }
                } else {
                    setReceiptHeader(null);
                    setReceiptList([]);
                    setReceiptDetails([]);
                }
            } catch (error) {
                console.error('[fetchSearchReceiptInfo] Error:', error);
                setReceiptHeader(null);
                setReceiptList([]);
                setReceiptDetails([]);
            } finally {
                setLoadingSearchReceipt(false);
            }
        };
        
        if (searchMode === 'ID' && isOpen) {
            const timeoutId = setTimeout(() => {
                fetchSearchReceiptInfo();
            }, 500);
            
            return () => clearTimeout(timeoutId);
        }
    }, [searchReceiptId, selectedCompany, searchMode, isOpen, api]);
    
    // Fetch receipt information when searchReceiptSourceno and searchReceiptOpid change
    useEffect(() => {
        const fetchSearchReceiptBySourceno = async () => {
            if (!searchReceiptSourceno || !searchReceiptSourceno.trim() || !searchReceiptOpid || !searchReceiptOpid.trim() || !selectedCompany || !currentOperator) {
                setReceiptHeader(null);
                setReceiptDetails([]);
                setFoundMtId(null);
                return;
            }
            
            if (!api || (!api.getExpenseGListBySourceno && !api.getExpenseGBySourceno)) {
                return;
            }
            
            setLoadingSearchReceipt(true);
            try {
                const sourceno = parseInt(searchReceiptSourceno.trim(), 10);
                const opid = parseInt(searchReceiptOpid.trim(), 10);
                const b_id = selectedCompany.b_id || selectedCompany.id;
                const days = parseInt(searchReceiptDays) || 30;
                
                if (isNaN(sourceno) || isNaN(opid) || !b_id) {
                    setLoadingSearchReceipt(false);
                    return;
                }
                
                let listResult = null;
                if (api.getExpenseGListBySourceno) {
                    listResult = await api.getExpenseGListBySourceno(sourceno, opid, b_id, days, 50);
                }
                
                if (listResult && listResult.success && Array.isArray(listResult.data)) {
                    const list = listResult.data;
                    setReceiptList(list);
                    
                    if (list.length > 0) {
                        await selectReceiptFromList(list[0]);
                    } else {
                        setReceiptHeader(null);
                        setReceiptDetails([]);
                        setFoundMtId(null);
                    }
                } else {
                    const result = await api.getExpenseGBySourceno(sourceno, opid, b_id, days);
                    
                    if (result.success && result.data) {
                        const expenseG = result.data;
                        setReceiptList([expenseG]);
                        await selectReceiptFromList(expenseG);
                    } else {
                        setReceiptHeader(null);
                        setReceiptDetails([]);
                        setFoundMtId(null);
                        setReceiptList([]);
                    }
                }
            } catch (error) {
                console.error('[fetchSearchReceiptBySourceno] Error:', error);
                setReceiptHeader(null);
                setReceiptList([]);
                setReceiptDetails([]);
                setFoundMtId(null);
            } finally {
                setLoadingSearchReceipt(false);
            }
        };
        
        if (searchMode === 'SOURCENO' && isOpen) {
            const timeoutId = setTimeout(() => {
                fetchSearchReceiptBySourceno();
            }, 500);
            
            return () => clearTimeout(timeoutId);
        }
    }, [searchReceiptSourceno, searchReceiptOpid, searchReceiptDays, selectedCompany, currentOperator, searchMode, api, isOpen]);

    // Fetch receipt details (rows)
    const fetchReceiptDetails = async (mt_id) => {
        if (!api || !api.getExpenseRows) {
            return;
        }
        
        setLoadingDetails(true);
        try {
            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;
                }
                setReceiptDetails(expenseRows);
            } else {
                setReceiptDetails([]);
            }
        } catch (error) {
            console.error('[fetchReceiptDetails] Error:', error);
            setReceiptDetails([]);
        } finally {
            setLoadingDetails(false);
        }
    };

    // Fetch receipt data from tax system (for lottery number, etc.)
    const fetchReceiptTaxData = async (mt_id) => {
        if (!mt_id || !selectedCompany) {
            return;
        }
        
        // Cart-д тухайн баримт ID тай бараа байвал татварын системд хайхгүй
        if (cart && Array.isArray(cart) && cart.length > 0) {
            const existingReceiptItem = cart.find(item => item.mt_id && Number(item.mt_id) === Number(mt_id));
            if (existingReceiptItem) {
                // Cart-д байгаа тул татварын системд хайхгүй
                setReceiptTaxData(null);
                return;
            }
        }
        
        const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
        if (!apiURL) {
            return;
        }
        
        try {
            let baseUrl = apiURL.trim();
            if (baseUrl.endsWith('/')) {
                baseUrl = baseUrl.slice(0, -1);
            }
            // Try to get receipt by mt_id from tax system
            // If mt_id is not the receipt ID in tax system, we might need to search differently
            // For now, try /rest/receipt/{mt_id} first
            const finalApiURL = `${baseUrl}/rest/receipt/${mt_id}`;
            
            const response = await fetch(finalApiURL, {
                method: 'GET',
                headers: { 'Accept': 'application/json' }
            });
            
            if (response.ok) {
                const responseText = await response.text();
                let responseData = null;
                try {
                    responseData = JSON.parse(responseText);
                } catch (e) {
                    responseData = responseText;
                }
                
                if (responseData && typeof responseData === 'object') {
                    setReceiptTaxData(responseData);
                    if (typeof window !== 'undefined' && typeof window.storeLastTaxReceiptResponse === 'function') {
                        window.storeLastTaxReceiptResponse({
                            source: 'receipt_get_mt',
                            url: finalApiURL,
                            httpStatus: response.status,
                            httpStatusText: response.statusText,
                            mtId: mt_id,
                            ok: true,
                            body: responseData
                        });
                    }
                }
            } else if (response.status === 404) {
                // 404 is normal if receipt hasn't been sent to tax system yet
                // Don't log this as an error, just set receiptTaxData to null
                setReceiptTaxData(null);
            }
        } catch (error) {
            // Only log non-network errors (404 is handled above)
            if (!error.message || !error.message.includes('404')) {
                console.error('[fetchReceiptTaxData] Error:', error);
            }
            // Don't show error to user, this is expected if receipt isn't in tax system yet
            setReceiptTaxData(null);
        }
    };

    // Add to cart
    const handleAddToCart = async () => {
        if (!foundMtId || receiptDetails.length === 0) {
            if (showAlert) showAlert('Баримтанд бараа олдсонгүй');
            return;
        }

        if (hasInspector) {
            if (showAlert) {
                showAlert('Inspector байгаа тул энэ баримтыг cart-д нэмэхгүй.');
            }
            return;
        }
        
        if (!operatorCanReturnTaxReceipt(currentOperator)) {
            if (showAlert) {
                showAlert('Татварын баримт буцаах эрх байхгүй. Админ оператор нэвтэрнэ үү.');
            }
            return;
        }
        
        if (!addToCart || typeof addToCart !== 'function') {
            if (showAlert) showAlert('Cart функц олдсонгүй');
            return;
        }
        
        // Шалгах: Cart-д тухайн баримт ID (mt_id) тай бараа байгаа эсэх
        if (cart && Array.isArray(cart) && cart.length > 0) {
            const existingReceiptItem = cart.find(item => item.mt_id && Number(item.mt_id) === Number(foundMtId));
            if (existingReceiptItem) {
                if (showAlert) {
                    showAlert(`Энэ баримтын бараа cart-д аль хэдийн байна. Дахин татварт илгээхгүй.`);
                }
                return;
            }
        }
        
        try {
            let addedCount = 0;
            for (const row of receiptDetails) {
                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,
                        originalMtId: foundMtId, // Нөхөн олгох баримтын анхны mt_id
                        isReturnReceipt: true // Нөхөн олгох баримт эсэхийг тэмдэглэх
                    };
                    
                    await addToCart(product);
                    addedCount++;
                }
            }
            
            if (addedCount > 0) {
                if (showAlert) showAlert(`${addedCount} бараа cart-д нэмэгдлээ`);
                onClose();
            } else {
                if (showAlert) showAlert('Cart-д бараа нэмэхэд алдаа гарлаа');
            }
        } catch (error) {
            console.error('Error loading receipt to cart:', error);
            if (showAlert) showAlert(`Алдаа: ${error.message || 'Cart-д нэмэхэд алдаа гарлаа'}`);
        }
    };

    if (!isOpen) return null;

    return (
        <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: 2000
        }} onClick={onClose}>
            <div style={{
                backgroundColor: 'white',
                padding: '20px',
                borderRadius: '8px',
                minWidth: '800px',
                maxWidth: '95%',
                maxHeight: '90vh',
                overflowY: 'auto'
            }} onClick={(e) => e.stopPropagation()}>
                <h3 style={{ marginTop: 0, marginBottom: '16px' }}>Баримт хайх</h3>
                
                {/* Search controls */}
                <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f8f9fa', borderRadius: '4px' }}>
                    <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'
                            }}
                        />
                    </div>

                    <div style={{ marginBottom: '12px', padding: '12px', border: '1px solid #dee2e6', borderRadius: '4px', background: '#ffffff' }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
                            <div style={{ fontWeight: 'bold' }}>Тайлан хэвлэх</div>
                            <div style={{ display: 'flex', gap: '8px' }}>
                                <button
                                    className="btn btn-primary"
                                    onClick={calculateDailyReport}
                                    disabled={dailyReportLoading || selectedReportType !== 'DAILY_CASHCODE'}
                                >
                                    {dailyReportLoading ? 'Тооцоолж байна...' : 'Тооцоолох'}
                                </button>
                                <button
                                    className="btn btn-secondary"
                                    onClick={handleReportPrint}
                                >
                                    Хэвлэх
                                </button>
                            </div>
                        </div>
                        <div style={{ marginBottom: '8px' }}>
                            <label style={{ display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
                                Тайлан сонгох:
                            </label>
                            <select
                                value={selectedReportType}
                                onChange={(e) => setSelectedReportType(e.target.value)}
                                style={{
                                    width: '100%',
                                    padding: '8px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    fontSize: '14px',
                                    boxSizing: 'border-box'
                                }}
                            >
                                {reportOptions.map(option => (
                                    <option key={option.value} value={option.value}>{option.label}</option>
                                ))}
                            </select>
                        </div>
                        {dailyReportError && (
                            <div style={{ color: '#e74c3c', fontSize: '12px', marginBottom: '6px' }}>{dailyReportError}</div>
                        )}
                        {dailyReportSummary && (
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: '8px' }}>
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d' }}>Cashcode</div>
                                    <div style={{ fontWeight: 'bold' }}>{dailyReportSummary.cashcode}</div>
                                </div>
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d' }}>Баримтын тоо</div>
                                    <div style={{ fontWeight: 'bold' }}>{dailyReportSummary.count}</div>
                                </div>
                                {selectedReportType === 'DAILY_PAYMENT' && (
                                    <>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Бэлэн</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalCash) : dailyReportSummary.totalCash}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Карт</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalBank) : dailyReportSummary.totalBank}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Бусад</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalOther) : dailyReportSummary.totalOther}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Нийт дүн</div>
                                            <div style={{ fontWeight: 'bold', color: '#2e7d32' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalAfterDiscount) : dailyReportSummary.totalAfterDiscount}
                                            </div>
                                        </div>
                                    </>
                                )}
                                {selectedReportType === 'DAILY_TAX' && (
                                    <>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>НӨАТ</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalVAT) : dailyReportSummary.totalVAT}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>НХАТ</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalCityTax) : dailyReportSummary.totalCityTax}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Нийт дүн</div>
                                            <div style={{ fontWeight: 'bold', color: '#2e7d32' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalAfterDiscount) : dailyReportSummary.totalAfterDiscount}
                                            </div>
                                        </div>
                                    </>
                                )}
                                {selectedReportType === 'DAILY_CASHCODE' && (
                                    <>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Нийт дүн</div>
                                            <div style={{ fontWeight: 'bold', color: '#2e7d32' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalAfterDiscount) : dailyReportSummary.totalAfterDiscount}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Хөнгөлөлтийн дүн</div>
                                            <div style={{ fontWeight: 'bold', color: '#d32f2f' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalDiscount) : dailyReportSummary.totalDiscount}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Хөнгөлөлт нэмсэн нийт дүн</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalBeforeDiscount) : dailyReportSummary.totalBeforeDiscount}
                                            </div>
                                        </div>
                                    </>
                                )}
                                {selectedReportType === 'SUMMARY' && (
                                    <>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Нийт дүн</div>
                                            <div style={{ fontWeight: 'bold', color: '#2e7d32' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalAfterDiscount) : dailyReportSummary.totalAfterDiscount}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Хөнгөлөлтийн дүн</div>
                                            <div style={{ fontWeight: 'bold', color: '#d32f2f' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalDiscount) : dailyReportSummary.totalDiscount}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Хөнгөлөлт нэмсэн нийт дүн</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalBeforeDiscount) : dailyReportSummary.totalBeforeDiscount}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>НӨАТ</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalVAT) : dailyReportSummary.totalVAT}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>НХАТ</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalCityTax) : dailyReportSummary.totalCityTax}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Бэлэн</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalCash) : dailyReportSummary.totalCash}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Карт</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalBank) : dailyReportSummary.totalBank}
                                            </div>
                                        </div>
                                        <div>
                                            <div style={{ fontSize: '11px', color: '#6c757d' }}>Бусад</div>
                                            <div style={{ fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(dailyReportSummary.totalOther) : dailyReportSummary.totalOther}
                                            </div>
                                        </div>
                                    </>
                                )}
                            </div>
                        )}
                    </div>
                    
                    <div style={{ marginBottom: '12px', display: 'flex', gap: '8px' }}>
                        <button
                            onClick={() => {
                                setSearchMode('ID');
                                setSearchReceiptId('');
                                setSearchReceiptCashcode('');
                                setSearchReceiptSourceno('');
                                setSearchReceiptOpid('');
                                setReceiptHeader(null);
                                setReceiptDetails([]);
                            }}
                            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('');
                                setReceiptHeader(null);
                                setReceiptDetails([]);
                            }}
                            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('');
                                setReceiptHeader(null);
                                setReceiptDetails([]);
                            }}
                            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>
                    </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' ? (
                        <>
                            <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>
                        </>
                    )}
                </div>

                {/* Loading indicator */}
                {loadingSearchReceipt && (
                    <div style={{ textAlign: 'center', padding: '20px', color: '#6c757d' }}>
                        Баримтын мэдээлэл хайж байна...
                    </div>
                )}

                {/* Receipt List (multiple results) */}
                {!loadingSearchReceipt && receiptList && receiptList.length > 1 && (
                    <div style={{ marginBottom: '16px' }}>
                        <h4 style={{ marginBottom: '12px', color: '#2e7d32' }}>Баримтын жагсаалт ({receiptList.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: '8px', textAlign: 'left', borderBottom: '2px solid #dee2e6' }}>MT ID</th>
                                        <th style={{ padding: '8px', textAlign: 'left', borderBottom: '2px solid #dee2e6' }}>Баримт №</th>
                                        <th style={{ padding: '8px', textAlign: 'left', borderBottom: '2px solid #dee2e6' }}>Огноо</th>
                                        <th style={{ padding: '8px', textAlign: 'left', borderBottom: '2px solid #dee2e6' }}>Дүн</th>
                                        <th style={{ padding: '8px', textAlign: 'left', borderBottom: '2px solid #dee2e6' }}>Inspector</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {receiptList.map((row) => (
                                        <tr
                                            key={row.mt_id}
                                            onClick={() => selectReceiptFromList(row)}
                                            style={{
                                                borderBottom: '1px solid #dee2e6',
                                                cursor: 'pointer',
                                                backgroundColor: row.mt_id === foundMtId ? '#e8f5e9' : 'transparent'
                                            }}
                                        >
                                            <td style={{ padding: '8px' }}>{row.mt_id}</td>
                                            <td style={{ padding: '8px' }}>{row.sourceno || ''}</td>
                                            <td style={{ padding: '8px' }}>{formatDateTimeIso(row.adate)}</td>
                                            <td style={{ padding: '8px' }}>
                                                {formatCurrency ? formatCurrency(row.total || row.totalAmount || 0) : (row.total || row.totalAmount || 0)}
                                            </td>
                                            <td style={{ padding: '8px' }}>{row.inspector || ''}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {/* Receipt Header Grid */}
                {receiptHeader && !loadingSearchReceipt && (
                    <div style={{ marginBottom: '16px' }}>
                        <h4 style={{ marginBottom: '12px', color: '#2e7d32' }}>Баримтын Header</h4>
                        <div style={{
                            display: 'grid',
                            gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
                            gap: '8px',
                            padding: '12px',
                            backgroundColor: '#f8f9fa',
                            borderRadius: '4px',
                            border: '1px solid #dee2e6'
                        }}>
                            {receiptHeader.mt_id && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>MT ID:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold' }}>{receiptHeader.mt_id}</div>
                                </div>
                            )}
                            {receiptHeader.cashcode && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Cashcode:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold' }}>{receiptHeader.cashcode}</div>
                                </div>
                            )}
                            {receiptHeader.sourceno && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Sourceno:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold' }}>{receiptHeader.sourceno}</div>
                                </div>
                            )}
                            {receiptHeader.opid && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Opid:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold' }}>{receiptHeader.opid}</div>
                                </div>
                            )}
                            {receiptHeader.adate && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Огноо:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold' }}>
                                        {formatDateTimeIso(receiptHeader.adate)}
                                    </div>
                                </div>
                            )}
                            {receiptHeader.totalAmount && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Нийт дүн:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold', color: '#2e7d32' }}>
                                        {formatCurrency ? formatCurrency(receiptHeader.totalAmount) : receiptHeader.totalAmount}
                                    </div>
                                </div>
                            )}
                            {receiptHeader.total && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Нийт дүн:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold', color: '#2e7d32' }}>
                                        {formatCurrency ? formatCurrency(receiptHeader.total) : receiptHeader.total}
                                    </div>
                                </div>
                            )}
                            {receiptHeader.b_id && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>B ID:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold' }}>{receiptHeader.b_id}</div>
                                </div>
                            )}
                            {receiptHeader.inspector && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Inspector:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold' }}>{receiptHeader.inspector}</div>
                                </div>
                            )}
                            {receiptTaxData && (receiptTaxData.lottery || receiptTaxData.lotteryNumber || receiptTaxData.lottery_id || (receiptTaxData.receipts && receiptTaxData.receipts[0] && (receiptTaxData.receipts[0].lottery || receiptTaxData.receipts[0].lotteryNumber || receiptTaxData.receipts[0].lottery_id))) && (
                                <div>
                                    <div style={{ fontSize: '11px', color: '#6c757d', marginBottom: '2px' }}>Сугалааны дугаар:</div>
                                    <div style={{ fontSize: '14px', fontWeight: 'bold', color: '#d32f2f' }}>
                                        {receiptTaxData.lottery || receiptTaxData.lotteryNumber || receiptTaxData.lottery_id || (receiptTaxData.receipts && receiptTaxData.receipts[0] && (receiptTaxData.receipts[0].lottery || receiptTaxData.receipts[0].lotteryNumber || receiptTaxData.receipts[0].lottery_id)) || 'N/A'}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {/* Receipt Details Grid */}
                {receiptDetails.length > 0 && !loadingDetails && (
                    <div style={{ marginBottom: '16px' }}>
                        <h4 style={{ marginBottom: '12px', color: '#2e7d32' }}>Баримтын Detail ({receiptDetails.length} мөр)</h4>
                        <div style={{
                            maxHeight: '400px',
                            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: '8px', textAlign: 'left', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>№</th>
                                        <th style={{ padding: '8px', textAlign: 'left', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Бараа</th>
                                        <th style={{ padding: '8px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Тоо</th>
                                        <th style={{ padding: '8px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Үнэ</th>
                                        <th style={{ padding: '8px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Хөнгөлөлт</th>
                                        <th style={{ padding: '8px', textAlign: 'right', borderBottom: '2px solid #dee2e6', fontWeight: 'bold' }}>Дүн</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {receiptDetails.map((row, index) => (
                                        <tr key={row.zid || index} style={{ borderBottom: '1px solid #dee2e6' }}>
                                            <td style={{ padding: '8px' }}>{index + 1}</td>
                                            <td style={{ padding: '8px' }}>{row.m_name || row.name || 'Бүтээгдэхүүн'}</td>
                                            <td style={{ padding: '8px', textAlign: 'right' }}>{getReceiptItemQty(row)}</td>
                                            <td style={{ padding: '8px', textAlign: 'right' }}>
                                                {formatCurrency ? formatCurrency(getReceiptItemPrice(row)) : getReceiptItemPrice(row)}
                                            </td>
                                            <td style={{ padding: '8px', textAlign: 'right' }}>
                                                {formatCurrency ? formatCurrency(row.discount || 0) : (row.discount || 0)}
                                            </td>
                                            <td style={{ padding: '8px', textAlign: 'right', fontWeight: 'bold' }}>
                                                {formatCurrency ? formatCurrency(getReceiptItemAmount(row)) : getReceiptItemAmount(row)}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {/* Loading details */}
                {loadingDetails && (
                    <div style={{ textAlign: 'center', padding: '20px', color: '#6c757d' }}>
                        Баримтын detail татаж байна...
                    </div>
                )}

                {/* No results */}
                {!loadingSearchReceipt && !receiptHeader && ((searchMode === 'ID' && searchReceiptId && searchReceiptId.trim()) || 
                  (searchMode === 'CASHCODE' && searchReceiptCashcode && searchReceiptCashcode.trim()) ||
                  (searchMode === 'SOURCENO' && searchReceiptSourceno && searchReceiptSourceno.trim() && searchReceiptOpid && searchReceiptOpid.trim())) && (
                    <div style={{ textAlign: 'center', padding: '20px', color: '#856404', backgroundColor: '#fff3cd', borderRadius: '4px' }}>
                        Баримт олдсонгүй
                    </div>
                )}

                {/* Action buttons */}
                <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '16px', flexWrap: 'wrap' }}>
                    {foundMtId && receiptDetails.length > 0 && (
                        <>
                            <button
                                onClick={handleAddToCart}
                                disabled={hasInspector || !operatorCanReturnTaxReceipt(currentOperator)}
                                style={{
                                    padding: '8px 16px',
                                    border: 'none',
                                    borderRadius: '4px',
                                    backgroundColor: (hasInspector || !operatorCanReturnTaxReceipt(currentOperator)) ? '#6c757d' : '#28a745',
                                    color: 'white',
                                    cursor: (hasInspector || !operatorCanReturnTaxReceipt(currentOperator)) ? 'not-allowed' : 'pointer',
                                    fontSize: '14px',
                                    fontWeight: 'bold',
                                    opacity: (hasInspector || !operatorCanReturnTaxReceipt(currentOperator)) ? 0.6 : 1
                                }}
                            >
                                Cart-д нэмэх
                            </button>
                            {onRefund && operatorCanReturnTaxReceipt(currentOperator) && (
                                <button
                                    onClick={async () => {
                                        const refundReceiptId = getRefundReceiptId();
                                        if (!refundReceiptId) {
                                            if (showAlert) showAlert('Буцаах баримтын ID олдсонгүй');
                                            return;
                                        }
                                        const refundDate = receiptHeader?.adate || receiptHeader?.date || receiptTaxData?.date || null;
                                        await onRefund(String(refundReceiptId), refundDate ? formatDateTimeIso(refundDate) : null);
                                    }}
                                    style={{
                                        padding: '8px 16px',
                                        border: 'none',
                                        borderRadius: '4px',
                                        backgroundColor: '#e74c3c',
                                        color: 'white',
                                        cursor: 'pointer',
                                        fontSize: '14px',
                                        fontWeight: 'bold'
                                    }}
                                >
                                    Буцаалт хийх
                                </button>
                            )}
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '8px' }}>
                                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                    <label style={{ fontSize: '14px', fontWeight: 'bold', minWidth: '120px' }}>
                                        Утасны дугаар:
                                    </label>
                                    <input
                                        type="text"
                                        value={phoneNumber}
                                        onChange={(e) => setPhoneNumber(e.target.value)}
                                        placeholder="99112233"
                                        style={{
                                            padding: '6px 12px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            flex: 1,
                                            maxWidth: '200px'
                                        }}
                                    />
                                    <button
                                        onClick={async () => {
                                            if (!phoneNumber || !phoneNumber.trim()) {
                                                if (showAlert) showAlert('Утасны дугаар оруулна уу');
                                                return;
                                            }
                                            
                                            if (!testMessage || !testMessage.trim()) {
                                                if (showAlert) showAlert('Мессеж оруулна уу');
                                                return;
                                            }
                                            
                                            if (!api || !api.sendSMS) {
                                                if (showAlert) showAlert('SMS илгээх функц олдсонгүй');
                                                return;
                                            }
                                            
                                            setIsSendingTestSMS(true);
                                            try {
                                                const smsResult = await api.sendSMS(phoneNumber.trim(), testMessage.trim());
                                                if (smsResult && smsResult.success) {
                                                    if (showAlert) showAlert('Тест мессеж амжилттай илгээгдлээ');
                                                    console.log('Test SMS sent successfully to:', phoneNumber);
                                                } else {
                                                    if (showAlert) showAlert(`Алдаа: ${smsResult?.error || 'SMS илгээхэд алдаа гарлаа'}`);
                                                    console.warn('Failed to send test SMS:', smsResult?.error || 'Unknown error');
                                                }
                                            } catch (smsError) {
                                                console.error('Error sending test SMS:', smsError);
                                                if (showAlert) showAlert(`Алдаа: ${smsError.message || 'SMS илгээхэд алдаа гарлаа'}`);
                                            } finally {
                                                setIsSendingTestSMS(false);
                                            }
                                        }}
                                        disabled={isSendingTestSMS || !phoneNumber || !phoneNumber.trim() || !testMessage || !testMessage.trim()}
                                        style={{
                                            padding: '6px 12px',
                                            border: 'none',
                                            borderRadius: '4px',
                                            backgroundColor: (isSendingTestSMS || !phoneNumber || !phoneNumber.trim() || !testMessage || !testMessage.trim()) ? '#6c757d' : '#17a2b8',
                                            color: 'white',
                                            cursor: (isSendingTestSMS || !phoneNumber || !phoneNumber.trim() || !testMessage || !testMessage.trim()) ? 'not-allowed' : 'pointer',
                                            fontSize: '13px',
                                            fontWeight: 'bold',
                                            opacity: (isSendingTestSMS || !phoneNumber || !phoneNumber.trim() || !testMessage || !testMessage.trim()) ? 0.6 : 1,
                                            whiteSpace: 'nowrap'
                                        }}
                                    >
                                        {isSendingTestSMS ? 'Илгээж байна...' : 'Турших'}
                                    </button>
                                </div>
                                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                    <label style={{ fontSize: '14px', fontWeight: 'bold', minWidth: '120px' }}>
                                        Тест мессеж:
                                    </label>
                                    <input
                                        type="text"
                                        value={testMessage}
                                        onChange={(e) => setTestMessage(e.target.value)}
                                        placeholder="Тест мессеж оруулна уу"
                                        style={{
                                            padding: '6px 12px',
                                            border: '1px solid #ced4da',
                                            borderRadius: '4px',
                                            fontSize: '14px',
                                            flex: 1,
                                            maxWidth: '400px'
                                        }}
                                    />
                                </div>
                                <button
                                    onClick={async () => {
                                        if (!operatorCanReturnTaxReceipt(currentOperator)) {
                                            if (showAlert) showAlert('Татварын баримт буцаах эрх байхгүй. Админ оператор нэвтэрнэ үү.');
                                            return;
                                        }
                                        if (!foundMtId) {
                                            if (showAlert) showAlert('Баримт олдсонгүй');
                                            return;
                                        }
                                        
                                        if (!selectedCompany) {
                                            if (showAlert) showAlert('Байгууллагын мэдээлэл олдсонгүй');
                                            return;
                                        }
                                        
                                        const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
                                        if (!apiURL) {
                                            if (showAlert) showAlert('Татварын системийн URL тохируулаагүй байна');
                                            return;
                                        }
                                        
                                        setIsResendingToTax(true);
                                        try {
                                            // Try to resend receipt to tax system by mt_id
                                            // For now, use sendToTaxSystem which sends all unsent receipts
                                            // In the future, we might need a specific endpoint like /rest/receipt/{mt_id}/send
                                            const result = await api.sendToTaxSystem(apiURL);
                                            
                                            if (result.success) {
                                                if (showAlert) showAlert(result.message || 'Татварт амжилттай илгээгдлээ');
                                                // Refresh receipt tax data to get updated lottery number
                                                await fetchReceiptTaxData(foundMtId);
                                                
                                                // SMS илгээх - refresh хийсний дараа шинэ receiptTaxData-г авах
                                                if (phoneNumber && phoneNumber.trim() && api && api.sendSMS) {
                                                    try {
                                                        // Refresh хийсний дараа бага зэрэг хүлээгээд receiptTaxData state-г ашиглах
                                                        await new Promise(resolve => setTimeout(resolve, 500));
                                                        
                                                        // Receipt tax data-аас сугалааны дугаарыг авах (state-аас)
                                                        const lotteryNumber = receiptTaxData?.lottery || receiptTaxData?.lotteryNumber || receiptTaxData?.lottery_id || 
                                                                             (receiptTaxData?.receipts && receiptTaxData.receipts[0] && 
                                                                              (receiptTaxData.receipts[0].lottery || receiptTaxData.receipts[0].lotteryNumber || receiptTaxData.receipts[0].lottery_id)) || 
                                                                             null;
                                                        
                                                        if (lotteryNumber) {
                                                            const smsMessage = `Нөхөн баримт: Сугалааны дугаар: ${lotteryNumber}`;
                                                            const smsResult = await api.sendSMS(phoneNumber.trim(), smsMessage);
                                                            if (smsResult && smsResult.success) {
                                                                console.log('SMS sent successfully to:', phoneNumber);
                                                            } else {
                                                                console.warn('Failed to send SMS:', smsResult?.error || 'Unknown error');
                                                            }
                                                        } else {
                                                            console.log('Lottery number not found, skipping SMS');
                                                        }
                                                    } catch (smsError) {
                                                        console.error('Error sending SMS:', smsError);
                                                        // SMS илгээхэд алдаа гарсан ч буцаалт амжилттай гэж үзнэ
                                                    }
                                                }
                                            } else {
                                                if (showAlert) showAlert(`Алдаа: ${result.error || 'Татварт илгээхэд алдаа гарлаа'}`);
                                            }
                                        } catch (error) {
                                            console.error('Error resending to tax system:', error);
                                            if (showAlert) showAlert(`Алдаа: ${error.message || 'Татварт илгээхэд алдаа гарлаа'}`);
                                        } finally {
                                            setIsResendingToTax(false);
                                        }
                                    }}
                                    disabled={isResendingToTax || !operatorCanReturnTaxReceipt(currentOperator)}
                                    style={{
                                        padding: '8px 16px',
                                        border: 'none',
                                        borderRadius: '4px',
                                        backgroundColor: (isResendingToTax || !operatorCanReturnTaxReceipt(currentOperator)) ? '#6c757d' : '#ff9800',
                                        color: 'white',
                                        cursor: (isResendingToTax || !operatorCanReturnTaxReceipt(currentOperator)) ? 'not-allowed' : 'pointer',
                                        fontSize: '14px',
                                        fontWeight: 'bold',
                                        opacity: (isResendingToTax || !operatorCanReturnTaxReceipt(currentOperator)) ? 0.6 : 1
                                    }}
                                >
                                    {isResendingToTax ? 'Илгээж байна...' : 'Татварт нөхөн илгээх'}
                                </button>
                            </div>
                        </>
                    )}
                    <button
                        onClick={onClose}
                        style={{
                            padding: '8px 16px',
                            border: '1px solid #ced4da',
                            borderRadius: '4px',
                            backgroundColor: 'white',
                            cursor: 'pointer',
                            fontSize: '14px'
                        }}
                    >
                        Хаах
                    </button>
                </div>
            </div>
        </div>
    );
}

// Make available globally for browser
if (typeof window !== 'undefined') {
    window.ReceiptSearchModal = ReceiptSearchModal;
}

