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

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

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

const SettingsCollapsible = typeof window !== 'undefined' && window.SettingsCollapsible
    ? window.SettingsCollapsible
    : function SettingsCollapsiblePassthrough({ children }) {
        return React.createElement('div', { className: 'settings-section' }, children);
    };

function SettingsModal({ 
    isOpen, 
    onClose,
    onSave,
    selectedCompany,
    currentOperator,
    showAlert,
    onMaterialClick,
    api,
    addToCart,
    setCart
}) {
    const [settings, setSettings] = useState({
        name: '',
        email: '',
        phone: '',
        calculatesVAT: true,
        address: '',
        merchantTin: '',
        registrationNumber: '',
        cityTaxRate: '',
        taxSystemURL: '',
        posId: '',
        lotNumber: '',
        sendTime: '',
        districtCode: '',
        branchNo: '',
        qpayClientId: '',
        qpayClientSecret: '',
        qpaySimpleInvoice: false,
        qpayInvoiceCode: '',
        qpayInvoiceReceiverCode: '',
        qpayCallbackUrl: '',
        qpayApiUrl: '',
        reportDailyCashcode: true,
        reportDailyPayment: true,
        reportDailyTax: true,
        reportSummary: true,
        allowDelete: null, // null = server.txt, true = allow, false = disallow
        wholesaleCenter: false, // бөөний төв: pcount/price_big нөхцөлд НХАТ тооцохгүй
        // Server.txt settings
        serverPosNo: '',
        serverReceiptWidth: '',
        serverLine6: '',
        serverPosPrinter: '',
        serverKitchenPrinter: ''
    });
    
    const [isUploading, setIsUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState('');
    const [isSendingToTax, setIsSendingToTax] = useState(false);
    const [isSyncingMaterials, setIsSyncingMaterials] = useState(false);
    const [isDownloading, setIsDownloading] = useState(false);
    const [downloadProgress, setDownloadProgress] = useState({ current: 0, total: 0 });
    const [showCreateUpdateButton, setShowCreateUpdateButton] = useState(false); // Default to false (hide button)
    const [reportType, setReportType] = useState('SUMMARY');
    const [reportTopN, setReportTopN] = useState(10);
    const [reportStart, setReportStart] = useState('');
    const [reportEnd, setReportEnd] = useState('');
    const [reportLoading, setReportLoading] = useState(false);
    const [reportError, setReportError] = useState('');
    const [reportSummary, setReportSummary] = useState(null);
    const [reportPreviewHtml, setReportPreviewHtml] = useState('');
    const [showQPayReportSection, setShowQPayReportSection] = useState(false);
    // Баримт хайх modal - шилжүүлсэн ReceiptSearchModal-д
    const [districtList, setDistrictList] = useState([]);
    const [districtListLoading, setDistrictListLoading] = useState(false);
    const [districtSyncing, setDistrictSyncing] = useState(false);
    /** Лавлагаа татах: ачаалал / амжилт / алдаа — хэрэглэгчид дууссаныг тод харуулна */
    const [districtSyncBanner, setDistrictSyncBanner] = useState(null);

    useEffect(() => {
        if (isOpen) {
            setDistrictSyncBanner(null);
        }
    }, [isOpen]);

    useEffect(() => {
        if (!isOpen || !api || !api.getDistrictList) {
            return;
        }
        let cancelled = false;
        setDistrictListLoading(true);
        api.getDistrictList()
            .then((r) => {
                if (!cancelled && r && r.success && Array.isArray(r.data)) {
                    setDistrictList(r.data);
                }
            })
            .catch((err) => console.error('getDistrictList:', err))
            .finally(() => {
                if (!cancelled) setDistrictListLoading(false);
            });
        return () => { cancelled = true; };
    }, [isOpen, api]);

    useEffect(() => {
        // Check device name - only show button if device name is 'DESKTOP-HBS4KC6'
        if (api && api.getDeviceName) {
            api.getDeviceName().then(result => {
                if (result && result.success) {
                    const deviceName = result.data || '';
                    setShowCreateUpdateButton(deviceName === 'DESKTOP-HBS4KC6');
                }
            }).catch(err => {
                console.error('Error checking device name:', err);
                setShowCreateUpdateButton(false); // Default to false (hide button)
            });
        }
    }, []);

    useEffect(() => {
        if (isOpen && selectedCompany) {
            setSettings({
                name: (selectedCompany.b_name || selectedCompany.name || '').trim(),
                email: (selectedCompany.b_email || selectedCompany.email || '').trim(),
                phone: (selectedCompany.b_phone || selectedCompany.phone || '').trim(),
                calculatesVAT: selectedCompany.b_calculates_vat !== undefined ? selectedCompany.b_calculates_vat : true,
                address: (selectedCompany.b_address || selectedCompany.address || '').trim(),
                merchantTin: (selectedCompany.merchantTin || '').trim(),
                registrationNumber: (selectedCompany.b_register || selectedCompany.b_registration_number || selectedCompany.registrationNumber || '').trim(),
                cityTaxRate: (selectedCompany.b_citytax || selectedCompany.cityTaxRate || '').toString(),
                taxSystemURL: (selectedCompany.apiURL || selectedCompany.taxSystemURL || '').trim(),
                posId: (selectedCompany.posId || selectedCompany.posID || '').toString().trim(),
                lotNumber: (selectedCompany.lotNumber || selectedCompany.b_lotcount || '').toString().trim(),
                sendTime: (selectedCompany.sendTime || selectedCompany.b_sendtime || '').trim(),
                districtCode: (selectedCompany.b_district || '').trim(),
                branchNo: (currentOperator?.dep_code || currentOperator?.dep_id?.toString() || '').trim(),
                qpayClientId: (selectedCompany.qpayClientId || selectedCompany.qpay_client_id || '').trim(),
                qpayClientSecret: (selectedCompany.qpayClientSecret || selectedCompany.qpay_client_secret || '').trim(),
                qpaySimpleInvoice: !!(selectedCompany.qpaySimpleInvoice || selectedCompany.qpay_simple_invoice),
                qpayInvoiceCode: (selectedCompany.qpayInvoiceCode || selectedCompany.qpay_invoice_code || '').trim(),
                qpayInvoiceReceiverCode: (selectedCompany.qpayInvoiceReceiverCode || selectedCompany.qpay_invoice_receiver_code || '').trim(),
                qpayCallbackUrl: (selectedCompany.qpayCallbackUrl || selectedCompany.qpay_callback_url || '').trim(),
                qpayApiUrl: (selectedCompany.qpayApiUrl || selectedCompany.qpay_api_url || '').trim(),
                reportDailyCashcode: selectedCompany.reportDailyCashcode ?? selectedCompany.report_daily_cashcode ?? true,
                reportDailyPayment: selectedCompany.reportDailyPayment ?? selectedCompany.report_daily_payment ?? true,
                reportDailyTax: selectedCompany.reportDailyTax ?? selectedCompany.report_daily_tax ?? true,
                reportSummary: selectedCompany.reportSummary ?? selectedCompany.report_summary ?? true,
                allowDelete: selectedCompany.allow_delete !== undefined && selectedCompany.allow_delete !== null ? !!selectedCompany.allow_delete : null,
                wholesaleCenter: !!(selectedCompany.b_wholesale_center === true || selectedCompany.b_wholesale_center === 1 || selectedCompany.b_wholesale_center === '1'),
                // Server.txt settings will be loaded separately
                serverPosNo: '',
                serverReceiptWidth: '',
                serverLine6: '',
                serverPosPrinter: '',
                serverKitchenPrinter: ''
            });
            
            // Load server.txt settings
            if (api && api.getServerSettings) {
                api.getServerSettings().then(result => {
                    if (result && result.success && result.data) {
                        setSettings(prev => ({
                            ...prev,
                            serverPosNo: result.data.posNo || '',
                            serverReceiptWidth: result.data.receiptWidth || '',
                            serverLine6: result.data.line6 || '',
                            serverPosPrinter: result.data.posPrinter || '',
                            serverKitchenPrinter: result.data.kitchenPrinter || ''
                        }));
                    }
                }).catch(err => {
                    console.error('Error loading server settings:', err);
                });
            }

        }
    }, [isOpen, selectedCompany, currentOperator]);

    useEffect(() => {
        if (isOpen) {
            const now = new Date();
            const start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
            const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
            const toLocal = (date) => {
                const pad = (n) => String(n).padStart(2, '0');
                return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
            };
            setReportStart(toLocal(start));
            setReportEnd(toLocal(end));
            setReportLoading(false);
            setReportError('');
            setReportSummary(null);
            setReportPreviewHtml('');
        }
    }, [isOpen]);

    const getReportOptions = () => {
        const options = [];
        if (settings.reportDailyCashcode) options.push({ value: 'DAILY_CASHCODE', label: 'Өдрийн тайлан (cashcode)' });
        if (settings.reportDailyPayment) options.push({ value: 'DAILY_PAYMENT', label: 'Өдрийн тайлан (Төлбөрийн төрлөөр)' });
        if (settings.reportDailyTax) options.push({ value: 'DAILY_TAX', label: 'Өдрийн тайлан (Татвар)' });
        if (settings.reportSummary) options.push({ value: 'SUMMARY', label: 'Хураангуй тайлан' });
        options.push({ value: 'TOP_N_PRODUCTS', label: 'Хамгийн сайн зарагдсан Top N барааны борлуулалтын тайлан' });
        return options;
    };

    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 = row?.tcount ?? row?.quantity ?? row?.qty ?? 0;
            const price = row?.price_low ?? row?.price ?? row?.unitPrice ?? row?.unit_price ?? 0;
            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 };
    };

    const buildReportHtml = (summary, startDate, endDate, selectedType, receiptWidthMm = 58) => {
        const formatAmount = (val) => formatCurrency ? formatCurrency(val) : String(val);
        const formatDate = (date) => {
            if (!date) return '';
            const d = new Date(date);
            if (isNaN(d.getTime())) return String(date);
            const pad = (n) => String(n).padStart(2, '0');
            return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
        };
        const widthNum = parseInt(receiptWidthMm, 10) || 58;
        const is58 = widthNum < 76;
        const paperWidthMm = is58 ? 58 : 80;
        const fontSizePx = is58 ? 10 : 12;
        const paddingPx = is58 ? 4 : 8;
        let reportTitle = 'Хураангуй тайлан';
        let bodyHtml = `
            <div class="row"><span class="label">Эхлэх:</span><span class="value">${formatDate(startDate)}</span></div>
            <div class="row"><span class="label">Дуусах:</span><span class="value">${formatDate(endDate)}</span></div>
            <div class="row"><span class="label">Cashcode:</span><span class="value">${summary.cashcode}</span></div>
            <div class="row"><span class="label">Баримтын тоо:</span><span class="value">${summary.count}</span></div>
            <div class="divider"></div>
        `;
        if (selectedType === 'DAILY_PAYMENT') {
            reportTitle = 'Өдрийн тайлан (Төлбөрийн төрлөөр)';
            bodyHtml += `
                <div class="row"><span class="label">Бэлэн:</span><span class="value">${formatAmount(summary.totalCash)}</span></div>
                <div class="row"><span class="label">Карт:</span><span class="value">${formatAmount(summary.totalBank)}</span></div>
                <div class="row"><span class="label">Бусад:</span><span class="value">${formatAmount(summary.totalOther)}</span></div>
                <div class="divider"></div>
                <div class="row total"><span>Нийт дүн:</span><span>${formatAmount(summary.totalAfterDiscount)}</span></div>
            `;
        } else if (selectedType === 'DAILY_TAX') {
            reportTitle = 'Өдрийн тайлан (Татвар)';
            bodyHtml += `
                <div class="row"><span class="label">НӨАТ:</span><span class="value">${formatAmount(summary.totalVAT)}</span></div>
                <div class="row"><span class="label">НХАТ:</span><span class="value">${formatAmount(summary.totalCityTax)}</span></div>
                <div class="divider"></div>
                <div class="row total"><span>Нийт дүн:</span><span>${formatAmount(summary.totalAfterDiscount)}</span></div>
            `;
        } else if (selectedType === 'DAILY_CASHCODE') {
            reportTitle = 'Өдрийн тайлан (Cashcode)';
            bodyHtml += `
                <div class="row"><span class="label">Нийт дүн:</span><span class="value">${formatAmount(summary.totalAfterDiscount)}</span></div>
                <div class="row"><span class="label">Хөнгөлөлтийн дүн:</span><span class="value">${formatAmount(summary.totalDiscount)}</span></div>
                <div class="divider"></div>
                <div class="row total"><span>Хөнгөлөлт нэмсэн нийт дүн:</span><span>${formatAmount(summary.totalBeforeDiscount)}</span></div>
            `;
        } else if (selectedType === 'TOP_N_PRODUCTS' && summary.items && Array.isArray(summary.items)) {
            reportTitle = 'Хамгийн сайн зарагдсан Top N барааны борлуулалтын тайлан';
            bodyHtml = `
                <div class="row"><span class="label">Эхлэх:</span><span class="value">${formatDate(startDate)}</span></div>
                <div class="row"><span class="label">Дуусах:</span><span class="value">${formatDate(endDate)}</span></div>
                <div class="divider"></div>
                <table class="topn-table" style="width:100%; border-collapse: collapse; font-size: ${fontSizePx}px;">
                    <thead><tr><th style="text-align:left;">#</th><th style="text-align:left;">Дотоод код</th><th style="text-align:left;">Бараа</th><th style="text-align:right;">Тоо</th><th style="text-align:right;">Дүн</th></tr></thead>
                    <tbody>
                ${summary.items.map((row, idx) => `
                    <tr><td>${idx + 1}</td><td>${(row.dotcode ?? '-').toString().replace(/</g, '&lt;')}</td><td>${(row.product_name || '-').toString().replace(/</g, '&lt;')}</td><td style="text-align:right;">${Number(row.total_qty) || 0}</td><td style="text-align:right;">${formatAmount(row.total_sales || 0)}</td></tr>
                `).join('')}
                    </tbody>
                </table>
            `;
        } else {
            reportTitle = 'Хураангуй тайлан';
            bodyHtml += `
                <div class="row"><span class="label">Нийт дүн:</span><span class="value">${formatAmount(summary.totalAfterDiscount)}</span></div>
                <div class="row"><span class="label">Хөнгөлөлтийн дүн:</span><span class="value">${formatAmount(summary.totalDiscount)}</span></div>
                <div class="row"><span class="label">Хөнгөлөлт нэмсэн нийт дүн:</span><span class="value">${formatAmount(summary.totalBeforeDiscount)}</span></div>
                <div class="divider"></div>
                <div class="row"><span class="label">НӨАТ:</span><span class="value">${formatAmount(summary.totalVAT)}</span></div>
                <div class="row"><span class="label">НХАТ:</span><span class="value">${formatAmount(summary.totalCityTax)}</span></div>
                <div class="divider"></div>
                <div class="row"><span class="label">Бэлэн:</span><span class="value">${formatAmount(summary.totalCash)}</span></div>
                <div class="row"><span class="label">Карт:</span><span class="value">${formatAmount(summary.totalBank)}</span></div>
                <div class="row"><span class="label">Бусад:</span><span class="value">${formatAmount(summary.totalOther)}</span></div>
            `;
        }
        return `
            <!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; }
                    .topn-table th, .topn-table td { border: 1px solid #ccc; padding: 2px 4px; }
                </style>
            </head>
            <body>
                <h3>${reportTitle}</h3>
                ${bodyHtml}
            </body>
            </html>
        `;
    };

    const runReport = async () => {
        if (!api) {
            if (showAlert) showAlert('API олдсонгүй.');
            return;
        }
        if (!selectedCompany || !currentOperator) {
            if (showAlert) showAlert('Байгууллага эсвэл операторын мэдээлэл дутуу байна.');
            return;
        }
        if (!reportStart || !reportEnd) {
            if (showAlert) showAlert('Тайлангийн хугацааг сонгоно уу.');
            return;
        }
        const startDate = new Date(reportStart);
        const endDate = new Date(reportEnd);
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime()) || startDate > endDate) {
            if (showAlert) showAlert('Тайлангийн хугацаа буруу байна.');
            return;
        }
        setReportLoading(true);
        setReportError('');
        setReportSummary(null);
        setReportPreviewHtml('');
        try {
            if (reportType === 'TOP_N_PRODUCTS') {
                const b_id = selectedCompany.b_id || selectedCompany.id;
                if (!b_id) throw new Error('Байгууллагын ID олдсонгүй.');
                const topN = Math.max(parseInt(reportTopN, 10) || 10, 1);
                const result = await api.getTopNSoldProducts(b_id, startDate, endDate, topN);
                if (!result?.success) throw new Error(result?.error || 'Тайлан татахад алдаа гарлаа.');
                const items = result.data || [];
                let receiptWidthForReport = 58;
                if (api.getReceiptWidth) {
                    try {
                        const widthRes = await api.getReceiptWidth();
                        if (widthRes?.success && widthRes.data != null) {
                            const w = parseInt(widthRes.data, 10);
                            receiptWidthForReport = (!isNaN(w) && w >= 76) ? 80 : 58;
                        }
                    } catch (e) { console.error('Error getting receipt width for report:', e); }
                }
                setReportSummary({ items });
                setReportPreviewHtml(buildReportHtml({ items }, startDate, endDate, 'TOP_N_PRODUCTS', receiptWidthForReport));
                return;
            }
            if (!api.getExpenseGListByCashcode || !api.getExpenseRows) {
                if (showAlert) showAlert('Тайлангийн API функц олдсонгүй.');
                return;
            }
            let cashcode = null;
            if (api.getCashCode) {
                try {
                    const cashcodeResult = await api.getCashCode();
                    if (cashcodeResult?.success && cashcodeResult.data !== undefined && cashcodeResult.data !== null) {
                        const parsed = parseInt(cashcodeResult.data, 10);
                        if (!isNaN(parsed)) cashcode = parsed;
                    }
                } catch (e) {
                    console.error('getCashCode error:', e);
                }
            }
            if (cashcode === null || cashcode === undefined || isNaN(cashcode)) {
                throw new Error('Cashcode олдсонгүй. Server.txt файлын 3-р мөрөнд 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 days = Math.max(1, Math.ceil((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000)) + 1);
            const listResult = await api.getExpenseGListByCashcode(cashcode, b_id, opid, days, null, 5000);
            if (!listResult?.success || !Array.isArray(listResult.data)) {
                throw new Error(listResult?.error || 'Тайлангийн жагсаалт олдсонгүй.');
            }
            const rowsInRange = listResult.data.filter(row => {
                const adate = row?.adate ? new Date(row.adate) : null;
                return adate && adate >= startDate && adate <= endDate;
            });
            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 rowsInRange) {
                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 && rowsInRange.length > 0) {
                const mtIds = rowsInRange.map(r => r.mt_id).filter(Boolean);
                const batchResult = await api.getExpenseRowsBatch(mtIds);
                const rowsByMtId = batchResult?.success ? (batchResult.data || {}) : {};
                for (const receipt of rowsInRange) {
                    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 < rowsInRange.length; i += BATCH_SIZE) {
                    const chunk = rowsInRange.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;
            const summary = {
                cashcode,
                totalAfterDiscount,
                totalDiscount,
                totalBeforeDiscount,
                totalVAT,
                totalCityTax,
                totalCash,
                totalBank,
                totalOther,
                count: rowsInRange.length
            };
            let receiptWidthForReport = 58;
            if (api.getReceiptWidth) {
                try {
                    const widthRes = await api.getReceiptWidth();
                    if (widthRes?.success && widthRes.data != null) {
                        const w = parseInt(widthRes.data, 10);
                        receiptWidthForReport = (!isNaN(w) && w >= 76) ? 80 : 58;
                    }
                } catch (e) {
                    console.error('Error getting receipt width for report:', e);
                }
            }
            setReportSummary(summary);
            setReportPreviewHtml(buildReportHtml(summary, startDate, endDate, reportType, receiptWidthForReport));
        } catch (err) {
            const message = err?.message || 'Тайлан тооцоолоход алдаа гарлаа.';
            setReportError(message);
            if (showAlert) showAlert(message);
        } finally {
            setReportLoading(false);
        }
    };

    const escapeCsvCell = (val) => {
        const s = val == null ? '' : String(val);
        if (/[,\t"\r\n]/.test(s)) return '"' + s.replace(/"/g, '""') + '"';
        return s;
    };

    const exportReportToExcel = () => {
        if (!reportSummary) {
            if (showAlert) showAlert('Тайлан бэлэн биш байна. Эхлээд тайлан ажиллуулна уу.');
            return;
        }
        const formatAmount = (val) => (formatCurrency ? formatCurrency(val) : String(val));
        const filename = `tailan_${reportType}_${new Date().toISOString().slice(0, 10)}`;

        let gridData = [];
        if (reportType === 'TOP_N_PRODUCTS' && reportSummary.items && Array.isArray(reportSummary.items)) {
            gridData.push(['№', 'Дотоод код', 'Бараа', 'Тоо', 'Дүн']);
            reportSummary.items.forEach((row, idx) => {
                gridData.push([
                    idx + 1,
                    row.dotcode ?? '',
                    row.product_name ?? '',
                    Number(row.total_qty) || 0,
                    Number(row.total_sales) || 0
                ]);
            });
        } else {
            const labels = {
                cashcode: 'Cashcode',
                count: 'Баримтын тоо',
                totalAfterDiscount: 'Нийт дүн',
                totalDiscount: 'Хөнгөлөлтийн дүн',
                totalBeforeDiscount: 'Хөнгөлөлт нэмсэн нийт дүн',
                totalVAT: 'НӨАТ',
                totalCityTax: 'НХАТ',
                totalCash: 'Бэлэн',
                totalBank: 'Карт',
                totalOther: 'Бусад'
            };
            gridData.push(['Талбар', 'Утга']);
            Object.keys(labels).forEach((key) => {
                if (reportSummary[key] !== undefined && reportSummary[key] !== null) {
                    const val = typeof reportSummary[key] === 'number' && key.toLowerCase().includes('total') ? formatAmount(reportSummary[key]) : reportSummary[key];
                    gridData.push([labels[key], val]);
                }
            });
        }

        const doCsvFallback = () => {
            const colSep = '\t';
            const csvRows = gridData.map(row => row.map(cell => escapeCsvCell(cell)).join(colSep));
            const csv = '\uFEFF' + csvRows.join('\r\n');
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${filename}.csv`;
            a.click();
            URL.revokeObjectURL(url);
            if (showAlert) showAlert('Тайлан CSV файл болон татагдлаа. Excel-ээр нээнэ.');
        };

        try {
            const XLSXLib = typeof XLSX !== 'undefined' ? XLSX : (typeof window !== 'undefined' ? window.XLSX : null);
            if (XLSXLib && XLSXLib.utils && typeof XLSXLib.utils.aoa_to_sheet === 'function') {
                const ws = XLSXLib.utils.aoa_to_sheet(gridData);
                if (gridData[0]) {
                    const colWidths = gridData[0].map((_, i) => ({
                        wch: Math.min(Math.max(8, gridData.reduce((m, r) => (r[i] != null ? Math.max(m, String(r[i]).length) : m), 0)), 50)
                    }));
                    ws['!cols'] = colWidths;
                }
                const wb = XLSXLib.utils.book_new();
                XLSXLib.utils.book_append_sheet(wb, ws, 'Тайлан');
                XLSXLib.writeFile(wb, `${filename}.xls`, { bookType: 'xls' });
                if (showAlert) showAlert('Тайлан Excel 97-2003 (.xls) файл болон татагдлаа.');
                return;
            }
        } catch (e) {
            console.warn('Excel .xls export failed, falling back to CSV:', e);
        }
        doCsvFallback();
    };

    const printReport = async () => {
        if (!reportPreviewHtml) {
            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);
            }
        }
        await api.silentPrintHtml(reportPreviewHtml, receiptWidth);
    };

    const handleGetMerchantTinFromRegistration = async (regNo) => {
        if (!regNo || !regNo.trim()) {
            return;
        }

        const regNoTrimmed = regNo.trim();
        console.log('Getting merchantTin from tax system for regNo:', regNoTrimmed);

        try {
            // Бүртгэлийн дугаараас TIN авах
            const tinInfoUrl = `https://api.ebarimt.mn/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();
                    setSettings({...settings, merchantTin: tin});
                    console.log('Got merchantTin from regNo:', tin);
                    if (showAlert && typeof showAlert === 'function') {
                        showAlert('Merchant TIN амжилттай авлаа');
                    }
                } else {
                    console.warn('Could not get TIN from registration number');
                    if (showAlert && typeof showAlert === 'function') {
                        showAlert('Бүртгэлийн дугаараас TIN олдсонгүй');
                    }
                }
            } else {
                console.warn('Failed to fetch TIN info, status:', tinInfoResponse.status);
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Татварын лавлагаанаас мэдээлэл авахад алдаа гарлаа');
                }
            }
        } catch (error) {
            console.error('Error getting merchantTin from registration number:', error);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Татварын лавлагаанаас мэдээлэл авахад алдаа гарлаа: ' + error.message);
            }
        }
    };



    /**
     * Аймаг/дүүргийн a_district лавлагааг barongoo_finance-аас татах
     * @param {{ afterSuccessNote?: string }} opts
     * @returns {Promise<boolean>} амжилттай эсэх
     */
    const runDistrictCatalogSync = async (opts = {}) => {
        if (!api || !api.syncDistrictsFromFinance) {
            const msg = 'Лавлагаа татах API байхгүй байна.';
            setDistrictSyncBanner({ status: 'err', text: msg });
            if (showAlert && typeof showAlert === 'function') {
                showAlert(msg);
            }
            return false;
        }
        setDistrictSyncBanner({ status: 'loading' });
        setDistrictSyncing(true);
        setUploadProgress('Аймаг, дүүргийн лавлагаа татаж байна…');
        try {
            const sr = await api.syncDistrictsFromFinance();
            if (!sr.success) {
                throw new Error(sr.error || 'Алдаа');
            }
            const count = sr.data && sr.data.count != null ? sr.data.count : null;
            const lr = await api.getDistrictList();
            if (lr.success && Array.isArray(lr.data)) {
                setDistrictList(lr.data);
            }
            const note = opts.afterSuccessNote ? ` ${opts.afterSuccessNote}` : '';
            const detail = count != null ? `${count} мөр ачаалагдлаа.` : 'Лавлагаа шинэчлэгдлээ.';
            const okMsg = (`✓ Дууслаа: ${detail}` + note).trim();
            setDistrictSyncBanner({ status: 'ok', text: okMsg });
            setUploadProgress(okMsg);
            if (showAlert && typeof showAlert === 'function') {
                showAlert(okMsg);
            }
            window.setTimeout(() => {
                setUploadProgress('');
                setDistrictSyncBanner((b) => (b && b.status === 'ok' ? null : b));
            }, 10000);
            return true;
        } catch (err) {
            console.error('runDistrictCatalogSync:', err);
            const em = err.message || String(err);
            setDistrictSyncBanner({ status: 'err', text: em });
            setUploadProgress('');
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Лавлагаа татахад алдаа: ' + em);
            }
            return false;
        } finally {
            setDistrictSyncing(false);
        }
    };

    const handleSave = async () => {
        if (!settings.name || settings.name.trim() === '') {
            const message = 'Байгууллагын нэр заавал оруулах шаардлагатай!';
            if (showAlert && typeof showAlert === 'function') {
                showAlert(message);
            }
            return;
        }

        // 2 оронтой кодыг буруу гэж үзнэ: a_district цэвэрлээд barongoo_finance-аас дахин татна
        const dc = (settings.districtCode || '').trim();
        if (dc.length === 2) {
            const ok = await runDistrictCatalogSync({
                afterSuccessNote: 'Дүүрэг/хорооны зөв кодыг жагсаалтаас дахин сонгоно уу.'
            });
            if (ok) {
                setSettings((prev) => ({ ...prev, districtCode: '' }));
            }
            return;
        }

        // Save server.txt settings
        if (api && api.updateServerSettings) {
            try {
                const serverSettings = {
                    posNo: settings.serverPosNo,
                    receiptWidth: settings.serverReceiptWidth,
                    line6: settings.serverLine6,
                    posPrinter: settings.serverPosPrinter,
                    kitchenPrinter: settings.serverKitchenPrinter
                };
                
                const serverResult = await api.updateServerSettings(serverSettings);
                if (!serverResult.success) {
                    console.error('Error saving server settings:', serverResult.error);
                    if (showAlert && typeof showAlert === 'function') {
                        showAlert('Server.txt тохиргоо хадгалахад алдаа гарлаа: ' + (serverResult.error || 'Тодорхойгүй алдаа'));
                    }
                }
            } catch (err) {
                console.error('Error saving server settings:', err);
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Server.txt тохиргоо хадгалахад алдаа гарлаа: ' + err.message);
                }
            }
        }

        if (onSave) {
            await onSave(settings);
        } else {
            console.log('Settings saved:', settings);
            const message = 'Тохиргоо хадгалагдлаа!';
            if (showAlert && typeof showAlert === 'function') {
                showAlert(message);
            }
            onClose();
        }
    };

    const handleCreateUpdate = async () => {
        if (!api || !api.createAndUploadUpdate) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('API функц олдсонгүй');
            }
            return;
        }

        setIsUploading(true);
        setUploadProgress('Шинэчлэл үүсгэж байна...');

        try {
            const result = await api.createAndUploadUpdate({
                ftpUrl: 'ftp://pos.baron.mn/UpdatePOS.zip',
                username: 'enchbaatar',
                password: '6L06*r7mw',
                excludePatterns: ['node_modules', '.git', 'dist', 'build', 'UpdatePOS.zip', '*.log', '*.tmp', 'PEXARConfig.ini']
            });

            if (result.success) {
                setUploadProgress('Шинэчлэл амжилттай хадгалагдлаа!');
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Шинэчлэл амжилттай хадгалагдлаа: ' + result.message);
                }
            } else {
                setUploadProgress('Алдаа: ' + result.message);
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Шинэчлэл хадгалахад алдаа гарлаа: ' + result.message);
                }
            }
        } catch (error) {
            setUploadProgress('Алдаа: ' + error.message);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Шинэчлэл хадгалахад алдаа гарлаа: ' + error.message);
            }
        } finally {
            setIsUploading(false);
            setTimeout(() => setUploadProgress(''), 3000);
        }
    };

    const handleSendToTaxSystem = async () => {
        if (!api || !api.sendToTaxSystem) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('API функц олдсонгүй');
            }
            return;
        }

        if (!selectedCompany || !selectedCompany.apiURL) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Татварын системийн URL тохируулаагүй байна. Тохиргоо хэсэгт API URL оруулна уу.');
            }
            return;
        }

        setIsSendingToTax(true);
        setUploadProgress('Татварын системд илгээж байна...');

        try {
            const apiURL = selectedCompany.apiURL || selectedCompany.apiUrl;
            const result = await api.sendToTaxSystem(apiURL);

            if (result.success) {
                setUploadProgress('Татварын системд амжилттай илгээгдлээ!');
                if (showAlert && typeof showAlert === 'function') {
                    showAlert(result.message || 'Татварын системд амжилттай илгээгдлээ');
                }
                // Line1 === Line2 үед алсын бааз рүү синк хийхгүй (илгээснээр мэдээ давхрахгүй)
                if (result.line1SameAsLine2) {
                    setUploadProgress('Татварт илгээгдлээ. Алсын бааз ажиллах баазтай ижил тул синк хийгдэхгүй.');
                    return;
                }
                // Line1 !== Line2 бол сүүлийн 3 хоногийн борлуулалтыг алсын сервер рүү синк
                if (api.getRemoteAllowed) {
                    try {
                        const allowedRes = await api.getRemoteAllowed();
                        if (allowedRes.success && allowedRes.allowed && api.syncAfterTax) {
                            setUploadProgress('Алсын сервер рүү синк хийж байна...');
                            const syncRes = await api.syncAfterTax();
                            if (syncRes.success && showAlert) {
                                const extra = syncRes.skipped
                                    ? ''
                                    : (syncRes.data ? ` (a_expenseG: ${syncRes.data.a_expenseG || 0}, a_expense: ${syncRes.data.a_expense || 0})` : '');
                                showAlert((syncRes.message || '') + extra);
                            } else if (!syncRes.success && showAlert) {
                                showAlert('Алсын синк: ' + (syncRes.error || 'алдаа'));
                            }
                        }
                    } catch (e) {
                        console.warn('syncAfterTax:', e);
                    }
                }
            } else {
                setUploadProgress('Алдаа: ' + (result.error || 'Тодорхойгүй алдаа'));
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Татварын системд илгээхэд алдаа гарлаа: ' + (result.error || 'Тодорхойгүй алдаа'));
                }
            }
        } catch (error) {
            setUploadProgress('Алдаа: ' + error.message);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Татварын системд илгээхэд алдаа гарлаа: ' + error.message);
            }
        } finally {
            setIsSendingToTax(false);
            setTimeout(() => setUploadProgress(''), 3000);
        }
    };

    const handleSyncMaterials = async () => {
        if (!api || !api.getRemoteAllowed || !api.syncMaterials) {
            if (showAlert) showAlert('API функц олдсонгүй');
            return;
        }
        try {
            const allowedRes = await api.getRemoteAllowed();
            if (!allowedRes.success || !allowedRes.allowed) {
                const msg = allowedRes.message || allowedRes.error || 'Line 1 ба Line 2 ижил эсвэл Line 2 тохируулаагүй. Бараа илгээх боломжгүй.';
                if (showAlert) showAlert(msg);
                return;
            }
            setIsSyncingMaterials(true);
            setUploadProgress('Барааны жагсаалт илгээж байна...');
            const bRegister = (typeof localStorage !== 'undefined' && localStorage.getItem) ? localStorage.getItem('b_register') : '';
            const bIdRaw = (typeof localStorage !== 'undefined' && localStorage.getItem) ? localStorage.getItem('b_id') : '';
            const bId = bIdRaw ? parseInt(bIdRaw, 10) : undefined;
            const result = await api.syncMaterials({ bRegister: bRegister || undefined, bId: !isNaN(bId) ? bId : undefined });
            if (result.success) {
                if (showAlert) showAlert(result.message || `Бараа ${result.data?.count || 0} мөр илгээгдлээ.`);
            } else {
                if (showAlert) showAlert('Бараа илгээхэд алдаа: ' + (result.error || ''));
            }
        } catch (error) {
            if (showAlert) showAlert('Бараа илгээхэд алдаа: ' + error.message);
        } finally {
            setIsSyncingMaterials(false);
            setTimeout(() => setUploadProgress(''), 3000);
        }
    };

    const handleDownloadUpdate = async () => {
        if (!api || !api.downloadAndExtractUpdate) {
            if (showAlert && typeof showAlert === 'function') {
                showAlert('API функц олдсонгүй');
            }
            return;
        }

        setIsDownloading(true);
        setDownloadProgress({ current: 0, total: 0 });
        setUploadProgress('Шинэчлэл татаж байна...');

        try {
            const ftpUrl = 'ftp://pos.baron.mn/UpdatePOS.zip';
            
            const result = await api.downloadAndExtractUpdate(
                ftpUrl,
                null, // appPath will be determined in main.js
                'enchbaatar',
                '6L06*r7mw',
                (stage, progress, total, fileName) => {
                    if (stage === 'download') {
                        setDownloadProgress({ current: progress, total: total });
                        setUploadProgress(`Шинэчлэл татаж байна... ${progress}%`);
                    } else if (stage === 'extract') {
                        setDownloadProgress({ current: progress, total: total });
                        setUploadProgress(`Шинэчлэл задлаж байна... ${progress}%${fileName ? ` - ${fileName}` : ''}`);
                    } else if (stage === 'complete') {
                        setDownloadProgress({ current: total, total: total });
                        setUploadProgress('Шинэчлэл амжилттай татагдлаа!');
                    }
                }
            );

            if (result.success) {
                setUploadProgress('Шинэчлэл амжилттай татагдлаа!');
                const fileCount = result.extractedFiles?.length || 0;
                if (showAlert && typeof showAlert === 'function') {
                    showAlert(`Шинэчлэл амжилттай татагдлаа!\n\n${fileCount} файл задлагдлаа.\n\nПрограмыг дахин ачааллана уу.`);
                }
            } else {
                setUploadProgress('Алдаа: ' + result.message);
                if (showAlert && typeof showAlert === 'function') {
                    showAlert('Шинэчлэл татахад алдаа гарлаа: ' + result.message);
                }
            }
        } catch (error) {
            setUploadProgress('Алдаа: ' + error.message);
            if (showAlert && typeof showAlert === 'function') {
                showAlert('Шинэчлэл татахад алдаа гарлаа: ' + error.message);
            }
        } finally {
            setIsDownloading(false);
            setTimeout(() => {
                setUploadProgress('');
                setDownloadProgress({ current: 0, total: 0 });
            }, 5000);
        }
    };

    if (!isOpen) return null;

    return (
        <>
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '560px', maxHeight: '85vh', overflowY: 'auto' }}>
                <div className="modal-header">
                    <div>
                        <h2 style={{ fontSize: '16px', margin: 0 }}>Тохиргоо</h2>
                        <p style={{ fontSize: '11px', color: '#6c757d', margin: '4px 0 0 0', lineHeight: 1.35 }}>
                            Хэсэг бүрийг ▶ дарж нээнэ. Эхний хэсэг анхнаасаа нээгдсэн байна.
                        </p>
                    </div>
                    <button className="modal-close" onClick={onClose} style={{ fontSize: '20px' }}>×</button>
                </div>
                
                <div className="modal-body" style={{ padding: '10px 12px 14px', fontSize: '13px' }}>
                    <SettingsCollapsible
                        title="Байгууллага ба татвар"
                        subtitle="Нэр, хаяг, Merchant TIN, хотын татвар, НӨАТ / бөөний төв"
                        defaultOpen={true}
                    >
                        <p style={{ fontSize: '12px', fontWeight: 600, margin: '0 0 8px', color: '#495057' }}>Үндсэн мэдээлэл</p>
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>Нэр <span>*</span></label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.name}
                                    onChange={(e) => setSettings({...settings, name: e.target.value.trim()})}
                                    placeholder="Байгууллагын нэр"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Имэйл</label>
                                <input
                                    type="email"
                                    className="form-input"
                                    value={settings.email}
                                    onChange={(e) => setSettings({...settings, email: e.target.value.trim()})}
                                    placeholder="Имэйл"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Утас</label>
                                <input
                                    type="tel"
                                    className="form-input"
                                    value={settings.phone}
                                    onChange={(e) => setSettings({...settings, phone: e.target.value.trim()})}
                                    placeholder="Утас"
                                />
                            </div>
                            <div className="settings-form-group" style={{ gridColumn: '1 / -1' }}>
                                <label>Хаяг</label>
                                <textarea
                                    className="form-input"
                                    value={settings.address}
                                    onChange={(e) => setSettings({...settings, address: e.target.value.trim()})}
                                    placeholder="Хаяг"
                                    rows="3"
                                    style={{ resize: 'vertical' }}
                                />
                            </div>
                        </div>
                        <p style={{ fontSize: '12px', fontWeight: 600, margin: '14px 0 8px', color: '#495057' }}>Татварын мэдээлэл</p>
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>Merchant TIN</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.merchantTin}
                                    onChange={(e) => setSettings({...settings, merchantTin: e.target.value.trim()})}
                                    placeholder="Merchant TIN"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Бүртгэлийн дугаар</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.registrationNumber}
                                    onChange={(e) => setSettings({...settings, registrationNumber: e.target.value.trim()})}
                                    onKeyPress={(e) => {
                                        if (e.key === 'Enter' && settings.registrationNumber && settings.registrationNumber.trim()) {
                                            handleGetMerchantTinFromRegistration(settings.registrationNumber);
                                        }
                                    }}
                                    placeholder="Бүртгэлийн дугаар (Enter дарахад Merchant TIN автоматаар тавигдана)"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Хотын татварын хувь (%)</label>
                                <input
                                    type="number"
                                    className="form-input"
                                    value={settings.cityTaxRate}
                                    onChange={(e) => setSettings({...settings, cityTaxRate: e.target.value})}
                                    placeholder="0.00"
                                    min="0"
                                    max="100"
                                    step="0.01"
                                />
                            </div>
                            <div className="settings-form-group">
                                <div className="settings-checkbox-group" onClick={() => setSettings({...settings, calculatesVAT: !settings.calculatesVAT})}>
                                    <input
                                        type="checkbox"
                                        checked={settings.calculatesVAT}
                                        onChange={(e) => setSettings({...settings, calculatesVAT: e.target.checked})}
                                    />
                                    <label>НӨАТ тооцдог</label>
                                </div>
                            </div>
                            <div className="settings-form-group">
                                <div className="settings-checkbox-group" onClick={() => setSettings({...settings, wholesaleCenter: !settings.wholesaleCenter})}>
                                    <input
                                        type="checkbox"
                                        checked={!!settings.wholesaleCenter}
                                        onChange={(e) => setSettings({...settings, wholesaleCenter: e.target.checked})}
                                    />
                                    <label>Бөөний төв (зарагдах тоо pcount-аас бага биш, price_big үед НХАТ тооцохгүй)</label>
                                </div>
                            </div>
                        </div>
                    </SettingsCollapsible>

                    <SettingsCollapsible
                        title="POS, дүүрэг"
                        subtitle="POS ID, салбар, дүүрэг/хороо (a_district), лавлагаа татах"
                    >
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>POS ID</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.posId}
                                    onChange={(e) => setSettings({...settings, posId: e.target.value.trim()})}
                                    placeholder="POS ID"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Салбарын дугаар</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.branchNo}
                                    onChange={(e) => setSettings({...settings, branchNo: e.target.value.trim()})}
                                    placeholder="Салбарын дугаар"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Дүүрэг, хорооны код (a_district)</label>
                                <div style={{ display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' }}>
                                    <select
                                        className="form-input"
                                        style={{ flex: '1', minWidth: '200px' }}
                                        disabled={districtListLoading || districtSyncing}
                                        value={settings.districtCode}
                                        onChange={(e) => setSettings({ ...settings, districtCode: e.target.value })}
                                    >
                                        <option value="">— Сонгох —</option>
                                        {districtList.map((d) => (
                                            <option key={d.code} value={d.code}>
                                                {d.name && d.name !== d.code ? `${d.code} — ${d.name}` : d.code}
                                            </option>
                                        ))}
                                        {settings.districtCode &&
                                            !districtList.some((d) => d.code === settings.districtCode) && (
                                                <option value={settings.districtCode}>
                                                    {settings.districtCode} (хуучин/жагсаалтад байхгүй)
                                                </option>
                                            )}
                                    </select>
                                    <button
                                        type="button"
                                        className="form-input"
                                        style={{ cursor: districtSyncing ? 'wait' : 'pointer', whiteSpace: 'nowrap' }}
                                        disabled={districtSyncing || districtListLoading || !api || !api.syncDistrictsFromFinance}
                                        onClick={() => runDistrictCatalogSync()}
                                    >
                                        {districtSyncing ? 'Татаж байна…' : 'Лавлагаа татах'}
                                    </button>
                                </div>
                                {districtSyncBanner && districtSyncBanner.status === 'loading' && (
                                    <div
                                        style={{
                                            marginTop: '10px',
                                            padding: '12px 14px',
                                            background: '#e8f4fc',
                                            border: '1px solid #2196f3',
                                            borderRadius: '8px',
                                            color: '#0d47a1',
                                            fontSize: '14px'
                                        }}
                                    >
                                        <strong>Түр хүлээнэ үү.</strong> Аймаг, дүүргийн лавлагаа (<code>a_district</code>)
                                        серверээс татаж байна…
                                    </div>
                                )}
                                {districtSyncBanner && districtSyncBanner.status === 'ok' && (
                                    <div
                                        style={{
                                            marginTop: '10px',
                                            padding: '12px 14px',
                                            background: '#e8f5e9',
                                            border: '1px solid #43a047',
                                            borderRadius: '8px',
                                            color: '#1b5e20',
                                            fontSize: '14px'
                                        }}
                                    >
                                        <strong>{districtSyncBanner.text}</strong>
                                    </div>
                                )}
                                {districtSyncBanner && districtSyncBanner.status === 'err' && (
                                    <div
                                        style={{
                                            marginTop: '10px',
                                            padding: '12px 14px',
                                            background: '#ffebee',
                                            border: '1px solid #e53935',
                                            borderRadius: '8px',
                                            color: '#b71c1c',
                                            fontSize: '14px'
                                        }}
                                    >
                                        <strong>Алдаа.</strong> {districtSyncBanner.text}
                                    </div>
                                )}
                                {districtListLoading && (
                                    <span style={{ fontSize: '12px', color: '#666' }}>Жагсаалт ачаалж байна…</span>
                                )}
                            </div>
                        </div>
                    </SettingsCollapsible>

                    <SettingsCollapsible
                        title="Систем ба QPay"
                        subtitle="Татварын системийн URL, лот, илгээх цаг, QPay холболт"
                    >
                        <p style={{ fontSize: '12px', fontWeight: 600, margin: '0 0 8px', color: '#495057' }}>Системийн тохиргоо</p>
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>Tax System URL</label>
                                <input
                                    type="url"
                                    className="form-input"
                                    value={settings.taxSystemURL}
                                    onChange={(e) => setSettings({...settings, taxSystemURL: e.target.value.trim()})}
                                    placeholder="http://..."
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Лот тоо</label>
                                <input
                                    type="number"
                                    className="form-input"
                                    value={settings.lotNumber}
                                    onChange={(e) => setSettings({...settings, lotNumber: e.target.value.trim()})}
                                    placeholder="Лот тоо"
                                    min="0"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Илгээх цаг</label>
                                <input
                                    type="time"
                                    className="form-input"
                                    value={settings.sendTime}
                                    onChange={(e) => setSettings({...settings, sendTime: e.target.value.trim()})}
                                    placeholder="Илгээх цаг"
                                />
                            </div>
                        </div>
                        <p style={{ fontSize: '12px', fontWeight: 600, margin: '14px 0 8px', color: '#495057' }}>QPay</p>
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>QPay Client ID</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.qpayClientId}
                                    onChange={(e) => setSettings({...settings, qpayClientId: e.target.value.trim()})}
                                    placeholder="QPay Client ID"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>QPay Client Secret</label>
                                <input
                                    type="password"
                                    className="form-input"
                                    value={settings.qpayClientSecret}
                                    onChange={(e) => setSettings({...settings, qpayClientSecret: e.target.value.trim()})}
                                    placeholder="QPay Client Secret"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Invoice code</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.qpayInvoiceCode}
                                    onChange={(e) => setSettings({...settings, qpayInvoiceCode: e.target.value.trim()})}
                                    placeholder="QPAY"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Receiver code</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.qpayInvoiceReceiverCode}
                                    onChange={(e) => setSettings({...settings, qpayInvoiceReceiverCode: e.target.value.trim()})}
                                    placeholder="terminal"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Callback URL</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.qpayCallbackUrl}
                                    onChange={(e) => setSettings({...settings, qpayCallbackUrl: e.target.value.trim()})}
                                    placeholder="https://your-domain.com/qpay/callback"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>QPay API URL</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.qpayApiUrl}
                                    onChange={(e) => setSettings({...settings, qpayApiUrl: e.target.value.trim()})}
                                    placeholder="https://merchant.qpay.mn"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>QPay simple invoice</label>
                                <div className="settings-checkbox-group">
                                    <input
                                        type="checkbox"
                                        checked={!!settings.qpaySimpleInvoice}
                                        onChange={(e) => setSettings({...settings, qpaySimpleInvoice: e.target.checked})}
                                    />
                                    <label>Receiver info/linesгүй invoice илгээх</label>
                                </div>
                            </div>
                        </div>
                    </SettingsCollapsible>

                    <SettingsCollapsible
                        title="Тайлан"
                        subtitle="Явуулах тайлангууд, устгах эрх, тайлан гаргах / хэвлэх / Excel"
                    >
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>Лавлагаанд харагдах тайлангууд</label>
                                <div className="settings-checkbox-group" style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={!!settings.reportDailyCashcode}
                                            onChange={(e) => setSettings({ ...settings, reportDailyCashcode: e.target.checked })}
                                        />
                                        Өдрийн тайлан (cashcode)
                                    </label>
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={!!settings.reportDailyPayment}
                                            onChange={(e) => setSettings({ ...settings, reportDailyPayment: e.target.checked })}
                                        />
                                        Өдрийн тайлан (Төлбөрийн төрлөөр)
                                    </label>
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={!!settings.reportDailyTax}
                                            onChange={(e) => setSettings({ ...settings, reportDailyTax: e.target.checked })}
                                        />
                                        Өдрийн тайлан (Татвар)
                                    </label>
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={!!settings.reportSummary}
                                            onChange={(e) => setSettings({ ...settings, reportSummary: e.target.checked })}
                                        />
                                        Хураангуй тайлан
                                    </label>
                                </div>
                            </div>
                        </div>
                        <p style={{ fontSize: '12px', fontWeight: 600, margin: '14px 0 8px', color: '#495057' }}>Устгах эрх</p>
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>Энэ дэлгүүрт сагснаас бараа устгах / тоо бууруулах</label>
                                <select
                                    className="form-input"
                                    value={settings.allowDelete === true ? 'true' : settings.allowDelete === false ? 'false' : 'server'}
                                    onChange={(e) => {
                                        const v = e.target.value;
                                        setSettings({ ...settings, allowDelete: v === 'server' ? null : v === 'true' });
                                    }}
                                >
                                    <option value="server">Server.txt-ийн дагуу</option>
                                    <option value="true">Тийм (эрх олгох)</option>
                                    <option value="false">Үгүй (эрхгүй)</option>
                                </select>
                                <span style={{ fontSize: '11px', color: '#6c757d' }}>Нэг дэлгүүрт л устгах ажиллахгүй бол энд &quot;Тийм&quot; сонгоно.</span>
                            </div>
                        </div>
                        <p style={{ fontSize: '12px', fontWeight: 600, margin: '14px 0 8px', color: '#495057' }}>Тайлан ажиллуулах</p>
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>Тайлан сонгох</label>
                                <select
                                    className="form-input"
                                    value={reportType}
                                    onChange={(e) => setReportType(e.target.value)}
                                >
                                    {getReportOptions().map(option => (
                                        <option key={option.value} value={option.value}>{option.label}</option>
                                    ))}
                                </select>
                            </div>
                            {reportType === 'TOP_N_PRODUCTS' && (
                                <div className="settings-form-group">
                                    <label>Top N (тоо)</label>
                                    <input
                                        type="number"
                                        min={1}
                                        className="form-input"
                                        value={reportTopN}
                                        onChange={(e) => setReportTopN(Math.max(1, parseInt(e.target.value, 10) || 10))}
                                    />
                                </div>
                            )}
                            <div className="settings-form-group">
                                <label>Эхлэх огноо/цаг</label>
                                <input
                                    type="datetime-local"
                                    className="form-input"
                                    value={reportStart}
                                    onChange={(e) => setReportStart(e.target.value)}
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Дуусах огноо/цаг</label>
                                <input
                                    type="datetime-local"
                                    className="form-input"
                                    value={reportEnd}
                                    onChange={(e) => setReportEnd(e.target.value)}
                                />
                            </div>
                        </div>
                        <div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
                            <button className="btn btn-primary" onClick={runReport} disabled={reportLoading}>
                                {reportLoading ? 'Тайлан гаргаж байна...' : 'Ажиллуулах'}
                            </button>
                            <button className="btn btn-secondary" onClick={printReport} disabled={!reportPreviewHtml}>
                                Хэвлэх
                            </button>
                            <button className="btn btn-secondary" onClick={exportReportToExcel} disabled={!reportSummary}>
                                Excel руу хөрвүүлэх
                            </button>
                        </div>
                        {reportError && (
                            <div style={{ marginTop: '8px', color: '#e74c3c', fontSize: '12px' }}>
                                {reportError}
                            </div>
                        )}
                        {reportPreviewHtml && (
                            <div style={{ marginTop: '12px', border: '1px solid #dee2e6', borderRadius: '4px', padding: '8px', maxHeight: '360px', overflowY: 'auto' }}>
                                <div dangerouslySetInnerHTML={{ __html: reportPreviewHtml }} />
                            </div>
                        )}
                    </SettingsCollapsible>

                    <SettingsCollapsible
                        title="Server.txt"
                        subtitle="POS №, баримтын өргөн, термаль горим, хэвлэгчийн нэрс"
                    >
                        <div className="settings-grid">
                            <div className="settings-form-group">
                                <label>POS дугаар (3-р мөр)</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.serverPosNo}
                                    onChange={(e) => setSettings({...settings, serverPosNo: e.target.value.trim()})}
                                    placeholder="POS дугаар"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Баримтын өргөн (5-р мөр)</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.serverReceiptWidth}
                                    onChange={(e) => setSettings({...settings, serverReceiptWidth: e.target.value.trim()})}
                                    placeholder="80, 58, 56, 54, 52, 50, 46, 40 эсвэл 36"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>6-р мөр (муу термаль: weak, low, muu, thermal, bad эсвэл 2)</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.serverLine6}
                                    onChange={(e) => setSettings({...settings, serverLine6: e.target.value.trim()})}
                                    placeholder="weak — нарийн хэвлэгчид том фонт/QR"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>ПОС-н хэвлэгч (10-р мөр)</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.serverPosPrinter}
                                    onChange={(e) => setSettings({...settings, serverPosPrinter: e.target.value.trim()})}
                                    placeholder="ПОС-н хэвлэгч"
                                />
                            </div>
                            <div className="settings-form-group">
                                <label>Гал тогооны хэвлэгч (11-р мөр)</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    value={settings.serverKitchenPrinter}
                                    onChange={(e) => setSettings({...settings, serverKitchenPrinter: e.target.value.trim()})}
                                    placeholder="Гал тогооны хэвлэгч"
                                />
                            </div>
                        </div>
                    </SettingsCollapsible>

                    <SettingsCollapsible title="Бусад" subtitle="Бараа, баримт хайх, QPay тайлан">
                        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                            {onMaterialClick && (
                                <button
                                    onClick={() => {
                                        onClose();
                                        if (onMaterialClick) onMaterialClick();
                                    }}
                                    style={{
                                        flex: 1,
                                        padding: '10px 16px',
                                        background: '#9b59b6',
                                        color: 'white',
                                        border: 'none',
                                        borderRadius: '4px',
                                        cursor: 'pointer',
                                        fontSize: '14px',
                                        minWidth: '120px',
                                        fontWeight: 'bold'
                                    }}
                                >
                                    📦 Бараа
                                </button>
                            )}
                            <button
                                onClick={() => {
                                    if (window.onOpenReceiptSearch && typeof window.onOpenReceiptSearch === 'function') {
                                        window.onOpenReceiptSearch();
                                    }
                                }}
                                style={{
                                    flex: 1,
                                    padding: '10px 16px',
                                    background: '#16a085',
                                    color: 'white',
                                    border: 'none',
                                    borderRadius: '4px',
                                    cursor: 'pointer',
                                    fontSize: '14px',
                                    minWidth: '120px',
                                    fontWeight: 'bold'
                                }}
                            >
                                🔍 Баримт хайх
                            </button>
                            <button
                                type="button"
                                onClick={() => setShowQPayReportSection(prev => !prev)}
                                style={{
                                    flex: 1,
                                    padding: '10px 16px',
                                    background: '#2c7be5',
                                    color: 'white',
                                    border: 'none',
                                    borderRadius: '4px',
                                    cursor: 'pointer',
                                    fontSize: '14px',
                                    minWidth: '120px',
                                    fontWeight: 'bold'
                                }}
                            >
                                📊 QPay Report {showQPayReportSection ? '(хаах)' : ''}
                            </button>
                        </div>
                        {showQPayReportSection && typeof window.QPayReportModal === 'function' && (
                            <window.QPayReportModal
                                embed
                                selectedCompany={selectedCompany}
                                showAlert={showAlert}
                            />
                        )}
                    </SettingsCollapsible>
                </div>

                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={onClose} disabled={isUploading || isSendingToTax || isSyncingMaterials || isDownloading}>
                        Цуцлах
                    </button>
                    <button 
                        className="btn btn-primary" 
                        onClick={handleSave}
                        disabled={isUploading || isSendingToTax || isSyncingMaterials || isDownloading}
                        style={{ marginRight: '10px' }}
                    >
                        Хадгалах
                    </button>
                    <button 
                        className="btn btn-primary" 
                        onClick={handleDownloadUpdate}
                        disabled={isUploading || isSendingToTax || isSyncingMaterials || isDownloading}
                        style={{ backgroundColor: '#ffc107', color: '#000', marginRight: '10px' }}
                    >
                        {isDownloading ? 'Татаж байна...' : 'Шинэчлэл татах'}
                    </button>
                    <button 
                        className="btn btn-primary" 
                        onClick={handleSendToTaxSystem}
                        disabled={isUploading || isSendingToTax || isDownloading || !selectedCompany?.apiURL}
                        style={{ backgroundColor: '#17a2b8', marginRight: '10px' }}
                    >
                        {isSendingToTax ? 'Илгээж байна...' : 'Татварын системд илгээх'}
                    </button>
                    <button 
                        className="btn btn-primary" 
                        onClick={handleSyncMaterials}
                        disabled={isUploading || isSendingToTax || isSyncingMaterials || isDownloading}
                        style={{ backgroundColor: '#6f42c1', marginRight: '10px' }}
                        title="server.txt Line 1 ≠ Line 2 үед л идэвхтэй. Нийт бараа (m_id, m_name, mcost, price_low, nodiscount, pcount) алсын сервер рүү илгээнэ."
                    >
                        {isSyncingMaterials ? 'Илгээж байна...' : 'Бараа илгээх'}
                    </button>
                    {showCreateUpdateButton && (
                        <button 
                            className="btn btn-primary" 
                            onClick={handleCreateUpdate}
                            disabled={isUploading || isSendingToTax || isSyncingMaterials || isDownloading}
                            style={{ backgroundColor: '#28a745' }}
                        >
                            {isUploading ? 'Хадгалж байна...' : 'Шинэчлэл хадгалах'}
                        </button>
                    )}
                </div>
                {uploadProgress && (
                    <div style={{ padding: '10px', textAlign: 'center', color: (isUploading || isSendingToTax || isSyncingMaterials || isDownloading || districtSyncing) ? '#007bff' : '#28a745', fontSize: '12px' }}>
                        {uploadProgress}
                        {isDownloading && downloadProgress.total > 0 && (
                            <div style={{ marginTop: '5px' }}>
                                <div style={{ width: '100%', backgroundColor: '#e0e0e0', borderRadius: '4px', height: '8px', overflow: 'hidden' }}>
                                    <div style={{ 
                                        width: `${(downloadProgress.current / downloadProgress.total) * 100}%`, 
                                        backgroundColor: '#007bff', 
                                        height: '100%', 
                                        transition: 'width 0.3s' 
                                    }}></div>
                                </div>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
        {/* Баримт хайх Modal - шилжүүлсэн ReceiptSearchModal-д */}
    </>
    );
}

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

