/**
 * Real-Time Verification Library
 * Handles all real-time verification checks for registration and login
 */

const RealtimeVerification = {
    // API endpoint
    apiEndpoint: '/interior/auth-system/api-realtime-verify.php',
    
    // Configuration
    config: {
        debounceDelay: 500,
        showFeedback: true,
        autoFormat: true,
        validatePassword: true
    },
    
    // Debounce timer
    debounceTimers: {},
    
    /**
     * Check if email is available
     */
    checkEmail: function(email, callback) {
        if (!email) {
            callback({ status: 'error', message: 'Email is required', available: false });
            return;
        }
        
        this.debounce('checkEmail', () => {
            fetch(this.apiEndpoint + '?action=check_email&email=' + encodeURIComponent(email))
                .then(response => response.json())
                .then(data => {
                    if (callback) callback(data);
                })
                .catch(error => {
                    console.error('Email check error:', error);
                    if (callback) callback({ status: 'error', message: 'Check failed', available: false });
                });
        });
    },
    
    /**
     * Check password strength
     */
    checkPasswordStrength: function(password, callback) {
        if (!password) {
            callback({ status: 'success', strength: 0, strength_text: 'None', feedback: [], valid: false });
            return;
        }
        
        fetch(this.apiEndpoint + '?action=check_password&password=' + encodeURIComponent(password))
            .then(response => response.json())
            .then(data => {
                if (callback) callback(data);
            })
            .catch(error => {
                console.error('Password check error:', error);
            });
    },
    
    /**
     * Check if passwords match
     */
    checkPasswordMatch: function(password, confirm, callback) {
        fetch(this.apiEndpoint + '?action=check_password_match&password=' + encodeURIComponent(password) + '&confirm=' + encodeURIComponent(confirm))
            .then(response => response.json())
            .then(data => {
                if (callback) callback(data);
            })
            .catch(error => {
                console.error('Password match error:', error);
            });
    },
    
    /**
     * Validate phone number
     */
    checkPhone: function(phone, callback) {
        if (!phone) {
            callback({ status: 'error', message: 'Phone is required', valid: false });
            return;
        }
        
        this.debounce('checkPhone', () => {
            fetch(this.apiEndpoint + '?action=check_phone&phone=' + encodeURIComponent(phone))
                .then(response => response.json())
                .then(data => {
                    if (callback) callback(data);
                })
                .catch(error => {
                    console.error('Phone check error:', error);
                });
        });
    },
    
    /**
     * Send OTP to email
     */
    sendOTP: function(email, name, callback) {
        if (!email || !name) {
            if (callback) callback({ status: 'error', message: 'Email and name required', otp_sent: false });
            return;
        }
        
        fetch(this.apiEndpoint + '?action=send_otp&email=' + encodeURIComponent(email) + '&name=' + encodeURIComponent(name))
            .then(response => response.json())
            .then(data => {
                if (callback) callback(data);
            })
            .catch(error => {
                console.error('OTP send error:', error);
                if (callback) callback({ status: 'error', message: 'Failed to send OTP', otp_sent: false });
            });
    },
    
    /**
     * Verify OTP code
     */
    verifyOTP: function(email, otp, callback) {
        if (!email || !otp) {
            if (callback) callback({ status: 'error', message: 'Email and OTP required', verified: false });
            return;
        }
        
        fetch(this.apiEndpoint + '?action=verify_otp&email=' + encodeURIComponent(email) + '&otp=' + encodeURIComponent(otp))
            .then(response => response.json())
            .then(data => {
                if (callback) callback(data);
            })
            .catch(error => {
                console.error('OTP verify error:', error);
                if (callback) callback({ status: 'error', message: 'Verification failed', verified: false });
            });
    },
    
    /**
     * Check login email exists
     */
    checkLoginEmail: function(email, role, callback) {
        if (!email) {
            if (callback) callback({ status: 'error', message: 'Email required', exists: false });
            return;
        }
        
        this.debounce('checkLoginEmail', () => {
            fetch(this.apiEndpoint + '?action=check_login_email&email=' + encodeURIComponent(email) + '&role=' + encodeURIComponent(role))
                .then(response => response.json())
                .then(data => {
                    if (callback) callback(data);
                })
                .catch(error => {
                    console.error('Login email check error:', error);
                });
        });
    },
    
    /**
     * Check OTP expiration time
     */
    checkOTPExpiry: function(email, callback) {
        if (!email) {
            if (callback) callback({ status: 'error', message: 'Email required', expired: true });
            return;
        }
        
        fetch(this.apiEndpoint + '?action=check_otp_expiry&email=' + encodeURIComponent(email))
            .then(response => response.json())
            .then(data => {
                if (callback) callback(data);
            })
            .catch(error => {
                console.error('OTP expiry check error:', error);
            });
    },
    
    /**
     * Check if 2FA is enabled for user
     */
    check2FA: function(email, callback) {
        if (!email) {
            if (callback) callback({ status: 'error', message: 'Email required', two_factor_enabled: false });
            return;
        }
        
        fetch(this.apiEndpoint + '?action=check_2fa&email=' + encodeURIComponent(email))
            .then(response => response.json())
            .then(data => {
                if (callback) callback(data);
            })
            .catch(error => {
                console.error('2FA check error:', error);
            });
    },
    
    /**
     * Debounce function to prevent excessive API calls
     */
    debounce: function(key, callback, delay) {
        delay = delay || this.config.debounceDelay;
        
        if (this.debounceTimers[key]) {
            clearTimeout(this.debounceTimers[key]);
        }
        
        this.debounceTimers[key] = setTimeout(() => {
            callback();
            delete this.debounceTimers[key];
        }, delay);
    },
    
    /**
     * Initialize real-time verification on form
     */
    init: function(formSelector, options) {
        // Merge options
        this.config = Object.assign(this.config, options);
        
        const form = document.querySelector(formSelector);
        if (!form) return;
        
        // Email field
        const emailInput = form.querySelector('[name="email"]');
        if (emailInput) {
            emailInput.addEventListener('blur', (e) => {
                this.checkEmail(e.target.value, (data) => {
                    this.showFieldFeedback(emailInput, data);
                });
            });
        }
        
        // Phone field
        const phoneInput = form.querySelector('[name="phone"]');
        if (phoneInput) {
            phoneInput.addEventListener('blur', (e) => {
                this.checkPhone(e.target.value, (data) => {
                    this.showFieldFeedback(phoneInput, data);
                });
            });
        }
        
        // Password field
        const passwordInput = form.querySelector('[name="password"]');
        if (passwordInput) {
            passwordInput.addEventListener('input', (e) => {
                this.checkPasswordStrength(e.target.value, (data) => {
                    this.showPasswordStrength(passwordInput, data);
                });
            });
        }
        
        // Confirm password field
        const confirmInput = form.querySelector('[name="confirm_password"]');
        if (confirmInput && passwordInput) {
            confirmInput.addEventListener('input', (e) => {
                this.checkPasswordMatch(passwordInput.value, e.target.value, (data) => {
                    this.showFieldFeedback(confirmInput, data);
                });
            });
        }
    },
    
    /**
     * Show field validation feedback
     */
    showFieldFeedback: function(input, data) {
        if (!this.config.showFeedback) return;
        
        // Remove existing feedback
        const existingFeedback = input.nextElementSibling;
        if (existingFeedback && existingFeedback.classList.contains('feedback-message')) {
            existingFeedback.remove();
        }
        
        // Create feedback element
        const feedback = document.createElement('div');
        feedback.className = 'feedback-message';
        
        if (data.status === 'success' && data.available !== false && data.match !== false && data.valid !== false) {
            feedback.className += ' success';
            feedback.innerHTML = '✅ ' + (data.message || 'Valid');
        } else {
            feedback.className += ' error';
            feedback.innerHTML = '❌ ' + (data.message || 'Invalid');
        }
        
        input.parentNode.insertBefore(feedback, input.nextSibling);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            if (feedback.parentNode) {
                feedback.remove();
            }
        }, 5000);
    },
    
    /**
     * Show password strength indicator
     */
    showPasswordStrength: function(input, data) {
        if (!this.config.showFeedback) return;
        
        // Remove existing strength meter
        const existingMeter = input.nextElementSibling;
        if (existingMeter && existingMeter.classList.contains('password-strength-meter')) {
            existingMeter.remove();
        }
        
        // Create strength meter
        const meter = document.createElement('div');
        meter.className = 'password-strength-meter';
        
        const colors = ['#dc3545', '#fd7e14', '#ffc107', '#17a2b8', '#28a745'];
        const color = colors[data.strength] || '#dc3545';
        
        meter.innerHTML = `
            <div class="strength-bar" style="width: ${(data.strength / 5) * 100}%; background: ${color};"></div>
            <span class="strength-text">${data.strength_text}</span>
        `;
        
        if (data.feedback && data.feedback.length > 0) {
            meter.innerHTML += '<div class="strength-feedback">' + data.feedback.join(' • ') + '</div>';
        }
        
        input.parentNode.insertBefore(meter, input.nextSibling);
    },
    
    /**
     * Start OTP countdown timer
     */
    startOTPTimer: function(containerSelector, email, onExpire) {
        const container = document.querySelector(containerSelector);
        if (!container) return;
        
        this.checkOTPExpiry(email, (data) => {
            if (data.expired) {
                if (onExpire) onExpire();
                return;
            }
            
            let remaining = data.remaining_seconds;
            
            const timerElement = document.createElement('div');
            timerElement.className = 'otp-timer';
            timerElement.textContent = 'Expires in: ' + this.formatTime(remaining);
            container.appendChild(timerElement);
            
            const interval = setInterval(() => {
                remaining--;
                timerElement.textContent = 'Expires in: ' + this.formatTime(remaining);
                
                if (remaining <= 0) {
                    clearInterval(interval);
                    timerElement.textContent = 'OTP Expired';
                    timerElement.style.color = 'red';
                    if (onExpire) onExpire();
                }
            }, 1000);
        });
    },
    
    /**
     * Format seconds to MM:SS
     */
    formatTime: function(seconds) {
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return minutes + ':' + (secs < 10 ? '0' : '') + secs;
    }
};

// Export for use
if (typeof module !== 'undefined' && module.exports) {
    module.exports = RealtimeVerification;
}
