
class AdminLogin {
    constructor() {
        this.init();
    }

    init() {
        const form = document.getElementById('loginForm');
        form.addEventListener('submit', (e) => this.handleLogin(e));
        document.getElementById('forgotPasswordBtn').addEventListener('click', () => this.openForgotModal());
        document.getElementById('closeForgotModal').addEventListener('click', () => this.closeForgotModal());
        document.getElementById('sendResetLink').addEventListener('click', () => this.handleForgotPassword());
        

        document.getElementById('forgotPasswordModal').addEventListener('click', (e) => {
            if (e.target.id === 'forgotPasswordModal') {
                this.closeForgotModal();
            }
        });
        const token = localStorage.getItem('token');
        if (token) {
            this.validateTokenAndRedirect(token);
        }
    }

    async validateTokenAndRedirect(token) {
        try {

            const response = await axios.get('/api/admin/users', {
                headers: { Authorization: `Bearer ${token}` }
            });
            
            if (response.data.success) {
                window.location.href = '/admin/dashboard';
            } else {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
            }
        } catch (error) {

            localStorage.removeItem('token');
            localStorage.removeItem('user');
        }
    }

    async handleLogin(e) {
        e.preventDefault();
        
        const email = document.getElementById('email').value;
        const password = document.getElementById('password').value;
        const messageDiv = document.getElementById('message');
        
        if (!email || !password) {
            this.showMessage('Please fill in all fields', 'error');
            return;
        }
        const submitBtn = e.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Signing In...';
        submitBtn.disabled = true;

        try {
            const response = await axios.post('/api/auth/login', {
                email,
                password
            });

            if (response.data.success) {

                localStorage.setItem('token', response.data.token);
                localStorage.setItem('user', JSON.stringify(response.data.user));
                
                this.showMessage('Login successful! Redirecting...', 'success');
                

                if (response.data.user.must_change_password) {
                    setTimeout(() => {
                        window.location.href = '/admin/dashboard?changePassword=1';
                    }, 1000);
                } else {

                    setTimeout(() => {
                        window.location.href = '/admin/dashboard';
                    }, 1000);
                }
            } else {
                this.showMessage(response.data.message || 'Login failed', 'error');
            }
        } catch (error) {
            console.error('Login error:', error);
            if (error.response && error.response.data && error.response.data.message) {
                this.showMessage(error.response.data.message, 'error');
            } else {
                this.showMessage('Login failed. Please try again.', 'error');
            }
        } finally {

            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    openForgotModal() {
        document.getElementById('forgotPasswordModal').classList.remove('hidden');
        document.getElementById('forgotEmail').focus();
    }

    closeForgotModal() {
        document.getElementById('forgotPasswordModal').classList.add('hidden');
        document.getElementById('forgotEmail').value = '';
        document.getElementById('forgotMessage').classList.add('hidden');
    }

    async handleForgotPassword() {
        const email = document.getElementById('forgotEmail').value;
        const messageDiv = document.getElementById('forgotMessage');
        const sendBtn = document.getElementById('sendResetLink');
        
        if (!email) {
            this.showForgotMessage('Please enter your email address', 'error');
            return;
        }
        const originalText = sendBtn.innerHTML;
        sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Sending...';
        sendBtn.disabled = true;

        try {
            const response = await axios.post('/api/auth/forgot-password', { email });

            if (response.data.success) {
                this.showForgotMessage('Reset link sent! Check your email or use the provided link.', 'success');
                

                if (response.data.resetLink) {
                    setTimeout(() => {
                        this.showForgotMessage(
                            `Demo link: <a href="${response.data.resetLink}" class="text-blue-600 underline" target="_blank">Reset Password</a>`, 
                            'info'
                        );
                    }, 2000);
                }
            } else {
                this.showForgotMessage(response.data.message || 'Failed to send reset link', 'error');
            }
        } catch (error) {
            console.error('Forgot password error:', error);
            this.showForgotMessage('Failed to send reset link. Please try again.', 'error');
        } finally {

            sendBtn.innerHTML = originalText;
            sendBtn.disabled = false;
        }
    }

    showForgotMessage(message, type) {
        const messageDiv = document.getElementById('forgotMessage');
        messageDiv.className = `mt-2 p-3 rounded text-sm ${
            type === 'success' 
                ? 'bg-green-100 border border-green-400 text-green-700' 
                : type === 'info'
                ? 'bg-blue-100 border border-blue-400 text-blue-700'
                : 'bg-red-100 border border-red-400 text-red-700'
        }`;
        messageDiv.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'info' ? 'info-circle' : 'exclamation-triangle'} mr-2"></i>
            ${message}
        `;
        messageDiv.classList.remove('hidden');
    }

    showMessage(message, type) {
        const messageDiv = document.getElementById('message');
        messageDiv.className = `mt-4 p-3 rounded ${
            type === 'success' 
                ? 'bg-green-100 border border-green-400 text-green-700' 
                : 'bg-red-100 border border-red-400 text-red-700'
        }`;
        messageDiv.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>
            ${message}
        `;
        messageDiv.classList.remove('hidden');
    }
}
document.addEventListener('DOMContentLoaded', () => {
    new AdminLogin();
});