class Auth extends Master {
    constructor() {
        super();
        this.btn = undefined;
        this.loginForm = document.getElementById('loginForm');
        this.registerForm = document.getElementById('registerForm');
        this.floatingShapes = document.querySelectorAll('.floating-shape');
    }

    initializeAuthService() {
        // Login form submission
        if (this.loginForm) {
            this.btn = document.querySelector('.btn-login');
            this.btn.addEventListener('click', async (e) => {
                toggleButtonContent(this.btn);
                disableElement(this.btn);
                await this.handleLogin(e); 
            });
        }

        // Register form submission
        if (this.registerForm) {
            this.btn = document.querySelector('.btn-register');
            this.btn.addEventListener('click', async (e) => { 
                toggleButtonContent(this.btn);
                disableElement(this.btn);
                await this.handleRegistration(e); 
            });
        }

        if (this.loginForm || this.registerForm) {
            this.setupFormValidations(); 
            this.setupFloatingAnimations();
            this.setupSocialLogins();
            this.setupRememberMe();
            this.setupKeyboardShortcuts();
            setupPasswordVisibility();
        }
    }

    async handleLogin(e) {
        e.preventDefault();
        
        // Get form data
        const formData = new FormData(this.loginForm);
        const btn = this.loginForm.querySelector('.btn-login'); 
        
        // Validate form
        if (!this.validateLoginForm(formData)) {
            enableElement(btn); 
            toggleButtonContent(btn, '', true);
            toast('error', 8000, lang.fields_are_required || lang.undefined_error)
            return;
        } 

        // proceed if no validation error!
        await this.simulateLogin(btn, formData);
    }

    async handleRegistration(e) {
        e.preventDefault();
        
        // Get form data
        const formData = new FormData(this.registerForm);
        const btn = this.registerForm.querySelector('.btn-register'); 
        
        // Validate form
        const validation = this.validateRegistrationForm(formData);
        if (!validation.isValid) {
            enableElement(btn); 
            toggleButtonContent(btn, '', true);
            toast('error', 8000, validation.message);
            return;
        }
        
        // Update step indicator
        this.updateStepIndicator(2);
        
        // Simulate API call
        await this.simulateRegistration(btn, formData);
    }

    setupFormValidations() {
        // Real-time password strength checker
        const passwordInput = document.getElementById('password');
        if (passwordInput) {
            passwordInput.addEventListener('input', (e) => this.updatePasswordStrength(e.target.value));
        }
        
        // Password confirmation check
        const confirmPassword = document.getElementById('confirm_password');
        if (confirmPassword) {
            confirmPassword.addEventListener('input', () => this.checkPasswordMatch());
        }
        
        // Email validation
        const emailInputs = document.querySelectorAll('input[type="email"]'); 
        emailInputs.forEach(input => {
            input.addEventListener('blur', (e) => this.validateEmail(e.target));
        });
        
        // Phone number validation
        const phoneInput = document.getElementById('tel');
        if (phoneInput) {
            phoneInput.addEventListener('blur', (e) => this.validatePhoneNumber(e.target));
        }
    }

    updatePasswordStrength(password) {
        const strengthFill = document.getElementById('strengthFill');
        const strengthText = document.getElementById('strengthText');
        const strengthScore = document.getElementById('strengthScore');
        
        if (!strengthFill || !strengthText || !strengthScore) return;
        
        let score = 0;
        let feedback = [];
        
        // Check criteria
        if (password.length >= 8) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[a-z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^A-Za-z0-9]/.test(password)) score++;
        
        // Update UI
        const strength = (score / 5) * 100;
        strengthFill.style.width = `${strength}%`;
        
        let color, text;
        switch (score) {
            case 0:
            case 1:
                color = '#dc3545';
                text = 'Very Weak';
                break;
            case 2:
                color = '#ff6b6b';
                text = 'Weak';
                break;
            case 3:
                color = '#ffc107';
                text = 'Fair';
                break;
            case 4:
                color = '#17a2b8';
                text = 'Good';
                break;
            case 5:
                color = '#28a745';
                text = 'Strong';
                break;
        }
        
