---
import Layout from '../layouts/Layout.astro';
import { verifyAuth } from '../lib/auth';

// Enable server-side rendering for auth checks
export const prerender = false;

// Server-side authentication check
const auth = await verifyAuth(Astro.request);
if (!auth) {
  return Astro.redirect('/login-new');
}
---

<Layout title="Scan Tickets - Black Canyon Tickets">
  <style>
    .bg-grid-pattern {
      background-image: 
        linear-gradient(var(--grid-pattern) 1px, transparent 1px),
        linear-gradient(90deg, var(--grid-pattern) 1px, transparent 1px);
      background-size: 20px 20px;
    }
  </style>
  <div class="min-h-screen" style="background: var(--bg-gradient);">
    <!-- Animated background elements -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none">
      <div class="absolute -top-40 -right-40 w-80 h-80 rounded-full blur-3xl animate-pulse" style="background: var(--bg-orb-1);"></div>
      <div class="absolute -bottom-40 -left-40 w-80 h-80 rounded-full blur-3xl animate-pulse" style="background: var(--bg-orb-2);"></div>
      <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 rounded-full blur-3xl animate-pulse" style="background: var(--bg-orb-3);"></div>
    </div>
    
    <!-- Grid pattern overlay -->
    <div class="absolute inset-0 bg-grid-pattern opacity-5"></div>
    
    <!-- Sticky Navigation -->
    <nav id="navigation" class="sticky top-0 z-50 backdrop-blur-xl shadow-2xl" style="background: var(--glass-bg); border-bottom: 1px solid var(--glass-border);" aria-label="Main navigation">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-20">
          <div class="flex items-center gap-6">
            <div class="flex items-center gap-3">
              <div class="w-10 h-10 rounded-xl flex items-center justify-center" style="background: var(--glass-text-accent);">
                <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
                </svg>
              </div>
              <h1 class="text-xl font-bold" style="color: var(--glass-text-primary);">
                BCT Scanner
              </h1>
            </div>
            
            <!-- Live Stats -->
            <div class="hidden md:flex items-center gap-4 ml-8">
              <div class="flex items-center gap-2 px-3 py-1.5 rounded-lg" style="background: var(--glass-bg-button);">
                <div class="w-2 h-2 rounded-full animate-pulse" style="background: var(--glass-text-accent);"></div>
                <span class="text-sm font-medium" style="color: var(--glass-text-primary);">Live</span>
              </div>
              <div class="flex items-center gap-2 px-3 py-1.5 rounded-lg" style="background: var(--glass-bg-button);">
                <svg class="w-4 h-4" style="color: var(--glass-text-accent);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                </svg>
                <span class="text-sm font-medium" style="color: var(--glass-text-primary);" id="attendance-count">0</span>
                <span class="text-sm" style="color: var(--glass-text-tertiary);">checked in</span>
              </div>
            </div>
          </div>
          
          <div class="flex items-center space-x-4">
            <span id="user-name" class="text-sm text-white/80 font-medium"></span>
            
            <!-- Lock Scanner Button -->
            <button
              id="lock-scanner-btn"
              aria-label="Lock scanner to this device"
              class="bg-gradient-to-r from-amber-600 to-orange-600 hover:from-amber-700 hover:to-orange-700 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105 flex items-center gap-2 hidden"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
              Lock Scanner
            </button>
            
            <!-- Unlock Button (only shown when locked) -->
            <button
              id="unlock-scanner-btn"
              aria-label="Unlock scanner"
              class="bg-gradient-to-r from-red-600 to-pink-600 hover:from-red-700 hover:to-pink-700 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105 flex items-center gap-2 hidden"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z" />
              </svg>
              <span id="unlock-text">Exit Admin</span>
            </button>
            
            <button
              id="help-btn"
              aria-label="Show scanner help and instructions"
              class="bg-white/10 hover:bg-white/20 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105 flex items-center gap-2"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Help
            </button>
            <button
              id="logout-btn"
              aria-label="Sign out of your account"
              class="bg-white/10 hover:bg-white/20 text-white px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md hover:scale-105"
            >
              Sign Out
            </button>
          </div>
        </div>
      </div>
    </nav>

    <main class="relative max-w-4xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <!-- Header -->
      <div class="text-center mb-8">
        <h2 class="text-4xl font-bold text-white mb-2 bg-gradient-to-r from-purple-400 to-pink-400 bg-clip-text text-transparent">
          Ticket Scanner
        </h2>
        <p class="text-white/80 text-lg">Scan QR codes to check guests in</p>
      </div>

      <!-- Scanner Card -->
      <div class="bg-black/40 backdrop-blur-2xl border border-white/20 rounded-3xl shadow-2xl overflow-hidden">
        <div id="scanner-section" class="p-8">
          <!-- Start Button -->
          <div id="start-section" class="text-center">
            <div class="w-32 h-32 bg-gradient-to-br from-purple-500/20 to-pink-500/20 rounded-full flex items-center justify-center mx-auto mb-8 border border-white/20">
              <svg class="w-16 h-16 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
            </div>
            <button
              id="start-scan-btn"
              aria-describedby="scanner-instructions"
              class="inline-flex items-center gap-3 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 text-white px-12 py-5 rounded-2xl font-bold text-lg transition-all duration-300 shadow-2xl hover:shadow-purple-500/25 hover:scale-105 border border-white/20"
            >
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
              Initialize Scanner
            </button>
            <div id="scanner-instructions" class="sr-only">
              Camera will activate and scan for QR codes automatically. Position QR codes within the camera frame for scanning.
            </div>
          </div>

          <!-- Camera Section -->
          <div id="camera-section" class="hidden">
            <div class="relative mb-8">
              <video id="preview" class="w-full rounded-2xl bg-black shadow-2xl border border-white/20"></video>
              <!-- Advanced Scanner Overlay -->
              <div class="absolute inset-0 pointer-events-none">
                <!-- Corner Brackets -->
                <div class="absolute top-8 left-8 w-12 h-12 border-t-4 border-l-4 border-purple-400 rounded-tl-2xl animate-pulse"></div>
                <div class="absolute top-8 right-8 w-12 h-12 border-t-4 border-r-4 border-purple-400 rounded-tr-2xl animate-pulse"></div>
                <div class="absolute bottom-8 left-8 w-12 h-12 border-b-4 border-l-4 border-purple-400 rounded-bl-2xl animate-pulse"></div>
                <div class="absolute bottom-8 right-8 w-12 h-12 border-b-4 border-r-4 border-purple-400 rounded-br-2xl animate-pulse"></div>
                
                <!-- Scanning Line -->
                <div class="absolute top-1/2 left-1/4 right-1/4 h-0.5 bg-gradient-to-r from-transparent via-purple-400 to-transparent animate-pulse"></div>
                
                <!-- Center Target -->
                <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-24 h-24 border-2 border-white/60 rounded-xl">
                  <div class="absolute inset-2 border border-white/40 rounded-lg"></div>
                  <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-2 h-2 bg-purple-400 rounded-full animate-ping"></div>
                </div>
              </div>
              
              <!-- Status Bar -->
              <div class="absolute bottom-4 left-1/2 transform -translate-x-1/2 bg-black/80 backdrop-blur-sm text-white px-6 py-2 rounded-2xl text-sm font-medium border border-white/20">
                <div class="flex items-center gap-2">
                  <div class="w-2 h-2 bg-purple-400 rounded-full animate-pulse"></div>
                  <span>Scanning for QR codes...</span>
                </div>
              </div>
            </div>
            
            <div class="text-center">
              <button
                id="stop-scan-btn"
                class="inline-flex items-center gap-3 bg-red-600/20 hover:bg-red-600/30 text-red-400 px-8 py-4 rounded-2xl font-medium transition-all duration-200 border border-red-400/30 hover:scale-105"
              >
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M6 6h12v12H6z" />
                </svg>
                Stop Scanner
              </button>
            </div>
          </div>
        </div>

        <!-- Manual Entry Section -->
        <div class="border-t border-white/20 p-8 bg-white/5">
          <h3 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <svg class="w-5 h-5 text-white/80" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
            Manual Entry
          </h3>
          <div class="flex gap-3">
            <input
              type="text"
              id="manual-ticket-id"
              placeholder="Enter ticket UUID"
              class="flex-1 px-4 py-3 bg-white/10 border border-white/30 rounded-xl text-white placeholder-white/60 focus:ring-2 focus:ring-blue-400 focus:border-purple-400 transition-all duration-200"
            />
            <button
              id="manual-checkin-btn"
              class="inline-flex items-center gap-2 bg-gradient-to-r from-emerald-600 to-blue-600 hover:from-emerald-700 hover:to-blue-700 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 whitespace-nowrap shadow-lg hover:shadow-xl hover:scale-105"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Check In
            </button>
            <button
              id="manual-checkout-btn"
              class="inline-flex items-center gap-2 bg-gradient-to-r from-orange-600 to-red-600 hover:from-orange-700 hover:to-red-700 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 whitespace-nowrap shadow-lg hover:shadow-xl hover:scale-105"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
              </svg>
              Check Out
            </button>
            <button
              id="backup-scan-btn"
              class="inline-flex items-center gap-2 bg-gradient-to-r from-yellow-600 to-amber-600 hover:from-yellow-700 hover:to-amber-700 text-white px-6 py-3 rounded-xl font-medium transition-all duration-200 whitespace-nowrap shadow-lg hover:shadow-xl hover:scale-105"
              title="Use CodeREADr backup scanner"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              Backup
            </button>
          </div>
        </div>
      </div>

      <!-- Lookup Search Section -->
      <div class="mt-8 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-xl overflow-hidden">
        <div class="p-8">
          <h3 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <svg class="w-5 h-5 text-white/80" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
            Ticket Lookup
          </h3>
          <div class="relative">
            <input
              type="text"
              id="ticket-search"
              placeholder="Search by name, email, or event..."
              class="w-full px-4 py-3 bg-white/10 border border-white/30 rounded-xl text-white placeholder-white/60 focus:ring-2 focus:ring-blue-400 focus:border-purple-400 transition-all duration-200"
              autocomplete="off"
            />
            <div id="search-loading" class="absolute right-3 top-3 hidden">
              <svg class="w-5 h-5 text-white/60 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            </div>
          </div>
          
          <!-- Search Results -->
          <div id="search-results" class="mt-4 space-y-2 max-h-80 overflow-y-auto hidden">
            <!-- Search results will appear here -->
          </div>
        </div>
      </div>

      <!-- Results Section -->
      <div id="scan-results" class="mt-8 space-y-4" aria-live="polite" aria-label="Scan results">
        <!-- Scan results will appear here -->
      </div>
      
      <!-- Screen reader announcements -->
      <div id="scan-announcements" class="sr-only" aria-live="assertive" aria-atomic="true">
        <!-- Screen reader announcements will appear here -->
      </div>
    </main>

    <!-- Help Modal -->
    <div id="help-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
          <!-- Modal Header -->
          <div class="flex items-center justify-between p-6 border-b border-white/20">
            <h2 class="text-xl font-semibold text-white">Scanner Help & Instructions</h2>
            <button
              id="close-help-modal"
              class="text-white/60 hover:text-white transition-colors"
              aria-label="Close help modal"
            >
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          
          <!-- Modal Content -->
          <div class="p-6 space-y-6">
            <!-- Quick Start -->
            <div>
              <h3 class="text-lg font-medium text-white mb-3 flex items-center gap-2">
                <svg class="w-5 h-5 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                Quick Start
              </h3>
              <div class="text-white/80 text-sm space-y-2">
                <p>1. <strong>Start Camera:</strong> Click "Start Camera" to begin scanning QR codes automatically</p>
                <p>2. <strong>Position QR Code:</strong> Hold the ticket QR code within the camera frame</p>
                <p>3. <strong>Automatic Check-in:</strong> The system will automatically detect and check in valid tickets</p>
                <p>4. <strong>Manual Entry:</strong> Use the manual entry field for tickets without QR codes</p>
                <p>5. <strong>Lookup Search:</strong> Search for specific tickets by name, email, or event</p>
              </div>
            </div>

            <!-- How It Works -->
            <div>
              <h3 class="text-lg font-medium text-white mb-3 flex items-center gap-2">
                <svg class="w-5 h-5 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                How the Scanner Works
              </h3>
              <div class="text-white/80 text-sm space-y-2">
                <p>• <strong>QR Code Detection:</strong> The camera continuously scans for QR codes containing ticket UUIDs</p>
                <p>• <strong>Instant Validation:</strong> Each ticket is checked against the database in real-time</p>
                <p>• <strong>Duplicate Prevention:</strong> Already checked-in tickets will show a warning message</p>
                <p>• <strong>Event Verification:</strong> Only tickets for current organization events are accepted</p>
                <p>• <strong>Secure UUIDs:</strong> Each ticket has a unique, non-guessable identifier for security</p>
              </div>
            </div>

            <!-- Common Issues -->
            <div>
              <h3 class="text-lg font-medium text-white mb-3 flex items-center gap-2">
                <svg class="w-5 h-5 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                </svg>
                Frequently Asked Questions
              </h3>
              <div class="space-y-4">
                <div class="bg-white/5 rounded-lg p-4">
                  <h4 class="font-medium text-white text-sm mb-2">Q: Camera won't start or shows error</h4>
                  <p class="text-white/70 text-sm">A: Check that you've granted camera permissions in your browser. Try refreshing the page and clicking "Allow" when prompted.</p>
                </div>
                <div class="bg-white/5 rounded-lg p-4">
                  <h4 class="font-medium text-white text-sm mb-2">Q: QR code won't scan</h4>
                  <p class="text-white/70 text-sm">A: Ensure the QR code is well-lit and within the frame. Try using manual entry with the ticket UUID if scanning fails.</p>
                </div>
                <div class="bg-white/5 rounded-lg p-4">
                  <h4 class="font-medium text-white text-sm mb-2">Q: Ticket shows "already checked in"</h4>
                  <p class="text-white/70 text-sm">A: This ticket has already been scanned. Check the guest list to verify the original check-in time, or use the checkout/reentry feature if needed.</p>
                </div>
                <div class="bg-white/5 rounded-lg p-4">
                  <h4 class="font-medium text-white text-sm mb-2">Q: Guest needs to leave and return</h4>
                  <p class="text-white/70 text-sm">A: Use the "Check Out" feature to allow reentry. This will reset the ticket's check-in status for temporary exits.</p>
                </div>
                <div class="bg-white/5 rounded-lg p-4">
                  <h4 class="font-medium text-white text-sm mb-2">Q: Can't find a specific ticket</h4>
                  <p class="text-white/70 text-sm">A: Use the lookup search feature to find tickets by guest name, email, or event title. This searches across all tickets in your organization.</p>
                </div>
              </div>
            </div>

            <!-- Tips -->
            <div>
              <h3 class="text-lg font-medium text-white mb-3 flex items-center gap-2">
                <svg class="w-5 h-5 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                </svg>
                Pro Tips
              </h3>
              <div class="text-white/80 text-sm space-y-2">
                <p>• <strong>Good Lighting:</strong> Ensure adequate lighting for best QR code scanning results</p>
                <p>• <strong>Steady Hands:</strong> Hold the device steady and let the camera focus on the QR code</p>
                <p>• <strong>Backup Method:</strong> Always have manual entry available for problem tickets</p>
                <p>• <strong>Check Results:</strong> Review scan results to ensure successful check-ins</p>
                <p>• <strong>Multiple Devices:</strong> Use multiple devices for faster processing at busy events</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- PIN Creation Modal -->
    <div id="pin-creation-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl max-w-md w-full">
          <!-- Modal Header -->
          <div class="flex items-center justify-between p-6 border-b border-white/20">
            <h2 class="text-xl font-semibold text-white">🔒 Lock Scanner</h2>
            <button
              id="close-pin-modal"
              class="text-white/60 hover:text-white transition-colors"
              aria-label="Close PIN creation modal"
            >
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          
          <!-- Modal Content -->
          <div class="p-6">
            <div class="text-center mb-6">
              <div class="w-16 h-16 bg-gradient-to-br from-amber-500/20 to-orange-500/20 rounded-full flex items-center justify-center mx-auto mb-4 border border-white/20">
                <svg class="w-8 h-8 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
              </div>
              <h3 class="text-lg font-medium text-white mb-2">Create Scanner PIN</h3>
              <p class="text-white/80 text-sm">Create a 4-digit PIN to restrict access to scan-only mode</p>
            </div>
            
            <form id="pin-creation-form" class="space-y-4">
              <div>
                <label for="pin-input" class="block text-sm font-medium text-white/90 mb-2">Enter 4-digit PIN</label>
                <input
                  type="password"
                  id="pin-input"
                  maxlength="4"
                  pattern="[0-9]{4}"
                  class="w-full px-4 py-3 bg-white/10 border border-white/30 rounded-xl text-white text-center text-xl font-mono placeholder-white/60 focus:ring-2 focus:ring-amber-400 focus:border-amber-400 transition-all duration-200"
                  placeholder="••••"
                  required
                />
              </div>
              
              <div>
                <label for="pin-confirm" class="block text-sm font-medium text-white/90 mb-2">Confirm PIN</label>
                <input
                  type="password"
                  id="pin-confirm"
                  maxlength="4"
                  pattern="[0-9]{4}"
                  class="w-full px-4 py-3 bg-white/10 border border-white/30 rounded-xl text-white text-center text-xl font-mono placeholder-white/60 focus:ring-2 focus:ring-amber-400 focus:border-amber-400 transition-all duration-200"
                  placeholder="••••"
                  required
                />
              </div>
              
              <div class="bg-amber-500/10 border border-amber-400/30 rounded-lg p-3">
                <p class="text-amber-200 text-sm">
                  <strong>Important:</strong> Your PIN will be sent to your email address. This device will be locked to scan-only mode until unlocked with the PIN.
                </p>
              </div>
              
              <div class="flex gap-3 pt-4">
                <button
                  type="button"
                  id="cancel-pin-btn"
                  class="flex-1 bg-white/10 hover:bg-white/20 text-white px-4 py-3 rounded-xl font-medium transition-all duration-200 border border-white/30"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  id="create-pin-btn"
                  class="flex-1 bg-gradient-to-r from-amber-600 to-orange-600 hover:from-amber-700 hover:to-orange-700 text-white px-4 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg"
                >
                  Lock Scanner
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- PIN Unlock Modal -->
    <div id="pin-unlock-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl max-w-md w-full">
          <!-- Modal Header -->
          <div class="flex items-center justify-between p-6 border-b border-white/20">
            <h2 class="text-xl font-semibold text-white">🔓 Unlock Scanner</h2>
            <button
              id="close-unlock-modal"
              class="text-white/60 hover:text-white transition-colors"
              aria-label="Close unlock modal"
            >
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          
          <!-- Modal Content -->
          <div class="p-6">
            <div class="text-center mb-6">
              <div class="w-16 h-16 bg-gradient-to-br from-red-500/20 to-pink-500/20 rounded-full flex items-center justify-center mx-auto mb-4 border border-white/20">
                <svg class="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z" />
                </svg>
              </div>
              <h3 class="text-lg font-medium text-white mb-2">Enter PIN to Unlock</h3>
              <p class="text-white/80 text-sm">Enter your 4-digit PIN to exit scan-only mode</p>
            </div>
            
            <form id="pin-unlock-form" class="space-y-4">
              <div>
                <label for="unlock-pin-input" class="block text-sm font-medium text-white/90 mb-2">4-digit PIN</label>
                <input
                  type="password"
                  id="unlock-pin-input"
                  maxlength="4"
                  pattern="[0-9]{4}"
                  class="w-full px-4 py-3 bg-white/10 border border-white/30 rounded-xl text-white text-center text-xl font-mono placeholder-white/60 focus:ring-2 focus:ring-red-400 focus:border-red-400 transition-all duration-200"
                  placeholder="••••"
                  required
                />
              </div>
              
              <div id="unlock-error" class="hidden bg-red-500/10 border border-red-400/30 rounded-lg p-3">
                <p class="text-red-200 text-sm">
                  <strong>Error:</strong> Invalid PIN. Please try again.
                </p>
              </div>
              
              <div class="flex gap-3 pt-4">
                <button
                  type="button"
                  id="cancel-unlock-btn"
                  class="flex-1 bg-white/10 hover:bg-white/20 text-white px-4 py-3 rounded-xl font-medium transition-all duration-200 border border-white/30"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  id="unlock-btn"
                  class="flex-1 bg-gradient-to-r from-red-600 to-pink-600 hover:from-red-700 hover:to-pink-700 text-white px-4 py-3 rounded-xl font-medium transition-all duration-200 shadow-lg"
                >
                  Unlock
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- Full-Screen Feedback Overlay -->
    <div id="feedback-overlay" class="fixed inset-0 z-[100] hidden">
      <!-- Success Screen (Green) -->
      <div id="success-screen" class="absolute inset-0 bg-gradient-to-br from-emerald-500 to-green-600 flex items-center justify-center hidden">
        <div class="text-center text-white">
          <div class="mb-8">
            <div class="w-32 h-32 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-6 animate-pulse">
              <svg class="w-16 h-16 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 class="text-6xl font-bold mb-4">VALID TICKET</h2>
            <p class="text-2xl opacity-90" id="success-message">Guest checked in successfully</p>
          </div>
          <div class="text-xl opacity-75">
            <p id="success-guest-name">John Doe</p>
            <p id="success-event-name">Summer Gala</p>
          </div>
        </div>
      </div>

      <!-- Error Screen (Red) -->
      <div id="error-screen" class="absolute inset-0 bg-gradient-to-br from-red-500 to-red-700 flex items-center justify-center hidden">
        <div class="text-center text-white">
          <div class="mb-8">
            <div class="w-32 h-32 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-6 animate-pulse">
              <svg class="w-16 h-16 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h2 class="text-6xl font-bold mb-4">INVALID TICKET</h2>
            <p class="text-2xl opacity-90 mb-8" id="error-message">Ticket not found</p>
          </div>
          <button
            id="error-acknowledge-btn"
            class="bg-white/20 hover:bg-white/30 text-white px-8 py-4 rounded-2xl text-xl font-semibold transition-all duration-200 border border-white/30 hover:scale-105"
          >
            Acknowledge
          </button>
        </div>
      </div>

      <!-- Warning Screen (Yellow) -->
      <div id="warning-screen" class="absolute inset-0 bg-gradient-to-br from-yellow-500 to-orange-600 flex items-center justify-center hidden">
        <div class="text-center text-white">
          <div class="mb-8">
            <div class="w-32 h-32 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-6 animate-pulse">
              <svg class="w-16 h-16 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <h2 class="text-6xl font-bold mb-4">ALREADY CHECKED IN</h2>
            <p class="text-2xl opacity-90 mb-8" id="warning-message">This ticket has already been scanned</p>
          </div>
          <div class="text-xl opacity-75 mb-8">
            <p id="warning-guest-name">John Doe</p>
            <p id="warning-event-name">Summer Gala</p>
            <p id="warning-checked-time">Checked in at 2:30 PM</p>
          </div>
          <button
            id="warning-acknowledge-btn"
            class="bg-white/20 hover:bg-white/30 text-white px-8 py-4 rounded-2xl text-xl font-semibold transition-all duration-200 border border-white/30 hover:scale-105"
          >
            Acknowledge
          </button>
        </div>
      </div>
    </div>
  </div>
