{% load i18n %}

function isMobile() {
    return (typeof (window) !== 'undefined') && (window.innerWidth < 768 || navigator.userAgent.toLowerCase().match(/(ipod|ipad|iphone|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|wince)/i) != null);
}

var passwd_tip = "{% blocktrans %}Password strength should be strong or very strong{% endblocktrans%}";

var template = `
    <div class="popover show registration-form-popover" role="tooltip">
        <div class="popover-head" id="popover-head">{% trans "Password strength" %}:</div>
        <div class="progress">
            <div class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25"></div>
            <div class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25"></div>
            <div class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25"></div>
            <div class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25"></div>
        </div>
        <div class="popover-content">{% trans "The password should contain different types of characters to make it strong: uppercase letters, lowercase letters, numbers and special characters." %}</div>
        <div class="arrow"></div>
    </div>
`;

function setupPasswordField(selector, passwdTip, baseTemplate) {
    var template = baseTemplate.replace('registration-form-popover', `registration-form-popover ${isMobile() ? 'mobile' : ''}`);
    var element = document.getElementById(selector);
    var popover = new bootstrap.Popover(element, {
        container: 'body',
        animation: false,
        content: passwdTip,
        placement: 'left',
        template: template,
        trigger: 'focus',
    });
    function check() {
        var pwd = element.value;
        if (pwd) {
            var level = strengthLevelMap[evaluatePasswordStrength(pwd.trim())];
            showStrength(level);
        } else {
            showStrength(0);
        }
    }
    element.addEventListener('keyup', () => {
        check();
    });
    element.addEventListener('focus', () => {
        // make sure popover open first, then check password strength level
        setTimeout(() => {
            check();
        }, 1);
    });
}

const passwordConfig = {
    labelColors: {
        1: "#E43C44", // weak
        2: "#FFA800", // medium
        3: "#26B20E", // strong
        4: "#26B20E"  // very strong
    },
    strengthLevels: ['', 'weak', 'medium', 'strong', 'very strong']
};

const strengthLevelMap = {
    weak: 1,
    medium: 2,
    strong: 3,
    very_strong: 4,
};

function checkPasswordStrength(pwd, strong_pwd_required) {
    if (pwd.length === 0) return false;
    const support_strength_types = strong_pwd_required ? ['strong', 'very_strong'] : ['medium', 'strong', 'very_strong'];
    return support_strength_types.includes(evaluatePasswordStrength(pwd));
}

function evaluatePasswordStrength(password) {
    const { length } = password;
    const hasUppercase = /[A-Z]/.test(password);
    const hasLowercase = /[a-z]/.test(password);
    const hasNumbers = /\d/.test(password);
    const hasSpecialChars = /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\]/.test(password);
    let strength = 0;

    strength += length >= 16 ? 4 : length >= 12 ? 3 : length >= 8 ? 2 : length >= 6 ? 1 : 0;

    strength += hasUppercase + hasLowercase + hasNumbers + hasSpecialChars;

    if (strength >= 8) return 'very_strong';
    if (strength >= 6) return 'strong';
    if (strength >= 4) return 'medium';
    return 'weak';
}

function showStrength(level) {
    const popoverHead = $("#popover-head");
    const passwordStrength = "{% trans 'Password strength' %}";
    const processList = document.querySelectorAll('.progress-bar');
    const { labelColors, strengthLevels } = passwordConfig;
    const colors = {
        1: ["#E43C44", "#DBDBDB", "#DBDBDB", "#DBDBDB"], // weak
        2: ["#FFA800", "#FFA800", "#DBDBDB", "#DBDBDB"], // medium
        3: ["#26B20E", "#26B20E", "#26B20E", "#DBDBDB"], // strong
        4: ["#26B20E", "#26B20E", "#26B20E", "#26B20E"]  // very strong
    };

    // Set default color if level is out of bounds
    const defaultColor = "#DBDBDB";
    const colorScheme = colors[level] || [defaultColor, defaultColor, defaultColor, defaultColor];

    // Apply the color scheme
    processList.forEach((bar, index) => {
        bar.style.backgroundColor = colorScheme[index];
    });
    const strengthLevel = strengthLevels[level] || '';
    popoverHead.html(`${passwordStrength} : <span style="color: ${labelColors[level]}">${strengthLevel}</span>`);
}