        strengthFill.style.background = color;
        strengthText.textContent = text;
        strengthText.style.color = color;
        strengthScore.textContent = `${score}/5`;
    }

    checkPasswordMatch() {
        const password = document.getElementById('password');
        const confirmPassword = document.getElementById('confirm_password');
        
        if (!password || !confirmPassword) return;
        
        if (confirmPassword.value && password.value !== confirmPassword.value) {
            confirmPassword.style.borderColor = '#dc3545';
            confirmPassword.style.boxShadow = '0 0 0 3px rgba(220, 53, 69, 0.1)';
        } else if (confirmPassword.value) {
            confirmPassword.style.borderColor = '#28a745';
            confirmPassword.style.boxShadow = '0 0 0 3px rgba(40, 167, 69, 0.1)';
        }
    }

    validateEmail(input) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        const isValid = emailRegex.test(input.value);
        
        if (!isValid) toast('error', 8000, lang.invalid_email || lang.undefined_error);
        return isValid;
    }

    validatePhoneNumber(input) {
        const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/;
        const isValid = phoneRegex.test(input.value.replace(/[\s\-\(\)]/g, ''));
        
        if (!isValid) toast('error', 8000, lang.invalid_phone || lang.undefined_error);
        return isValid;
    }

    setupFloatingAnimations() {
        this.floatingShapes.forEach((shape, index) => {
            if (!shape) return;
            
            // Set random animation delays
            const delay = index * -7;
            shape.style.animationDelay = `${delay}s`;
            
            // Add hover effect
            shape.addEventListener('mouseenter', () => {
                shape.style.opacity = '0.2';
                shape.style.transform = 'scale(1.1)';
            });
            
            shape.addEventListener('mouseleave', () => {
                shape.style.opacity = '0.1';
                shape.style.transform = 'scale(1)';
            });
        });
    }

    setupSocialLogins() {
        const socialButtons = document.querySelectorAll('.btn-social');
        socialButtons.forEach(button => {
            button.addEventListener('click', (e) => this.handleSocialLogin(e.target));
        });
    }

    handleSocialLogin(btn) {
        const provider = btn.textContent.trim().toLowerCase();
        
        // Show loading 
        disableElement(btn); 
        toggleButtonContent(btn, '<i class="fas fa-spinner fa-spin"></i> Connecting...');
               
        toast('info', 4000, `Connecting with ${provider}...`);
     
        // Simulate social login
        setTimeout(async () => {
            let request = undefined;
            if (btn.classList.contains('login')) {
                request = await this.pingSocialLoginRequest(provider);
            }

            if (btn.classList.contains('register')) {
                request = await this.pingSocialRegisterRequest(provider);
            }
            
            if (request) {
                setTimeout(() => this.redirectToDashboard(), 1000);
            } else {
                enableElement(btn); 
                toggleButtonContent(btn, '', true);
                setTimeout(() => {
                    toast('error', 8000, `${provider} login failed. Please try again.`); 
                }, 3000);
            }
        }, 1500);
    }

    async pingSocialLoginRequest(provider) {
        return false;
    }

    async pingSocialRegisterRequest(provider) { 
        return false;
    }

    setupRememberMe() {
        const rememberMe = document.getElementById('rememberMe');
        if (rememberMe) {
            // Check if remember me was previously set
            const remembered = localStorage.getItem('streamPayRememberMe');
            if (remembered === 'true') {
                rememberMe.checked = true;
                
                // Auto-fill credentials (in a real app, this would be handled more securely)
                const savedEmail = localStorage.getItem('streamPayEmail');
                if (savedEmail && this.loginForm) {
                    const emailInput = this.loginForm.querySelector('input[name="email"]');
                    if (emailInput) emailInput.value = savedEmail;
                }
            }
            
            rememberMe.addEventListener('change', (e) => {
                if (e.target.checked && this.loginForm) {
                    const emailInput = this.loginForm.querySelector('input[name="email"]');
                    if (emailInput && emailInput.value) {
                        localStorage.setItem('streamPayEmail', emailInput.value);
                    }
                    localStorage.setItem('streamPayRememberMe', 'true');
                } else {
                    localStorage.removeItem('streamPayEmail');
                    localStorage.removeItem('streamPayRememberMe');
                }
            });
        }
    }

    validateLoginForm(formData) {
        const email = formData.get('email');
        const password = formData.get('password');
        
        if (!email || !password) {
            return false;
        }
        
        if (!this.validateEmail({ value: email })) {
            return false;
        }
        
        return true;
    }

    validateRegistrationForm(formData) {
        const username = formData.get('username');
        const email = formData.get('email');
        const tel = formData.get('tel');
        const password = formData.get('password');
        const confirmPassword = formData.get('confirm_password');
        const terms = formData.get('terms');

        if (!username || !email || !tel || !password || !confirmPassword) {
            return { isValid: false, message: lang.required_fields };
        }
    
        if (!this.validateEmail({ value: email })) {
            return { isValid: false, message: lang.invalid_email };
        }
    
        if (!this.validatePhoneNumber({ value: tel })) {
            return { isValid: false, message: lang.invalid_phone };
        }
    
        if (password.length < 8) {
            return { isValid: false, message: lang.password_too_short };
        }
    
        if (password !== confirmPassword) {
            return { isValid: false, message: lang.password_mismatch };
        }
    
        if (!terms) {
            return { isValid: false, message: lang.terms_unchecked };
        }
    
        return { isValid: true, message: lang.validation_passed };
    }

    async simulateLogin(btn, formData) { 
        setTimeout(async () => { // debounce timer
            const email = formData.get('email');
            const password = formData.get('password'); 
            
            if (!email || password.length < 6) { 
                enableElement(btn); 
                toggleButtonContent(btn, '', true);
                toast('error', 5000, lang.invalid_credentials);
                return;
            } 

            try {
                const res = await fetch(formRouteParser(this.loginForm), {
                    method: this.loginForm.method || 'POST', 
                    headers: { 
                        'X-Requested-With': 'XMLHttpRequest', 
                    },
                    body: formData
                });

                enableElement(btn); 
                toggleButtonContent(btn, '', true);

                if (!res.ok) {
                    toast('error', 5000, lang.undefined_error);
                    return;
                }

                console.log(res);
                const response = await res.json(); 

                if (response?.status === 'success') { 
                    toast(response.status, 5000, lang.login_success || lang.undefined_error); 
                    if (response.route) route(response.route);
                    return;
                }

                if (response?.status === 'error') {
                    toast(response.status, 5000, response.message || lang.undefined_error);
                    return;
                }

                toast('error', 5000, lang.undefined_error);

            } catch (error) {
                enableElement(btn);
                toggleButtonContent(btn, '', true);
                console.log(error.message || error);
                toast('error', 5000, lang.undefined_error);
            } 
        }, 1500); 
    }

    async simulateRegistration(btn, formData) { 
        setTimeout(async () => { // debounce timeout
            const username = formData.get('username');
            const email = formData.get('email');
            
            if (!username || !email) {
                enableElement(btn);
                toggleButtonContent(btn, '', true);
                toast('error', 5000, lang.registration_failed || lang.undefined_error);
                return;
            }

            try {
                const res = await fetch(formRouteParser(this.registerForm), {
                    method: this.registerForm.method || 'POST', 
                    headers: { 
                        'X-Requested-With': 'XMLHttpRequest', 
                    },
                    body: formData
                });

                toggleButtonContent(btn, '', true);
                
                if (!res.ok) {
                    toast('error', 5000, lang.undefined_error);
                    return;
                }

                const response = await res.json();
                console.log(response);

                if (response?.status === 'success') { 
                    this.updateStepIndicator(3);
                    toast(response.status, 5000, lang.signup_success || lang.undefined_error); 
                    setTimeout(() => { 
                        disableElement(btn);
                        if (response.route) route(response.route);
                    }, 3000);
                    return;
                }

                enableElement(btn); 

                if (response?.status === 'error') {
                    toast(response.status, 5000, response.message || lang.undefined_error);
                    return;
                }

                toast('error', 5000, lang.undefined_error);

            } catch (error) {
                enableElement(btn);
                toggleButtonContent(btn, '', true);
                console.log(error.message || error);
                toast('error', 5000, lang.undefined_error);
            }  
        }, 2000); 
    }

    updateStepIndicator(step) {
        const steps = document.querySelectorAll('.step');
        if (!steps.length) return;
        
        steps.forEach((stepEl, index) => {
            if (index < step) {
                stepEl.classList.add('active');
            } else {
                stepEl.classList.remove('active');
            }
        });
    }

    redirectToDashboard() {
        toast('success', 8000, 'Redirecting to dashboard...');
        setTimeout(() => {
            route('/dashboard');
        }, 1500);
    }

    redirectToVerification() {
        toast('success', 8000, 'Redirecting to verification...');
        setTimeout(() => {
            route('/verify-email');
        }, 1500);
    }

    setupKeyboardShortcuts() {
        // Add keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            // Ctrl/Cmd + Enter to submit form
            if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                const activeForm = document.querySelector('form:focus-within');
                if (activeForm) {
                    activeForm.dispatchEvent(new Event('submit', { cancelable: true }));
                }
            }
            
            // Escape to close alerts
            if (e.key === 'Escape') {
                const alerts = document.querySelectorAll('.custom-alert, .alert-dismissible');
                alerts.forEach(alert => {
                    const closeBtn = alert.querySelector('.btn-close');
                    if (closeBtn) closeBtn.click();
                });
            }
        });
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    const authService = new Auth(); 
    authService.initializeAuthService();
});