(function() {
    const form = document.getElementById('dz-auth-form');
    const errorDiv = document.getElementById('dz-auth-error');
    const successDiv = document.getElementById('dz-auth-success');

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        errorDiv.classList.add('hidden');
        successDiv.classList.add('hidden');

        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        try {
            const response = await fetch(form.action, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
            });

            const result = await response.json();
            if (response.ok) {
                successDiv.textContent = result.message || 'Check your email for a reset link.';
                successDiv.classList.remove('hidden');
                form.querySelector('button[type="submit"]').disabled = true;
            } else {
                errorDiv.textContent = result.detail || 'Something went wrong.';
                errorDiv.classList.remove('hidden');
            }
        } catch (err) {
            errorDiv.textContent = 'Network error. Please try again.';
            errorDiv.classList.remove('hidden');
        }
    });
})();
