// app/cnx/professeur/main.js

const ProfesseurLogin = {
    config: {
        apiUrl: '/est-concours/model/api/employee.php',
        maxAttempts: 3,
        redirectUrl: '/est-concours/app/view/prof/concours/'
    },

    elements: {
        form: null,
        emailInput: null,
        passwordInput: null,
        loginBtn: null,
        messageContainer: null,
        loadingSpinner: null
    },

    init() {
        this.cacheElements();
        this.bindEvents();
        this.setupAutoFocus();
    },

    cacheElements() {
        this.elements.form = document.getElementById('loginForm');
        this.elements.emailInput = document.getElementById('email');
        this.elements.passwordInput = document.getElementById('password');
        this.elements.loginBtn = document.querySelector('#loginBtn');
        this.elements.messageContainer = this.createMessageContainer();

        this.elements.loadingSpinner = document.createElement('span');
        this.elements.loadingSpinner.className = 'spinner-border spinner-border-sm';
        this.elements.loadingSpinner.setAttribute('role', 'status');
        this.elements.loadingSpinner.setAttribute('aria-hidden', 'true');
    },

    createMessageContainer() {
        const container = document.createElement('div');
        container.id = 'loginMessage';
        container.className = 'mb-3';

        const logo = document.querySelector('.logo');
        if (logo) {
            logo.parentNode.insertBefore(container, logo.nextSibling);
        } else {
            const form = document.querySelector('form');
            if (form) {
                form.parentNode.insertBefore(container, form);
            }
        }

        return container;
    },

    bindEvents() {
        if (this.elements.form) {
            this.elements.form.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleLogin();
            });
        }

        if (this.elements.passwordInput) {
            this.elements.passwordInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this.handleLogin();
                }
            });
        }

        document.querySelectorAll('input[required]').forEach(input => {
            input.addEventListener('blur', function () {
                this.classList.toggle('is-invalid', !this.value.trim());
                const errorId = this.id + '-error';
                const errorEl = document.getElementById(errorId);
                if (errorEl) {
                    errorEl.classList.toggle('show', !this.value.trim());
                }
            });
        });
    },

    setupAutoFocus() {
        if (this.elements.emailInput) {
            this.elements.emailInput.focus();
        }
    },

    async handleLogin() {
        if (!this.validateForm()) {
            return;
        }

        const email = this.elements.emailInput.value.trim();
        const password = this.elements.passwordInput.value.trim();

        this.setLoadingState(true);

        try {
            const response = await this.sendLoginRequest(email, password);

            if (response.success) {
                this.handleSuccess(response);
            } else {
                this.handleError(response);
            }
        } catch (error) {
            console.error('Login error:', error);
            this.showMessage('error', 'Une erreur est survenue. Veuillez réessayer.');
        } finally {
            this.setLoadingState(false);
        }
    },

    async sendLoginRequest(email, password) {
        const response = await fetch(`${this.config.apiUrl}?action=login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                password: password
            })
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        return await response.json();
    },

    async handleSuccess(data) {
        try {
            const userData = {
                id: data.id,
                email: data.email,
                nom: data.nom,
                prenom: data.prenom,
                telephone: data.telephone,
                departement: data.departement,
                grade: data.grade,
                loginTime: new Date().toISOString()
            };
            sessionStorage.setItem('professeur', JSON.stringify(userData));
            document.cookie = `professeur_session=true; path=/; max-age=${60 * 60 * 24}`;
        } catch (e) {
            console.warn('Could not store session data:', e);
        }

        this.showMessage('success', 'Connexion réussie ! Redirection en cours...');


        setTimeout(() => {
            window.location.href = this.config.redirectUrl + '?prof_id=' + data.id;
        }, 800);
    },

    handleError(response) {
        const message = response.message || 'Email ou mot de passe incorrect';

        if (message.toLowerCase().includes('bloqué')) {
            this.showMessage('error', '🚫 ' + message);
            this.elements.loginBtn.disabled = true;
            this.showContactAdmin();
        } else {
            this.showMessage('warning', '⚠️ ' + message);
            this.highlightError();
        }

        this.elements.passwordInput.value = '';
        this.elements.passwordInput.focus();
    },

    validateForm() {
        const email = this.elements.emailInput.value.trim();
        const password = this.elements.passwordInput.value.trim();
        let isValid = true;

        this.elements.emailInput.classList.remove('is-invalid');
        this.elements.passwordInput.classList.remove('is-invalid');
        document.getElementById('email-error')?.classList.remove('show');
        document.getElementById('password-error')?.classList.remove('show');

        if (!email) {  // ✅ تغيير: cin → email
            this.elements.emailInput.classList.add('is-invalid');
            document.getElementById('email-error')?.classList.add('show');
            isValid = false;
        }

        if (!password) {
            this.elements.passwordInput.classList.add('is-invalid');
            document.getElementById('password-error')?.classList.add('show');
            isValid = false;
        }

        return isValid;
    },

    setLoadingState(loading) {
        const btn = this.elements.loginBtn;
        if (!btn) return;

        if (loading) {
            btn.disabled = true;
            btn.innerHTML = `
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                Connexion en cours...
            `;
        } else {
            btn.disabled = false;
            btn.innerHTML = `
                <i class="fas fa-sign-in-alt"></i> Se Connecter
            `;
        }
    },

    showMessage(type, message) {
        const container = this.elements.messageContainer;
        if (!container) return;

        const alertClass = {
            'success': 'alert-success',
            'error': 'alert-error',
            'warning': 'alert-warning',
            'info': 'alert-info'
        };

        const iconMap = {
            'success': 'fa-check-circle',
            'error': 'fa-times-circle',
            'warning': 'fa-exclamation-triangle',
            'info': 'fa-info-circle'
        };

        container.innerHTML = `
            <div class="alert alert-custom ${alertClass[type] || 'alert-info'} alert-dismissible fade show" role="alert">
                <i class="fas ${iconMap[type] || 'fa-info-circle'}"></i>
                <span>${message}</span>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
    },

    highlightError() {
        this.elements.emailInput.classList.add('is-invalid');
        this.elements.passwordInput.classList.add('is-invalid');
    },

    showContactAdmin() {
        const container = this.elements.messageContainer;
        if (!container) return;

        const contactHtml = `
            <div class="mt-3 text-center">
                <small class="text-muted">
                    <i class="fas fa-phone"></i> Contactez l'administrateur au 
                    <a href="tel:+212XXXXXXXX">+212 XXXXXXXXX</a>
                </small>
            </div>
        `;

        const existingAlert = container.querySelector('.alert');
        if (existingAlert) {
            existingAlert.insertAdjacentHTML('afterend', contactHtml);
        }
    },

    forgotPassword() {
        const email = this.elements.emailInput.value.trim();

        if (!email) {
            this.showMessage('warning', 'Veuillez entrer votre email pour réinitialiser votre mot de passe.');
            this.elements.emailInput.focus();
            return;
        }

        this.showMessage('info', `📧 Un email de réinitialisation a été envoyé à ${email}`);
    }
};

// Initialisation
document.addEventListener('DOMContentLoaded', () => {
    ProfesseurLogin.init();

    window.forgotPassword = function () {
        ProfesseurLogin.forgotPassword();
    };
});

// Styles CSS
const style = document.createElement('style');
style.textContent = `
    .alert-custom {
        border-radius: 6px;
        padding: 12px 15px;
        margin-bottom: 20px;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .alert-custom i {
        font-size: 18px;
        flex-shrink: 0;
    }
    
    .alert-custom.alert-error {
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
    }
    
    .alert-custom.alert-success {
        background-color: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
    }
    
    .alert-custom.alert-warning {
        background-color: #fff3cd;
        border: 1px solid #ffeaa7;
        color: #856404;
    }
    
    .alert-custom.alert-info {
        background-color: #d1ecf1;
        border: 1px solid #bee5eb;
        color: #0c5460;
    }
    
    .spinner-border {
        display: inline-block;
        width: 1rem;
        height: 1rem;
        vertical-align: text-bottom;
        border: 0.2em solid currentColor;
        border-right-color: transparent;
        border-radius: 50%;
        animation: spinner-border .75s linear infinite;
    }
    
    @keyframes spinner-border {
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(style);
