<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Barcode Scanner Detector - Back Camera</title>
<style>
  video {
    width: 300px;
    height: 100px;
    /* max-width: 600px; */
    margin: auto;
    display: block;
  }
</style>
</head>
<body>
  <h1>Barcode Scanner Detector - Back Camera</h1>
  <button id="start-scan-btn">Start Scan</button>
  <video id="barcode-scanner" autoplay playsinline></video>

  <form id="barcode-form">
    <label for="barcodeInput">Detected Barcode:</label>
    <input type="text" id="barcodeInput" name="barcode" readonly>
  </form>

  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const video = document.getElementById('barcode-scanner');
      const barcodeInput = document.getElementById('barcodeInput');
      const startScanButton = document.getElementById('start-scan-btn');
      let stream = null; // To store the camera stream

      startScanButton.addEventListener('click', async () => {
        try {
          stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
          video.srcObject = stream;

          video.addEventListener('loadedmetadata', () => {
            video.play();
            detectBarcode();
          });
        } catch (error) {
          console.error('Error accessing camera:', error);
        }
      });

      async function detectBarcode() {
        const barcodeDetector = new BarcodeDetector();
        
        try {
          const barcodes = await barcodeDetector.detect(video);
          if (barcodes.length > 0) {
            const detectedBarcode = barcodes[0].rawValue;
            barcodeInput.value = detectedBarcode;
            // Close the camera stream
            closeCamera();
          } else {
            setTimeout(detectBarcode, 200); // Check again after 200ms
          }
        } catch (error) {
          console.error('Barcode detection error:', error);
        }
      }

      function closeCamera() {
        if (stream) {
          const tracks = stream.getTracks();
          tracks.forEach(track => track.stop());
          video.srcObject = null;
        }
      }
    });
  </script>
</body>
</html>
