<?php
session_start();

// Se já estiver logado, redirecionar para dashboard
if (isset($_SESSION['auth_token'])) {
    require_once __DIR__ . '/backend/classes/Session.php';
    $session = new Session();
    $user_data = $session->validateSession($_SESSION['auth_token']);
    
    if ($user_data) {
        header("Location: /dashboard");
        exit();
    }
}

// Buscar configurações do sistema
require_once __DIR__ . '/backend/classes/ConfigSistema.php';
$configSistema = new ConfigSistema();
$config = $configSistema->getConfig();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" href="assets/icone.png">
    <title><?php echo htmlspecialchars($config['nome_sistema']); ?> - Recuperar Senha</title>
    <link rel="stylesheet" href="css/register.css">
    <style>
        /* Fix para erros de CSS que podem estar impedindo o JavaScript */
        .form-control, .code-input {
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }
        
        /* Garantir que elementos existam */
        #alert-container {
            min-height: 20px;
        }
        
        .register-form {
            position: relative;
        }
        
        /* Debug - destacar elementos importantes */
        #recover-form {
            border: 1px solid transparent;
        }
        
        #email-step, #code-step {
            position: relative;
        }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* Fallback logo styles for server compatibility */
        .logo-image {
            max-width: 200px !important;
            max-height: 80px !important;
            width: auto !important;
            height: auto !important;
            object-fit: contain !important;
        }
        
        /* Welcome logo styles */
        .welcome-logo {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        
        .welcome-logo-img {
            width: 60px;
            height: 60px;
            object-fit: contain;
        }
        
        .welcome-section h1 {
            text-align: center;
            color: #1a202c;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .welcome-section p {
            text-align: center;
            color: #718096;
            font-size: 14px;
            margin-bottom: 2px;
        }
        
        /* Resend code section styles */
        .resend-code-section {
            text-align: center;
            margin-top: 10px;
        }
        
        .resend-code-section p {
            color: #718096;
            font-size: 14px;
            margin: 0;
        }
        
        .resend-link {
            color: #00d4aa;
            text-decoration: none;
            font-weight: 500;
            transition: color 0.2s ease;
        }
        
        .resend-link:hover {
            color: #00b894;
            text-decoration: underline;
        }

        /* ESTILO PARA O BOTÃO DESABILITADO DO CONTADOR */
        .resend-link.disabled {
            color: #a0aec0;
            cursor: not-allowed;
            text-decoration: none;
            pointer-events: none;
        }

        /* NOVO ESTILO PARA O ÍCONE DE OLHO */
        .password-toggle {
            cursor: pointer;
            color: #a0aec0; /* Cor padrão dos ícones */
            margin-left: 8px;
            padding: 4px; /* Aumenta um pouco a área de clique */
            transition: color 0.3s ease;
        }
        
        .password-toggle:hover {
            color: #718096; /* Cor ao passar o mouse */
        }

        /* Ajuste fino para garantir que o input não sofra com o novo ícone */
        .input-wrapper input {
            flex: 1; /* O input ocupa o espaço restante */
        }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="register-content">
            <div class="left-side">
                <div class="logo-container">
                    <div class="logo-main">
                     </div>
                </div>
            </div>

            <div class="right-side">
                <div class="register-form-container">
                <div class="welcome-section">
                    <div class="welcome-logo">
                        <img src="/assets/icone.png" alt="Onyxpag Logo" class="welcome-logo-img">
                    </div>
                    <p><b>Recupere o acesso à sua conta Onyxpag</b></p>
                </div>

                <div id="alert-container"></div>
                
                <div id="user-email-area" style="display: none; margin-bottom: 5px;">
                    <p id="user-email-display" style="text-align: center; color: #718096; font-size: 14px; margin: 0; font-weight: 500;"></p>
                </div>

                <div id="message-area" style="display: none; margin-bottom: 15px;">
                    <div id="error-message" class="error-message" style="display: none;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 8px;">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="15" y1="9" x2="9" y2="15"></line>
                            <line x1="9" y1="9" x2="15" y2="15"></line>
                        </svg>
                        <span id="error-text">Não reconhecemos esse E-mail, por favor verifique</span>
                    </div>
                    
                    <div id="success-message" class="success-message" style="display: none;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 8px;">
                            <polyline points="20 6 9 17 4 12"></polyline>
                        </svg>
                        <span id="success-text">Email válido! Agora digite o código de verificação.</span>
                    </div>

                    <div id="info-message" class="info-message" style="display: none;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 8px;">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="12" y1="16" x2="12" y2="12"></line>
                            <line x1="12" y1="8" x2="12.01" y2="8"></line>
                        </svg>
                        <span id="info-text"></span>
                    </div>
                    
                    <div id="loading-message" class="loading-message" style="display: none;">
                        <div class="spinner-small"></div>
                        <span id="loading-text">Verificando email...</span>
                    </div>
                </div>

                <form class="register-form" id="recover-form">
                    <div id="email-step">
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label for="email">Email</label>
                            <div class="input-wrapper">
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon lucide-mail">
                                    <path d="m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"></path>
                                    <rect x="2" y="4" width="20" height="16" rx="2"></rect>
                                </svg>
                                <input type="email" id="email" name="email" placeholder="Digite seu email" required>
                            </div>
                        </div>

                        <button type="submit" class="register-btn" id="recover-btn">
                            <span class="btn-text">Enviar Instruções</span>
                            <div class="btn-loading" style="display: none;">
                                <div class="spinner"></div>
                            </div>
                        </button>
                    </div>

                    <div id="code-step" style="display: none;">
                        <div class="form-group">
                            <label><center>Código de Verificação</center></label>
                            <div class="code-inputs">
                                <input type="text" class="code-input" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                <input type="text" class="code-input" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                <input type="text" class="code-input" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                <input type="text" class="code-input" maxlength="1" pattern="[0-9]" inputmode="numeric">
                                <input type="text" class="code-input" maxlength="1" pattern="[0-9]" inputmode="numeric">
                            </div>
                        </div>

                        <button type="button" class="register-btn" id="verify-code-btn">
                            <span class="btn-text">Verificar Código</span>
                            <div class="btn-loading" style="display: none;">
                                <div class="spinner"></div>
                            </div>
                        </button>

                        <div class="resend-code-section">
                            <p>Não recebeu o código? <a href="#" id="resend-code-link" class="resend-link">Reenviar código</a></p>
                        </div>
                    </div>

                    <div id="password-step" style="display: none;">
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label for="new-password">Nova Senha</label>
                            <div class="input-wrapper">
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon lucide-lock">
                                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                                    <circle cx="12" cy="16" r="1"></circle>
                                    <path d="m12 13 0 6"></path>
                                    <path d="M8 11V7a4 4 0 0 1 8 0v4"></path>
                                </svg>
                                <input type="password" id="new-password" name="new-password" placeholder="Digite sua nova senha" required>
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="password-toggle" data-target="new-password">
                                    <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/>
                                    <circle cx="12" cy="12" r="3"/>
                                </svg>
                            </div>
                        </div>

                        <div class="form-group" style="margin-bottom: 20px;">
                            <label for="confirm-password">Confirmar Nova Senha</label>
                            <div class="input-wrapper">
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon lucide-lock">
                                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                                    <circle cx="12" cy="16" r="1"></circle>
                                    <path d="m12 13 0 6"></path>
                                    <path d="M8 11V7a4 4 0 0 1 8 0v4"></path>
                                </svg>
                                <input type="password" id="confirm-password" name="confirm-password" placeholder="Confirme sua nova senha" required>
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="password-toggle" data-target="confirm-password">
                                    <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/>
                                    <circle cx="12" cy="12" r="3"/>
                                </svg>
                            </div>
                        </div>
                        <button type="button" class="register-btn" id="reset-password-btn">
                            <span class="btn-text">Alterar Senha</span>
                            <div class="btn-loading" style="display: none;">
                                <div class="spinner"></div>
                            </div>
                        </button>

                    </div>
                </form>

                <div class="register-footer">
                    </br>
                    <p>Lembrou da senha? <a href="/" class="login-link">Faça seu login</a></p>
                     </br>
                    <p>Não possui uma conta? <a href="/register" class="login-link">Criar conta</a></p>
                </div>
            </div>
        </div>
    </div>

    <script>
	window.addEventListener('DOMContentLoaded', function () {
		const recoverForm = document.getElementById('recover-form');
		const recoverBtn = document.getElementById('recover-btn');
		const emailInput = document.getElementById('email');
		const userEmailArea = document.getElementById('user-email-area');
		const userEmailDisplay = document.getElementById('user-email-display');

		const emailStep = document.getElementById('email-step');
		const codeStep = document.getElementById('code-step');
		const passwordStep = document.getElementById('password-step');
        
        // Elementos dos novos passos
        const verifyCodeBtn = document.getElementById('verify-code-btn');
        const resetPasswordBtn = document.getElementById('reset-password-btn');
        const backToCodeBtn = document.getElementById('back-to-code-btn');
        const resendCodeLink = document.getElementById('resend-code-link');

		if (!recoverForm || !recoverBtn || !emailInput || !emailStep || !codeStep || !passwordStep) {
			return;
		}

		function showMessage(type, message = '') {
			const messageArea = document.getElementById('message-area');
			const errorMessage = document.getElementById('error-message');
			const successMessage = document.getElementById('success-message');
			const infoMessage = document.getElementById('info-message');
			const loadingMessage = document.getElementById('loading-message');
            const loadingText = document.getElementById('loading-text');

			if (!messageArea || !errorMessage || !successMessage || !infoMessage || !loadingMessage) {
				return;
			}

			errorMessage.style.display = 'none';
			successMessage.style.display = 'none';
			infoMessage.style.display = 'none';
			loadingMessage.style.display = 'none';
			messageArea.style.display = 'block';

			if (type === 'error') {
				if (message) {
					document.getElementById('error-text').textContent = message;
				}
				errorMessage.style.display = 'flex';
				return;
			}

			if (type === 'success') {
				if (message) {
					document.getElementById('success-text').textContent = message;
				}
				successMessage.style.display = 'flex';
				return;
			}

			if (type === 'info') {
				if (message) {
					document.getElementById('info-text').textContent = message;
				}
				infoMessage.style.display = 'flex';
				return;
			}

			if (type === 'loading') {
                if (message && loadingText) {
                    loadingText.textContent = message;
                } else if (loadingText) {
                    loadingText.textContent = 'Verificando...';
                }
				loadingMessage.style.display = 'flex';
				return;
			}
		}

		function hideMessage() {
			const messageArea = document.getElementById('message-area');
			if (messageArea) {
				messageArea.style.display = 'none';
			}
		}

		function setButtonLoading(isLoading) {
			const btnText = recoverBtn.querySelector('.btn-text');
			const btnLoading = recoverBtn.querySelector('.btn-loading');

			recoverBtn.disabled = isLoading;
			if (btnText) {
				btnText.style.display = isLoading ? 'none' : 'inline';
			}
			if (btnLoading) {
				btnLoading.style.display = isLoading ? 'block' : 'none';
			}
		}

		function showCodeStep(email) {
			emailStep.style.display = 'none';
			passwordStep.style.display = 'none';
			codeStep.style.display = 'block';

			if (userEmailArea && userEmailDisplay) {
				userEmailDisplay.textContent = email;
				userEmailArea.style.display = 'block';
			}

			const firstCodeInput = document.querySelector('.code-input');
			if (firstCodeInput) {
				firstCodeInput.focus();
			}
		}

        function showPasswordStep() {
            codeStep.style.display = 'none';
            passwordStep.style.display = 'block';
            
            const newPasswordInput = document.getElementById('new-password');
            if (newPasswordInput) {
                newPasswordInput.focus();
            }
        }

        // NOVA FUNÇÃO PARA GERENCIAR O TOGGLE DE SENHA
        function setupPasswordToggles() {
            const toggles = document.querySelectorAll('.password-toggle');
            
            toggles.forEach(toggle => {
                toggle.addEventListener('click', function() {
                    const targetId = this.getAttribute('data-target');
                    const input = document.getElementById(targetId);
                    if (!input) return;

                    if (input.type === 'password') {
                        // Mostrar senha
                        input.type = 'text';
                        // Troca o ícone para "olho riscado" (ocultar)
                        this.innerHTML = '<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7c.68 0 1.35-.06 1.99-.17"/><line x1="2" y1="2" x2="22" y2="22"/>';
                    } else {
                        // Ocultar senha
                        input.type = 'password';
                         // Troca o ícone de volta para "olho normal" (mostrar)
                        this.innerHTML = '<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>';
                    }
                });
            });
        }

        // Chama a função de setup dos toggles
        setupPasswordToggles();

		function setupCodeInputs() {
			const codeInputs = document.querySelectorAll('.code-input');
			codeInputs.forEach((input, index) => {
				input.addEventListener('input', function () {
					this.value = this.value.replace(/[^0-9]/g, '');
					if (this.value.length > 1) {
						this.value = this.value.slice(-1);
					}
					if (this.value.length === 1 && index < codeInputs.length - 1) {
						const nextInput = codeInputs[index + 1];
						if (nextInput) {
							nextInput.focus();
						}
					}
				});

				input.addEventListener('keydown', function (e) {
					if (e.key === 'Backspace' && this.value === '' && index > 0) {
						const prevInput = codeInputs[index - 1];
						if (prevInput) {
							prevInput.focus();
						}
					}
				});

				input.addEventListener('paste', function (e) {
					e.preventDefault();
					const pastedText = (e.clipboardData || window.clipboardData).getData('text');
					const numbers = pastedText.replace(/[^0-9]/g, '').slice(0, 5);
					if (numbers.length === 0) {
						return;
					}
					codeInputs.forEach(inp => inp.value = '');
					for (let i = 0; i < Math.min(numbers.length, codeInputs.length); i++) {
						if (codeInputs[i]) {
							codeInputs[i].value = numbers[i];
						}
					}
					const focusIndex = Math.min(numbers.length, codeInputs.length - 1);
					if (codeInputs[focusIndex]) {
						codeInputs[focusIndex].focus();
					}
				});
			});
		}

		setupCodeInputs();

		async function handleRecoverSubmit(e) {
			if (e && typeof e.preventDefault === 'function') {
				e.preventDefault();
			}

			const email = (emailInput.value || '').trim();
			if (!email) {
				showMessage('error', 'ops! Não reconhecemos esse email');
				return;
			}

			hideMessage();
			setButtonLoading(true);
			showMessage('loading', 'Verificando email...');

			try {
				const response = await fetch('backend/api/recuperacont.php', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({ email })
				});

				const data = await response.json();
				if (data && data.success) {
					fetch('backend/api/enviacodvalidacao.php', {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify({ email })
					}).catch(() => {});

					showMessage('success', 'Foi enviado um código de verificação para o email');
					showCodeStep(email);
					return;
				}

				showMessage('error', data.message || 'ops! Não reconhecemos esse email');
			} catch (err) {
				showMessage('error', 'Erro ao conectar com o servidor.');
			} finally {
				setButtonLoading(false);
			}
		}

        // LÓGICA DE REENVIAR CÓDIGO COM CONTADOR
        async function handleResendCode(e) {
            if (e && typeof e.preventDefault === 'function') {
                e.preventDefault();
            }

            if (resendCodeLink.classList.contains('disabled')) {
                return;
            }

            const email = (emailInput.value || '').trim();
            if (!email) return;

            resendCodeLink.classList.add('disabled');
            let timeLeft = 60;
            resendCodeLink.textContent = `Aguarde ${timeLeft}s`;

            const timerId = setInterval(() => {
                timeLeft--;
                if (timeLeft <= 0) {
                    clearInterval(timerId);
                    resendCodeLink.classList.remove('disabled');
                    resendCodeLink.textContent = 'Reenviar código';
                } else {
                    resendCodeLink.textContent = `Aguarde ${timeLeft}s`;
                }
            }, 1000);

            hideMessage();
            showMessage('loading', 'Reenviando um novo código...');

            try {
                const response = await fetch('backend/api/recuperacont.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ email })
                });

                const data = await response.json();
                
                if (data && data.success) {
                    fetch('backend/api/enviacodvalidacao.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ email })
                    }).catch(() => {});

                    showMessage('success', 'Um novo código foi enviado para seu email!');
                    
                    const codeInputs = document.querySelectorAll('.code-input');
                    codeInputs.forEach(input => input.value = '');
                    if(codeInputs[0]) codeInputs[0].focus();
                    
                } else {
                    showMessage('error', data.message || 'Erro ao gerar novo código.');
                }
            } catch (err) {
                showMessage('error', 'Erro ao conectar com o servidor para reenviar.');
            }
        }

        async function handleVerifyCode(e) {
            if (e && typeof e.preventDefault === 'function') {
                e.preventDefault();
            }

            const codeInputs = document.querySelectorAll('.code-input');
            let codigo = '';
            codeInputs.forEach(input => codigo += input.value);

            if (codigo.length !== 5) {
                showMessage('error', 'Por favor, preencha todos os 5 dígitos do código.');
                return;
            }

            hideMessage();
            
            const btnText = verifyCodeBtn.querySelector('.btn-text');
            const btnLoading = verifyCodeBtn.querySelector('.btn-loading');
            
            verifyCodeBtn.disabled = true;
            if (btnText) btnText.style.display = 'none';
            if (btnLoading) btnLoading.style.display = 'block';

            showMessage('loading', 'Verificando código...');

            try {
                const response = await fetch('backend/api/validarcodigo.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ codigo })
                });

                const data = await response.json();
                
                if (data && data.success) {
                    showMessage('success', 'Código validado! Agora digite sua nova senha.');
                    showPasswordStep();
                } else {
                    showMessage('error', data.message || 'Código incorreto.');
                    codeInputs.forEach(input => input.value = '');
                    if(codeInputs[0]) codeInputs[0].focus();
                }
            } catch (err) {
                showMessage('error', 'Erro ao conectar com o servidor. Tente novamente.');
            } finally {
                verifyCodeBtn.disabled = false;
                if (btnText) btnText.style.display = 'inline';
                if (btnLoading) btnLoading.style.display = 'none';
            }
        }

        async function handleResetPassword(e) {
            if (e && typeof e.preventDefault === 'function') {
                e.preventDefault();
            }

            const newPasswordInput = document.getElementById('new-password');
            const confirmPasswordInput = document.getElementById('confirm-password');
            
            const senha = newPasswordInput.value;
            const confirmar_senha = confirmPasswordInput.value;

            if (!senha || !confirmar_senha) {
                showMessage('error', 'Por favor, preencha as duas senhas.');
                return;
            }

            if (senha !== confirmar_senha) {
                showMessage('error', 'As senhas não coincidem. Tente novamente.');
                return;
            }
            
            if (senha.length < 6) {
                showMessage('error', 'A senha deve ter pelo menos 6 caracteres.');
                return;
            }

            hideMessage();
            
            const btnText = resetPasswordBtn.querySelector('.btn-text');
            const btnLoading = resetPasswordBtn.querySelector('.btn-loading');
            
            resetPasswordBtn.disabled = true;
            if (backToCodeBtn) backToCodeBtn.disabled = true;
            
            if (btnText) btnText.style.display = 'none';
            if (btnLoading) btnLoading.style.display = 'block';

            showMessage('loading', 'Salvando nova senha...');

            try {
                const response = await fetch('backend/api/salvarsenha.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ senha: senha, confirmar_senha: confirmar_senha })
                });

                const data = await response.json();
                
                if (data && data.success) {
                    showMessage('success', 'Senha alterada com sucesso! Redirecionando para o login...');
                    
                    newPasswordInput.parentElement.parentElement.style.display = 'none';
                    confirmPasswordInput.parentElement.parentElement.style.display = 'none';
                    resetPasswordBtn.style.display = 'none';
                    if (backToCodeBtn) backToCodeBtn.style.display = 'none';
                    
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 2500);
                    
                } else {
                    showMessage('error', data.message || 'Erro ao alterar a senha.');
                    resetPasswordBtn.disabled = false;
                    if (backToCodeBtn) backToCodeBtn.disabled = false;
                    if (btnText) btnText.style.display = 'inline';
                    if (btnLoading) btnLoading.style.display = 'none';
                }
            } catch (err) {
                showMessage('error', 'Erro ao conectar com o servidor. Tente novamente.');
                resetPasswordBtn.disabled = false;
                if (backToCodeBtn) backToCodeBtn.disabled = false;
                if (btnText) btnText.style.display = 'inline';
                if (btnLoading) btnLoading.style.display = 'none';
            }
        }

		recoverForm.addEventListener('submit', handleRecoverSubmit);
		recoverBtn.addEventListener('click', handleRecoverSubmit);
        
        if (verifyCodeBtn) {
            verifyCodeBtn.addEventListener('click', handleVerifyCode);
        }

        if (resetPasswordBtn) {
            resetPasswordBtn.addEventListener('click', handleResetPassword);
        }

        if (resendCodeLink) {
            resendCodeLink.addEventListener('click', handleResendCode);
        }

        if (backToCodeBtn) {
            backToCodeBtn.addEventListener('click', function() {
                passwordStep.style.display = 'none';
                codeStep.style.display = 'block';
                showMessage('info', 'Por favor, digite o código de verificação novamente.');
            });
        }
	});
	</script>
    
    <style>
    /* Estilos para alerts */
    .alert {
        margin: 15px 0;
        padding: 12px 15px;
        border-radius: 8px;
        font-size: 14px;
        animation: slideIn 0.3s ease-out;
    }
    
    .alert-success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    
    .alert-error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    
    .alert-info {
        background-color: #d1ecf1;
        color: #0c5460;
        border: 1px solid #bee5eb;
    }
    
    .alert-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .alert-close {
        background: none;
        border: none;
        font-size: 18px;
        cursor: pointer;
        color: inherit;
        opacity: 0.7;
    }
    
    .alert-close:hover {
        opacity: 1;
    }
    
    /* Loading spinner */
    .spinner {
        width: 18px;
        height: 18px;
        border: 2px solid #ffffff;
        border-top: 2px solid transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    /* Estilos para campos de código */
    .code-description {
        font-size: 14px;
        color: #666;
        margin-bottom: 16px;
        text-align: center;
    }
    
    .code-inputs {
        display: flex;
        gap: 12px;
        justify-content: center;
        margin-bottom: 20px;
    }
    
    .code-input {
        width: 50px;
        height: 50px;
        text-align: center;
        font-size: 18px;
        font-weight: 600;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        background: #fff;
        transition: all 0.3s ease;
    }
    
    .code-input:focus {
        outline: none;
        border-color: #118d43;
        box-shadow: 0 0 0 3px rgba(17, 141, 67, 0.1);
    }
    
    .code-input:valid {
        border-color: #118d43;
        background-color: #f8fff9;
    }
    
    .secondary-btn {
        background: #6c757d;
        color: white;
        border: none;
        padding: 12px 24px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .secondary-btn:hover {
        background: #5a6268;
    }
    
    @media (max-width: 480px) {
        .code-inputs {
            gap: 8px;
        }
        
        .code-input {
            width: 40px;
            height: 40px;
            font-size: 16px;
        }
    }
    
    /* Estilos para mensagens */
    .error-message, .success-message, .info-message, .loading-message {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 16px;
    }
    
    .error-message {
        background-color: #fee;
        color: #c53030;
        border: 1px solid #feb2b2;
    }
    
    .success-message {
        background-color: #f0fff4;
        color: #38a169;
        border: 1px solid #9ae6b4;
    }
    
    .loading-message {
        background-color: #ebf8ff;
        color: #3182ce;
        border: 1px solid #90cdf4;
    }

    .info-message {
        background-color: #ebf8ff;
        color: #3182ce;
        border: 1px solid #90cdf4;
    }
    
    .spinner-small {
        width: 16px;
        height: 16px;
        border: 2px solid #3182ce;
        border-top: 2px solid transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-right: 8px;
    }
    </style>
</body>
</html>