</Layout>

<script>
  import { supabase } from '../lib/supabase';
  import { parseQRCode } from '../lib/qr';
  
  // Import ZXing library for better QR code scanning
  import('https://unpkg.com/@zxing/library@latest/esm/index.js').then(module => {
    window.ZXing = module;
  }).catch(err => {
    console.warn('ZXing library not available, using basic scanning');
  });

  const startScanBtn = document.getElementById('start-scan-btn');
  const stopScanBtn = document.getElementById('stop-scan-btn');
  const startSection = document.getElementById('start-section');
  const cameraSection = document.getElementById('camera-section');
  const preview = document.getElementById('preview') as HTMLVideoElement;
  const scanResults = document.getElementById('scan-results');
  const manualTicketId = document.getElementById('manual-ticket-id') as HTMLInputElement;
  const manualCheckinBtn = document.getElementById('manual-checkin-btn');
  const manualCheckoutBtn = document.getElementById('manual-checkout-btn');
  const logoutBtn = document.getElementById('logout-btn');
  const helpBtn = document.getElementById('help-btn');
  const helpModal = document.getElementById('help-modal');
  const closeHelpModal = document.getElementById('close-help-modal');
  const userNameSpan = document.getElementById('user-name');
  const ticketSearch = document.getElementById('ticket-search') as HTMLInputElement;
  const searchResults = document.getElementById('search-results');
  const searchLoading = document.getElementById('search-loading');
  const attendanceCount = document.getElementById('attendance-count');
  
  // Full-screen feedback elements
  const feedbackOverlay = document.getElementById('feedback-overlay');
  const successScreen = document.getElementById('success-screen');
  const errorScreen = document.getElementById('error-screen');
  const warningScreen = document.getElementById('warning-screen');
  const errorAcknowledgeBtn = document.getElementById('error-acknowledge-btn');
  const warningAcknowledgeBtn = document.getElementById('warning-acknowledge-btn');

  let scanning = false;
  let stream: MediaStream | null = null;
  let codeReader: any = null;

  // Page is already authenticated via server-side check
  // No need for client-side auth verification due to httpOnly cookies
  
  // Initialize page functionality
  document.addEventListener('DOMContentLoaded', async () => {
    // Page is authenticated, continue with initialization
    await loadUserInfo();
    await updateAttendanceCount();
  });

  // Listen for explicit sign out events only
  supabase.auth.onAuthStateChange((event, session) => {
    if (event === 'SIGNED_OUT') {
      window.location.href = '/login-new';
    }
  });

  // Load user info
  async function loadUserInfo() {
    const { data: { user } } = await supabase.auth.getUser();
    if (user) {
      userNameSpan.textContent = user.user_metadata.name || user.email;
    }
  }

  // Start camera
  async function startCamera() {
    try {
      stream = await navigator.mediaDevices.getUserMedia({
        video: { 
          facingMode: 'environment',
          width: { ideal: 1920 },
          height: { ideal: 1080 }
        }
      });
      preview.srcObject = stream;
      preview.play();
      
      cameraSection.classList.remove('hidden');
      startSection.classList.add('hidden');
      scanning = true;
      
      // Initialize ZXing scanner if available
      if (window.ZXing) {
        try {
          codeReader = new window.ZXing.BrowserQRCodeReader();
          // Start continuous scanning
          codeReader.decodeFromVideoDevice(undefined, preview, (result, err) => {
            if (result) {
              handleQRCodeResult(result.text);
            }
          });
        } catch (error) {
          console.warn('ZXing scanner failed, falling back to basic scanning');
          scanLoop();
        }
      } else {
        // Fallback to basic scanning
        scanLoop();
      }
    } catch (error) {
      console.error('Error accessing camera:', error);
      alert('Unable to access camera. Please ensure you have granted camera permissions.');
    }
  }

  // Stop camera
  function stopCamera() {
    scanning = false;
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
      stream = null;
    }
    
    cameraSection.classList.add('hidden');
    startSection.classList.remove('hidden');
  }

  // Handle QR code result
  function handleQRCodeResult(qrText: string) {
    if (!scanning) return;
    
    // Parse QR code to extract ticket UUID
    const ticketUuid = parseQRCode(qrText);
    if (ticketUuid) {
      checkInTicket(ticketUuid);
    } else {
      showResult('error', 'Invalid QR code format');
    }
  }

  // Scan loop (simplified - in reality you'd use a QR code scanning library)
  function scanLoop() {
    if (!scanning) return;
    
    // This is a placeholder - you'd integrate with a QR code scanning library
    // like @zxing/library or instascan
    
    setTimeout(() => {
      if (scanning) {
        scanLoop();
      }
    }, 100);
  }

  // Check in ticket with CodeREADr backup
  async function checkInTicket(ticketUuid: string, useBackup: boolean = false) {
    try {
      // First, find the ticket
      const { data: ticket, error: findError } = await supabase
        .from('tickets')
        .select(`
          *,
          events (
            title,
            venue,
            start_time
          )
        `)
        .eq('uuid', ticketUuid)
        .single();

      if (findError || !ticket) {
        // If primary scan fails, try CodeREADr backup
        if (!useBackup) {
          console.warn('Primary scan failed, trying CodeREADr backup');
          return await checkInTicketWithCodereadr(ticketUuid);
        }
        throw new Error('Ticket not found');
      }

      if (ticket.checked_in) {
        showResult('warning', 'Ticket already checked in', ticket);
        return;
      }

      // Check in the ticket
      const { error: updateError } = await supabase
        .from('tickets')
        .update({
          checked_in: true,
          scanned_at: new Date().toISOString(),
          scan_method: useBackup ? 'codereadr' : 'qr'
        })
        .eq('uuid', ticketUuid);

      if (updateError) {
        throw updateError;
      }

      showResult('success', 'Ticket checked in successfully', ticket);
      await updateAttendanceCount();
    } catch (error) {
      console.error('Error checking in ticket:', error);
      
      // If primary scan fails and we haven't tried backup yet, try CodeREADr
      if (!useBackup && error.message !== 'Ticket not found') {
        console.warn('Primary check-in failed, trying CodeREADr backup');
        return await checkInTicketWithCodereadr(ticketUuid);
      }
      
      showResult('error', error.message || 'Error checking in ticket');
    }
  }

  // CodeREADr backup check-in function
  async function checkInTicketWithCodereadr(ticketUuid: string) {
    try {
      // Show backup scanning indicator
      showBackupScanningIndicator();
      
      // Get current user info for scannedBy parameter
      const { data: { user } } = await supabase.auth.getUser();
      const scannedBy = user?.id || 'unknown';
      
      // Get current event (you might need to modify this based on your event selection logic)
      const eventId = await getCurrentEventId();
      
      if (!eventId) {
        throw new Error('No event selected for scanning');
      }

      // Call CodeREADr API
      const response = await fetch('/api/codereadr/scan', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ticketUuid,
          eventId,
          scannedBy
        })
      });

      const result = await response.json();
      
      hideBackupScanningIndicator();

      if (result.success) {
        showResult('success', 'Ticket checked in via backup system', {
          purchaser_name: result.ticket_data.purchaser_name,
          purchaser_email: result.ticket_data.purchaser_email,
          events: { title: result.ticket_data.event_title }
        });
        await updateAttendanceCount();
      } else {
        throw new Error(result.error || 'Backup scan failed');
      }

    } catch (error) {
      console.error('CodeREADr backup scan error:', error);
      hideBackupScanningIndicator();
      showResult('error', `Backup scan failed: ${error.message}`);
    }
  }

  // Get current event ID - you might need to modify this based on your event selection logic
  async function getCurrentEventId(): Promise<string | null> {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return null;

      // Get user's organization
      const { data: userData } = await supabase
        .from('users')
        .select('organization_id')
        .eq('id', user.id)
        .single();

      if (!userData?.organization_id) return null;

      // Get the most recent event for this organization
      const { data: events } = await supabase
        .from('events')
        .select('id')
        .eq('organization_id', userData.organization_id)
        .gte('start_time', new Date().toISOString())
        .order('start_time', { ascending: true })
        .limit(1);

      return events && events.length > 0 ? events[0].id : null;
    } catch (error) {
      console.error('Error getting current event ID:', error);
      return null;
    }
  }

  // Show backup scanning indicator
  function showBackupScanningIndicator() {
    const indicator = document.createElement('div');
    indicator.id = 'backup-scanning-indicator';
    indicator.className = 'fixed top-4 right-4 bg-yellow-600 text-white px-4 py-2 rounded-lg shadow-lg z-50 flex items-center gap-2';
    indicator.innerHTML = `
      <svg class="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
      <span>Trying backup scanner...</span>
    `;
    document.body.appendChild(indicator);
  }

  // Hide backup scanning indicator
  function hideBackupScanningIndicator() {
    const indicator = document.getElementById('backup-scanning-indicator');
    if (indicator) {
      indicator.remove();
    }
  }

  // Check out ticket (for reentry)
  async function checkOutTicket(ticketUuid: string) {
    try {
      // First, find the ticket
      const { data: ticket, error: findError } = await supabase
        .from('tickets')
        .select(`
          *,
          events (
            title,
            venue,
            start_time
          )
        `)
        .eq('uuid', ticketUuid)
        .single();

      if (findError || !ticket) {
        throw new Error('Ticket not found');
      }

      if (!ticket.checked_in) {
        showResult('warning', 'Ticket is not checked in', ticket);
        return;
      }

      // Check out the ticket (reset for reentry)
      const { error: updateError } = await supabase
        .from('tickets')
        .update({
          checked_in: false,
          scanned_at: null
        })
        .eq('uuid', ticketUuid);

      if (updateError) {
        throw updateError;
      }

      showResult('success', 'Ticket checked out - reentry enabled', ticket);
      await updateAttendanceCount();
    } catch (error) {
      console.error('Error checking out ticket:', error);
      showResult('error', error.message || 'Error checking out ticket');
    }
  }

  // Update live attendance count
  async function updateAttendanceCount() {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

      // Get current user's organization
      const { data: userData } = await supabase
        .from('users')
        .select('organization_id')
        .eq('id', user.id)
        .single();

      if (!userData?.organization_id) return;

      // Count checked in tickets for organization's events
      const { count } = await supabase
        .from('tickets')
        .select('*', { count: 'exact', head: true })
        .eq('checked_in', true)
        .in('event_id', 
          supabase
            .from('events')
            .select('id')
            .eq('organization_id', userData.organization_id)
        );

      if (attendanceCount) {
        attendanceCount.textContent = count?.toString() || '0';
      }
    } catch (error) {
      console.error('Error updating attendance count:', error);
    }
  }

  // Search tickets
  let searchTimeout: NodeJS.Timeout;
  async function searchTickets(query: string) {
    if (!query.trim()) {
      searchResults.classList.add('hidden');
      return;
    }

    // Show loading
    searchLoading.classList.remove('hidden');
    
    try {
      // Search in tickets table with related event and organization data
      const { data: tickets, error } = await supabase
        .from('tickets')
        .select(`
          *,
          events (
            id,
            title,
            venue,
            start_time,
            organization_id
          ),
          ticket_types (
            name,
            price
          )
        `)
        .or(`purchaser_name.ilike.%${query}%,purchaser_email.ilike.%${query}%,uuid.ilike.%${query}%`)
        .order('created_at', { ascending: false })
        .limit(10);

      if (error) throw error;

      // Also search by event title
      const { data: eventTickets, error: eventError } = await supabase
        .from('tickets')
        .select(`
          *,
          events!inner (
            id,
            title,
            venue,
            start_time,
            organization_id
          ),
          ticket_types (
            name,
            price
          )
        `)
        .ilike('events.title', `%${query}%`)
        .order('created_at', { ascending: false })
        .limit(10);

      if (eventError) throw eventError;

      // Combine and deduplicate results
      const allTickets = [...(tickets || []), ...(eventTickets || [])];
      const uniqueTickets = allTickets.filter((ticket, index, self) => 
        index === self.findIndex(t => t.id === ticket.id)
      );

      displaySearchResults(uniqueTickets);
    } catch (error) {
      console.error('Search error:', error);
      searchResults.innerHTML = `
        <div class="p-4 bg-red-500/20 border border-red-400/30 rounded-lg">
          <p class="text-red-400 text-sm">Error searching tickets: ${error.message}</p>
        </div>
      `;
      searchResults.classList.remove('hidden');
    } finally {
      searchLoading.classList.add('hidden');
    }
  }

  // Display search results
  function displaySearchResults(tickets: any[]) {
    if (tickets.length === 0) {
      searchResults.innerHTML = `
        <div class="p-4 bg-white/5 border border-white/10 rounded-lg text-center">
          <p class="text-white/60 text-sm">No tickets found matching your search</p>
        </div>
      `;
      searchResults.classList.remove('hidden');
      return;
    }

    searchResults.innerHTML = tickets.map(ticket => {
      const eventDate = new Date(ticket.events.start_time).toLocaleDateString();
      const isCheckedIn = ticket.checked_in;
      
      return `
        <div class="p-4 bg-white/5 border border-white/10 rounded-lg hover:bg-white/10 transition-colors cursor-pointer ticket-result" 
             data-ticket-uuid="${ticket.uuid}"
             role="button"
             tabindex="0">
          <div class="flex items-center justify-between">
            <div class="flex-1">
              <div class="flex items-center gap-3 mb-2">
                <h4 class="font-medium text-white">${ticket.purchaser_name || 'No name'}</h4>
                <span class="px-2 py-1 text-xs rounded-full ${
                  isCheckedIn 
                    ? 'bg-emerald-500/20 text-emerald-400' 
                    : 'bg-blue-500/20 text-purple-400'
                }">
                  ${isCheckedIn ? 'Checked In' : 'Not Checked In'}
                </span>
              </div>
              <div class="text-sm text-white/80 space-y-1">
                <div class="flex items-center gap-2">
                  <svg class="w-4 h-4 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
                  </svg>
                  ${ticket.purchaser_email}
                </div>
                <div class="flex items-center gap-2">
                  <svg class="w-4 h-4 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                  ${ticket.events.title} - ${eventDate}
                </div>
                <div class="flex items-center gap-2">
                  <svg class="w-4 h-4 text-white/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
                  </svg>
                  ${ticket.ticket_types?.name || 'General'} - $${ticket.price}
                </div>
              </div>
            </div>
            <div class="flex items-center gap-2">
              ${!isCheckedIn ? `
                <button class="check-in-btn bg-gradient-to-r from-emerald-600 to-green-600 hover:from-emerald-700 hover:to-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 flex items-center gap-2"
                        data-ticket-uuid="${ticket.uuid}">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  Check In
                </button>
              ` : `
                <div class="text-emerald-400 text-sm font-medium">
                  ✓ Checked In
                </div>
              `}
            </div>
          </div>
        </div>
      `;
    }).join('');

    searchResults.classList.remove('hidden');

    // Add event listeners to check-in buttons
    const checkInBtns = searchResults.querySelectorAll('.check-in-btn');
    checkInBtns.forEach(btn => {
      btn.addEventListener('click', async (e) => {
        e.stopPropagation();
        const ticketUuid = btn.getAttribute('data-ticket-uuid');
        if (ticketUuid) {
          await checkInTicket(ticketUuid);
          // Refresh search results after check-in
          setTimeout(() => searchTickets(ticketSearch.value), 500);
        }
      });
    });
  }

  // Show full-screen feedback
  function showResult(type: 'success' | 'warning' | 'error', message: string, ticket?: any) {
    // Announce to screen readers
    const announcements = document.getElementById('scan-announcements');
    if (announcements) {
      announcements.textContent = `${type}: ${message}${ticket ? ` for ${ticket.events.title}` : ''}`;
    }

    // Hide all screens first
    successScreen?.classList.add('hidden');
    errorScreen?.classList.add('hidden');
    warningScreen?.classList.add('hidden');
    
    // Show the overlay
    feedbackOverlay?.classList.remove('hidden');

    if (type === 'success') {
      // Show success screen (green)
      successScreen?.classList.remove('hidden');
      
      // Update content
      const successMessage = document.getElementById('success-message');
      const successGuestName = document.getElementById('success-guest-name');
      const successEventName = document.getElementById('success-event-name');
      
      if (successMessage) successMessage.textContent = message;
      if (successGuestName && ticket) {
        successGuestName.textContent = ticket.purchaser_name || ticket.purchaser_email || 'Guest';
      }
      if (successEventName && ticket) {
        successEventName.textContent = ticket.events?.title || 'Event';
      }
      
      // Auto-dismiss after 3 seconds
      setTimeout(() => {
        feedbackOverlay?.classList.add('hidden');
      }, 3000);
      
    } else if (type === 'warning') {
      // Show warning screen (yellow)
      warningScreen?.classList.remove('hidden');
      
      // Update content
      const warningMessage = document.getElementById('warning-message');
      const warningGuestName = document.getElementById('warning-guest-name');
      const warningEventName = document.getElementById('warning-event-name');
      const warningCheckedTime = document.getElementById('warning-checked-time');
      
      if (warningMessage) warningMessage.textContent = message;
      if (warningGuestName && ticket) {
        warningGuestName.textContent = ticket.purchaser_name || ticket.purchaser_email || 'Guest';
      }
      if (warningEventName && ticket) {
        warningEventName.textContent = ticket.events?.title || 'Event';
      }
      if (warningCheckedTime && ticket && ticket.scanned_at) {
        const scanTime = new Date(ticket.scanned_at).toLocaleTimeString();
        warningCheckedTime.textContent = `Checked in at ${scanTime}`;
      }
      
    } else {
      // Show error screen (red)
      errorScreen?.classList.remove('hidden');
      
      // Update content
      const errorMessage = document.getElementById('error-message');
      if (errorMessage) errorMessage.textContent = message;
    }
  }

  // Event listeners
  startScanBtn?.addEventListener('click', startCamera);
  stopScanBtn?.addEventListener('click', stopCamera);
  
  // Acknowledge button event listeners
  errorAcknowledgeBtn?.addEventListener('click', () => {
    feedbackOverlay?.classList.add('hidden');
  });
  
  warningAcknowledgeBtn?.addEventListener('click', () => {
    feedbackOverlay?.classList.add('hidden');
  });

  manualCheckinBtn?.addEventListener('click', async () => {
    const ticketId = manualTicketId.value.trim();
    if (!ticketId) {
      alert('Please enter a ticket ID');
      return;
    }
    
    await checkInTicket(ticketId);
    manualTicketId.value = '';
  });

  manualCheckoutBtn?.addEventListener('click', async () => {
    const ticketId = manualTicketId.value.trim();
    if (!ticketId) {
      alert('Please enter a ticket ID');
      return;
    }
    
    await checkOutTicket(ticketId);
    manualTicketId.value = '';
  });

  // Backup scan button
  const backupScanBtn = document.getElementById('backup-scan-btn');
  backupScanBtn?.addEventListener('click', async () => {
    const ticketId = manualTicketId.value.trim();
    if (!ticketId) {
      alert('Please enter a ticket ID');
      return;
    }
    
    await checkInTicketWithCodereadr(ticketId);
    manualTicketId.value = '';
  });

  logoutBtn?.addEventListener('click', async () => {
    await supabase.auth.signOut();
    window.location.href = '/';
  });

  // Help modal functionality
  helpBtn?.addEventListener('click', () => {
    helpModal?.classList.remove('hidden');
  });

  closeHelpModal?.addEventListener('click', () => {
    helpModal?.classList.add('hidden');
  });

  // Close modal when clicking outside
  helpModal?.addEventListener('click', (e) => {
    if (e.target === helpModal) {
      helpModal.classList.add('hidden');
    }
  });

  // Search functionality
  ticketSearch.addEventListener('input', (e) => {
    const query = e.target.value;
    
    // Clear previous timeout
    if (searchTimeout) {
      clearTimeout(searchTimeout);
    }
    
    // Debounce search to avoid too many requests
    searchTimeout = setTimeout(() => {
      searchTickets(query);
    }, 300);
  });

  // Clear search results when input is cleared
  ticketSearch.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      ticketSearch.value = '';
      searchResults.classList.add('hidden');
    }
  });

  // Initialize is now handled by DOMContentLoaded listener above
  
  // Scanner Lock Functionality
  const lockScannerBtn = document.getElementById('lock-scanner-btn');
  const unlockScannerBtn = document.getElementById('unlock-scanner-btn');
  const pinCreationModal = document.getElementById('pin-creation-modal');
  const pinUnlockModal = document.getElementById('pin-unlock-modal');
  const closePinModal = document.getElementById('close-pin-modal');
  const closeUnlockModal = document.getElementById('close-unlock-modal');
  const pinCreationForm = document.getElementById('pin-creation-form');
  const pinUnlockForm = document.getElementById('pin-unlock-form');
  const pinInput = document.getElementById('pin-input');
  const pinConfirm = document.getElementById('pin-confirm');
  const unlockPinInput = document.getElementById('unlock-pin-input');
  const unlockError = document.getElementById('unlock-error');
  const cancelPinBtn = document.getElementById('cancel-pin-btn');
  const cancelUnlockBtn = document.getElementById('cancel-unlock-btn');
  const navigation = document.getElementById('navigation');

  let isLocked = false;
  let currentEventId = null;

  // Check if scanner is already locked on page load
  async function checkScannerLockStatus() {
    try {
      const isLockedStored = localStorage.getItem('scannerLocked');
      const storedEventId = localStorage.getItem('scannerLockedEventId');
      
      if (isLockedStored === 'true' && storedEventId) {
        currentEventId = storedEventId;
        enterLockMode();
      } else {
        // Show lock button if we have events to lock
        await loadAvailableEvents();
      }
    } catch (error) {
      console.error('Error checking scanner lock status:', error);
    }
  }

  // Load available events for locking
  async function loadAvailableEvents() {
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) return;
      
      const { data: userData } = await supabase
        .from('users')
        .select('organization_id')
        .eq('id', session.user.id)
        .single();
      
      if (!userData?.organization_id) return;
      
      const { data: events } = await supabase
        .from('events')
        .select('id, title, start_time, scanner_lock_enabled')
        .eq('organization_id', userData.organization_id)
        .gte('start_time', new Date().toISOString())
        .order('start_time', { ascending: true });
      
      if (events && events.length > 0) {
        // For now, we'll use the first upcoming event
        // In a full implementation, you'd want to let the user choose
        currentEventId = events[0].id;
        lockScannerBtn.classList.remove('hidden');
      }
    } catch (error) {
      console.error('Error loading events:', error);
    }
  }

  // Enter lock mode
  function enterLockMode() {
    isLocked = true;
    lockScannerBtn.classList.add('hidden');
    unlockScannerBtn.classList.remove('hidden');
    
    // Hide other navigation elements
    const helpBtn = document.getElementById('help-btn');
    const logoutBtn = document.getElementById('logout-btn');
    if (helpBtn) helpBtn.classList.add('hidden');
    if (logoutBtn) logoutBtn.classList.add('hidden');
    
    // Hide back button functionality and prevent navigation
    preventNavigation();
    
    localStorage.setItem('scannerLocked', 'true');
    localStorage.setItem('scannerLockedEventId', currentEventId);
  }

  // Exit lock mode
  function exitLockMode() {
    isLocked = false;
    lockScannerBtn.classList.remove('hidden');
    unlockScannerBtn.classList.add('hidden');
    
    // Show other navigation elements
    const helpBtn = document.getElementById('help-btn');
    const logoutBtn = document.getElementById('logout-btn');
    if (helpBtn) helpBtn.classList.remove('hidden');
    if (logoutBtn) logoutBtn.classList.remove('hidden');
    
    // Restore navigation
    restoreNavigation();
    
    localStorage.removeItem('scannerLocked');
    localStorage.removeItem('scannerLockedEventId');
  }

  // Prevent navigation when locked
  function preventNavigation() {
    // Disable browser back button
    history.pushState(null, null, location.href);
    window.addEventListener('popstate', handlePopState);
    
    // Disable common keyboard shortcuts
    document.addEventListener('keydown', handleKeyDown);
    
    // Disable context menu
    document.addEventListener('contextmenu', handleContextMenu);
  }

  // Restore navigation when unlocked
  function restoreNavigation() {
    window.removeEventListener('popstate', handlePopState);
    document.removeEventListener('keydown', handleKeyDown);
    document.removeEventListener('contextmenu', handleContextMenu);
  }

  // Handle back button when locked
  function handlePopState(e) {
    if (isLocked) {
      history.pushState(null, null, location.href);
      e.preventDefault();
    }
  }

  // Handle keyboard shortcuts when locked
  function handleKeyDown(e) {
    if (isLocked) {
      // Disable F5, Ctrl+R, Ctrl+W, Alt+F4, etc.
      if (e.key === 'F5' || 
          (e.ctrlKey && (e.key === 'r' || e.key === 'R' || e.key === 'w' || e.key === 'W')) ||
          (e.altKey && e.key === 'F4')) {
        e.preventDefault();
        return false;
      }
    }
  }

  // Handle context menu when locked
  function handleContextMenu(e) {
    if (isLocked) {
      e.preventDefault();
      return false;
    }
  }

  // Setup PIN creation
  async function setupScannerLock(pin) {
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) throw new Error('Not authenticated');
      
      const { data: userData } = await supabase
        .from('users')
        .select('organization_id, email')
        .eq('id', session.user.id)
        .single();
      
      if (!userData?.organization_id) throw new Error('User not in organization');
      
      const response = await fetch('/api/scanner-lock/setup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`
        },
        body: JSON.stringify({
          eventId: currentEventId,
          pin: pin,
          organizerEmail: userData.email
        })
      });
      
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.error || 'Failed to setup scanner lock');
      }
      
      // Send email with PIN
      await sendPinEmail(result.event, pin, userData.email);
      
      enterLockMode();
      pinCreationModal.classList.add('hidden');
      
      // Show success message
      alert('Scanner locked successfully! PIN has been sent to your email.');
      
    } catch (error) {
      console.error('Error setting up scanner lock:', error);
      alert('Failed to lock scanner: ' + error.message);
    }
  }

  // Verify PIN for unlock
  async function verifyPinForUnlock(pin) {
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) throw new Error('Not authenticated');
      
      const response = await fetch('/api/scanner-lock/verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`
        },
        body: JSON.stringify({
          eventId: currentEventId,
          pin: pin
        })
      });
      
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.error || 'Invalid PIN');
      }
      
      if (result.success) {
        exitLockMode();
        pinUnlockModal.classList.add('hidden');
        unlockError.classList.add('hidden');
        unlockPinInput.value = '';
      } else {
        throw new Error('Invalid PIN');
      }
      
    } catch (error) {
      console.error('Error verifying PIN:', error);
      unlockError.classList.remove('hidden');
      unlockPinInput.value = '';
    }
  }

  // Send PIN email
  async function sendPinEmail(event, pin, email) {
    try {
      const response = await fetch('/api/send-pin-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ event, pin, email, type: 'immediate' })
      });
      
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.error || 'Failed to send email');
      }
      
      console.log('PIN email sent successfully:', result.emailId);
      
    } catch (error) {
      console.error('Error sending PIN email:', error);
      // Don't throw error as this is not critical for the lock functionality
    }
  }

  // Event listeners for scanner lock
  lockScannerBtn?.addEventListener('click', () => {
    pinCreationModal.classList.remove('hidden');
    pinInput.focus();
  });

  unlockScannerBtn?.addEventListener('click', () => {
    pinUnlockModal.classList.remove('hidden');
    unlockPinInput.focus();
  });

  closePinModal?.addEventListener('click', () => {
    pinCreationModal.classList.add('hidden');
  });

  closeUnlockModal?.addEventListener('click', () => {
    pinUnlockModal.classList.add('hidden');
  });

  cancelPinBtn?.addEventListener('click', () => {
    pinCreationModal.classList.add('hidden');
  });

  cancelUnlockBtn?.addEventListener('click', () => {
    pinUnlockModal.classList.add('hidden');
  });

  // PIN creation form
  pinCreationForm?.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const pin = pinInput.value.trim();
    const confirmPin = pinConfirm.value.trim();
    
    if (pin !== confirmPin) {
      alert('PINs do not match');
      return;
    }
    
    if (!/^\d{4}$/.test(pin)) {
      alert('PIN must be exactly 4 digits');
      return;
    }
    
    await setupScannerLock(pin);
  });

  // PIN unlock form
  pinUnlockForm?.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const pin = unlockPinInput.value.trim();
    
    if (!/^\d{4}$/.test(pin)) {
      unlockError.classList.remove('hidden');
      return;
    }
    
    await verifyPinForUnlock(pin);
  });

  // Close modals when clicking outside
  pinCreationModal?.addEventListener('click', (e) => {
    if (e.target === pinCreationModal) {
      pinCreationModal.classList.add('hidden');
    }
  });

  pinUnlockModal?.addEventListener('click', (e) => {
    if (e.target === pinUnlockModal) {
      pinUnlockModal.classList.add('hidden');
    }
  });

  // Auto-format PIN inputs
  [pinInput, pinConfirm, unlockPinInput].forEach(input => {
    input?.addEventListener('input', (e) => {
      e.target.value = e.target.value.replace(/[^0-9]/g, '').slice(0, 4);
    });
  });

  // Check scanner lock status on page load
  checkScannerLockStatus();
</script>