{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-qrcode me-2"></i>Bet Verification
            <small class="text-muted">Scan QR codes from thermal receipts</small>
        </h1>
    </div>
</div>

<!-- Back Button -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-shield-alt me-2"></i>Cashier Verification Center
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <a href="{{ url_for('main.cashier_bets') }}" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-2"></i>Back to Bets
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- QR Code for Mobile Access - Left Side -->
    <div class="col-lg-6 col-md-6">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-mobile-alt me-2"></i>Mobile Verification Access
                </h5>
            </div>
            <div class="card-body text-center">
                <p class="text-muted mb-3">
                    Scan this QR code with your mobile device to access the verification page
                </p>
                
                <!-- QR Code Generation -->
                <div id="mobile-qr-code" class="mb-3">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
                
                <!-- Mobile URL -->
                <div class="mb-3">
                    <label class="form-label">Mobile Verification URL:</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="mobile-url" value="{{ mobile_verify_url }}" readonly>
                        <button class="btn btn-outline-secondary" onclick="copyToClipboard('mobile-url')">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Instructions -->
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Instructions:</strong><br>
                    1. Scan this QR code with your mobile device<br>
                    2. Use the mobile verification page to scan thermal receipt QR codes<br>
                    3. View bet details and results instantly
                </div>
            </div>
        </div>
    </div>

    <!-- Desktop QR Scanner - Right Side -->
    <div class="col-lg-6 col-md-6">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-camera me-2"></i>Code Scanner
                </h5>
            </div>
            <div class="card-body">
                <!-- 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">
                        Use a barcode scanner device or type the code manually
                    </div>
                </div>
                
                <!-- Scanner Controls -->
                <div class="mb-3">
                    <button class="btn btn-success me-2" id="start-scanner">
                        <i class="fas fa-play me-2"></i>Start Camera
                    </button>
                    <button class="btn btn-secondary" 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">
                    <video id="qr-video" width="100%" style="max-width: 400px; display: none;"></video>
                    <canvas id="qr-canvas" style="display: none;"></canvas>
                    <div id="scanner-placeholder" class="bg-light p-5 rounded">
                        <i class="fas fa-camera fa-3x text-muted mb-2"></i>
                        <p class="text-muted">Click "Start Camera" to scan QR codes</p>
                    </div>
                </div>

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

<!-- Bet Details Modal -->
<div class="modal fade" id="betDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <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" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>Close
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/currency.js') }}"></script>
<script src="https://unpkg.com/jsqr/dist/jsQR.js"></script>
<script>
let video = null;
let canvas = null;
let canvasContext = null;
let animationFrame = null;

document.addEventListener('DOMContentLoaded', function() {
    // Generate QR code for mobile access
    generateMobileAccessQR();
    
    // 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();
        }
    });
});

function generateMobileAccessQR() {
    const mobileUrl = document.getElementById('mobile-url').value;
    const qrContainer = document.getElementById('mobile-qr-code');
    
    // Use QR Server API for generating QR code
    const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(mobileUrl)}&format=png`;
    qrContainer.innerHTML = `<img src="${qrImageUrl}" alt="Mobile Access QR Code" class="img-fluid" style="max-width: 300px;">`;
}

async function startScanner() {
    try {
        // Check browser compatibility with better error handling
        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 or localhost for camera access.';
            } else {
                errorMsg += 'Your browser may not support camera access or it may be disabled.';
            }
            throw new Error(errorMsg);
        }
        
        // Request camera permission with better error handling
        let stream;
        try {
            // Try with back camera first (mobile)
            stream = await navigator.mediaDevices.getUserMedia({
                video: {
                    facingMode: { ideal: 'environment' },
                    width: { ideal: 640 },
                    height: { ideal: 480 }
                }
            });
        } 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: ' + error.message));
            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('Camera active - Point at QR code or barcode', 'info');
        
        // Start scanning
        scanQRCode();
        
    } catch (error) {
        console.error('Error starting scanner:', error);
        
        let errorMessage = 'Failed to start camera: ';
        let showTroubleshooting = true;
        
        if (error.name === 'NotAllowedError') {
            errorMessage += 'Camera permission denied. Please click "Allow" when prompted, or check your browser settings to enable camera access for this site.';
        } else if (error.name === 'NotFoundError') {
            errorMessage += 'No camera found. Please ensure your device has a camera connected and enabled.';
        } else if (error.name === 'NotReadableError') {
            errorMessage += 'Camera is currently in use. Please close other applications using the camera and try again.';
        } else if (error.name === 'OverconstrainedError') {
            errorMessage += 'Camera settings not supported. This may be a compatibility issue with your camera.';
        } else if (error.name === 'NotSupportedError') {
            errorMessage += 'Camera API not supported. Please use a modern browser (Chrome, Firefox, Safari).';
        } else if (error.name === 'SecurityError') {
            errorMessage += 'Secure connection required. Please access via HTTPS or localhost.';
        } else if (error.message.includes('HTTPS') || error.message.includes('localhost')) {
            errorMessage += error.message;
            showTroubleshooting = false;
        } else {
            errorMessage += error.message || 'Unknown error occurred.';
        }
        
        showScannerStatus(errorMessage, 'danger');
        
        // Add troubleshooting suggestions
        if (showTroubleshooting) {
            showCameraTroubleshooting();
        }
    }
}

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`, 'warning');
        // Continue scanning if using camera
        if (codeType === 'QR') {
            animationFrame = requestAnimationFrame(scanQRCode);
        }
        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
    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: ' + error.message, 'danger');
        });
}

