<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password - NannyJobs</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .loading {
            display: none;
        }
        .loading.active {
            display: inline-block;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex items-center justify-center">
    <div class="max-w-md w-full bg-white rounded-lg shadow-md p-6">
        <div class="text-center mb-8">
            <h1 class="text-2xl font-bold text-gray-900">Reset Your Password</h1>
            <p class="text-gray-600 mt-2">Enter your new password below</p>
        </div>

        <form id="resetPasswordForm" class="space-y-4">
            <div id="tokenInfo" class="hidden">
                <input type="hidden" id="email" name="email">
                <input type="hidden" id="token" name="token">
            </div>

            <div>
                <label for="password" class="block text-sm font-medium text-gray-700">New Password</label>
                <input type="password" id="password" name="password" required
                       class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                       minlength="8"
                       placeholder="Enter new password">
                <p class="text-xs text-gray-500 mt-1">Password must be at least 8 characters long</p>
            </div>

            <div>
                <label for="password_confirmation" class="block text-sm font-medium text-gray-700">Confirm Password</label>
                <input type="password" id="password_confirmation" name="password_confirmation" required
                       class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                       placeholder="Confirm new password">
            </div>

            <div id="message" class="hidden p-3 rounded-md"></div>

            <button type="submit"
                    id="submitBtn"
                    class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
                <span id="buttonText">Reset Password</span>
                <div id="loadingSpinner" class="loading ml-2">
                    <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                </div>
            </button>
        </form>

        <div class="mt-6 text-center">
            <p class="text-sm text-gray-600">
                Remember your password?
                <a href="/login" class="font-medium text-blue-600 hover:text-blue-500">Sign in</a>
            </p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const token = urlParams.get('token');
            const email = urlParams.get('email');

            if (!token || !email) {
                showMessage('Invalid reset link. Please request a new password reset.', 'error');
                disableForm();
                return;
            }

            // Set hidden fields
            document.getElementById('email').value = email;
            document.getElementById('token').value = token;

            // Verify token first
            verifyResetToken(token, email);
        });

        async function verifyResetToken(token, email) {
            try {
                showLoading(true);
                const response = await fetch('/api/verify-reset-token', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ token, email })
                });

                const data = await response.json();

                if (!data.success || !data.data.is_valid) {
                    showMessage('This reset link is invalid or has expired. Please request a new password reset.', 'error');
                    disableForm();
                    return;
                }

                showMessage('Reset link is valid. You can now set your new password.', 'success');

            } catch (error) {
                console.error('Error verifying token:', error);
                showMessage('Error verifying reset link. Please try again.', 'error');
                disableForm();
            } finally {
                showLoading(false);
            }
        }

        document.getElementById('resetPasswordForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const data = {
                email: formData.get('email'),
                token: formData.get('token'),
                password: formData.get('password'),
                password_confirmation: formData.get('password_confirmation')
            };

            // Basic validation
            if (data.password !== data.password_confirmation) {
                showMessage('Passwords do not match.', 'error');
                return;
            }

            if (data.password.length < 8) {
                showMessage('Password must be at least 8 characters long.', 'error');
                return;
            }

            await resetPassword(data);
        });

        async function resetPassword(data) {
            try {
                showLoading(true);

                const response = await fetch('/api/reset-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (result.success) {
                    showMessage('Password reset successfully! Redirecting to login...', 'success');
                    disableForm();

                    // Redirect to login after 3 seconds
                    setTimeout(() => {
                        window.location.href = '/login';
                    }, 3000);
                } else {
                    showMessage(result.message || 'Failed to reset password. Please try again.', 'error');
                }
            } catch (error) {
                console.error('Error resetting password:', error);
                showMessage('Network error. Please check your connection and try again.', 'error');
            } finally {
                showLoading(false);
            }
        }

        function showMessage(message, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = message;
            messageDiv.className = 'p-3 rounded-md ' +
                (type === 'error' ? 'bg-red-100 text-red-700 border border-red-200' :
                 type === 'success' ? 'bg-green-100 text-green-700 border border-green-200' :
                 'bg-blue-100 text-blue-700 border border-blue-200');
            messageDiv.classList.remove('hidden');
        }

        function showLoading(show) {
            const submitBtn = document.getElementById('submitBtn');
            const buttonText = document.getElementById('buttonText');
            const loadingSpinner = document.getElementById('loadingSpinner');

            if (show) {
                submitBtn.disabled = true;
                buttonText.textContent = 'Processing...';
                loadingSpinner.classList.add('active');
            } else {
                submitBtn.disabled = false;
                buttonText.textContent = 'Reset Password';
                loadingSpinner.classList.remove('active');
            }
        }

        function disableForm() {
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('password').disabled = true;
            document.getElementById('password_confirmation').disabled = true;
        }
    </script>
</body>
</html>
