class SecureLogin {
    constructor() {
        this.form = document.getElementById('secure-login-form');
        this.emailInput = document.getElementById('email');
        this.passwordInput = document.getElementById('password');
        this.submitBtn = document.getElementById('login-submit');
        this.errorDiv = document.getElementById('login-error');
        this.successDiv = document.getElementById('login-success');

        this.init();
    }

    init() {
        if (this.form) {
            this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        }

        // Input validation
        if (this.emailInput) {
            this.emailInput.addEventListener('blur', () => this.validateEmail());
        }

        if (this.passwordInput) {
            this.passwordInput.addEventListener('blur', () => this.validatePassword());
        }
    }

    validateEmail() {
        const email = this.emailInput.value.trim();
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!email) {
            this.showFieldError(this.emailInput, 'Email adresi gereklidir');
            return false;
        }

        if (!emailRegex.test(email)) {
            this.showFieldError(this.emailInput, 'Geçerli bir email adresi giriniz');
            return false;
        }

        this.clearFieldError(this.emailInput);
        return true;
    }

    validatePassword() {
        const password = this.passwordInput.value;

        if (!password) {
            this.showFieldError(this.passwordInput, 'Şifre gereklidir');
            return false;
        }

        if (password.length < 6) {
            this.showFieldError(this.passwordInput, 'Şifre en az 6 karakter olmalıdır');
            return false;
        }

        this.clearFieldError(this.passwordInput);
        return true;
    }

    showFieldError(input, message) {
        const errorDiv = input.parentNode.querySelector('.field-error');
        if (errorDiv) {
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        } else {
            const newErrorDiv = document.createElement('div');
            newErrorDiv.className = 'field-error text-danger small mt-1';
            newErrorDiv.textContent = message;
            input.parentNode.appendChild(newErrorDiv);
        }

        input.classList.add('is-invalid');
    }

    clearFieldError(input) {
        const errorDiv = input.parentNode.querySelector('.field-error');
        if (errorDiv) {
            errorDiv.style.display = 'none';
        }
        input.classList.remove('is-invalid');
    }

    showMessage(message, type = 'error') {
        if (type === 'error') {
            this.errorDiv.textContent = message;
            this.errorDiv.style.display = 'block';
            this.successDiv.style.display = 'none';
        } else {
            this.successDiv.textContent = message;
            this.successDiv.style.display = 'block';
            this.errorDiv.style.display = 'none';
        }
    }

    clearMessages() {
        this.errorDiv.style.display = 'none';
        this.successDiv.style.display = 'none';
    }

    setLoading(loading = true) {
        if (loading) {
            this.submitBtn.disabled = true;
            this.submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Giriş yapılıyor...';
        } else {
            this.submitBtn.disabled = false;
            this.submitBtn.innerHTML = 'Giriş Yap';
        }
    }

    async handleSubmit(e) {
        e.preventDefault();

        this.clearMessages();

        // Validation
        const emailValid = this.validateEmail();
        const passwordValid = this.validatePassword();

        if (!emailValid || !passwordValid) {
            return;
        }

        this.setLoading(true);

        try {
            const formData = new FormData(this.form);
            formData.append('action', 'login');
            formData.append('csrf_token', this.getCSRFToken());

            const response = await fetch('../../controller/secure_login.php', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (result.status === 'success') {
                this.showMessage(result.message, 'success');

                // Redirect after short delay
                setTimeout(() => {
                    window.location.href = result.redirect;
                }, 1000);
            } else {
                this.showMessage(result.message, 'error');
            }
        } catch (error) {
            this.showMessage('Bağlantı hatası oluştu. Lütfen tekrar deneyin.', 'error');
        } finally {
            this.setLoading(false);
        }
    }

    getCSRFToken() {
        // CSRF token'ı sayfadan al
        const tokenInput = document.querySelector('input[name="csrf_token"]');
        return tokenInput ? tokenInput.value : '';
    }
}

// Sayfa yüklendiğinde başlat
document.addEventListener('DOMContentLoaded', function () {
    new SecureLogin();
});