class AuthManager {
    constructor(app) {
        this.app = app;
        this.setupAuthListeners();
        this.isLoading = false;
    }

    setupAuthListeners() {
        // Use event delegation for dynamic forms
        document.addEventListener('submit', (e) => {
            if (e.target.id === 'login-form') {
                e.preventDefault();
                this.handleLogin(e.target);
            }

            if (e.target.id === 'register-form') {
                e.preventDefault();
                this.handleRegister(e.target);
            }
        });

        document.addEventListener('click', (e) => {
            if (e.target.id === 'show-register') {
                e.preventDefault();
                this.showRegisterForm();
            }

            if (e.target.id === 'show-login') {
                e.preventDefault();
                this.showLoginForm();
            }

            // Password visibility toggle
            if (e.target.closest('.password-toggle')) {
                const toggle = e.target.closest('.password-toggle');
                const input = toggle.previousElementSibling;
                const icon = toggle.querySelector('i');

                if (input.type === 'password') {
                    input.type = 'text';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    input.type = 'password';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            }
        });

        // Real-time validation
        document.addEventListener('input', (e) => {
            if (e.target.closest('#register-form')) {
                this.validateRegisterField(e.target);
            }
        });

        // Remember me checkbox
        document.addEventListener('change', (e) => {
            if (e.target.id === 'remember-me') {
                localStorage.setItem('remember_me', e.target.checked);
            }
        });
    }

    validateRegisterField(field) {
        const validationMessages = {
            name: {
                pattern: /^[a-zA-Z\s]{2,}$/,
                message: 'Name should contain only letters and spaces, minimum 2 characters'
            },
            email: {
                pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                message: 'Please enter a valid email address'
            },
            password: {
                pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
                message: 'Password must be at least 8 characters and contain uppercase, lowercase, number and special character'
            },
            phone: {
                pattern: /^\+?[\d\s-]{10,}$/,
                message: 'Please enter a valid phone number'
            }
        };

        const validation = validationMessages[field.name];
        if (!validation) return;

        const feedbackEl = field.parentElement.querySelector('.validation-feedback');
        if (!feedbackEl) {
            const feedback = document.createElement('div');
            feedback.className = 'validation-feedback';
            field.parentElement.appendChild(feedback);
        }

        if (field.value && !validation.pattern.test(field.value)) {
            field.classList.add('invalid');
            field.parentElement.querySelector('.validation-feedback').textContent = validation.message;
        } else {
            field.classList.remove('invalid');
            field.parentElement.querySelector('.validation-feedback').textContent = '';
        }
    }

    _setLoadingState(form, isLoading) {
        const submitBtn = form.querySelector('button[type="submit"]');
        if (!submitBtn) return;

        this.isLoading = isLoading;
        submitBtn.disabled = isLoading;

        if (isLoading) {
            // Store original text if not already stored
            if (!submitBtn.dataset.originalText) {
                submitBtn.dataset.originalText = submitBtn.innerHTML;
            }
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Logging in...';
        } else {
            // Restore original text
            submitBtn.innerHTML = submitBtn.dataset.originalText || 'Login';
        }
    }

    async _handleLoginSuccess(result, form) {
        this.app.currentUser = result.user;

        // Handle remember me
        const emailInput = form.querySelector('input[name="email"]');
        const rememberMe = form.querySelector('#remember-me');
        if (rememberMe && rememberMe.checked) {
            localStorage.setItem('remember_email', emailInput.value.trim());
        } else {
            localStorage.removeItem('remember_email');
        }

        this.showSuccess('Login successful! Redirecting...');

        // Refresh auth state and update UI
        await this.app.checkAuth();
        this.app.updateUI();

        // Redirect after a short delay
        setTimeout(() => {
            const pageToLoad = this.app.previousPage && this.app.previousPage !== 'login' ? this.app.previousPage : 'home';
            this.app.loadPage(pageToLoad);
        }, 1000);
    }

    _handleLoginError(error, form) {
        console.error('Login error:', error);
        this.showError(error.message || 'Login failed. Please try again.');

        const passwordInput = form.querySelector('input[name="password"]');
        if (passwordInput) {
            passwordInput.value = '';
            passwordInput.focus();
        }
    }

    async handleLogin(form) {
        if (this.isLoading) return;

        const emailInput = form.querySelector('input[name="email"]');
        const passwordInput = form.querySelector('input[name="password"]');

        if (!emailInput.value || !passwordInput.value) {
            this.showError('Please enter both email and password');
            return;
        }

        this._setLoadingState(form, true);

        try {
            const response = await fetch('api/auth/login.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: emailInput.value.trim(), password: passwordInput.value }) });
            const result = await response.json();

            if (!response.ok || !result.success) throw new Error(result.message || 'Login failed');

            await this._handleLoginSuccess(result, form);
        } catch (error) {
            this._handleLoginError(error, form);
        } finally {
            this._setLoadingState(form, false);
        }
    }

    async handleRegister(form) {
        const formData = new FormData(form);
        const data = {
            name: formData.get('name'),
            email: formData.get('email'),
            password: formData.get('password'),
            phone: formData.get('phone'),
            role: formData.get('role')
        };

        try {
            const response = await fetch('api/auth/register.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                this.showSuccess('Registration successful! Please login.');
                this.showLoginForm();
            } else {
                this.showError(result.message);
            }
        } catch (error) {
            this.showError('Registration failed. Please try again.');
        }
    }

    showLoginForm() {
        this.app.showLoginForm();
    }

    showRegisterForm() {
        this.app.showRegisterForm();
    }

    showError(message) {
        this.app.notifier.show(message, 'error');
    }

    showSuccess(message) {
        this.app.notifier.show(message, 'success');
    }
}