/**
 * Authentication Handler
 * Manages Firebase authentication flows
 */

class AuthHandler {
    constructor() {
        this.initializeEventListeners();
    }

    initializeEventListeners() {
        // Mobile OTP Login
        const mobileLoginForm = document.getElementById('mobileLoginForm');
        if (mobileLoginForm) {
            mobileLoginForm.addEventListener('submit', (e) => this.handleMobileLogin(e));
        }

        // Mobile OTP Signup
        const mobileSignupForm = document.getElementById('mobileSignupForm');
        if (mobileSignupForm) {
            mobileSignupForm.addEventListener('submit', (e) => this.handleMobileSignup(e));
        }

        // Email Login Form
        const emailLoginForm = document.getElementById('emailLoginForm');
        if (emailLoginForm) {
            emailLoginForm.addEventListener('submit', (e) => this.handleEmailLogin(e));
        }

        // Google Login
        const googleLoginBtn = document.getElementById('googleLoginBtn');
        if (googleLoginBtn) {
            googleLoginBtn.addEventListener('click', () => this.handleGoogleLogin());
        }

        // Google Signup
        const googleSignupBtn = document.getElementById('googleSignupBtn');
        if (googleSignupBtn) {
            googleSignupBtn.addEventListener('click', () => this.handleGoogleSignup());
        }

        // Facebook Login
        const facebookLoginBtn = document.getElementById('facebookLoginBtn');
        if (facebookLoginBtn) {
            facebookLoginBtn.addEventListener('click', () => this.handleFacebookLogin());
        }

        // Facebook Signup
        const facebookSignupBtn = document.getElementById('facebookSignupBtn');
        if (facebookSignupBtn) {
            facebookSignupBtn.addEventListener('click', () => this.handleFacebookSignup());
        }
    }

    // Email/Password Login
    async handleEmailLogin(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const submitBtn = e.target.querySelector('button[type="submit"]');
        
        submitBtn.disabled = true;
        submitBtn.textContent = 'Signing in...';
        
        try {
            const response = await fetch('/controllers/login.php', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success) {
                if (result.requires_2fa) {
                    // Store email for display
                    const email = formData.get('user_email');
                    if (email) {
                        sessionStorage.setItem('verifyEmail', email);
                    }
                }
                window.location.href = result.redirect || '/';
            } else {
                this.showError(result.errors.join('<br>'));
                submitBtn.disabled = false;
                submitBtn.textContent = 'Sign In';
            }
        } catch (error) {
            this.showError('Login failed. Please try again.');
            submitBtn.disabled = false;
            submitBtn.textContent = 'Sign In';
        }
    }

    // Mobile OTP Login
    async handleMobileLogin(e) {
        e.preventDefault();
        
        const mobileNumber = document.getElementById('mobile_number').value;
        const sendOtpBtn = document.getElementById('sendOtpBtn');
        
        if (!mobileNumber) {
            this.showError('Please enter a mobile number');
            return;
        }

        sendOtpBtn.disabled = true;
        sendOtpBtn.textContent = 'Sending OTP...';

        try {
            // Initialize reCAPTCHA
            if (!window.recaptchaVerifier) {
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
                    'size': 'normal',
                    'callback': (response) => {
                        // reCAPTCHA solved
                    }
                });
            }

            // Send OTP
            const confirmationResult = await firebase.auth().signInWithPhoneNumber(
                mobileNumber, 
                window.recaptchaVerifier
            );
            
            window.confirmationResult = confirmationResult;
            
            // Store mobile number for verification page
            localStorage.setItem('verifyMobile', mobileNumber);
            localStorage.setItem('isSignup', 'false');
            
