{% extends "base.html" %}
{% block content %}
<div class="max-w-lg mx-auto space-y-6">
  <div class="bg-white rounded-lg shadow-md p-6 text-center">
    <h1 class="text-2xl font-garamond font-bold text-irish-green mb-3">Scan QR Code</h1>
    <p class="text-gray-600 mb-6">Position the QR code from your quiz master in the camera view</p>
    
    <!-- QR Scanner Container -->
    <div class="relative bg-black rounded-lg overflow-hidden" style="height: 300px;">
      <div id="qr-reader" class="w-full h-full"></div>
      <div id="scanner-overlay" class="absolute inset-0 flex items-center justify-center">
        <div class="text-white">
          <i class="fas fa-camera text-4xl mb-2 opacity-70"></i>
          <p>Camera loading...</p>
        </div>
      </div>
    </div>
    
    <div class="mt-4 text-sm text-gray-500">
      Make sure the QR code is well-lit and clearly visible
    </div>

    <!-- Camera Selection Dropdown -->
    <div class="mt-4">
      <label for="camera-select" class="block text-sm font-medium text-gray-700">Select Camera:</label>
      <select id="camera-select" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-irish-green focus:border-irish-green sm:text-sm rounded-md">
        <option value="">Loading cameras...</option>
      </select>
    </div>
    
    <!-- Manual Entry Fallback -->
    <div class="mt-8 border-t pt-6">
      <h3 class="font-bold mb-3">Or enter code manually</h3>
      <form action="/redeem/manual" method="post" class="flex">
        <input type="text" name="code" placeholder="Enter code here" required
            class="flex-grow border border-gray-300 rounded-l-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-irish-green">
        <button type="submit" class="bg-irish-green text-white px-4 py-2 rounded-r-md">Submit</button>
      </form>
    </div>
  </div>
  
  <!-- How It Works -->
  <div class="bg-white rounded-lg shadow-md p-6">
    <h3 class="text-xl font-semibold font-garamond text-irish-green mb-4">How It Works</h3>
    <div class="space-y-4">
      <div class="flex items-start">
        <div class="bg-cream-white p-2 rounded-full mr-3 mt-1">
          <span class="w-6 h-6 flex items-center justify-center text-irish-green font-bold">1</span>
        </div>
        <div>
          <p class="font-medium">Scan QR Code</p>
          <p class="text-gray-600 text-sm">Scan the QR code provided by your quiz master.</p>
        </div>
      </div>
      
      <div class="flex items-start">
        <div class="bg-cream-white p-2 rounded-full mr-3 mt-1">
          <span class="w-6 h-6 flex items-center justify-center text-irish-green font-bold">2</span>
        </div>
        <div>
          <p class="font-medium">Select Your Team</p>
          <p class="text-gray-600 text-sm">Choose which team should receive these points.</p>
        </div>
      </div>
      
      <div class="flex items-start">
        <div class="bg-cream-white p-2 rounded-full mr-3 mt-1">
          <span class="w-6 h-6 flex items-center justify-center text-irish-green font-bold">3</span>
        </div>
        <div>
          <p class="font-medium">Climb the Leaderboard</p>
          <p class="text-gray-600 text-sm">Watch your team rise in the rankings!</p>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Back Link -->
  <div class="text-center">
    <a href="/dashboard" class="text-irish-green hover:underline">
      <i class="fas fa-arrow-left mr-1"></i> Back to Dashboard
    </a>
  </div>
</div>

<!-- HTML5 QR Code Scanner Library -->
<script src="https://unpkg.com/html5-qrcode"></script>
<script>
  document.addEventListener('DOMContentLoaded', async function() {
    const cameraSelect = document.getElementById('camera-select');
    const html5QrCode = new Html5Qrcode("qr-reader");
    const qrOverlay = document.getElementById('scanner-overlay');

    // Fetch available cameras
    try {
      const devices = await Html5Qrcode.getCameras();
      cameraSelect.innerHTML = devices.map(device => `<option value="${device.id}">${device.label || 'Camera'}</option>`).join('');
    } catch (error) {
      console.error("Error fetching cameras: ", error);
      cameraSelect.innerHTML = '<option value="">No cameras found</option>';
    }

    // Start scanner on camera selection
    cameraSelect.addEventListener('change', async function() {
      const selectedCameraId = cameraSelect.value;
      if (selectedCameraId) {
        try {
          // Stop the scanner if it is running
          if (html5QrCode && html5QrCode.isScanning) {
            await html5QrCode.stop();
          }

          // Start the scanner with the newly selected camera
          await html5QrCode.start(
            { deviceId: { exact: selectedCameraId } },
            { fps: 10, qrbox: { width: 250, height: 250 } },
            onScanSuccess,
            (errorMessage) => {
              if (!errorMessage.includes("No MultiFormat Readers")) {
                console.log("QR code parse error: ", errorMessage);
              }
            }
          );
          qrOverlay.style.display = 'none';
        } catch (err) {
          console.error("Error switching camera: ", err);
        }
      }
    });

    // Success function
    function onScanSuccess(decodedText, decodedResult) {
      if (html5QrCode && html5QrCode.isScanning) {
        html5QrCode.stop().then(() => {
          console.log("Scanner stopped successfully.");
          qrOverlay.innerHTML = '<div class="text-white text-center"><i class="fas fa-circle-notch fa-spin text-3xl mb-3"></i><p>Code detected!</p><p>Redirecting...</p></div>';
          qrOverlay.style.backgroundColor = 'rgba(0, 104, 55, 0.8)';
          qrOverlay.style.display = 'flex';
          window.location.href = '/redeem/' + decodedText;
        }).catch(err => {
          console.error("Error stopping the scanner: ", err);
          window.location.href = '/redeem/' + decodedText;
        });
      } else {
        window.location.href = '/redeem/' + decodedText;
      }
    }
  });
</script>
{% endblock %}
