import { DataService } from './api.js';

// Função para mostrar mensagens (toast)
function showToast(message, type = 'success') {
    const container = document.getElementById('toast-container');
    if (!container) return;
    const icon = type === 'success' ? 'fa-check-circle' : 'fa-times-circle';
    const color = type === 'success' ? 'bg-green-500' : 'bg-red-500';
    const toast = document.createElement('div');
    toast.className = `toast flex items-center gap-3 text-white font-bold ${color} px-6 py-3 rounded-lg shadow-xl`;
    toast.innerHTML = `<i class="fas ${icon}"></i> <p>${message}</p>`;
    container.appendChild(toast);
    setTimeout(() => { toast.remove(); }, 3500);
}

document.addEventListener('DOMContentLoaded', () => {
    const recoveryForm = document.getElementById('recovery-form');
    const emailInput = document.getElementById('recovery-email');
    const newPasswordInput = document.getElementById('new-password');
    const confirmPasswordInput = document.getElementById('confirm-password');

    const urlParams = new URLSearchParams(window.location.search);
    const email = urlParams.get('email');

    if (email) {
        emailInput.value = email;
    } else {
        alert('E-mail inválido ou não encontrado. Volte para a página de login.');
        window.location.href = 'login.html';
    }

    recoveryForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const newPassword = newPasswordInput.value;
        const confirmPassword = confirmPasswordInput.value;

        if (!newPassword || newPassword.length < 6) {
            showToast('A nova senha deve ter pelo menos 6 caracteres.', 'error');
            return;
        }
        if (newPassword !== confirmPassword) {
            showToast('As senhas não coincidem.', 'error');
            return;
        }

        const payload = { email: email, newPassword: newPassword };

        try {
            const result = await DataService.updatePasswordByEmail(payload);
            showToast(result.message, 'success');
            
            setTimeout(() => {
                window.location.href = 'login.html';
            }, 2000);

        } catch (error) {
            showToast(error.message, 'error');
        }
    });
});