$(document).ready(function () {
    const $form = $('#changePasswordForm');
    const $newPassword = $('#newPassword');
    const $strengthMeter = $('#strengthMeter');
    const $strengthText = $('#strengthText');
    const $confirmPassword = $('#confirmPassword');
    const $matchWarning = $('#matchWarning');

    // Password visibility toggle
    $('.password-toggle').on('click', function () {
        const $btn = $(this);
        const $input = $btn.siblings('input');
        const $icon = $btn.find('i');

        if ($input.attr('type') === 'password') {
            $input.attr('type', 'text');
            $icon.removeClass('bi-eye').addClass('bi-eye-slash');
        } else {
            $input.attr('type', 'password');
            $icon.removeClass('bi-eye-slash').addClass('bi-eye');
        }
    });

    // Real-time matching logic
    function checkPasswordMatch() {
        const password = $newPassword.val();
        const confirmPassword = $confirmPassword.val();

        if (confirmPassword.length > 0 && password !== confirmPassword) {
            $matchWarning.show();
        } else {
            $matchWarning.hide();
        }
    }

    $newPassword.on('input', checkPasswordMatch);
    $confirmPassword.on('input', checkPasswordMatch);

    // Password strength logic
    $newPassword.on('input', function () {
        const password = $(this).val();
        const strength = calculateStrength(password);
        updateStrengthUI(strength);
    });

    function calculateStrength(password) {
        let score = 0;
        if (!password) return 0;
        if (password.length >= 8) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[a-z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^A-Za-z0-9]/.test(password)) score++;
        return score;
    }

    function updateStrengthUI(score) {
        let color = '';
        let text = '';
        let width = '';

        switch (score) {
            case 0:
                width = '0%';
                text = 'بہت کمزور';
                color = 'bg-danger';
                break;
            case 1:
            case 2:
                width = '40%';
                text = 'کمزور';
                color = 'bg-warning';
                break;
            case 3:
                width = '60%';
                text = 'اوسط';
                color = 'bg-info';
                break;
            case 4:
                width = '80%';
                text = 'مضبوط';
                color = 'bg-primary';
                break;
            case 5:
                width = '100%';
                text = 'بہت مضبوط';
                color = 'bg-success';
                break;
        }

        $strengthMeter.css('width', width).removeClass('bg-danger bg-warning bg-info bg-primary bg-success').addClass(color);
        $strengthText.text(text).removeClass('text-danger text-warning text-info text-primary text-success').addClass('text-' + color.replace('bg-', ''));
    }

    // Form submission
    $form.on('submit', function (e) {
        e.preventDefault();

        const oldPassword = $('#oldPassword').val();
        const newPassword = $newPassword.val();
        const confirmPassword = $('#confirmPassword').val();

        if (newPassword !== confirmPassword) {
            Swal.fire('غلطی', 'نیا پاس ورڈ اور اس کی تصدیق ایک جیسے نہیں ہیں۔', 'error');
            return;
        }

        const data = {
            oldPassword: oldPassword,
            newPassword: newPassword,
            confirmPassword: confirmPassword
        };

        const $btn = $('#btnChangePassword');
        const originalText = $btn.html();
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>صبر کریں...');

        $.ajax({
            url: 'APIs/changePassword.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    Swal.fire({
                        title: 'کامیابی',
                        text: response.message,
                        icon: 'success',
                        timer: 3000,
                        showConfirmButton: false
                    });
                    $form[0].reset();
                    updateStrengthUI(0);
                } else {
                    Swal.fire('غلطی', response.message, 'error');
                }
                $btn.prop('disabled', false).html(originalText);
            },
            error: function () {
                Swal.fire('خرابی', 'سرور سے رابطہ کرنے میں ناکامی آئی۔', 'error');
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });
});
