<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ page_title }} - MBetter</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .mobile-header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .verification-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
        }
        
        .scanner-container {
            border-radius: 15px;
            overflow: hidden;
            background: #000;
        }
        
        #qr-video {
            width: 100%;
            height: auto;
            max-height: 300px;
            object-fit: cover;
        }
        
        .btn-mobile {
            border-radius: 25px;
            padding: 12px 30px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            transition: all 0.3s ease;
        }
        
        .btn-mobile:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
        }
        
        .status-alert {
            border-radius: 15px;
            border: none;
            backdrop-filter: blur(10px);
        }
        
        .modal-content {
            border-radius: 20px;
            border: none;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        }
        
        .badge {
            border-radius: 10px;
        }
        
        .table {
            border-radius: 10px;
            overflow: hidden;
        }
        
        .boxing-glove {
            color: #ff6b35;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        
        .loading-spinner {
            animation: spin 2s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- Mobile Header -->
    <div class="mobile-header py-3 mb-4">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-2">
                    <i class="fas fa-hand-rock boxing-glove fa-2x"></i>
                </div>
                <div class="col-8 text-center">
                    <h4 class="mb-0 fw-bold text-dark">MBetter</h4>
                    <small class="text-muted">Bet Verification</small>
                </div>
                <div class="col-2 text-end">
                    <i class="fas fa-qrcode fa-2x text-primary"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container pb-4">
        <!-- Scanner Card -->
        <div class="verification-card p-4 mb-4">
            <div class="text-center mb-4">
                <i class="fas fa-camera fa-3x text-primary mb-3"></i>
                <h3 class="fw-bold text-dark">Scan Receipt Code</h3>
                <p class="text-muted">Point your camera at the QR code or barcode on your thermal receipt</p>
            </div>
            
            <!-- Manual Barcode Input -->
            <div class="mb-4">
                <div class="form-floating">
                    <input type="text" class="form-control" id="barcode-input" placeholder="Barcode Scanner Input" autocomplete="off">
                    <label for="barcode-input">
                        <i class="fas fa-barcode me-2"></i>Barcode Scanner Input
                    </label>
                </div>
                <div class="form-text text-center">
                    Use a barcode scanner device or type the code manually
                </div>
            </div>

            <!-- Scanner Controls -->
            <div class="text-center mb-4">
                <button class="btn btn-success btn-mobile me-2" id="start-scanner">
                    <i class="fas fa-play me-2"></i>Start Camera
                </button>
                <button class="btn btn-secondary btn-mobile" id="stop-scanner" disabled>
                    <i class="fas fa-stop me-2"></i>Stop Camera
                </button>
            </div>

            <!-- Camera Preview -->
            <div id="scanner-container" class="text-center mb-3">
                <div class="scanner-container">
                    <video id="qr-video" style="display: none;"></video>
                    <canvas id="qr-canvas" style="display: none;"></canvas>
                    <div id="scanner-placeholder" class="bg-dark text-white p-5">
                        <i class="fas fa-camera fa-4x text-muted mb-3"></i>
                        <p class="text-muted mb-0">Camera will appear here</p>
                    </div>
                </div>
            </div>

            <!-- Scanner Status -->
            <div id="scanner-status" class="status-alert alert alert-info text-center" style="display: none;">
                <i class="fas fa-info-circle me-2"></i>
                <span id="scanner-message">Ready to scan QR codes</span>
            </div>
        </div>

        <!-- Instructions Card -->
        <div class="verification-card p-4">
            <h5 class="fw-bold text-dark mb-3">
                <i class="fas fa-question-circle me-2"></i>How to Use
            </h5>
            <div class="row">
                <div class="col-12">
                    <div class="d-flex align-items-start mb-3">
                        <div class="badge bg-primary rounded-circle me-3 p-2" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center;">1</div>
                        <div>
                            <h6 class="fw-bold">Start the Scanner</h6>
                            <p class="text-muted mb-0">Tap "Start Scanner" to activate your camera</p>
                        </div>
                    </div>
                    <div class="d-flex align-items-start mb-3">
                        <div class="badge bg-primary rounded-circle me-3 p-2" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center;">2</div>
                        <div>
                            <h6 class="fw-bold">Scan QR Code or Barcode</h6>
                            <p class="text-muted mb-0">Point your camera at the QR code or barcode on your thermal receipt</p>
                        </div>
                    </div>
                    <div class="d-flex align-items-start">
                        <div class="badge bg-primary rounded-circle me-3 p-2" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center;">3</div>
                        <div>
                            <h6 class="fw-bold">View Results</h6>
                            <p class="text-muted mb-0">See your bet details and current results</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bet Details Modal -->
    <div class="modal fade" id="betDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-fullscreen-sm-down modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold">
                        <i class="fas fa-receipt me-2"></i>Bet Verification Results
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="bet-details-content">
                    <!-- Bet details will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-mobile" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- QR Scanner JS -->
    <script src="https://unpkg.com/jsqr/dist/jsQR.js"></script>
    <!-- Currency Formatter (simple version for mobile) -->
    <script>
        // Simple currency formatter for mobile
        function formatCurrency(amount) {
            // Default to Ugandan Shilling if no configuration available
            const symbol = 'USh';
            const position = 'before';
            const formattedAmount = parseFloat(amount).toFixed(2);
            
            return position === 'before' ? `${symbol}${formattedAmount}` : `${formattedAmount}${symbol}`;
        }
    </script>
    <script>
        let video = null;
        let canvas = null;
        let canvasContext = null;
        let animationFrame = null;

        document.addEventListener('DOMContentLoaded', function() {
            // Initialize QR scanner elements
            video = document.getElementById('qr-video');
            canvas = document.getElementById('qr-canvas');
            canvasContext = canvas.getContext('2d');
            
            // Scanner controls
            document.getElementById('start-scanner').addEventListener('click', startScanner);
            document.getElementById('stop-scanner').addEventListener('click', stopScanner);
            
            // Barcode input handling
            const barcodeInput = document.getElementById('barcode-input');
            barcodeInput.addEventListener('input', handleBarcodeInput);
            barcodeInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    processBarcodeInput();
                }
            });
        });

        async function startScanner() {
            try {
                // Check browser compatibility first
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    let errorMsg = 'Camera access not available. ';
                    if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
                        errorMsg += 'Please access this page via HTTPS for camera access on mobile devices.';
                    } else {
                        errorMsg += 'Your browser may not support camera access. Please use Chrome, Safari, or Firefox.';
                    }
                    throw new Error(errorMsg);
                }

                // Request camera with progressive fallback for mobile
                let stream;
                try {
                    // Try back camera first (preferred for QR scanning)
                    stream = await navigator.mediaDevices.getUserMedia({
                        video: {
                            facingMode: { ideal: 'environment' },
                            width: { ideal: 1280 },
                            height: { ideal: 720 }
                        }
                    });
                } catch (envError) {
                    console.warn('Back camera failed, trying front camera:', envError);
                    try {
                        // Fallback to front camera
                        stream = await navigator.mediaDevices.getUserMedia({
                            video: {
                                facingMode: 'user',
                                width: { ideal: 640 },
                                height: { ideal: 480 }
                            }
                        });
                    } catch (userError) {
                        console.warn('Front camera failed, trying any camera:', userError);
                        // Final fallback to any available camera
                        stream = await navigator.mediaDevices.getUserMedia({
                            video: {
                                width: { ideal: 640 },
                                height: { ideal: 480 }
                            }
                        });
                    }
                }
                
                video.srcObject = stream;
                
                // Wait for video to be ready
                await new Promise((resolve, reject) => {
                    video.onloadedmetadata = () => resolve();
                    video.onerror = (error) => reject(new Error('Video loading failed'));
                    setTimeout(() => reject(new Error('Video loading timeout')), 10000);
                });
                
                await video.play();
                
                document.getElementById('scanner-placeholder').style.display = 'none';
                video.style.display = 'block';
                
                document.getElementById('start-scanner').disabled = true;
                document.getElementById('stop-scanner').disabled = false;
                
                showScannerStatus('Scanner active - Point camera at QR code or barcode', 'info');
                
                // Start scanning
                scanQRCode();
                
            } catch (error) {
                console.error('Error starting scanner:', error);
                
                let errorMessage = 'Failed to start camera: ';
                
                if (error.name === 'NotAllowedError') {
                    errorMessage += 'Camera permission denied. Please tap "Allow" when prompted, or enable camera access in your browser settings for this site.';
                } else if (error.name === 'NotFoundError') {
                    errorMessage += 'No camera found. Please ensure your device has a working camera.';
                } else if (error.name === 'NotReadableError') {
                    errorMessage += 'Camera is currently in use. Please close other camera apps and try again.';
                } else if (error.name === 'OverconstrainedError') {
                    errorMessage += 'Camera settings not supported. This may be a compatibility issue with your device.';
                } else if (error.name === 'NotSupportedError') {
                    errorMessage += 'Camera API not supported. Please use a modern mobile browser.';
                } else if (error.name === 'SecurityError') {
                    errorMessage += 'Secure connection required. Please access via HTTPS.';
                } else if (error.message.includes('HTTPS') || error.message.includes('browser')) {
                    errorMessage += error.message;
                } else {
                    errorMessage += error.message || 'Unknown error occurred.';
                }
                
                showScannerStatus(errorMessage, 'danger');
                showMobileCameraTroubleshooting();
            }
        }

        function showMobileCameraTroubleshooting() {
            const scannerContainer = document.getElementById('scanner-container');
            const troubleshootingHtml = `
                <div class="alert alert-warning mt-3">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>Camera Troubleshooting for Mobile</h6>
                    <ul class="mb-0 small">
                        <li>Ensure you're using <strong>HTTPS</strong> (look for the lock icon in your browser)</li>
                        <li>Tap "Allow" when prompted for camera permission</li>
                        <li>Check your device settings to ensure camera access is enabled for this browser</li>
                        <li>Close other camera apps (Instagram, Snapchat, etc.) and try again</li>
                        <li>Try refreshing the page and allowing camera access again</li>
                        <li>Use Chrome, Safari, or Firefox browsers for best compatibility</li>
                        <li>If on iOS, make sure you're using Safari or Chrome (not private mode)</li>
                        <li>On Android, ensure Chrome has camera permissions in system settings</li>
                    </ul>
                </div>
            `;
            scannerContainer.insertAdjacentHTML('afterend', troubleshootingHtml);
        }

        function stopScanner() {
            if (video && video.srcObject) {
                video.srcObject.getTracks().forEach(track => track.stop());
                video.srcObject = null;
            }
            
            if (animationFrame) {
                cancelAnimationFrame(animationFrame);
            }
            
            video.style.display = 'none';
            document.getElementById('scanner-placeholder').style.display = 'block';
            
            document.getElementById('start-scanner').disabled = false;
            document.getElementById('stop-scanner').disabled = true;
            
            hideScannerStatus();
        }

        function scanQRCode() {
            if (video.readyState === video.HAVE_ENOUGH_DATA) {
                canvas.height = video.videoHeight;
                canvas.width = video.videoWidth;
                
                canvasContext.drawImage(video, 0, 0, canvas.width, canvas.height);
                const imageData = canvasContext.getImageData(0, 0, canvas.width, canvas.height);
                
                const code = jsQR(imageData.data, imageData.width, imageData.height, {
                    inversionAttempts: "dontInvert",
                });
                
                if (code) {
                    console.log('QR Code detected:', code.data);
                    handleCodeDetected(code.data, 'QR');
                    return; // Stop scanning after successful detection
                }
                
                // TODO: Add barcode detection from camera feed
                // For now, camera scanning focuses on QR codes
            }
            
            animationFrame = requestAnimationFrame(scanQRCode);
        }

        function handleCodeDetected(codeData, codeType = 'QR') {
            const cleanData = codeData.trim();
            
            // Try to extract UUID from the data
            let betUuid = cleanData;
            
            // If it's a barcode, it might be formatted differently
            if (codeType === 'Barcode') {
                betUuid = extractUuidFromBarcode(cleanData);
            }
            
            // Validate UUID format
            const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
            if (!uuidRegex.test(betUuid)) {
                showScannerStatus(`Invalid ${codeType.toLowerCase()} code format. Please scan a valid bet receipt.`, 'warning');
                // Continue scanning after a delay if using camera
                if (codeType === 'QR') {
                    setTimeout(() => {
                        animationFrame = requestAnimationFrame(scanQRCode);
                    }, 2000);
                }
                return;
            }
            
            showScannerStatus(`${codeType} code detected! Verifying bet...`, 'success');
            
            // Stop scanner if using camera
            if (codeType === 'QR') {
                stopScanner();
            }
            
            // Clear barcode input
            document.getElementById('barcode-input').value = '';
            
            // Verify bet
            verifyBet(betUuid);
        }

        function handleBarcodeInput(event) {
            const input = event.target;
            const value = input.value;
            
            // Auto-process if we detect a complete barcode (usually ends with Enter)
            // For barcode scanners, we'll handle this in the keypress event
            if (value.length > 0) {
                // Visual feedback that input is being processed
                input.classList.add('is-valid');
                setTimeout(() => input.classList.remove('is-valid'), 500);
            }
        }

        function processBarcodeInput() {
            const input = document.getElementById('barcode-input');
            const barcodeData = input.value.trim();
            
            if (!barcodeData) {
                showScannerStatus('Please enter a barcode value', 'warning');
                return;
            }
            
            console.log('Barcode input detected:', barcodeData);
            handleCodeDetected(barcodeData, 'Barcode');
        }

        function extractUuidFromBarcode(barcodeData) {
            // Extract UUID from barcode data
            // The barcode might contain just the UUID or be formatted as "MBETTER-{UUID}"
            if (barcodeData.startsWith('MBETTER-')) {
                return barcodeData.substring(8); // Remove "MBETTER-" prefix
            }
            
            // Check if it's already a UUID format
            const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
            if (uuidRegex.test(barcodeData)) {
                return barcodeData;
            }
            
            // For other barcode formats, try to extract UUID-like patterns
            const uuidMatch = barcodeData.match(/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i);
            if (uuidMatch) {
                return uuidMatch[0];
            }
            
            // Return the original data for validation to fail appropriately
            return barcodeData;
        }

        function verifyBet(betUuid) {
            fetch(`/api/verify-bet/${betUuid}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayBetDetails(data.bet);
                    } else {
                        showScannerStatus('Bet not found: ' + (data.error || 'Unknown error'), 'danger');
                    }
                })
                .catch(error => {
                    console.error('Error verifying bet:', error);
                    showScannerStatus('Error verifying bet. Please check your connection.', 'danger');
                });
        }

        function displayBetDetails(bet) {
            const modalContent = document.getElementById('bet-details-content');
            
            let statusBadge = '';
            let statusClass = '';
            switch(bet.overall_status) {
                case 'won':
                    statusBadge = '<span class="badge bg-success fs-6"><i class="fas fa-trophy me-1"></i>Won</span>';
                    statusClass = 'text-success';
                    break;
                case 'lost':
                    statusBadge = '<span class="badge bg-danger fs-6"><i class="fas fa-times me-1"></i>Lost</span>';
                    statusClass = 'text-danger';
                    break;
                case 'cancelled':
                    statusBadge = '<span class="badge bg-secondary fs-6"><i class="fas fa-ban me-1"></i>Cancelled</span>';
                    statusClass = 'text-secondary';
                    break;
                default:
                    statusBadge = '<span class="badge bg-warning fs-6"><i class="fas fa-clock me-1"></i>Pending</span>';
                    statusClass = 'text-warning';
            }
            
            let detailsHtml = '';
            bet.details.forEach(detail => {
                let resultBadge = '';
                switch(detail.result) {
                    case 'won':
                    case 'win':
                        resultBadge = '<span class="badge bg-success">Won</span>';
                        break;
                    case 'lost':
                        resultBadge = '<span class="badge bg-danger">Lost</span>';
                        break;
                    case 'cancelled':
                        resultBadge = '<span class="badge bg-secondary">Cancelled</span>';
                        break;
                    default:
                        resultBadge = '<span class="badge bg-warning">Pending</span>';
                }
                
                detailsHtml += `
                    <div class="card mb-3">
                        <div class="card-body p-3">
                            <div class="row">
                                <div class="col-8">
                                    <h6 class="fw-bold mb-1">Match #${detail.match ? detail.match.match_number : 'Unknown'}</h6>
                                    <p class="text-muted small mb-1">${detail.match ? detail.match.fighter1_township + ' vs ' + detail.match.fighter2_township : 'Match info unavailable'}</p>
                                    ${detail.match && detail.match.result ? `<p class="text-info small mb-1"><i class="fas fa-trophy me-1"></i>Result: ${detail.match.result}</p>` : ''}
                                    <span class="badge bg-primary">${detail.outcome}</span>
                                </div>
                                <div class="col-4 text-end">
                                    <h6 class="fw-bold mb-1">${formatCurrency(detail.amount)}</h6>
                                    ${resultBadge}
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            modalContent.innerHTML = `
                <!-- Status Section -->
                <div class="text-center mb-4">
                    <i class="fas fa-hand-rock boxing-glove fa-3x mb-3"></i>
                    <h3 class="fw-bold mb-2 ${statusClass}">
                        ${bet.overall_status.charAt(0).toUpperCase() + bet.overall_status.slice(1)}
                    </h3>
                    ${statusBadge}
                </div>
                
                <!-- Bet Summary -->
                <div class="row mb-4">
                    <div class="col-6">
                        <div class="text-center p-3 bg-light rounded">
                            <h6 class="text-muted mb-1">Bet ID</h6>
                            <p class="fw-bold mb-0 font-monospace">${bet.uuid.substring(0, 8)}...</p>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="text-center p-3 bg-light rounded">
                            <h6 class="text-muted mb-1">Total Amount</h6>
                            <p class="fw-bold mb-0 text-success fs-5">${formatCurrency(bet.total_amount)}</p>
                        </div>
                    </div>
                </div>
                
                <!-- Date Info -->
                <div class="text-center mb-4">
                    <p class="text-muted mb-0">
                        <i class="fas fa-calendar me-1"></i>
                        ${new Date(bet.bet_datetime).toLocaleDateString()}
                        <i class="fas fa-clock ms-2 me-1"></i>
                        ${new Date(bet.bet_datetime).toLocaleTimeString()}
                    </p>
                </div>
                
                <!-- Bet Details -->
                <h6 class="fw-bold mb-3">
                    <i class="fas fa-list me-2"></i>Bet Details (${bet.details_count} items)
                </h6>
                ${detailsHtml}
                
                <!-- Results Summary -->
                <div class="row text-center mb-4">
                    <div class="col-3">
                        <div class="p-2 bg-warning bg-opacity-10 rounded">
                            <h5 class="text-warning fw-bold mb-0">${bet.results.pending}</h5>
                            <small class="text-muted">Pending</small>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="p-2 bg-success bg-opacity-10 rounded">
                            <h5 class="text-success fw-bold mb-0">${bet.results.won}</h5>
                            <small class="text-muted">Won</small>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="p-2 bg-danger bg-opacity-10 rounded">
                            <h5 class="text-danger fw-bold mb-0">${bet.results.lost}</h5>
                            <small class="text-muted">Lost</small>
                        </div>
                    </div>
                    <div class="col-3">
                        <div class="p-2 bg-secondary bg-opacity-10 rounded">
                            <h5 class="text-secondary fw-bold mb-0">${bet.results.cancelled}</h5>
                            <small class="text-muted">Cancelled</small>
                        </div>
                    </div>
                </div>
                
                ${bet.results.winnings > 0 ? `
                <div class="alert alert-success text-center">
                    <i class="fas fa-trophy fa-2x mb-2"></i>
                    <h5 class="fw-bold mb-0">Potential Winnings: ${formatCurrency(bet.results.winnings)}</h5>
                </div>
                ` : ''}
                
                <div class="text-center">
                    <small class="text-muted">
                        <i class="fas fa-check-circle me-1"></i>
                        Verified at: ${new Date(bet.verified_at).toLocaleString()}
                    </small>
                </div>
            `;
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('betDetailsModal'));
            modal.show();
        }

        function showScannerStatus(message, type) {
            const statusDiv = document.getElementById('scanner-status');
            const messageSpan = document.getElementById('scanner-message');
            
            statusDiv.className = `status-alert alert alert-${type} text-center`;
            messageSpan.textContent = message;
            statusDiv.style.display = 'block';
        }

        function hideScannerStatus() {
            document.getElementById('scanner-status').style.display = 'none';
        }
    </script>
</body>
</html>