function displayBetDetails(bet) {
    const modalContent = document.getElementById('bet-details-content');
    
    let statusBadge = '';
    switch(bet.overall_status) {
        case 'won':
            statusBadge = '<span class="badge bg-success"><i class="fas fa-trophy me-1"></i>Won</span>';
            break;
        case 'lost':
            statusBadge = '<span class="badge bg-danger"><i class="fas fa-times me-1"></i>Lost</span>';
            break;
        case 'cancelled':
            statusBadge = '<span class="badge bg-secondary"><i class="fas fa-ban me-1"></i>Cancelled</span>';
            break;
        default:
            statusBadge = '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
    }
    
    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 += `
            <tr>
                <td><strong>Match #${detail.match ? detail.match.match_number : 'Unknown'}</strong><br>
                    <small class="text-muted">${detail.match ? detail.match.fighter1_township + ' vs ' + detail.match.fighter2_township : 'Match info unavailable'}</small>
                </td>
                <td><span class="badge bg-primary">${detail.outcome}</span></td>
                <td><strong class="currency-amount" data-amount="${detail.amount}">${formatCurrency(detail.amount)}</strong></td>
                <td>${resultBadge}</td>
            </tr>
        `;
    });
    
    modalContent.innerHTML = `
        <div class="row mb-3">
            <div class="col-md-6">
                <h6 class="text-muted">Bet ID</h6>
                <p class="font-monospace">${bet.uuid.substring(0, 8)}...</p>
            </div>
            <div class="col-md-6">
                <h6 class="text-muted">Status</h6>
                <p>${statusBadge}</p>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-6">
                <h6 class="text-muted">Date & Time</h6>
                <p>${new Date(bet.bet_datetime).toLocaleString()}</p>
            </div>
            <div class="col-md-6">
                <h6 class="text-muted">Total Amount</h6>
                <p><strong class="text-success currency-amount" data-amount="${bet.total_amount}">${formatCurrency(bet.total_amount)}</strong></p>
            </div>
        </div>
        
        <h6 class="mb-3">Bet Details (${bet.details_count} items)</h6>
        <div class="table-responsive">
            <table class="table table-sm table-striped">
                <thead class="table-dark">
                    <tr>
                        <th>Match</th>
                        <th>Outcome</th>
                        <th>Amount</th>
                        <th>Result</th>
                    </tr>
                </thead>
                <tbody>
                    ${detailsHtml}
                </tbody>
            </table>
        </div>
        
        <div class="row mt-3">
            <div class="col-md-3 text-center">
                <h6 class="text-warning">${bet.results.pending}</h6>
                <small class="text-muted">Pending</small>
            </div>
            <div class="col-md-3 text-center">
                <h6 class="text-success">${bet.results.won}</h6>
                <small class="text-muted">Won</small>
            </div>
            <div class="col-md-3 text-center">
                <h6 class="text-danger">${bet.results.lost}</h6>
                <small class="text-muted">Lost</small>
            </div>
            <div class="col-md-3 text-center">
                <h6 class="text-secondary">${bet.results.cancelled}</h6>
                <small class="text-muted">Cancelled</small>
            </div>
        </div>
        
        ${bet.results.winnings > 0 ? `
        <div class="alert alert-success mt-3">
            <i class="fas fa-trophy me-2"></i>
            <strong>Potential Winnings: <span class="currency-amount" data-amount="${bet.results.winnings}">${formatCurrency(bet.results.winnings)}</span></strong>
        </div>
        ` : ''}
        
        <div class="text-center mt-3">
            <small class="text-muted">Verified at: ${new Date(bet.verified_at).toLocaleString()}</small>
        </div>
    `;
    
    // Update currency formatting
    document.querySelectorAll('.currency-amount').forEach(element => {
        const amount = parseFloat(element.dataset.amount || 0);
        element.textContent = formatCurrency(amount);
    });
    
    // 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 = `alert alert-${type}`;
    messageSpan.textContent = message;
    statusDiv.style.display = 'block';
}

function hideScannerStatus() {
    document.getElementById('scanner-status').style.display = 'none';
}

function showCameraTroubleshooting() {
    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</h6>
            <ul class="mb-0">
                <li>Ensure you're using <strong>HTTPS</strong> or accessing via <strong>localhost</strong></li>
                <li>Click the camera icon in your browser's address bar to allow camera access</li>
                <li>Close other applications that might be using the camera</li>
                <li>Try refreshing the page and allowing camera access again</li>
                <li>Use a modern browser: Chrome, Firefox, or Safari</li>
                <li>For mobile: Use the built-in camera app or mobile browsers</li>
            </ul>
        </div>
    `;
    scannerContainer.insertAdjacentHTML('afterend', troubleshootingHtml);
}

function copyToClipboard(elementId) {
    const element = document.getElementById(elementId);
    element.select();
    element.setSelectionRange(0, 99999);
    document.execCommand('copy');
    
    // Show feedback
    const button = element.nextElementSibling;
    const originalHtml = button.innerHTML;
    button.innerHTML = '<i class="fas fa-check"></i>';
    button.classList.add('btn-success');
    button.classList.remove('btn-outline-secondary');
    
    setTimeout(() => {
        button.innerHTML = originalHtml;
        button.classList.remove('btn-success');
        button.classList.add('btn-outline-secondary');
    }, 2000);
}
</script>
{% endblock %}