const API_BASE_URL = '/est-concours/model/api/candidat.php?action=forgot_password' ;

document.addEventListener('DOMContentLoaded', function () {

    const form = document.getElementById('forgotForm');
    const emailInput = document.getElementById('email');
    const submitBtn = document.getElementById('submitBtn');
    const messageContainer = document.getElementById('messageContainer');

    // Focus sur le champ Email au chargement
    emailInput.focus();

    form.addEventListener('submit', async function (e) {
        e.preventDefault();

        const email = emailInput.value.trim();

        // Validation simple
        if (!email) {
            emailInput.classList.add('is-invalid');
            document.getElementById('email-error').classList.add('show');
            return;
        }

        // Reset erreurs
        emailInput.classList.remove('is-invalid');
        document.getElementById('email-error').classList.remove('show');

        // État chargement
        setLoading(true);
        messageContainer.innerHTML = '';

        try {
            const response = await fetch(`${API_BASE_URL}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ email: email })
            });

            const result = await response.json();

            if (result.success) {
                // Succès : afficher message + nouveau mot de passe
                showMessage('success', result.message, result.new_password ?? null);
                form.style.display = 'none'; // Cacher le formulaire
            } else {
                // Erreur : Email non trouvé
                showMessage('error', result.message);
            }

        } catch (err) {
            console.error(err);
            showMessage('error', 'Erreur de connexion au serveur. Veuillez réessayer.');
        } finally {
            setLoading(false);
        }
    });

    function setLoading(loading) {
        if (loading) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = `
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                Envoi en cours...
            `;
        } else {
            submitBtn.disabled = false;
            submitBtn.innerHTML = `<i class="fas fa-paper-plane"></i> Envoyer le nouveau mot de passe`;
        }
    }

    function showMessage(type, message, newPassword = null) {
        let icon = type === 'success' ? 'fa-check-circle' : 'fa-times-circle';
        let alertClass = type === 'success' ? 'alert-success' : 'alert-error';

        let html = `
            <div class="alert-custom ${alertClass}">
                <i class="fas ${icon}"></i>
                <div>
                    <div>${message}</div>
                    ${newPassword ? `
                    <div class="mt-2 p-2 rounded" style="background:#f0f9ff; border:1px solid #00c0ed;">
                        <strong>Votre nouveau mot de passe :</strong>
                        <span style="font-family:monospace; font-size:16px; color:#00c0ed; margin-left:8px;">${newPassword}</span>
                    </div>
                    <div class="mt-1" style="font-size:12px; color:#6c757d;">
                        <i class="fas fa-info-circle"></i> Notez ce mot de passe et changez-le après votre connexion.
                    </div>
                    ` : ''}
                </div>
            </div>
        `;

        if (type === 'success') {
            html += `
                <div class="mt-3">
                    <a href="/est-concours/app/cnx/candidat/login/"
                       class="btn btn-custom-primary d-flex align-items-center justify-content-center gap-2">
                        <i class="fas fa-sign-in-alt"></i> Aller à la connexion
                    </a>
                </div>
            `;
        }

        messageContainer.innerHTML = html;
    }
});
