document.getElementById('scan-btn').addEventListener('click', function() {
    const btn = this;
    const resultDiv = document.getElementById('result');
    
    // إخفاء الزر وإظهار حاوية الكاميرا
    btn.style.display = 'none';
    resultDiv.style.display = 'none';

    // تشغيل الكاميرا
    const html5QrCode = new Html5Qrcode("reader");
    const config = { fps: 10, qrbox: { width: 250, height: 250 } };

    html5QrCode.start(
        { facingMode: "environment" }, // استخدام الكاميرا الخلفية
        config,
        (decodedText) => {
            // عند نجاح المسح
            html5QrCode.stop().then(() => {
                resultDiv.style.display = 'block';
                resultDiv.innerHTML = `<p>تم المسح بنجاح!</p><p>${decodedText}</p>`;
                
                // إعادة إظهار الزر
                btn.style.display = 'block';
                btn.innerHTML = '<i class="fas fa-camera"></i> مسح باركود آخر';
            }).catch(err => console.error("خطأ في إيقاف الكاميرا", err));
        },
        (errorMessage) => {
            // تجاهل أخطاء المسح المستمرة
        }
    ).catch(err => {
        // في حال رفض إذن الكاميرا
        resultDiv.style.display = 'block';
        resultDiv.innerHTML = `<p style="color:red;">تعذر فتح الكاميرا. تأكد من السماح للمتصفح بالوصول للكاميرا.</p>`;
        btn.style.display = 'block';
    });
});
