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

    // Extract token from query string
    const params = new URLSearchParams(window.location.search);
    const token = params.get('token');
    if (!token) {
        errorDiv.textContent = 'Missing reset token. Please use the link from your email.';
        errorDiv.classList.remove('hidden');
        form.querySelector('button[type="submit"]').disabled = true;
        return;
    }
    tokenInput.value = token;

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

        const password = document.getElementById('new_password').value;
        const confirm = document.getElementById('confirm_password').value;

        if (password !== confirm) {
            errorDiv.textContent = 'Passwords do not match.';
            errorDiv.classList.remove('hidden');
            return;
        }

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

            if (response.ok) {
                window.location.href = '/app';
            } else {
                const error = await response.json();
                errorDiv.textContent = error.detail || 'Reset failed. The link may have expired.';
                errorDiv.classList.remove('hidden');
            }
        } catch (err) {
            errorDiv.textContent = 'Network error. Please try again.';
            errorDiv.classList.remove('hidden');
        }
    });
})();
