function LabelPrintCenter() {
    const { products, formatLKR } = window.MockData;
    const [selectedProduct, setSelectedProduct] = React.useState(null);
    const [selectedVariations, setSelectedVariations] = React.useState({});
    const [searchTerm, setSearchTerm] = React.useState('');
    const [printPreview, setPrintPreview] = React.useState(false);
    const [labelConfig, setLabelConfig] = React.useState({ width: 58, height: 40 });

    // Filter products
    const filteredProducts = products.filter(p => 
        p.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
        p.variations.some(v => v.sku.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    const handleProductSelect = (product) => {
        setSelectedProduct(product);
        // Reset selections
        const initialSelections = {};
        product.variations.forEach(v => {
            initialSelections[v.id] = { ...v, printQty: 1, selected: false };
        });
        setSelectedVariations(initialSelections);
        setPrintPreview(false);
    };

    const toggleVariation = (id) => {
        setSelectedVariations(prev => ({
            ...prev,
            [id]: { ...prev[id], selected: !prev[id].selected }
        }));
    };

    const updatePrintQty = (id, qty) => {
        if (qty < 1) return;
        setSelectedVariations(prev => ({
            ...prev,
            [id]: { ...prev[id], printQty: parseInt(qty) }
        }));
    };

    const handlePrint = async () => {
        const printArea = document.getElementById('print-area');
        const receiptArea = document.getElementById('receipt-print-area');
        
        if (!printArea) {
             console.error('Print area not found');
             return;
        }
        
        // 1. Prepare DOM
        // Clear BOTH areas to prevent overlap
        printArea.innerHTML = ''; 
        if (receiptArea) receiptArea.innerHTML = '';

        // Add class to body to target print styles exclusively for labels
        document.body.classList.remove('printing-receipt');
        document.body.classList.add('printing-labels');

        const itemsToPrint = Object.values(selectedVariations).filter(v => v.selected);
        
        if (itemsToPrint.length === 0) {
            await window.AppDialog.alert('No Selection', 'Please select at least one variation to print.', 'warning');
            return;
        }

        // 2. Generate Label HTML - collect all labels first, then mark page breaks
        const labelList = [];
        const barcodeTasks = [];
        let labelCounter = 0; // Use a reliable incrementing counter for unique IDs

        itemsToPrint.forEach(item => {
            for (let i = 0; i < item.printQty; i++) {
                // Use counter (not Date.now) to guarantee uniqueness within a single print job
                const uniqueId = `bc_${item.id.replace(/[^a-zA-Z0-9]/g, '_')}_${labelCounter++}`;
                barcodeTasks.push({ id: uniqueId, value: item.barcode });
                labelList.push({ uniqueId, item });
            }
        });

        // Build HTML: all labels except the last get page-break-after: always
        let batchHtml = `
            <style>
                @media print {
                    .label-container {
                        width: ${labelConfig.width}mm !important;
                        height: ${labelConfig.height - 0.5}mm !important;
                    }
                }
            </style>
        `;
        labelList.forEach((entry, idx) => {
            const { uniqueId, item } = entry;
            const isLast = idx === labelList.length - 1;
            batchHtml += `
                <div class="label-container${isLast ? '' : ' label-break'}">
                    <div class="label-store">NOAHVELLE</div>
                    <div class="label-product">${selectedProduct.name.substring(0, 22)}</div>
                    <div class="label-meta">
                        <span>Size: <b>${item.size}</b></span>
                        ${item.color && item.color !== 'N/A' ? `<span> &bull; ${item.color.substring(0, 8)}</span>` : ''}
                    </div>
                    <div class="label-price">${formatLKR(selectedProduct.price)}</div>
                    <svg class="label-barcode" id="${uniqueId}"></svg>
                    <div class="label-sku">${item.sku}</div>
                </div>
            `;
        });

        printArea.innerHTML = batchHtml;

        // 3. Render Barcodes
        setTimeout(async () => {
            try {
                const barcodeLib = window.JsBarcode || (typeof JsBarcode !== 'undefined' ? JsBarcode : null);
                
                if (barcodeLib) {
                    barcodeTasks.forEach(task => {
                        try {
                            barcodeLib(`#${task.id}`, task.value, {
                                format: "CODE128",
                                width: labelConfig.width > 60 ? 2.5 : (labelConfig.width < 50 ? 1.5 : 2),
                                height: labelConfig.height > 40 ? 45 : (labelConfig.height < 35 ? 25 : 35),
                                displayValue: false,
                                margin: 0,
                                textMargin: 0,
                                flat: true
                            });
                        } catch (err) {
                            console.error(`Failed to render barcode for ${task.id}`, err);
                        }
                    });
                } else {
                    await window.AppDialog.alert('Not Ready', 'Barcode library not ready. Please reload the page.', 'warning');
                    return;
                }
                
                // 4. Trigger Print Dialog
                setTimeout(() => {
                    const totalLabelCount = itemsToPrint.reduce((sum, item) => sum + item.printQty, 0);
                    if (window.setupPrintConfig) window.setupPrintConfig('label', totalLabelCount);
                    window.print();
                    setTimeout(() => document.body.classList.remove('printing-labels'), 1000);
                }, 500);

            } catch (e) {
                console.error("Barcode rendering error", e);
            }
        }, 100);

        // Update local stats
        itemsToPrint.forEach(item => {
            item.printedLabelCount += item.printQty;
        });
    };

    const totalLabels = Object.values(selectedVariations)
        .filter(v => v.selected)
        .reduce((sum, v) => sum + v.printQty, 0);

    return (
        <div className="space-y-6">
            <h2 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                <span className="icon-printer text-[var(--primary)]"></span>
                Barcode Label Print Center
            </h2>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* 1. Product Selection */}
                <div className="card lg:col-span-1 h-[calc(100vh-12rem)] flex flex-col">
                    <h3 className="font-bold text-gray-700 mb-4">1. Select Product</h3>
                    <div className="relative mb-4">
                        <span className="icon-search absolute left-3 top-2.5 text-gray-400"></span>
                        <input 
                            type="text" 
                            placeholder="Search products..." 
                            className="input-field pl-10"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                    <div className="flex-1 overflow-y-auto space-y-2 pr-2">
                        {filteredProducts.map(p => (
                            <div 
                                key={p.id} 
                                onClick={() => handleProductSelect(p)}
                                className={`p-3 rounded-lg border cursor-pointer transition-all flex items-center gap-3 ${
                                    selectedProduct?.id === p.id 
                                    ? 'border-[var(--primary)] bg-emerald-50 shadow-sm' 
                                    : 'border-gray-200 hover:bg-gray-50'
                                }`}
                            >
                                <img src={p.image} className="w-10 h-10 rounded bg-gray-200 object-cover" />
                                <div className="min-w-0">
                                    <p className="text-sm font-medium text-gray-900 truncate">{p.name}</p>
                                    <p className="text-xs text-gray-500">{p.category}</p>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* 2. Variation Selection & Configuration */}
                <div className="card lg:col-span-2 flex flex-col">
                    <h3 className="font-bold text-gray-700 mb-4">2. Configure Labels {selectedProduct && `for ${selectedProduct.name}`}</h3>
                    
                    {!selectedProduct ? (
                        <div className="flex-1 flex flex-col items-center justify-center text-gray-400 border-2 border-dashed border-gray-200 rounded-lg">
                            <span className="icon-tag text-4xl mb-2"></span>
                            <p>Select a product to generate labels</p>
                        </div>
                    ) : (
                        <>
                            <div className="overflow-x-auto mb-6">
                                <table className="w-full text-left text-sm">
                                    <thead className="bg-gray-50 text-gray-600 font-semibold">
                                        <tr>
                                            <th className="px-4 py-3 w-10">
                                                <input type="checkbox" className="rounded" 
                                                    onChange={(e) => {
                                                        const checked = e.target.checked;
                                                        const newSels = { ...selectedVariations };
                                                        Object.keys(newSels).forEach(k => newSels[k].selected = checked);
                                                        setSelectedVariations(newSels);
                                                    }}
                                                />
                                            </th>
                                            <th className="px-4 py-3">Variant</th>
                                            <th className="px-4 py-3">SKU</th>
                                            <th className="px-4 py-3">Barcode</th>
                                            <th className="px-4 py-3">Copies</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-100">
                                        {Object.values(selectedVariations).map(v => (
                                            <tr key={v.id} className={v.selected ? 'bg-blue-50/30' : ''}>
                                                <td className="px-4 py-3">
                                                    <input 
                                                        type="checkbox" 
                                                        checked={v.selected}
                                                        onChange={() => toggleVariation(v.id)}
                                                        className="rounded text-[var(--primary)] focus:ring-[var(--primary)]"
                                                    />
                                                </td>
                                                <td className="px-4 py-3">
                                                    <span className="font-medium text-gray-900">{v.size}</span>
                                                    {v.color && <span className="text-gray-500 ml-2">({v.color})</span>}
                                                </td>
                                                <td className="px-4 py-3 font-mono text-xs">{v.sku}</td>
                                                <td className="px-4 py-3 font-mono text-xs">{v.barcode}</td>
                                                <td className="px-4 py-3">
                                                    <div className="flex items-center gap-2">
                                                        <button 
                                                            className="w-6 h-6 rounded bg-gray-100 hover:bg-gray-200 flex items-center justify-center"
                                                            onClick={() => updatePrintQty(v.id, v.printQty - 1)}
                                                        >-</button>
                                                        <input 
                                                            type="number" 
                                                            value={v.printQty}
                                                            onChange={(e) => updatePrintQty(v.id, e.target.value)}
                                                            className="w-12 text-center border rounded py-0.5 text-sm"
                                                        />
                                                        <button 
                                                            className="w-6 h-6 rounded bg-gray-100 hover:bg-gray-200 flex items-center justify-center"
                                                            onClick={() => updatePrintQty(v.id, v.printQty + 1)}
                                                        >+</button>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>

                            <div className="mt-auto border-t border-gray-100 pt-6 flex justify-between items-center">
                                <div>
                                    <p className="text-sm text-gray-600">
                                        Total Labels to Print: <span className="font-bold text-gray-900 text-lg">{totalLabels}</span>
                                    </p>
                                    <div className="flex items-center gap-2 mt-1">
                                        <span className="text-xs text-gray-500">Printer Size:</span>
                                        <select 
                                            className="text-xs border border-gray-300 rounded p-1 bg-white"
                                            value={`${labelConfig.width}x${labelConfig.height}`}
                                            onChange={(e) => {
                                                const [w, h] = e.target.value.split('x');
                                                setLabelConfig({ width: parseInt(w), height: parseInt(h) });
                                            }}
                                        >
                                            <option value="58x40">Standard XP (58mm x 40mm)</option>
                                            <option value="50x30">Medium (50mm x 30mm)</option>
                                            <option value="40x30">Small (40mm x 30mm)</option>
                                            <option value="80x50">Large (80mm x 50mm)</option>
                                        </select>
                                    </div>
                                </div>
                                <div className="flex gap-3">
                                    <button 
                                        className="btn btn-secondary"
                                        onClick={() => setPrintPreview(!printPreview)}
                                    >
                                        {printPreview ? 'Hide Preview' : 'Show Preview'}
                                    </button>
                                    <button 
                                        className="btn btn-primary shadow-lg shadow-emerald-500/20"
                                        onClick={handlePrint}
                                        disabled={totalLabels === 0}
                                    >
                                        <span className="icon-printer mr-2"></span>
                                        Print Labels
                                    </button>
                                </div>
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* Label Preview Section */}
            {printPreview && selectedProduct && totalLabels > 0 && (
                <div className="card bg-gray-800 border-gray-700 text-white animate-fade-in">
                    <h3 className="font-bold text-gray-300 mb-4 flex items-center gap-2">
                        <span className="icon-eye"></span> Print Preview (Scale 1:1 on Screen)
                    </h3>
                    <div className="flex flex-wrap gap-4 justify-center bg-gray-900 p-8 rounded-lg overflow-hidden">
                        {/* Simulation of one label */}
                        <div className="bg-white text-black w-[219px] h-[151px] p-1 flex flex-col items-center justify-center relative shadow-xl transform scale-125 origin-center">
                            <div className="text-[10px] font-bold uppercase mb-[1px] text-center w-full">NOAHVELLE</div>
                            <div className="text-[12px] font-bold text-center leading-none mb-[2px] w-full truncate">{selectedProduct.name}</div>
                            <div className="text-[9px] mb-0">Size: <b>{Object.values(selectedVariations).find(v => v.selected)?.size || 'M'}</b></div>
                            <div className="text-[11px] font-extrabold">{formatLKR(selectedProduct.price)}</div>
                            <div className="w-[90%] h-[35px] bg-black my-1 opacity-20 relative">
                                <span className="absolute inset-0 flex items-center justify-center text-xs text-white">BARCODE SVG</span>
                            </div>
                            <div className="text-[8px] font-mono">20260401</div>
                        </div>
                    </div>
                    <p className="text-center text-xs text-gray-400 mt-4">Preview shows layout structure. Actual barcode lines will be generated during print.</p>
                </div>
            )}
        </div>
    );
}