            // Redirect to OTP verification page
            window.location.href = '/verify-otp.php';
            
        } catch (error) {
            this.showError(error.message);
            sendOtpBtn.disabled = false;
            sendOtpBtn.textContent = 'Send OTP';
        }
    }

    // Mobile OTP Signup
    async handleMobileSignup(e) {
        e.preventDefault();
        
        const name = document.getElementById('signup_name').value;
        const mobileNumber = document.getElementById('signup_mobile').value;
        const termsAccepted = document.getElementById('mobile_terms').checked;
        const sendOtpBtn = document.getElementById('sendSignupOtpBtn');
        
        if (!name || !mobileNumber) {
            this.showError('Please fill in all fields');
            return;
        }

        if (!termsAccepted) {
            this.showError('Please accept the terms and conditions');
            return;
        }

        sendOtpBtn.disabled = true;
        sendOtpBtn.textContent = 'Sending OTP...';

        try {
            // Initialize reCAPTCHA
            if (!window.recaptchaVerifier) {
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-signup', {
                    'size': 'normal',
                    'callback': (response) => {
                        // reCAPTCHA solved
                    }
                });
            }

            // Send OTP
            const confirmationResult = await firebase.auth().signInWithPhoneNumber(
                mobileNumber, 
                window.recaptchaVerifier
            );
            
            window.confirmationResult = confirmationResult;
            
            // Store data for verification
            localStorage.setItem('verifyMobile', mobileNumber);
            localStorage.setItem('signupName', name);
            localStorage.setItem('isSignup', 'true');
            
            // Redirect to OTP verification page
            window.location.href = '/verify-otp.php';
            
        } catch (error) {
            this.showError(error.message);
            sendOtpBtn.disabled = false;
            sendOtpBtn.textContent = 'Send OTP';
        }
    }

    // Verify OTP
    async verifyOTP(otp) {
        try {
            // Check if this is 2FA email verification
            const is2FA = window.location.pathname.includes('verify-otp');
            
            if (is2FA) {
                // 2FA Email Verification
                const formData = new FormData();
                formData.append('verification_code', otp);
                
                const response = await fetch('/controllers/verify_2fa.php', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // Clear stored data
                    sessionStorage.removeItem('verifyEmail');
                    
                    // Show success message
                    if (typeof UIkit !== 'undefined') {
                        UIkit.notification('Login successful!', {status: 'success'});
                    }
                    
                    // Redirect
                    setTimeout(() => {
                        window.location.href = result.redirect || '/';
                    }, 500);
                } else {
                    throw new Error(result.errors ? result.errors.join(', ') : 'Verification failed');
                }
                
                return;
            }
            
            // Original Firebase OTP verification
            const confirmationResult = window.confirmationResult;
            
            if (!confirmationResult) {
                throw new Error('No confirmation result found. Please request OTP again.');
            }
            
            // Verify the OTP
            const result = await confirmationResult.confirm(otp);
            const user = result.user;
            const idToken = await user.getIdToken();
            
            // Get stored data
            const phoneNumber = localStorage.getItem('verifyMobile');
            const isSignup = localStorage.getItem('isSignup') === 'true';
            const name = localStorage.getItem('signupName') || 'User';
            
            // Send to backend
            const response = await fetch('/controllers/firebase_auth.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'otp_login',
                    phoneNumber: phoneNumber,
                    name: name,
                    firebaseUid: user.uid,
                    idToken: idToken
                })
            });
            
            const backendResult = await response.json();
            
            if (backendResult.success) {
                // Clear stored data
                localStorage.removeItem('verifyMobile');
                localStorage.removeItem('signupName');
                localStorage.removeItem('isSignup');
                
                // Redirect
                window.location.href = backendResult.redirect || '/';
            } else {
                throw new Error(backendResult.error || 'Verification failed');
            }
            
        } catch (error) {
            throw error;
        }
    }

    // Resend OTP
    async resendOTP() {
        // Check if this is 2FA email verification
        const is2FA = window.location.pathname.includes('verify-otp');
        
        if (is2FA) {
            // Resend 2FA email code
            try {
                const response = await fetch('/controllers/resend_2fa.php', {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    if (typeof UIkit !== 'undefined') {
                        UIkit.notification(result.message || 'Verification code sent!', {status: 'success'});
                    }
                } else {
                    this.showError(result.errors ? result.errors.join(', ') : 'Failed to resend code');
                }
            } catch (error) {
                this.showError('Failed to resend code. Please try again.');
            }
            return;
        }
        
        // Original Firebase OTP resend
        const mobileNumber = localStorage.getItem('verifyMobile');
        
        if (!mobileNumber) {
            this.showError('Mobile number not found. Please start over.');
            return;
        }
        
        try {
            // Reinitialize reCAPTCHA
            window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
                'size': 'normal',
                'callback': (response) => {
                    // reCAPTCHA solved
                }
            });
            
            // Resend OTP
            const confirmationResult = await firebase.auth().signInWithPhoneNumber(
                mobileNumber,
                window.recaptchaVerifier
            );
            
            window.confirmationResult = confirmationResult;
            
            if (typeof UIkit !== 'undefined') {
                UIkit.notification('OTP sent successfully!', {status: 'success'});
            }
            
        } catch (error) {
            this.showError(error.message);
        }
    }

    // Google Login
    async handleGoogleLogin() {
        try {
            // Check if Firebase is initialized
            if (typeof firebase === 'undefined' || !firebase.auth) {
                this.showError('Firebase is not configured. Please contact the administrator.');
                console.error('Firebase not initialized');
                return;
            }

            const provider = new firebase.auth.GoogleAuthProvider();
            const result = await firebase.auth().signInWithPopup(provider);
            
            // Get user data
            const user = result.user;
            const idToken = await user.getIdToken();
            
            // Send to backend
            await this.sendToBackend({
                action: 'social_login',
                provider: 'google',
                userData: {
                    uid: user.uid,
                    email: user.email,
                    displayName: user.displayName,
                    photoURL: user.photoURL
                },
                idToken: idToken
            });
            
        } catch (error) {
            console.error('Google login error:', error);
            this.showError(error.message || 'Google login failed. Please try again.');
        }
    }

    // Google Signup
    async handleGoogleSignup() {
        // Same as login for social auth
        await this.handleGoogleLogin();
    }

    // Facebook Login
    async handleFacebookLogin() {
        try {
            // Check if Firebase is initialized
            if (typeof firebase === 'undefined' || !firebase.auth) {
                this.showError('Firebase is not configured. Please contact the administrator.');
                console.error('Firebase not initialized');
                return;
            }

            const provider = new firebase.auth.FacebookAuthProvider();
            const result = await firebase.auth().signInWithPopup(provider);
            
            // Get user data
            const user = result.user;
            const idToken = await user.getIdToken();
            
            // Send to backend
            await this.sendToBackend({
                action: 'social_login',
                provider: 'facebook',
                userData: {
                    uid: user.uid,
                    email: user.email,
                    displayName: user.displayName,
                    photoURL: user.photoURL
                },
                idToken: idToken
            });
            
        } catch (error) {
            console.error('Facebook login error:', error);
            this.showError(error.message || 'Facebook login failed. Please try again.');
        }
    }

    // Facebook Signup
    async handleFacebookSignup() {
        // Same as login for social auth
        await this.handleFacebookLogin();
    }

    // Send authentication data to backend
    async sendToBackend(data) {
        try {
            const response = await fetch('/controllers/firebase_auth.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                // Redirect to home or dashboard
                window.location.href = result.redirect || '/';
            } else {
                this.showError(result.error || 'Authentication failed');
            }
        } catch (error) {
            this.showError('Server error. Please try again.');
        }
    }

    // Show error message
    showError(message) {
        if (typeof UIkit !== 'undefined') {
            UIkit.notification(message, {status: 'danger', pos: 'top-center'});
        } else {
            alert(message);
        }
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    window.authHandler = new AuthHandler();
});
