{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}" />
    <link rel="stylesheet" href="{% static 'assets/css/plugins.min.css' %}" />
    <link rel="stylesheet" href="{% static 'assets/fontawesome/css/all.min.css' %}"/>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <title>Accreditation</title>

    <style>
        :root {
            --primary: #0f1729;
            --primary-dark: #0B1426;
            --secondary: #D4AF37;
            --accent: #D4AF37;
            --light: #F8F9FA;
            --dark: #212529;
            --success: #4CC9F0;
            --warning: #F72585;
            --danger: #EF233C;
            --gray: #6C757D;
            --gradient: linear-gradient(135deg, #0f1729 0%, #D4AF37 100%);
            --card-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 10px -2px rgba(0, 0, 0, 0.05);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body, html {
            height: 100%;
            font-family: 'Poppins', sans-serif;
            background: var(--light);
            overflow: hidden;
            color: var(--dark);
        }

        .app-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            max-width: 100%;
            margin: 0 auto;
            position: relative;
            overflow: hidden;
        }

        /* Header Styles */
        .app-header {
            background: var(--primary);
            color: var(--secondary);
            padding: 1rem 1.5rem;
            position: relative;
            z-index: 100;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo-container {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: rgba(212, 175, 55, 0.2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }

        .app-title {
            font-weight: 700;
            font-size: 1.25rem;
        }

        .status-badge {
            background: rgba(212, 175, 55, 0.2);
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 0;
            overflow: hidden;
        }

        /* Scanner Section */
        .scanner-section {
            background: white;
            padding: 1.5rem;
            border-radius: 0 0 24px 24px;
            box-shadow: var(--card-shadow);
            margin-bottom: 1rem;
            z-index: 10;
        }

        .section-title {
            font-weight: 600;
            font-size: 1.1rem;
            margin-bottom: 1rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .section-title i {
            color: var(--primary);
        }

        /* Form Styles */
        .form-container {
            margin-bottom: 1rem;
        }

        .form-group {
            margin-bottom: 1.25rem;
        }

        .form-label {
            font-weight: 500;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
            color: var(--gray);
        }

        .input-with-icon {
            position: relative;
        }

        .input-icon {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray);
            z-index: 5;
        }

        .form-control {
            padding-left: 48px;
            height: 56px;
            border-radius: 12px;
            border: 2px solid #E9ECEF;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.15);
        }

        .btn-primary {
            background: var(--primary);
            color: var(--secondary);
            border: none;
            border-radius: 12px;
            height: 56px;
            font-weight: 600;
            font-size: 1rem;
            box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
            transition: all 0.3s ease;
        }

        .btn-primary:hover, .btn-primary:focus {
            background: var(--primary-dark);
            color: var(--secondary);
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(67, 97, 238, 0.4);
        }

        /* Autocomplete Styles */
        .autocomplete-container {
            position: relative;
        }

        .autocomplete-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border-radius: 0 0 12px 12px;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
            max-height: 250px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
            border: 2px solid var(--primary);
            border-top: none;
        }

        .autocomplete-item {
            padding: 16px;
            cursor: pointer;
            border-bottom: 1px solid #f8f9fa;
            transition: background-color 0.2s;
        }

        .autocomplete-item:hover,
        .autocomplete-item.active {
            background-color: #f8f9fa;
        }

        .autocomplete-item:last-child {
            border-bottom: none;
        }

        .autocomplete-item.accredited-guest {
            background-color: rgba(239, 68, 68, 0.1);
            border-left: 3px solid #ef4444;
        }

        .autocomplete-item.accredited-guest .guest-title {
            color: #dc2626;
        }

        .guest-title {
            font-weight: 600;
            color: var(--dark);
            font-size: 0.95rem;
        }

        .guest-details {
            font-size: 0.8rem;
            color: var(--gray);
            margin-top: 4px;
        }

        .loading-spinner {
            text-align: center;
            padding: 20px;
            color: var(--gray);
        }

        /* Guests List */
        .guests-section {
            flex: 1;
            overflow-y: auto;
            padding: 0 1.5rem 1.5rem;
            display: flex;
            flex-direction: column;
        }

        .guests-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .guests-count {
            font-weight: 600;
            color: var(--dark);
            font-size: 1rem;
        }

        .guests-container {
            flex: 1;
            overflow-y: auto;
        }

        .guest-card {
            background: white;
            border-radius: 16px;
            padding: 1.25rem;
            margin-bottom: 1rem;
            box-shadow: var(--card-shadow);
            border-left: 6px solid var(--success);
            animation: slideIn 0.4s ease-out;
            transition: transform 0.3s ease;
        }

        .guest-card:hover {
            transform: translateY(-4px);
        }

        .guest-card.duplicate {
            border-left-color: var(--warning);
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .guest-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.75rem;
        }

        .guest-name {
            font-weight: 600;
            font-size: 1.1rem;
            color: var(--dark);
            margin-bottom: 0.25rem;
        }

        .guest-status {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            padding: 4px 10px;
            border-radius: 20px;
            background: rgba(76, 201, 240, 0.1);
            color: var(--success);
        }

        .guest-status.duplicate {
            background: rgba(247, 37, 133, 0.1);
            color: var(--warning);
        }

        .guest-details-grid {
            display: grid;
            /*grid-template-columns: 1fr 1fr;*/
            gap: 0.5rem;
            margin-bottom: 0.75rem;
        }

        .guest-detail {
            display: flex;
            align-items: center;
            gap: 4px;
            /*flex-direction: column;*/
        }

        .detail-label {
            font-size: 0.75rem;
            color: var(--gray);
            margin-bottom: 2px;
        }

        .detail-value {
            font-size: 0.9rem;
            font-weight: 500;
            color: var(--dark);
        }

        .guest-time {
            text-align: right;
            font-size: 0.75rem;
            color: var(--gray);
        }

        /* Empty State */
        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 3rem 1rem;
            text-align: center;
            color: var(--gray);
        }

        .empty-icon {
            font-size: 3.5rem;
            margin-bottom: 1rem;
            color: #E9ECEF;
        }

        .empty-text {
            font-size: 1rem;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }

        .empty-subtext {
            font-size: 0.9rem;
        }

        /* Alert Styles */
        .alert-toast {
            position: fixed;
            top: 1rem;
            right: 1rem;
            z-index: 1050;
            min-width: 300px;
            max-width: 90%;
            border-radius: 12px;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
            animation: slideInRight 0.4s ease-out;
            display: none;
        }

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(100%);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        /* QR Scanner Button */
        .qr-scanner-btn {
            position: fixed;
            bottom: 24px;
            right: 24px;
            width: 64px;
            height: 64px;
            border-radius: 50%;
            background: var(--primary);
            color: var(--secondary);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
            z-index: 100;
            border: none;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .qr-scanner-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 25px rgba(67, 97, 238, 0.5);
        }

        /* QR Scanner Modal */
        .qr-scanner-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.95);
            z-index: 2000;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .qr-scanner-modal.active {
            opacity: 1;
            visibility: visible;
        }

        .scanner-container {
            width: 95%;
            max-width: 500px;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            transform: scale(0.9);
            transition: transform 0.3s ease;
        }

        .qr-scanner-modal.active .scanner-container {
            transform: scale(1);
        }

        .scanner-header {
            background: var(--primary);
            color: var(--secondary);
            padding: 1.5rem;
            text-align: center;
            position: relative;
        }

        .scanner-title {
            font-weight: 600;
            font-size: 1.2rem;
            margin: 0;
        }

        .close-scanner {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: rgba(212, 175, 55, 0.2);
            border: none;
            color: var(--secondary);
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background 0.2s;
        }

        .close-scanner:hover {
            background: rgba(212, 175, 55, 0.3);
        }

        .scanner-body {
            padding: 2rem;
            text-align: center;
        }

        #qr-scanner {
            width: 100%;
            height: 300px;
            background: #000;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            position: relative;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #qr-scanner video {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 12px;
        }

        .scanner-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 10;
        }

        .scanner-frame {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 220px;
            height: 220px;
            border: 3px solid var(--primary);
            border-radius: 12px;
            background: transparent;
            box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.5);
        }

        .scanner-frame::before, .scanner-frame::after {
            content: '';
            position: absolute;
            width: 25px;
            height: 25px;
            border: 3px solid var(--primary);
        }

        .scanner-frame::before {
            top: -3px;
            left: -3px;
            border-right: none;
            border-bottom: none;
            border-radius: 8px 0 0 0;
        }

        .scanner-frame::after {
            bottom: -3px;
            right: -3px;
            border-left: none;
            border-top: none;
            border-radius: 0 0 8px 0;
        }

        .scanner-instructions {
            color: var(--gray);
            font-size: 0.9rem;
            margin-bottom: 1.5rem;
        }

        .scanner-actions {
            display: flex;
            gap: 12px;
        }

        .scanner-actions button {
            flex: 1;
            padding: 12px;
            border-radius: 10px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-cancel {
            background: var(--primary);
            color: var(--secondary);
        }

        .btn-cancel:hover {
            background: var(--primary-dark);
            color: var(--secondary);
        }

        /* Scanner Status */
        .scanner-status {
            margin-top: 10px;
            font-size: 0.8rem;
            color: var(--gray);
        }

        .permission-help {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 12px;
            margin-top: 10px;
            font-size: 0.8rem;
            color: #856404;
            display: none;
        }

        .permission-help ul {
            margin: 8px 0 0 0;
            padding-left: 20px;
            text-align: left;
        }

        /* Mobile Responsive */
        @media (min-width: 768px) {
            .app-container {
                max-width: 600px;
            }

            .guests-section {
                padding: 0 2rem 2rem;
            }

            .scanner-section {
                padding: 2rem;
            }
        }

        @media (min-width: 992px) {
            .app-container {
                max-width: 800px;
            }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- Header -->
        <header class="app-header">
            <div class="header-content">
                <div class="logo-container">
                    <div class="logo-icon">
                        <i class="fas fa-id-card-alt"></i>
                    </div>
                    <h1 class="app-title">Accreditation</h1>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Scanner Section -->
            <section class="scanner-section">
                <h2 class="section-title">
                    <i class="fas fa-user-check"></i> Guest Check-In
                </h2>

                <div class="form-container">
                    <form id="scanForm" method="post">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="name" class="form-label">Search by Guest Name</label>
                            <div class="autocomplete-container">
                                <div class="input-with-icon">
                                    <i class="fas fa-search input-icon"></i>
                                    <input type="text" name="name" id="name"
                                           class="form-control form-control-lg"
                                           required autofocus
                                           autocomplete="off"
                                           placeholder="Enter guest name..." />
                                </div>
                                <div class="autocomplete-dropdown" id="autocompleteDropdown">
                                    <!-- Dropdown items will be populated here -->
                                </div>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary col-12" id="submitButton">
                            <i class="fas fa-check-circle me-2"></i> CHECK IN
                        </button>
                    </form>
                </div>
            </section>

            <!-- Guests List -->
            <section class="guests-section">
                <div class="guests-header">
                    <h2 class="section-title">
                        <i class="fas fa-list-alt"></i> Recent Guest Check-Ins
                    </h2>
                    <div class="guests-count" id="guestsCount">0 Guests</div>
                </div>

                <div class="guests-container" id="guestsList">
                    <div class="empty-state" id="emptyState">
                        <i class="fas fa-users empty-icon"></i>
                        <p class="empty-text">No guests checked in yet</p>
                        <p class="empty-subtext">Check in your first guest to get started</p>
                    </div>
                </div>
            </section>
        </main>

        <!-- QR Scanner Button -->
        <button class="qr-scanner-btn" id="qrScannerButton">
            <i class="fas fa-qrcode"></i>
        </button>

        <!-- QR Scanner Modal -->
        <div class="qr-scanner-modal" id="qrScannerModal">
            <div class="scanner-container">
                <div class="scanner-header">
                    <h3 class="scanner-title">Scan QR Code</h3>
                    <button class="close-scanner" id="closeScanner">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="scanner-body">
                    <div id="qr-scanner">
                        <!-- Camera feed will be inserted here by the scanner library -->
                        <div class="scanner-overlay">
                            <div class="scanner-frame"></div>
                        </div>
                    </div>
                    <!--<p class="scanner-instructions">-->
                    <!--    Position the QR code within the frame to scan automatically-->
                    <!--</p>-->
                    <div class="scanner-status" id="scannerStatus">
                        Initializing camera...
                    </div>
                    <div class="permission-help" id="permissionHelp">
                        <strong>Camera access required</strong>
                        <ul>
                            <li>Check if camera permissions are enabled for this site</li>
                            <li>Make sure no other app is using the camera</li>
                            <li>Try refreshing the page and allowing camera access</li>
                        </ul>
                    </div>
                    <div class="scanner-actions">
                        <button class="btn-cancel" id="cancelScan">
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Check-in Modal -->
        <div class="modal fade" id="checkInModal" tabindex="-1" aria-labelledby="checkInModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="checkInModalLabel">Check-in Guest</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div id="ticketInfo" class="mb-3">
                            <!-- Ticket info will be populated here -->
                        </div>
                        <div class="mb-3 d-none" id="quantitySection">
                            <label for="checkInQuantity" class="form-label">Number of guests to check in:</label>
                            <input type="number" class="form-control" id="checkInQuantity" value="1">
                        </div>
                        <!-- <div class="text-center mb-3">
                            <button type="button" class="btn btn-success btn-sm" id="accreditAllBtn">
                                <i class="fas fa-check-double me-1"></i>Accredit All Remaining Guests
                            </button>
                        </div> -->
                        <div id="errorMessage" class="text-danger" style="display: none;"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="confirmCheckIn">Check In</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Alert Toast -->
    <div class="alert alert-success alert-dismissible fade show alert-toast" role="alert" id="alertToast">
        <div class="d-flex">
            <div class="me-3">
                <i class="fas fa-check-circle" id="alertIcon"></i>
            </div>
            <div class="flex-grow-1">
                <h6 class="alert-heading mb-1" id="alertTitle">Success</h6>
        <p class="mb-0" id="alertMessage">Guest checked in successfully</p>
    </div>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
</div>

<script src="{% static 'assets/js/core/jquery-3.7.1.min.js' %}"></script>
<script src="{% static 'assets/js/core/bootstrap.min.js' %}"></script>
<!-- QR Code Scanner Library -->
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>

<script>
    $(document).ready(function() {
        let selectedGuestName = '';
        let currentFocus = -1;
        let guestCount = 0;
        let qrScanner = null;
        let isScannerActive = false;

        // Wait for html5-qrcode library to load
        function waitForLibrary(callback, maxAttempts = 20) {
            let attempts = 0;

            const checkLibrary = setInterval(() => {
                attempts++;
                console.log(`Checking for Html5Qrcode library... Attempt ${attempts}`);

                if (typeof Html5Qrcode !== 'undefined') {
                    clearInterval(checkLibrary);
                    console.log('Html5Qrcode library loaded successfully!');
                    callback(true);
                } else if (attempts >= maxAttempts) {
                    clearInterval(checkLibrary);
                    console.error('Html5Qrcode library failed to load after ' + maxAttempts + ' attempts');
                    callback(false);
                }
            }, 250); // Check every 250ms
        }

        // Initialize after checking library
        waitForLibrary(function(loaded) {
            if (loaded) {
                initializeApp();
            } else {
                // Show error and disable QR button
                $('#qrScannerButton').on('click', function() {
                    showAlert('QR Scanner library failed to load. Please refresh the page.', 'danger');
                });
                console.error('Failed to load Html5Qrcode library. Check your internet connection and CDN availability.');
            }
        });

        function initializeApp() {
            console.log('Initializing app with QR scanner support...');

            // Focus the input field on page load
            // $('#name').focus();

            // QR Scanner functionality
            const qrScannerButton = $('#qrScannerButton');
            const qrScannerModal = $('#qrScannerModal');
            const closeScanner = $('#closeScanner');
            const cancelScan = $('#cancelScan');
            const scannerStatus = $('#scannerStatus');
            const permissionHelp = $('#permissionHelp');

            // Open QR Scanner
            qrScannerButton.on('click', function() {
                console.log('QR Scanner button clicked');
                qrScannerModal.addClass('active');

                // Add a small delay to ensure modal is visible
                setTimeout(() => {
                    initializeQrScanner();
                }, 300);
            });

            // Close QR Scanner
            function closeQrScanner() {
                console.log('Closing QR Scanner');
                qrScannerModal.removeClass('active');
                stopQrScanner();
            }

            closeScanner.on('click', closeQrScanner);
            cancelScan.on('click', closeQrScanner);

            // Close modal when clicking outside
            qrScannerModal.on('click', function(e) {
                if ($(e.target).is('#qrScannerModal')) {
                    closeQrScanner();
                }
            });

            // Stop QR Scanner
            function stopQrScanner() {
                if (qrScanner && isScannerActive) {
                    console.log('Stopping QR Scanner...');
                    scannerStatus.text('Stopping camera...');

                    qrScanner.stop().then(() => {
                        isScannerActive = false;
                        scannerStatus.text('Camera stopped');
                        console.log("QR Scanner stopped successfully");
                    }).catch(err => {
                        console.error("Failed to stop QR scanner", err);
                        scannerStatus.text('Error stopping camera');
                        isScannerActive = false;
                    });
                }
            }

            // Initialize QR Scanner
            function initializeQrScanner() {
                console.log('Initializing QR Scanner...');

                // Check if scanner is already active
                if (isScannerActive) {
                    console.log('Scanner already active');
                    return;
                }

                // Check for camera support
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    console.error('Camera not supported on this device/browser');
                    scannerStatus.text('Camera not supported on this device or browser');
                    permissionHelp.show();
                    showAlert('Camera not supported on this device or browser', 'danger');
                    return;
                }

                scannerStatus.text('Requesting camera permission...');
                permissionHelp.hide();

                // Create scanner instance
                if (!qrScanner) {
                    try {
                        qrScanner = new Html5Qrcode("qr-scanner");
                        console.log('Html5Qrcode instance created');
                    } catch (err) {
                        console.error('Failed to create Html5Qrcode instance:', err);
                        scannerStatus.text('Failed to initialize scanner');
                        showAlert('Failed to initialize QR scanner', 'danger');
                        return;
                    }
                }

                const config = {
                    fps: 10,
                    qrbox: { width: 200, height: 200 },
                    aspectRatio: 1.0,
                    disableFlip: false
                };

                console.log('Getting camera list...');

                // Try to get cameras
                Html5Qrcode.getCameras().then(cameras => {
                    console.log('Cameras found:', cameras.length);

                    if (cameras && cameras.length > 0) {
                        cameras.forEach((camera, index) => {
                            console.log(`Camera ${index}:`, camera.label, camera.id);
                        });

                        scannerStatus.text('Camera found. Starting scanner...');

                        // Try rear camera first
                        let cameraId = null;
                        const rearCamera = cameras.find(camera => {
                            const label = camera.label.toLowerCase();
                            return label.includes('back') ||
                                   label.includes('rear') ||
                                   label.includes('environment');
                        });

                        if (rearCamera) {
                            cameraId = rearCamera.id;
                            console.log("Using rear camera:", rearCamera.label);
                        } else {
                            cameraId = cameras[cameras.length - 1].id;
                            console.log("Using last camera:", cameras[cameras.length - 1].label);
                        }

                        startScanner(cameraId, config);

                    } else {
                        console.log('No cameras in list, trying default camera');
                        startScannerWithConstraints(config);
                    }
                }).catch(err => {
                    console.error("Error getting camera list:", err);
                    console.log('Attempting to start with default camera...');
                    startScannerWithConstraints(config);
                });
            }

            // Start scanner with specific camera ID
            function startScanner(cameraId, config) {
                console.log('Starting scanner with camera ID:', cameraId);

                qrScanner.start(
                    cameraId,
                    config,
                    onQrScanSuccess,
                    onQrScanFailure
                ).then(() => {
                    isScannerActive = true;
                    scannerStatus.text('Scanner active. Point camera at QR code.');
                    console.log("QR Scanner started successfully");
                }).catch(err => {
                    console.error("Failed to start scanner with camera ID:", err);
                    scannerStatus.text('Failed with selected camera, trying default...');
                    startScannerWithConstraints(config);
                });
            }

            // Start scanner with media constraints
            function startScannerWithConstraints(config) {
                console.log('Starting scanner with constraints...');

                const constraints = { facingMode: "environment" };

                qrScanner.start(
                    constraints,
                    config,
                    onQrScanSuccess,
                    onQrScanFailure
                ).then(() => {
                    isScannerActive = true;
                    scannerStatus.text('Scanner active. Point camera at QR code.');
                    console.log("QR Scanner started with environment camera");
                }).catch(envErr => {
                    console.error("Environment camera failed:", envErr);

                    const userConstraints = { facingMode: "user" };

                    qrScanner.start(
                        userConstraints,
                        config,
                        onQrScanSuccess,
                        onQrScanFailure
                    ).then(() => {
                        isScannerActive = true;
                        scannerStatus.text('Scanner active (front camera). Point at QR code.');
                        console.log("QR Scanner started with user camera");
                    }).catch(userErr => {
                        console.error("All camera attempts failed:", userErr);
                        handleCameraError(userErr);
                    });
                });
            }

            // Handle camera errors
            function handleCameraError(error) {
                let errorMessage = 'Failed to access camera';

                if (error) {
                    console.error('Camera error details:', error);

                    const errorString = error.toString().toLowerCase();

                    if (errorString.includes('notallowederror') || errorString.includes('permission')) {
                        errorMessage = 'Camera permission denied. Please allow camera access.';
                    } else if (errorString.includes('notfounderror')) {
                        errorMessage = 'No camera found on this device.';
                    } else if (errorString.includes('notreadableerror')) {
                        errorMessage = 'Camera is already in use.';
                    } else if (errorString.includes('notsupportederror')) {
                        errorMessage = 'Camera not supported on this browser.';
                    } else if (error.message) {
                        errorMessage = error.message;
                    }
                }

                scannerStatus.text(errorMessage);
                permissionHelp.show();
                showAlert(errorMessage, 'danger');
            }

            // Handle QR scan success
            function onQrScanSuccess(decodedText, decodedResult) {
                console.log("QR Code scanned:", decodedText);

                if (navigator.vibrate) {
                    navigator.vibrate(200);
                }

                stopQrScanner();

                setTimeout(() => {
                    qrScannerModal.removeClass('active');
                }, 100);

                // Show check-in modal with ticket details
                processScan(decodedText);
                showAlert('QR code scanned successfully', 'success');
            }

            // Handle QR scan failure
            function onQrScanFailure(error) {
                if (error &&
                    !error.includes("No QR code found") &&
                    !error.includes("NotFoundException") &&
                    !error.includes("No MultiFormat Readers")) {
                    console.log("Scan error:", error);
                }
            }

            // REST OF YOUR EXISTING FUNCTIONS
            // (Keep all your existing autocomplete, form handling, etc.)

            // Handle input for autocomplete
            $('#name').on('input', function() {
                const query = $(this).val().trim();
                selectedGuestName = '';

                if (query.length >= 2) {
                    searchGuests(query);
                } else {
                    hideDropdown();
                }
            });

            // Handle keyboard navigation
            $('#name').on('keydown', function(e) {
                const dropdown = $('#autocompleteDropdown');
                const items = dropdown.find('.autocomplete-item');

                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    currentFocus++;
                    if (currentFocus >= items.length) currentFocus = 0;
                    addActive(items);
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    currentFocus--;
                    if (currentFocus < 0) currentFocus = items.length - 1;
                    addActive(items);
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    if (currentFocus > -1 && items.length > 0) {
                        items.eq(currentFocus).click();
                    } else if (selectedGuestName) {
                        $('#scanForm').submit();
                    }
                } else if (e.key === 'Escape') {
                    hideDropdown();
                }
            });

            $(document).on('click', function(e) {
                if (!$(e.target).closest('.autocomplete-container').length) {
                    hideDropdown();
                }
            });

            $('#scanForm').on('submit', function(event) {
                event.preventDefault();
                const name = selectedGuestName || $('#name').val().trim();
                if (!name) {
                    showAlert('Please enter guest name', 'warning');
                    return;
                }
                processScan(name);
            });

            function searchGuests(query) {
                $.ajax({
                    url: "{% url 'search_guests' %}",
                    type: "GET",
                    data: { 'q': query },
                    beforeSend: function() {
                        showDropdown();
                        $('#autocompleteDropdown').html(`
                            <div class="loading-spinner">
                                <i class="fas fa-spinner fa-spin me-2"></i> Searching...
                            </div>
                        `);
                    },
                    success: function(data) {
                        displaySearchResults(data.tickets);
                    },
                    error: function() {
                        $('#autocompleteDropdown').html(`
                            <div class="autocomplete-item">
                                <span class="text-danger">Error searching guests</span>
                            </div>
                        `);
                    }
                });
            }

            function displaySearchResults(tickets) {
                const dropdown = $('#autocompleteDropdown');
                currentFocus = -1;

                if (tickets.length === 0) {
                    dropdown.html(`
                        <div class="autocomplete-item">
                            <span class="text-muted">No tickets found</span>
                        </div>
                    `);
                    return;
                }

                let html = '';
                tickets.forEach(function(ticket) {
                    const details = [];
                    if (ticket.email) details.push(`${ticket.email}`);
                    const accreditedClass = ticket.is_accredited ? 'accredited-guest' : '';

                    html += `
                        <div class="autocomplete-item ${accreditedClass}" data-name="${ticket.name}">
                            <div class="guest-title">${ticket.name}</div>
                            ${details.length > 0 ? `<div class="guest-details">${details.join(' • ')}</div>` : ''}
                        </div>
                    `;
                });

                dropdown.html(html);
                dropdown.find('.autocomplete-item').on('click', function() {
                    const name = $(this).data('name');
                    selectGuest(name);
                });
            }

            function selectGuest(name) {
                selectedGuestName = name;
                $('#name').val(name);
                hideDropdown();
            }

            function addActive(items) {
                removeActive(items);
                if (currentFocus >= 0 && currentFocus < items.length) {
                    items.eq(currentFocus).addClass('active');
                }
            }

            function removeActive(items) {
                items.removeClass('active');
            }

            function showDropdown() {
                $('#autocompleteDropdown').show();
            }

            function hideDropdown() {
                $('#autocompleteDropdown').hide();
                currentFocus = -1;
            }

            function processScan(code, accreditAll = false) {
                $('#submitButton').html(`
                    <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                    Processing...
                `).prop('disabled', true);

                $.ajax({
                    url: "{% url 'check_in' %}",
                    type: "POST",
                    data: {
                        'name': code,
                        'accredit_all': accreditAll ? 'true' : 'false',
                        'csrfmiddlewaretoken': "{{ csrf_token }}"
                    },
                    success: function(data) {
                        if (data.status === 200 && data.ticket) {
                            // Show modal with ticket info
                            showCheckInModal(data.ticket);
                        } else if (data.status === 200) {
                            // Direct success (shouldn't happen in new flow)
                            showAlert(data.message, 'success');
                        } else if (data.status === 403) {
                            showAlert(data.message, 'warning');
                        } else if (data.status === 404) {
                            showAlert('Guest not found', 'danger');
                        } else if (data.status === 400) {
                            showAlert(data.message, 'danger');
                        }

                        $('#name').val('');
                        selectedGuestName = '';
                        hideDropdown();
                    },
                    error: function() {
                        showAlert('Error processing request', 'danger');
                    },
                    complete: function() {
                        $('#submitButton').html('<i class="fas fa-check-circle me-2"></i> CHECK IN').prop('disabled', false);
                    }
                });
            }

            function showCheckInModal(ticket) {
                $('#ticketInfo').html(`
                    <div class="card">
                        <div class="card-body">
                            <h2 class="card-title">${ticket.name}</h2>
                            <p class="card-text">
                                Email: ${ticket.email || 'N/A'}<br>
                                Phone: ${ticket.phone || 'N/A'}<br>
                            </p>
                            <br />
                            ${ticket.has_driver ? `<span class="card-text">With Driver: Yes</span>` : ''}
                        </div>
                    </div>
                `);

                // Check if all tickets are already accredited
                if (ticket.accredited_quantity >= ticket.total_quantity) {
                    // Replace quantity input with completion message
                    $('#quantitySection').html(`
                        <div class="alert alert-success">
                            <h6 class="alert-heading"><i class="fas fa-check-circle me-2"></i>Guest Already Checked In</h6>
                        </div>
                    `).removeClass('d-none');
                    // Hide the Check In button and show only Close
                    $('.modal-footer').html(`
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    `);
                } else {
                    // Show normal quantity input
                    $('#quantitySection').html(`
                        <label for="checkInQuantity" class="form-label">Number of tickets to check in:</label>
                        <input type="number" class="form-control" id="checkInQuantity" min="1" value="1">
                    `).removeClass('d-none');
                    $('#checkInQuantity').val(1).attr('max', ticket.remaining_quantity);
                    // Restore normal footer
                    $('.modal-footer').html(`
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="confirmCheckIn">Check In</button>
                    `);
                    // Re-bind the click handler
                    $('#confirmCheckIn').off('click').on('click', function() {
                        const quantity = parseInt($('#checkInQuantity').val());
                        const maxQuantity = parseInt($('#checkInQuantity').attr('max'));

                        if (quantity <= 0) {
                            $('#errorMessage').text('Please enter a valid quantity greater than 0.').show();
                            return;
                        }

                        if (quantity > maxQuantity) {
                            $('#errorMessage').text(`Cannot check in more than ${maxQuantity} tickets.`).show();
                            return;
                        }

                        $('#errorMessage').hide();
                        performCheckIn(quantity);
                    });

                    // Handle "Accredit All" button
                    $('#accreditAllBtn').off('click').on('click', function() {
                        const maxQuantity = parseInt($('#checkInQuantity').attr('max'));

                        if (maxQuantity <= 0) {
                            $('#errorMessage').text('No tickets remaining to accredit.').show();
                            return;
                        }

                        $('#errorMessage').hide();
                        performCheckIn(maxQuantity, true); // true indicates accredit all
                    });
                }

                $('#errorMessage').hide();
                $('#checkInModal').modal('show');
            }

            $('#confirmCheckIn').on('click', function() {
                const quantity = parseInt($('#checkInQuantity').val());
                const maxQuantity = parseInt($('#checkInQuantity').attr('max'));

                if (quantity <= 0) {
                    $('#errorMessage').text('Please enter a valid quantity greater than 0.').show();
                    return;
                }

                if (quantity > maxQuantity) {
                    $('#errorMessage').text(`Cannot check in more than ${maxQuantity} tickets.`).show();
                    return;
                }

                $('#errorMessage').hide();
                performCheckIn(quantity);
            });

            function performCheckIn(quantity, accreditAll = false) {
                $('#confirmCheckIn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Processing...');
                $('#accreditAllBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Processing...');

                const ticketName = $('#ticketInfo .card-title').text().trim();

                $.ajax({
                    url: "{% url 'check_in' %}",
                    type: "POST",
                    data: {
                        'name': ticketName,
                        'quantity': quantity,
                        'accredit_all': accreditAll ? 'true' : 'false',
                        'csrfmiddlewaretoken': "{{ csrf_token }}"
                    },
                    success: function(data) {
                        if (data.status === 200) {
                            showAlert(data.message, 'success');
                            $('#checkInModal').modal('hide');
                            // Add to recent check-ins list
                            if (data.guest) {
                                addGuestCard(data.guest, false);
                                updateGuestCount(1);
                            }
                        } else if (data.status === 400) {
                            $('#errorMessage').text(data.message).show();
                        } else {
                            showAlert('Error during check-in', 'danger');
                        }
                    },
                    error: function() {
                        showAlert('Error processing check-in', 'danger');
                    },
                    complete: function() {
                        $('#confirmCheckIn').prop('disabled', false).html('Check In');
                        $('#accreditAllBtn').prop('disabled', false).html('<i class="fas fa-check-double me-1"></i>Accredit All Remaining Tickets');
                    }
                });
            }

            function addGuestCard(guest, isDuplicate) {
                if ($('#emptyState').length) {
                    $('#emptyState').remove();
                }

                const cardClass = isDuplicate ? 'guest-card duplicate' : 'guest-card';
                const statusClass = isDuplicate ? 'guest-status duplicate' : 'guest-status';
                const statusIcon = isDuplicate ? 'fa-exclamation-circle' : 'fa-check-circle';
                const statusText = isDuplicate ? 'Already Accredited' : 'Checked In';

                const emailHtml = guest.email ? `
                    <div class="guest-detail">
                        <span class="detail-label">Email: </span>
                        <span class="detail-value"> ${guest.email}</span>
                    </div>
                ` : '';
                const phoneHtml = guest.phone ? `
                    <div class="guest-detail">
                        <span class="detail-label">Phone: </span>
                        <span class="detail-value"> ${guest.phone}</span>
                    </div>
                ` : '';

                const hasDriverHtml = guest.has_driver ? `
                    <div class="guest-detail">
                        <span class="detail-label">With Driver: </span>
                        <span class="detail-value"> Yes</span>
                    </div>
                ` : '';

                const guestCard = `
                    <div class="${cardClass}">
                        <div class="guest-header">
                            <div>
                                <div class="guest-name"> ${guest.name}</div>
                            </div>
                            <div class="${statusClass}">
                                <i class="fas ${statusIcon}"></i> ${statusText}
                            </div>
                        </div>
                        <div class="guest-details-grid">
                            ${emailHtml}
                            ${phoneHtml}
                            ${hasDriverHtml}
                        </div>
                        <div class="guest-time">
                            ${new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
                        </div>
                    </div>
                `;

                $('#guestsList').prepend(guestCard);
                $('#guestsList').scrollTop(0);
            }

            function updateGuestCount(increment) {
                guestCount += increment;
                $('#guestsCount').text(guestCount + ' Guest' + (guestCount !== 1 ? 's' : ''));
            }

            function showAlert(message, type) {
                const alert = $('#alertToast');
                const icon = $('#alertIcon');
                const title = $('#alertTitle');
                const messageEl = $('#alertMessage');

                alert.removeClass('alert-success alert-warning alert-danger');

                switch(type) {
                    case 'success':
                        alert.addClass('alert-success');
                        icon.removeClass().addClass('fas fa-check-circle');
                        title.text('Success');
                        break;
                    case 'warning':
                        alert.addClass('alert-warning');
                        icon.removeClass().addClass('fas fa-exclamation-triangle');
                        title.text('Warning');
                        break;
                    case 'danger':
                        alert.addClass('alert-danger');
                        icon.removeClass().addClass('fas fa-times-circle');
                        title.text('Error');
                        break;
                }

                messageEl.text(message);
                alert.show();

                setTimeout(() => {
                    alert.hide();
                }, 4000);
            }
        }
    });
</script>
</body>
</html>