<section class="w-full py-12 md:py-24 lg:py-32">
    <div class="container mx-auto px-4 md:px-6">
        <div class="mx-auto max-w-sm bg-white shadow-lg rounded-lg">
            <div class="p-6 flex items-center space-x-2">
                <i data-lucide="lock" class="h-6 w-6 text-blue-600"></i>
                <h2 class="text-xl font-headline font-bold">Change Password</h2>
            </div>
            <div class="p-6 pt-0">
                <% if (error) { %>
                    <div class="mb-4 text-red-600 text-sm text-center"><%= error %></div>
                    <% } %>
                    <form id="change-password-form" action="/student/change-password" method="POST">
                        <div class="grid gap-4">
                            <div class="grid gap-2">
                                <label for="currentPassword" class="text-sm font-medium">Current Password</label>
                                <input
                                id="currentPassword"
                                name="currentPassword"
                                type="password"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                aria-describedby="currentPasswordHelp"
                                />
                                <p id="currentPasswordHelp" class="text-xs text-gray-500">Enter your current password.</p>
                            </div>
                            <div class="grid gap-2">
                                <label for="newPassword" class="text-sm font-medium">New Password</label>
                                <input
                                id="newPassword"
                                name="newPassword"
                                type="password"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                aria-describedby="newPasswordHelp"
                                />
                                <p id="newPasswordHelp" class="text-xs text-gray-500">Must be at least 8 characters, with uppercase, lowercase, number, and special character.</p>
                                <div id="passwordStrength" class="text-xs mt-1 hidden">
                                    Strength: <span id="strengthText" class="font-medium"></span>
                                </div>
                            </div>
                            <div class="grid gap-2">
                                <label for="confirmPassword" class="text-sm font-medium">Confirm New Password</label>
                                <input
                                id="confirmPassword"
                                name="confirmPassword"
                                type="password"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                aria-describedby="confirmPasswordHelp"
                                />
                                <p id="confirmPasswordHelp" class="text-xs text-gray-500">Re-enter your new password to confirm.</p>
                            </div>
                            <button
                            type="submit"
                            class="w-full bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition flex items-center justify-center space-x-2"
                            aria-label="Change password"
                            >
                            <i data-lucide="save" class="h-4 w-4"></i>
                            <span>Change Password</span>
                        </button>
                    </div>
                </form>
                <div class="mt-4 text-center text-sm">
                    <a href="/student/dashboard" class="text-blue-600 hover:underline" aria-label="Back to dashboard">Back to Dashboard</a>
                </div>
            </div>
        </div>
    </div>
</section>

<script nonce="<%= nonce %>">
    const form = document.getElementById('change-password-form');
    const newPasswordInput = document.getElementById('newPassword');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    const passwordStrength = document.getElementById('passwordStrength');
    const strengthText = document.getElementById('strengthText');

    // Password strength checker
    function checkPasswordStrength(password) {
        const minLength = password.length >= 8;
        const hasUpper = /[A-Z]/.test(password);
        const hasLower = /[a-z]/.test(password);
        const hasNumber = /[0-9]/.test(password);
        const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);

        const strength = [minLength, hasUpper, hasLower, hasNumber, hasSpecial].filter(Boolean).length;
        let strengthLabel = '';
        let colorClass = '';

        switch (strength) {
            case 0:
            case 1:
            strengthLabel = 'Weak';
            colorClass = 'text-red-600';
            break;
            case 2:
            case 3:
            strengthLabel = 'Medium';
            colorClass = 'text-yellow-600';
            break;
            case 4:
            case 5:
            strengthLabel = 'Strong';
            colorClass = 'text-green-600';
            break;
        }

        return { strengthLabel, colorClass };
    }

    // Update password strength indicator
    newPasswordInput.addEventListener('input', () => {
        const password = newPasswordInput.value;
        if (password.length > 0) {
            passwordStrength.classList.remove('hidden');
            const { strengthLabel, colorClass } = checkPasswordStrength(password);
            strengthText.textContent = strengthLabel;
            strengthText.className = `font-medium ${colorClass}`;
        } else {
            passwordStrength.classList.add('hidden');
        }
    });

    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = newPasswordInput.value;
        const confirmPassword = confirmPasswordInput.value;

        // Client-side validation
        if (!currentPassword || !newPassword || !confirmPassword) {
            Swal.fire({
                icon: 'error',
                title: 'Missing Fields',
                text: 'Please fill out all required fields.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            return;
        }

        const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>]).{8,}$/;
        if (!passwordRegex.test(newPassword)) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Password',
                text: 'New password must be at least 8 characters, with uppercase, lowercase, number, and special character.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            return;
        }

        if (newPassword !== confirmPassword) {
            Swal.fire({
                icon: 'error',
                title: 'Password Mismatch',
                text: 'New password and confirmation do not match.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
            return;
        }

        try {
            // 🔐 Retrieve token
            const token = localStorage.getItem('jwtToken');
            if (!token) {
                return Swal.fire({ icon: 'error', title: 'Not Authenticated', text: 'Please log in to update your profile.' });
            }


            if (!token) {
                Swal.fire({
                    icon: 'error',
                    title: 'Session Expired',
                    text: 'Please log in again.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                }).then(() => {
                    window.location.href = '/auth/login';
                });
                return;
            }

            const response = await api.post('/api/v1/users/change-password', {
                currentPassword,
                newPassword
            });

            Swal.fire({
                icon: 'success',
                title: 'Password Changed',
                text: 'Your password has been updated successfully.',
                timer: 1500,
                showConfirmButton: false,
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#2563eb'
            }).then(() => {
                window.location.href = '/student/dashboard';
            });
        } catch (err) {
            console.error('Error changing password:', err);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: err.response?.data?.message || 'An error occurred while changing your password.',
                customClass: {
                    popup: 'bg-white rounded-lg shadow-lg',
                    title: 'text-gray-900 font-headline',
                    content: 'text-gray-600'
                },
                background: '#f9fafb',
                iconColor: '#dc2626'
            });
        }
    });

    // Initialize Lucide icons
    lucide.createIcons();
</script>