// OCR Scanner for Student ID Cards
class OCRScanner {
    constructor() {
        this.stream = null;
        this.video = null;
        this.canvas = null;
        this.init();
    }

    init() {
        this.video = document.getElementById('cameraVideo');
        this.canvas = document.getElementById('captureCanvas');
        this.setupEventListeners();
    }

    setupEventListeners() {
        const captureBtn = document.getElementById('captureBtn');
        const cancelScanBtn = document.getElementById('cancelScanBtn');
        const closeScannerBtn = document.getElementById('closeScannerBtn');
        const useIdBtn = document.getElementById('useIdBtn');

        if (captureBtn) {
            captureBtn.addEventListener('click', () => this.captureAndProcess());
        }

        if (cancelScanBtn) {
            cancelScanBtn.addEventListener('click', () => this.closeScanner());
        }

        if (closeScannerBtn) {
            closeScannerBtn.addEventListener('click', () => this.closeScanner());
        }

        if (useIdBtn) {
            useIdBtn.addEventListener('click', () => this.useDetectedId());
        }
    }

    async openScanner() {
        const modal = document.getElementById('scannerModal');
        if (!modal) return;

        try {
            // Request camera access
            this.stream = await navigator.mediaDevices.getUserMedia({
                video: {
                    facingMode: 'environment', // Use back camera on mobile
                    width: { ideal: 1280 },
                    height: { ideal: 720 }
                }
            });

            if (this.video) {
                this.video.srcObject = this.stream;
            }

            modal.classList.add('active');

            // Reset UI
            document.getElementById('ocrResult')?.classList.add('hidden');
            document.getElementById('captureBtn')?.classList.remove('hidden');
            document.getElementById('useIdBtn')?.classList.add('hidden');

        } catch (error) {
            console.error('Camera access error:', error);
            alert('Unable to access camera. Please check permissions.');
        }
    }

    closeScanner() {
        const modal = document.getElementById('scannerModal');

        // Stop camera stream
        if (this.stream) {
            this.stream.getTracks().forEach(track => track.stop());
            this.stream = null;
        }

        if (this.video) {
            this.video.srcObject = null;
        }

        if (modal) {
            modal.classList.remove('active');
        }
    }

    async captureAndProcess() {
        if (!this.video || !this.canvas) return;

        const captureBtn = document.getElementById('captureBtn');
        if (captureBtn) {
            captureBtn.disabled = true;
            captureBtn.textContent = 'Processing...';
        }

        try {
            // Capture frame from video
            const context = this.canvas.getContext('2d');
            this.canvas.width = this.video.videoWidth;
            this.canvas.height = this.video.videoHeight;
            context.drawImage(this.video, 0, 0);

            // Convert to blob
            const blob = await new Promise(resolve => this.canvas.toBlob(resolve));

            // Perform OCR
            const result = await Tesseract.recognize(blob, 'eng', {
                logger: (m) => {
                    if (m.status === 'recognizing text') {
                        if (captureBtn) {
                            captureBtn.textContent = `Processing... ${Math.round(m.progress * 100)}%`;
                        }
                    }
                }
            });

            // Extract student ID from text
            const studentId = this.extractStudentId(result.data.text);

            if (studentId) {
                this.displayResult(studentId);
            } else {
                alert('Could not detect Student ID. Please try again or enter manually.');
            }

        } catch (error) {
            console.error('OCR error:', error);
            alert('Failed to process image. Please try again.');
        } finally {
            if (captureBtn) {
                captureBtn.disabled = false;
                captureBtn.textContent = 'Capture';
            }
        }
    }

    extractStudentId(text) {
        // Clean up text
        text = text.replace(/\s+/g, ' ').trim();

        // Common patterns for student IDs
        const patterns = [
            /\b([A-Z]{2,4}\d{4,8})\b/i,           // e.g., CS2021001, BT20CS001
            /\b(\d{8,12})\b/,                      // e.g., 202100123
            /\b([A-Z]\d{7,10})\b/i,               // e.g., S20210001
            /Student\s*ID[:\s]*([A-Z0-9]+)/i,     // "Student ID: XYZ123"
            /ID[:\s]*([A-Z0-9]+)/i,               // "ID: XYZ123"
            /Roll\s*No[:\s]*([A-Z0-9]+)/i        // "Roll No: XYZ123"
        ];

        for (const pattern of patterns) {
            const match = text.match(pattern);
            if (match && match[1]) {
                return match[1].toUpperCase();
            }
        }

        return null;
    }

    displayResult(studentId) {
        const resultDiv = document.getElementById('ocrResult');
        const detectedIdSpan = document.getElementById('detectedId');
        const captureBtn = document.getElementById('captureBtn');
        const useIdBtn = document.getElementById('useIdBtn');

        if (detectedIdSpan) {
            detectedIdSpan.textContent = studentId;
        }

        if (resultDiv) {
            resultDiv.classList.remove('hidden');
        }

        if (captureBtn) {
            captureBtn.classList.add('hidden');
        }

        if (useIdBtn) {
            useIdBtn.classList.remove('hidden');
            useIdBtn.dataset.studentId = studentId;
        }
    }

    useDetectedId() {
        const useIdBtn = document.getElementById('useIdBtn');
        const studentId = useIdBtn?.dataset.studentId;

        if (studentId) {
            // Dispatch custom event with student ID
            window.dispatchEvent(new CustomEvent('ocrComplete', {
                detail: { studentId }
            }));

            this.closeScanner();
        }
    }
}

// Initialize OCR scanner
const ocrScanner = new OCRScanner();

// Export for global use
window.ocrScanner = ocrScanner;
