// formatCurrency should be loaded before this file
const _fmtCurPayment = typeof window !== 'undefined' ? window.formatCurrency : (typeof require !== 'undefined' ? require('../utils/formatCurrency.js').formatCurrency : null);
const formatCurrency = _fmtCurPayment || ((v) => (v != null ? Number(v).toFixed(2) : '0.00'));
const { useEffect, useRef } = React;
const api = typeof window !== 'undefined' && window.api ? window.api : null;

function PaymentModal({ 
    isOpen, 
    onClose, 
    onConfirm,
    calculateTotal,
    calculateVATTotal,
    calculateCityTaxTotal,
    calculateGrandTotal,
    showAlert,
    showConfirm,
    selectedCompany,
    currentOperator,
    currentMtId,
    createNewTransactionHeader,
    f10Pressed = false // F10 товч даралт
}) {
    const [documentType, setDocumentType] = React.useState('B2C'); // 'B2C' or 'B2B'
    const [paymentMethod, setPaymentMethod] = React.useState('CASH'); // 'CASH', 'PAYMENT_CARD', or 'QPAY'
    const [registrationNumber, setRegistrationNumber] = React.useState(''); // B2B баримтын регистерийн дугаар
    const [companyInfo, setCompanyInfo] = React.useState(null); // Байгууллагын мэдээлэл
    const [selectedBank, setSelectedBank] = React.useState(null); // QPay-д сонгогдсон банк
    const [paidAmount, setPaidAmount] = React.useState(''); // Бэлэн мөнгөөр төлөхөд төлсөн дүн
    const [qpayAmount, setQpayAmount] = React.useState(''); // QPay төлбөрийн дүн
    const [isCreatingQpayInvoice, setIsCreatingQpayInvoice] = React.useState(false);
    const [qpayInvoiceResult, setQpayInvoiceResult] = React.useState(null);
    const [qpayQrImage, setQpayQrImage] = React.useState('');
    const [qpayQrText, setQpayQrText] = React.useState('');
    const [isQPayWindowOpen, setIsQPayWindowOpen] = React.useState(false);
    const [qpayAccessToken, setQpayAccessToken] = React.useState(null);
    const [qpayInvoiceId, setQpayInvoiceId] = React.useState(null);
    const [qpayStatusMessage, setQpayStatusMessage] = React.useState('');
    const [qpayPollConfig, setQpayPollConfig] = React.useState({ sandbox: false, apiUrl: '' });
    const paymentButtonRef = useRef(null); // Төлбөр төлөх товчны ref
    const paidAmountInputRef = useRef(null); // Paid amount input ref
    const regNoInputRef = useRef(null); // Registration number input ref
    
    const handleMissingMerchantTin = (proceedAsB2C) => {
        if (documentType !== 'B2B') return false;
        if (!registrationNumber || !registrationNumber.trim()) return false;
        if (companyInfo && companyInfo.customerTin) return false;
        const message = 'merchantTin байхгүй эсвэл татварын системтэй холбогдохгүй байна.\n\nХувь хүнээр авах уу?\n(Үгүй бол дахин оролдоно уу)';
        if (showConfirm && typeof showConfirm === 'function') {
            showConfirm(message, proceedAsB2C);
        } else if (showAlert && typeof showAlert === 'function') {
            showAlert(message);
        }
        return true;
    };
    
    // Монголын банкуудын жагсаалт
    const banks = [
        { code: '040000', name: 'ХААН банк', icon: '🏦' },
        { code: '150000', name: 'Голомт банк', icon: '🏛️' },
        { code: '170000', name: 'Төрийн банк', icon: '🏢' },
        { code: '050000', name: 'Төв банк', icon: '🏪' },
        { code: '060000', name: 'Худалдаа хөгжлийн банк', icon: '🏬' },
        { code: '190000', name: 'Хас банк', icon: '🏗️' },
        { code: '200000', name: 'Капитал банк', icon: '🏭' },
        { code: '210000', name: 'БОДБ', icon: '🏨' }
    ];

    // Байгууллагын мэдээлэл хайх функц
    const handleSearchCompany = async () => {
        if (!registrationNumber || !registrationNumber.trim() || documentType !== 'B2B') {
            setCompanyInfo(null);
            return;
        }

        const regNoTrimmed = registrationNumber.trim();
        setCompanyInfo({ loading: true });

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

            // Step 1: regNo-оос TIN авах
            const taxInfoBaseUrl = ((selectedCompany?.taxUrl || 'https://api.ebarimt.mn') + '').replace(/\/+$/, '');
            const tinInfoUrl = `${taxInfoBaseUrl}/api/info/check/getTinInfo?regNo=${encodeURIComponent(regNoTrimmed)}`;
            const tinInfoResponse = await fetch(tinInfoUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });

            if (tinInfoResponse.ok) {
                const tinInfoData = await tinInfoResponse.json();
                if (tinInfoData.status === 200 && tinInfoData.data) {
                    const tin = tinInfoData.data.toString();

                    // Step 2: TIN-аас байгууллагын мэдээлэл авах
                    const companyInfoUrl = `${taxInfoBaseUrl}/api/info/check/getInfo?tin=${encodeURIComponent(tin)}`;
                    const companyInfoResponse = await fetch(companyInfoUrl, {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json'
                        }
                    });

                    if (companyInfoResponse.ok) {
                        const companyInfoData = await companyInfoResponse.json();
                        if (companyInfoData.status === 200 && companyInfoData.data && companyInfoData.data.found) {
                            const updatedInfo = {
                                companyName: companyInfoData.data.name || '',
                                customerTin: tin,
                                regNo: regNoTrimmed,
                                vatPayer: companyInfoData.data.vatPayer || false,
                                cityPayer: companyInfoData.data.cityPayer || false,
                                success: true,
                                loading: false
                            };
                            setCompanyInfo(updatedInfo);
                            if (api && api.updateClientRegNoAndCompanyInfo) {
                                try {
                                    await api.updateClientRegNoAndCompanyInfo(null, {
                                        regNo: regNoTrimmed,
                                        companyName: updatedInfo.companyName,
                                        customerTin: updatedInfo.customerTin,
                                        vatPayer: updatedInfo.vatPayer,
                                        cityPayer: updatedInfo.cityPayer
                                    });
                                } catch (updateError) {
                                    console.error('Error updating local company info from tax system:', updateError);
                                }
                            }
                        } else {
                            setCompanyInfo({
                                companyName: 'Олдсонгүй',
                                regNo: regNoTrimmed,
                                success: false,
                                loading: false,
                                error: companyInfoData.msg || 'Байгууллагын мэдээлэл олдсонгүй'
                            });
                        }
                    } else {
                        setCompanyInfo({
                            companyName: 'Олдсонгүй',
                            regNo: regNoTrimmed,
                            success: false,
                            loading: false,
                            error: `HTTP ${companyInfoResponse.status} алдаа`
                        });
                    }
                } else {
                    setCompanyInfo({
                        companyName: 'Олдсонгүй',
                        regNo: regNoTrimmed,
                        success: false,
                        loading: false,
                        error: tinInfoData.msg || 'TIN олдсонгүй'
                    });
                }
            } else {
                setCompanyInfo({
                    companyName: 'Олдсонгүй',
                    regNo: regNoTrimmed,
                    success: false,
                    loading: false,
                    error: `HTTP ${tinInfoResponse.status} алдаа`
                });
            }
        } catch (error) {
            console.error('Error fetching company info:', error);
            setCompanyInfo({
                companyName: 'Алдаа гарлаа',
                regNo: regNoTrimmed,
                success: false,
                loading: false,
                error: error.message || 'Алдаа гарлаа'
            });
        }
    };
    
    // Төлбөр хийх цонх нээгдэхэд paid amount input руу focus хийх (cash payment бол)
    // F10 дарахад regNoInput select хийх тул f10Pressed байвал энэ focus логикийг алгасах
    useEffect(() => {
        if (isOpen) {
            // F10 дарахад regNoInput select хийх тул энд focus хийхгүй
            if (f10Pressed) {
                return;
            }
            
            // Төлөх дүнг default-оор оруулах
            const grandTotal = calculateGrandTotal();
            if (paymentMethod === 'CASH') {
                setPaidAmount(grandTotal.toFixed(2));
            }
            if (paymentMethod === 'QPAY') {
                setQpayAmount(grandTotal.toFixed(2));
            }
            
            // Бага зэрэг хүлээгээд focus хийх (modal render болох хүртэл)
            const timer = setTimeout(() => {
                try {
                    if (paymentMethod === 'CASH' && paidAmountInputRef.current) {
                        paidAmountInputRef.current.focus();
                        paidAmountInputRef.current.select();
                    } else if (paymentButtonRef.current) {
                        paymentButtonRef.current.focus();
                    }
                } catch (err) {
                    console.error('Error focusing payment input:', err);
                }
            }, 100);
            
            return () => clearTimeout(timer);
        } else {
            // Modal хаагдах үед бүх мэдээллийг reset хийх (шинэ баримт үүсгэхэд)
            setPaidAmount('');
            setRegistrationNumber(''); // B2B худалдан авагч байгууллагын регистерийн дугаар
            setCompanyInfo(null); // Байгууллагын мэдээлэл
            setDocumentType('B2C'); // B2C руу буцаах
            setSelectedBank(null); // QPay банк сонголт
            setQpayAmount('');
            setQpayInvoiceResult(null);
            setQpayQrImage('');
            setQpayQrText('');
            setIsQPayWindowOpen(false);
            setQpayAccessToken(null);
            setQpayInvoiceId(null);
            setQpayStatusMessage('');
            setQpayPollConfig({ sandbox: false, apiUrl: '' });
        }
    }, [isOpen, paymentMethod, calculateGrandTotal, f10Pressed]);
    
    // Payment method-г CASH руу солиход paid amount input руу focus хийх
    useEffect(() => {
        if (isOpen && paymentMethod === 'CASH' && !f10Pressed) {
            // Төлөх дүнг default-оор оруулах
            const grandTotal = calculateGrandTotal();
            setPaidAmount(grandTotal.toFixed(2));
            
            const timer = setTimeout(() => {
                try {
                    if (paidAmountInputRef.current) {
                        paidAmountInputRef.current.focus();
                        paidAmountInputRef.current.select();
                    }
                } catch (err) {
                    console.error('Error focusing paid amount input:', err);
                }
            }, 50);
            
            return () => clearTimeout(timer);
        } else if (isOpen && paymentMethod !== 'CASH') {
            // CASH биш бол paid amount-г цэвэрлэх
            setPaidAmount('');
        }
    }, [paymentMethod, isOpen, calculateGrandTotal, f10Pressed]);

    useEffect(() => {
        if (isOpen && paymentMethod === 'QPAY') {
            const grandTotal = calculateGrandTotal();
            if (!qpayAmount) {
                setQpayAmount(grandTotal.toFixed(2));
            }
        }
    }, [paymentMethod, isOpen, calculateGrandTotal, qpayAmount]);

    const submitQPayPayment = () => {
        const grandTotal = calculateGrandTotal();
        const paid = paymentMethod === 'CASH' ? (parseFloat(paidAmount) || 0) : grandTotal;
        const change = paymentMethod === 'CASH' ? Math.max(0, paid - grandTotal) : 0;
        
        const proceedAsB2C = () => onConfirm({
            documentType: 'B2C',
            paymentMethod,
            registrationNumber: null,
            companyName: null,
            customerName: null,
            customerTin: null,
            vatPayer: null,
            cityPayer: null,
            selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
            qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
            qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
            qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
            paidAmount: paymentMethod === 'CASH' ? paid : null,
            change: paymentMethod === 'CASH' ? change : null
        });
        if (handleMissingMerchantTin(proceedAsB2C)) return;
        onConfirm({ 
            documentType, 
            paymentMethod, 
            registrationNumber: documentType === 'B2B' ? registrationNumber : null,
            companyName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
            customerName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
            customerTin: documentType === 'B2B' && companyInfo && companyInfo.customerTin ? companyInfo.customerTin : null,
            vatPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.vatPayer : null,
            cityPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.cityPayer : null,
            selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
            qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
            qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
            qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
            paidAmount: paymentMethod === 'CASH' ? paid : null,
            change: paymentMethod === 'CASH' ? change : null
        });
    };

    const handleCreateQPayInvoice = async () => {
        if (!api || !api.getQPayToken || !api.createQPayInvoice) {
            if (showAlert) showAlert('QPay API функц олдсонгүй');
            return;
        }
        if (!selectedCompany) {
            if (showAlert) showAlert('Байгууллагын мэдээлэл олдсонгүй');
            return;
        }
        if (!selectedBank) {
            if (showAlert) showAlert('Банк сонгоно уу');
            return;
        }
        const amountValue = parseFloat(qpayAmount);
        if (!amountValue || amountValue <= 0) {
            if (showAlert) showAlert('Төлбөрийн дүн оруулна уу');
            return;
        }
        const invoiceCode = (selectedCompany.qpayInvoiceCode || selectedCompany.qpay_invoice_code || 'BANK_TRANSFER').trim() || 'BANK_TRANSFER';
        let effectiveMtId = currentMtId;
        if (!effectiveMtId && createNewTransactionHeader) {
            try {
                const headerResult = await createNewTransactionHeader(currentOperator, selectedCompany);
                effectiveMtId = headerResult?.mt_id || headerResult?.MT_ID || null;
            } catch (headerErr) {
                console.error('Error creating transaction header for QPay invoice:', headerErr);
            }
        }
        const receiverCode = selectedCompany.qpayInvoiceReceiverCode || selectedCompany.qpay_invoice_receiver_code;
        let branchCode = null;
        if (api && api.getCashCode) {
            try {
                const posBId = selectedCompany?.b_id ?? null;
                const posDepId = currentOperator?.dep_id != null && currentOperator?.dep_id !== ''
                    ? currentOperator.dep_id
                    : (currentOperator?.dep_code ?? null);
                const cashcodeResult = await api.getCashCode(posBId, posDepId);
                if (cashcodeResult && cashcodeResult.success) {
                    const cashcodeValue = cashcodeResult.data !== undefined && cashcodeResult.data !== null ? cashcodeResult.data : '';
                    branchCode = String(cashcodeValue);
                }
            } catch (cashErr) {
                console.error('Error getting cashcode for QPay branch_code:', cashErr);
            }
        }
        const callbackUrl = selectedCompany.qpayCallbackUrl || selectedCompany.qpay_callback_url;
        const qpayClientId = selectedCompany.qpayClientId || selectedCompany.qpay_client_id;
        const qpayClientSecret = selectedCompany.qpayClientSecret || selectedCompany.qpay_client_secret;
        const qpaySandboxFlag = selectedCompany.qpaySandbox ?? selectedCompany.qpay_sandbox ?? selectedCompany.qpay_is_sandbox ?? false;
        const qpayApiUrl = selectedCompany.qpayApiUrl || selectedCompany.qpay_api_url || '';
        const useSimpleInvoice = !!(selectedCompany.qpaySimpleInvoice || selectedCompany.qpay_simple_invoice);

        if (!qpayClientId || !qpayClientSecret) {
            if (showAlert) showAlert('QPay Client ID/Secret тохируулаагүй байна');
            return;
        }
        if (!invoiceCode || !receiverCode || !branchCode || !callbackUrl || !effectiveMtId) {
            if (showAlert) showAlert('QPay тохиргоо дутуу байна (invoice_code/receiver_code/cashcode/callback/mt_id)');
            return;
        }

        setIsCreatingQpayInvoice(true);
        try {
            const tokenResult = await api.getQPayToken(qpayClientId, qpayClientSecret, !!qpaySandboxFlag, qpayApiUrl);
            if (!tokenResult.success) {
                const errorText = tokenResult.error || 'QPay токен авахад алдаа гарлаа';
                if (showAlert) {
                    if (typeof errorText === 'string' && errorText.includes('NO_CREDENDIALS')) {
                        showAlert('QPay Client ID/Secret эсвэл API URL буруу байна. Settings -> QPay хэсгээ шалгана уу.');
                    } else {
                        showAlert(errorText);
                    }
                }
                return;
            }
            const qpayToken = tokenResult.data?.access_token || tokenResult.data?.token || tokenResult.data?.accessToken;
            if (!qpayToken) {
                if (showAlert) showAlert('QPay токен олдсонгүй');
                return;
            }

            const invoiceData = useSimpleInvoice ? {
                invoice_code: invoiceCode,
                sender_invoice_no: String(effectiveMtId),
                invoice_receiver_code: receiverCode,
                invoice_description: `Order ${Math.round(amountValue)}`,
                sender_branch_code: branchCode,
                amount: Math.round(amountValue),
                callback_url: callbackUrl
            } : {
                invoice_code: invoiceCode,
                sender_invoice_no: String(effectiveMtId),
                invoice_receiver_code: receiverCode,
                sender_branch_code: branchCode,
                invoice_description: `Order ${Math.round(amountValue)}`,
                enable_expiry: 'false',
                allow_partial: false,
                minimum_amount: null,
                allow_exceed: false,
                maximum_amount: null,
                amount: Math.round(amountValue),
                callback_url: callbackUrl,
                sender_staff_code: currentOperator?.opercode || currentOperator?.operator_code || 'online',
                note: null
            };

            const invoiceResult = await api.createQPayInvoice(qpayToken, invoiceData, !!qpaySandboxFlag, qpayApiUrl);
            setQpayInvoiceResult(invoiceResult);
            if (!invoiceResult.success && typeof invoiceResult.error === 'string' && invoiceResult.error.includes('INVOICE_CODE_INVALID')) {
                const message = `QPay invoice_code буруу байна: ${invoiceCode}\n\nSettings -> QPay хэсэгт зөв invoice_code оруулна уу.`;
                if (showAlert) showAlert(message);
            }
            if (invoiceResult.success && invoiceResult.data) {
                const data = invoiceResult.data;
                const invoiceId = data.invoice_id || data.invoiceId || data.id || data.object_id || null;
                const qrImage = data.qr_image || data.qrImage || data.qr;
                const qrText = data.qr_text || data.qrText || data.qr_code || data.qrCode || '';
                if (qrImage) {
                    const src = qrImage.startsWith('data:') || qrImage.startsWith('http')
                        ? qrImage
                        : `data:image/png;base64,${qrImage}`;
                    setQpayQrImage(src);
                } else {
                    setQpayQrImage('');
                }
                setQpayQrText(qrText || '');
                setQpayAccessToken(qpayToken);
                setQpayInvoiceId(invoiceId);
                setQpayStatusMessage('Төлбөр хүлээж байна...');
                setQpayPollConfig({ sandbox: !!qpaySandboxFlag, apiUrl: qpayApiUrl || '' });
                setIsQPayWindowOpen(true);
            }
        } catch (error) {
            console.error('Error creating QPay invoice:', error);
            setQpayInvoiceResult({ success: false, error: error.message || 'Алдаа гарлаа' });
        } finally {
            setIsCreatingQpayInvoice(false);
        }
    };

    useEffect(() => {
        if (!isQPayWindowOpen || !qpayAccessToken || !qpayInvoiceId || !api || !api.checkQPayPayment) {
            return undefined;
        }
        let isActive = true;
        let pollTimer = null;
        
        const pollPayment = async () => {
            try {
                const checkResult = await api.checkQPayPayment(
                    'INVOICE',
                    qpayInvoiceId,
                    qpayAccessToken,
                    !!qpayPollConfig.sandbox,
                    1,
                    100,
                    qpayPollConfig.apiUrl
                );
                if (!isActive) return;
                if (checkResult && checkResult.success) {
                    const statusValue = checkResult.data?.status || checkResult.data?.data?.status;
                    const paid = statusValue && String(statusValue).toUpperCase() === 'PAID';
                    const payments = checkResult.data?.data?.payments || checkResult.data?.payments || checkResult.data?.data;
                    const paidInList = Array.isArray(payments) && payments.some(payment => {
                        const paymentStatus = payment?.payment_status || payment?.status || payment?.paymentStatus;
                        return paymentStatus && String(paymentStatus).toUpperCase() === 'PAID';
                    });
                    if (paid || paidInList) {
                        setQpayStatusMessage('Төлбөр амжилттай.');
                        setIsQPayWindowOpen(false);
                        submitQPayPayment();
                        return;
                    }
                }
            } catch (pollError) {
                console.error('Error polling QPay payment:', pollError);
            }
            if (isActive) {
                pollTimer = setTimeout(pollPayment, 3000);
            }
        };
        
        pollTimer = setTimeout(pollPayment, 1000);
        return () => {
            isActive = false;
            if (pollTimer) clearTimeout(pollTimer);
        };
    }, [isQPayWindowOpen, qpayAccessToken, qpayInvoiceId, qpayPollConfig, api]);

    // F10 дарахад байгууллага radio button сонгогдоод regNoInput-д зөвхөн select хийх
    useEffect(() => {
        if (isOpen && f10Pressed) {
            // Байгууллага radio button сонгох
            setDocumentType('B2B');
            
            // regNoInput-д зөвхөн select хийх (focus, click хийхгүй)
            const timer = setTimeout(() => {
                if (regNoInputRef.current) {
                    try {
                        // Зөвхөн select хийх, focus/click хийхгүй
                        if (document.activeElement !== regNoInputRef.current) {
                            regNoInputRef.current.focus();
                        }
                        regNoInputRef.current.select();
                    } catch (err) {
                        // Алдаа гарвал зөвхөн лог хийх, гацахгүй
                        console.warn('Could not select regNoInput:', err);
                    }
                }
            }, 400);
            
            return () => clearTimeout(timer);
        }
    }, [isOpen, f10Pressed]);

    if (!isOpen) return null;

    return (
        <>
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h2>Төлбөр төлөх</h2>
                    <button className="modal-close" onClick={onClose}>×</button>
                </div>
                
                <div className="modal-body">
                    <div className="form-group">
                        <label>Баримтын төрөл:</label>
                        <div className="radio-group">
                            <label className="radio-label">
                                <input
                                    type="radio"
                                    name="documentType"
                                    value="B2C"
                                    checked={documentType === 'B2C'}
                                    onChange={(e) => setDocumentType(e.target.value)}
                                />
                                <span>Иргэн (B2C)</span>
                            </label>
                            <label className="radio-label">
                                <input
                                    type="radio"
                                    name="documentType"
                                    value="B2B"
                                    checked={documentType === 'B2B'}
                                    onChange={(e) => setDocumentType(e.target.value)}
                                />
                                <span>Байгууллага (B2B)</span>
                            </label>
                        </div>
                    </div>

                    {documentType === 'B2B' && (
                        <div className="form-group">
                            <label>Байгууллагын регистерийн дугаар:</label>
                            <input
                                ref={regNoInputRef}
                                type="text"
                                className="form-input"
                                value={registrationNumber}
                                onChange={(e) => {
                                    const nextValue = e.target.value;
                                    setRegistrationNumber(nextValue);
                                    if (companyInfo) {
                                        setCompanyInfo(null);
                                    }
                                }}
                                onKeyPress={(e) => {
                                    if (e.key === 'Enter' && registrationNumber && registrationNumber.trim()) {
                                        if (companyInfo && companyInfo.success) {
                                            if (paymentMethod === 'CASH') {
                                                if (paidAmountInputRef.current) {
                                                    paidAmountInputRef.current.focus();
                                                    paidAmountInputRef.current.select();
                                                }
                                            } else {
                                                const grandTotal = calculateGrandTotal();
                                                const proceedAsB2C = () => onConfirm({
                                                    documentType: 'B2C',
                                                    paymentMethod,
                                                    registrationNumber: null,
                                                    companyName: null,
                                                    customerName: null,
                                                    customerTin: null,
                                                    vatPayer: null,
                                                    cityPayer: null,
                                                    selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
                                                    paidAmount: paymentMethod === 'CASH' ? (parseFloat(paidAmount) || 0) : grandTotal,
                                                    change: 0,
                                                    silentPrint: true
                                                });
                                                if (handleMissingMerchantTin(proceedAsB2C)) return;
                                                onConfirm({ 
                                                    documentType, 
                                                    paymentMethod, 
                                                    registrationNumber: documentType === 'B2B' ? registrationNumber : null,
                                                    companyName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                                    customerName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                                    customerTin: documentType === 'B2B' && companyInfo && companyInfo.customerTin ? companyInfo.customerTin : null,
                                                    vatPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.vatPayer : null,
                                                    cityPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.cityPayer : null,
                                                    selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
                                                    qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                                    qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                                    qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                                    paidAmount: paymentMethod === 'CASH' ? (parseFloat(paidAmount) || 0) : grandTotal,
                                                    change: 0,
                                                    silentPrint: true
                                                });
                                            }
                                        } else {
                                            handleSearchCompany();
                                        }
                                    }
                                }}
                                placeholder="Регистерийн дугаар оруулна уу (Enter дараад хайх)"
                            />
                            {companyInfo && (
                                <div style={{
                                    marginTop: '8px',
                                    padding: '8px',
                                    background: companyInfo.success ? '#1e3a2e' : '#3a1e1e',
                                    borderRadius: '4px',
                                    border: `1px solid ${companyInfo.success ? '#2ecc71' : '#e74c3c'}`,
                                    fontSize: '12px'
                                }}>
                                    {companyInfo.loading ? (
                                        <div style={{ color: '#3498db' }}>Хайж байна...</div>
                                    ) : (
                                        <>
                                            <div style={{ 
                                                fontWeight: 'bold', 
                                                color: companyInfo.success ? '#2ecc71' : '#e74c3c',
                                                marginBottom: '4px'
                                            }}>
                                                Байгууллагын нэр: {companyInfo.companyName || 'Олдсонгүй'}
                                            </div>
                                            {companyInfo.customerTin && (
                                                <div style={{ fontSize: '11px', color: '#95a5a6', marginBottom: '2px' }}>
                                                    TIN: {companyInfo.customerTin}
                                                </div>
                                            )}
                                            {companyInfo.vatPayer !== undefined && (
                                                <div style={{ fontSize: '11px', color: '#95a5a6', marginBottom: '2px' }}>
                                                    НӨАТ төлөгч: {companyInfo.vatPayer ? 'Тийм' : 'Үгүй'}
                                                </div>
                                            )}
                                            {companyInfo.cityPayer !== undefined && (
                                                <div style={{ fontSize: '11px', color: '#95a5a6', marginBottom: '2px' }}>
                                                    НХАТ төлөгч: {companyInfo.cityPayer ? 'Тийм' : 'Үгүй'}
                                                </div>
                                            )}
                                            {companyInfo.error && (
                                                <div style={{ fontSize: '11px', color: '#e74c3c', marginTop: '4px' }}>
                                                    Алдаа: {companyInfo.error}
                                                </div>
                                            )}
                                        </>
                                    )}
                                </div>
                            )}
                        </div>
                    )}

                    <div className="form-group">
                        <label>Төлбөрийн арга:</label>
                        <select
                            className="form-select"
                            value={paymentMethod}
                            onChange={(e) => {
                                setPaymentMethod(e.target.value);
                                if (e.target.value !== 'QPAY') {
                                    setSelectedBank(null);
                                }
                                if (e.target.value !== 'CASH') {
                                    setPaidAmount(''); // Reset paid amount when switching away from cash
                                }
                            }}
                        >
                            <option value="CASH">Бэлэн мөнгө (CASH)</option>
                            <option value="PAYMENT_CARD">Карт (PAYMENT_CARD)</option>
                            <option value="QPAY">QPay (QPAY)</option>
                        </select>
                    </div>

                    {paymentMethod === 'CASH' && (
                        <div className="form-group">
                            <label>Төлсөн дүн:</label>
                            <input
                                ref={paidAmountInputRef}
                                type="number"
                                className="form-input"
                                value={paidAmount}
                                onChange={(e) => {
                                    const value = e.target.value;
                                    // Allow empty, numbers, and decimals
                                    if (value === '' || /^\d*\.?\d*$/.test(value)) {
                                        setPaidAmount(value);
                                    }
                                }}
                                onKeyPress={(e) => {
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        const grandTotal = calculateGrandTotal();
                                        const paid = parseFloat(paidAmount) || 0;
                                        
                                        if (paid <= 0) {
                                            if (showAlert && typeof showAlert === 'function') {
                                                showAlert('Төлсөн дүн оруулна уу.');
                                            }
                                            if (paidAmountInputRef.current) {
                                                paidAmountInputRef.current.focus();
                                                paidAmountInputRef.current.select();
                                            }
                                            return;
                                        }
                                        
                                        const change = paid - grandTotal;
                                        
                                        // If underpayment, show warning and ask for confirmation
                                        if (change < 0) {
                                            const shortage = Math.abs(change);
                                            const confirmMessage = `⚠️ ДУТУУ ТӨЛБӨР ⚠️\n\nТөлсөн дүн хүрэхгүй байна.\nДутуу: ${formatCurrency(shortage)}\nТөлөх: ${formatCurrency(grandTotal)}\nТөлсөн: ${formatCurrency(paid)}\n\nДутуу төлбөртэй үргэлжлүүлэх үү?`;
                                            
                                            if (showConfirm && typeof showConfirm === 'function') {
                                                showConfirm(confirmMessage, () => {
                                                    // If confirmed, proceed with payment
                                                    const changeValue = Math.max(0, change);
                                                    const proceedAsB2C = () => onConfirm({
                                                        documentType: 'B2C',
                                                        paymentMethod,
                                                        registrationNumber: null,
                                                        companyName: null,
                                                        customerName: null,
                                                        customerTin: null,
                                                        vatPayer: null,
                                                        cityPayer: null,
                                                        selectedBank: null,
                                                        qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                                        qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                                        qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                                        paidAmount: paid,
                                                        change: changeValue,
                                                        silentPrint: true
                                                    });
                                                    if (handleMissingMerchantTin(proceedAsB2C)) return;
                                                    onConfirm({ 
                                                        documentType, 
                                                        paymentMethod, 
                                                        registrationNumber: documentType === 'B2B' ? registrationNumber : null,
                                                        companyName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                                        customerName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                                        customerTin: documentType === 'B2B' && companyInfo && companyInfo.customerTin ? companyInfo.customerTin : null,
                                                        vatPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.vatPayer : null,
                                                        cityPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.cityPayer : null,
                                                        selectedBank: null,
                                                        qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                                        qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                                        qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                                        paidAmount: paid,
                                                        change: changeValue,
                                                        silentPrint: true
                                                    });
                                                });
                                            }
                                            return;
                                        }
                                        
                                        // If valid payment (exact or overpayment), proceed with payment
                                        const changeValue = Math.max(0, change);
                                        const proceedAsB2C = () => onConfirm({
                                            documentType: 'B2C',
                                            paymentMethod,
                                            registrationNumber: null,
                                            companyName: null,
                                            customerName: null,
                                            customerTin: null,
                                            vatPayer: null,
                                            cityPayer: null,
                                            selectedBank: null,
                                            qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                            qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                            qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                            paidAmount: paid,
                                            change: changeValue,
                                            silentPrint: true
                                        });
                                        if (handleMissingMerchantTin(proceedAsB2C)) return;
                                        onConfirm({ 
                                            documentType, 
                                            paymentMethod, 
                                            registrationNumber: documentType === 'B2B' ? registrationNumber : null,
                                            companyName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                            customerName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                            customerTin: documentType === 'B2B' && companyInfo && companyInfo.customerTin ? companyInfo.customerTin : null,
                                            vatPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.vatPayer : null,
                                            cityPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.cityPayer : null,
                                            selectedBank: null,
                                            qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                            qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                            qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                            paidAmount: paid,
                                            change: changeValue,
                                            silentPrint: true
                                        });
                                    }
                                }}
                                onFocus={(e) => e.target.select()}
                                placeholder="Төлсөн дүн (Enter дараад төлөх)"
                                step="0.01"
                                min="0"
                            />
                            {paidAmount && parseFloat(paidAmount) > 0 && (
                                (() => {
                                    const grandTotal = calculateGrandTotal();
                                    const paid = parseFloat(paidAmount) || 0;
                                    const change = paid - grandTotal;
                                    if (change > 0) {
                                        return (
                                            <div style={{
                                                marginTop: '8px',
                                                padding: '8px',
                                                background: '#fff3cd',
                                                borderRadius: '4px',
                                                border: '1px solid #ffc107',
                                                fontSize: '14px',
                                                fontWeight: 'bold',
                                                color: '#856404'
                                            }}>
                                                Хариулт: {formatCurrency(change)}
                                            </div>
                                        );
                                    } else if (change < 0) {
                                        return (
                                            <div style={{
                                                marginTop: '8px',
                                                padding: '12px',
                                                background: '#f8d7da',
                                                borderRadius: '4px',
                                                border: '2px solid #dc3545',
                                                fontSize: '14px',
                                                fontWeight: 'bold',
                                                color: '#721c24',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '8px'
                                            }}>
                                                <span style={{ fontSize: '18px' }}>⚠️</span>
                                                <div>
                                                    <div style={{ marginBottom: '4px' }}>⚠️ ДУТУУ ТӨЛБӨР ⚠️</div>
                                                    <div>Дутуу: {formatCurrency(Math.abs(change))}</div>
                                                    <div style={{ fontSize: '12px', marginTop: '4px', opacity: 0.9 }}>
                                                        Төлсөн дүн хүрэхгүй байна. Үлдсэн дүнг цуглуулана уу.
                                                    </div>
                                                </div>
                                            </div>
                                        );
                                    }
                                    return null;
                                })()
                            )}
                        </div>
                    )}

                    {paymentMethod === 'QPAY' && (
                        <div className="form-group">
                            <label>Банк сонгох:</label>
                            <div style={{
                                display: 'grid',
                                gridTemplateColumns: 'repeat(4, 1fr)',
                                gap: '8px',
                                marginTop: '8px'
                            }}>
                                {banks.map((bank) => (
                                    <div
                                        key={bank.code}
                                        onClick={() => setSelectedBank(bank)}
                                        style={{
                                            padding: '12px',
                                            border: selectedBank?.code === bank.code ? '2px solid #3498db' : '1px solid #ddd',
                                            borderRadius: '8px',
                                            textAlign: 'center',
                                            cursor: 'pointer',
                                            backgroundColor: selectedBank?.code === bank.code ? '#ebf5fb' : '#fff',
                                            transition: 'all 0.2s',
                                            fontSize: '12px'
                                        }}
                                        onMouseEnter={(e) => {
                                            if (selectedBank?.code !== bank.code) {
                                                e.currentTarget.style.backgroundColor = '#f8f9fa';
                                                e.currentTarget.style.borderColor = '#3498db';
                                            }
                                        }}
                                        onMouseLeave={(e) => {
                                            if (selectedBank?.code !== bank.code) {
                                                e.currentTarget.style.backgroundColor = '#fff';
                                                e.currentTarget.style.borderColor = '#ddd';
                                            }
                                        }}
                                    >
                                        <div style={{ fontSize: '24px', marginBottom: '4px' }}>{bank.icon}</div>
                                        <div style={{ fontWeight: selectedBank?.code === bank.code ? 'bold' : 'normal' }}>
                                            {bank.name}
                                        </div>
                                    </div>
                                ))}
                            </div>
                            {selectedBank && (
                                <div style={{
                                    marginTop: '8px',
                                    padding: '8px',
                                    background: '#1e3a2e',
                                    borderRadius: '4px',
                                    border: '1px solid #2ecc71',
                                    fontSize: '12px',
                                    color: '#2ecc71'
                                }}>
                                    Сонгогдсон банк: {selectedBank.name} ({selectedBank.code})
                                </div>
                            )}
                            <div style={{ marginTop: '12px' }}>
                                <label>QPay төлбөрийн дүн:</label>
                                <input
                                    type="number"
                                    className="form-input"
                                    value={qpayAmount}
                                    onChange={(e) => setQpayAmount(e.target.value)}
                                    placeholder="Дүн оруулна уу"
                                    min="0"
                                    step="0.01"
                                />
                                <div style={{ marginTop: '8px', display: 'flex', gap: '8px', alignItems: 'center' }}>
                                    <button
                                        className="btn btn-primary"
                                        onClick={handleCreateQPayInvoice}
                                        disabled={isCreatingQpayInvoice || !selectedBank}
                                        style={{ minWidth: '140px' }}
                                    >
                                        {isCreatingQpayInvoice ? 'Үүсгэж байна...' : 'QR үүсгэх'}
                                    </button>
                                </div>
                                {qpayInvoiceResult && !qpayInvoiceResult.success && (
                                    <div style={{ marginTop: '8px', color: '#e74c3c', fontSize: '12px' }}>
                                        Алдаа: {qpayInvoiceResult.error || 'QPay invoice үүсгэхэд алдаа гарлаа'}
                                    </div>
                                )}
                            </div>
                        </div>
                    )}

                    <div className="payment-summary">
                        <div className="summary-row">
                            <span>Дэд дүн:</span>
                            <span>{formatCurrency(calculateTotal())}</span>
                        </div>
                        <div className="summary-row">
                            <span>НӨАТ:</span>
                            <span>{formatCurrency(calculateVATTotal())}</span>
                        </div>
                        <div className="summary-row">
                            <span>НХАТ:</span>
                            <span>{formatCurrency(calculateCityTaxTotal())}</span>
                        </div>
                        <div className="summary-row total-row">
                            <span>Төлөх:</span>
                            <span>{formatCurrency(calculateGrandTotal())}</span>
                        </div>
                        {paymentMethod === 'CASH' && paidAmount && parseFloat(paidAmount) > 0 && (
                            <>
                                <div className="summary-row">
                                    <span>Төлсөн:</span>
                                    <span>{formatCurrency(parseFloat(paidAmount) || 0)}</span>
                                </div>
                                {(() => {
                                    const grandTotal = calculateGrandTotal();
                                    const paid = parseFloat(paidAmount) || 0;
                                    const change = paid - grandTotal;
                                    if (change > 0) {
                                        return (
                                            <div className="summary-row" style={{ 
                                                background: '#fff3cd', 
                                                padding: '8px', 
                                                borderRadius: '4px',
                                                fontWeight: 'bold',
                                                color: '#856404'
                                            }}>
                                                <span>Хариулт:</span>
                                                <span>{formatCurrency(change)}</span>
                                            </div>
                                        );
                                    } else if (change < 0) {
                                        return (
                                            <div className="summary-row" style={{ 
                                                background: '#f8d7da', 
                                                padding: '10px', 
                                                borderRadius: '4px',
                                                fontWeight: 'bold',
                                                color: '#721c24',
                                                border: '2px solid #dc3545',
                                                display: 'flex',
                                                justifyContent: 'space-between',
                                                alignItems: 'center'
                                            }}>
                                                <span>⚠️ Дутуу:</span>
                                                <span>{formatCurrency(Math.abs(change))}</span>
                                            </div>
                                        );
                                    }
                                    return null;
                                })()}
                            </>
                        )}
                    </div>
                </div>

                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={onClose}>
                        Цуцлах
                    </button>
                    <button 
                        ref={paymentButtonRef}
                        className="btn btn-primary" 
                        onClick={() => {
                            if (paymentMethod === 'QPAY' && !selectedBank) {
                                if (showAlert && typeof showAlert === 'function') {
                                    showAlert('QPay төлбөрийн арга сонгосон бол банк сонгоно уу.');
                                }
                                return;
                            }
                            if (paymentMethod === 'CASH') {
                                const grandTotal = calculateGrandTotal();
                                const paid = parseFloat(paidAmount) || 0;
                                if (paid <= 0) {
                                    if (showAlert && typeof showAlert === 'function') {
                                        showAlert('Төлсөн дүн оруулна уу.');
                                    }
                                    return;
                                }
                                if (paid < grandTotal) {
                                    const shortage = grandTotal - paid;
                                    const confirmMessage = `⚠️ ДУТУУ ТӨЛБӨР ⚠️\n\nТөлсөн дүн хүрэхгүй байна.\nДутуу: ${formatCurrency(shortage)}\nТөлөх: ${formatCurrency(grandTotal)}\nТөлсөн: ${formatCurrency(paid)}\n\nДутуу төлбөртэй үргэлжлүүлэх үү?`;
                                    
                                    if (showConfirm && typeof showConfirm === 'function') {
                                        showConfirm(confirmMessage, () => {
                                            // If confirmed, proceed with payment
                                            const grandTotal = calculateGrandTotal();
                                            const paid = paymentMethod === 'CASH' ? (parseFloat(paidAmount) || 0) : grandTotal;
                                            const change = paymentMethod === 'CASH' ? Math.max(0, paid - grandTotal) : 0;
                                            
                                            const proceedAsB2C = () => onConfirm({
                                                documentType: 'B2C',
                                                paymentMethod,
                                                registrationNumber: null,
                                                companyName: null,
                                                customerName: null,
                                                customerTin: null,
                                                vatPayer: null,
                                                cityPayer: null,
                                                selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
                                                qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                                qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                                qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                                paidAmount: paymentMethod === 'CASH' ? paid : null,
                                                change: paymentMethod === 'CASH' ? change : null
                                            });
                                            if (handleMissingMerchantTin(proceedAsB2C)) return;
                                            onConfirm({ 
                                                documentType, 
                                                paymentMethod, 
                                                registrationNumber: documentType === 'B2B' ? registrationNumber : null,
                                                companyName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                                customerName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                                customerTin: documentType === 'B2B' && companyInfo && companyInfo.customerTin ? companyInfo.customerTin : null,
                                                vatPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.vatPayer : null,
                                                cityPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.cityPayer : null,
                                                selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
                                                qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                                qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                                qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                                paidAmount: paymentMethod === 'CASH' ? paid : null,
                                                change: paymentMethod === 'CASH' ? change : null
                                            });
                                        });
                                    }
                                    return;
                                }
                            }
                            const grandTotal = calculateGrandTotal();
                            const paid = paymentMethod === 'CASH' ? (parseFloat(paidAmount) || 0) : grandTotal;
                            const change = paymentMethod === 'CASH' ? Math.max(0, paid - grandTotal) : 0;
                            
                            const proceedAsB2C = () => onConfirm({
                                documentType: 'B2C',
                                paymentMethod,
                                registrationNumber: null,
                                companyName: null,
                                customerName: null,
                                customerTin: null,
                                vatPayer: null,
                                cityPayer: null,
                                selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
                                qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                paidAmount: paymentMethod === 'CASH' ? paid : null,
                                change: paymentMethod === 'CASH' ? change : null
                            });
                            if (handleMissingMerchantTin(proceedAsB2C)) return;
                            onConfirm({ 
                                documentType, 
                                paymentMethod, 
                                registrationNumber: documentType === 'B2B' ? registrationNumber : null,
                                companyName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                customerName: documentType === 'B2B' && companyInfo && companyInfo.companyName ? companyInfo.companyName : null,
                                customerTin: documentType === 'B2B' && companyInfo && companyInfo.customerTin ? companyInfo.customerTin : null,
                                vatPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.vatPayer : null,
                                cityPayer: documentType === 'B2B' && companyInfo ? !!companyInfo.cityPayer : null,
                                selectedBank: paymentMethod === 'QPAY' ? selectedBank : null,
                                qpayAmount: paymentMethod === 'QPAY' ? parseFloat(qpayAmount) || null : null,
                                qpayInvoiceCreated: paymentMethod === 'QPAY' ? !!(qpayInvoiceResult && qpayInvoiceResult.success) : false,
                                qpayInvoiceData: paymentMethod === 'QPAY' ? (qpayInvoiceResult?.data || null) : null,
                                paidAmount: paymentMethod === 'CASH' ? paid : null,
                                change: paymentMethod === 'CASH' ? change : null
                            });
                        }}
                        disabled={paymentMethod === 'QPAY' && !selectedBank}
                    >
                        Төлбөр төлөх
                    </button>
                </div>
            </div>
        </div>
        {isQPayWindowOpen && (
            <div className="modal-overlay" onClick={() => setIsQPayWindowOpen(false)}>
                <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '480px' }}>
                    <div className="modal-header">
                        <h2>QPay төлбөр</h2>
                        <button className="modal-close" onClick={() => setIsQPayWindowOpen(false)}>×</button>
                    </div>
                    <div className="modal-body">
                        {qpayQrImage ? (
                            <div style={{ textAlign: 'center', maxHeight: '520px', overflowY: 'auto' }}>
                                <img src={qpayQrImage} alt="QPay QR" style={{ width: '100%', height: 'auto' }} />
                            </div>
                        ) : (
                            <div>QR үүсээгүй байна</div>
                        )}
                        {qpayStatusMessage && (
                            <div style={{ marginTop: '12px', textAlign: 'center', fontWeight: 'bold' }}>
                                {qpayStatusMessage}
                            </div>
                        )}
                    </div>
                </div>
            </div>
        )}
        </>
    );
}

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

