/**
 * Password
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const passwordStrengthMeterPlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {
        /**
         * entropy bits:
         * < 28: too weak
         * 35: weak
         * 59: strong
         * >60: very strong, financial
         */

        form.querySelectorAll('.dp-password-indicator').forEach((container) => {
            const indicator = container.querySelector('div.dp-indicator');
            if (!indicator) return;

            const entropy = container.dataset.entropy ? JSON.parse(container.dataset.entropy) : { min: 0, max: 60 };
            const labels = container.dataset.labels ? JSON.parse(container.dataset.labels) : ['Too weak', 'Weak', 'Strong', 'Very strong'];

            const passwordInput = container.querySelector('input[type="password"]');
            if (!passwordInput) return;

            passwordInput.addEventListener('keyup', () => {
                const password = passwordInput.value;
                const strength = getPasswordStrength(password); // assumes you have this function

                // Calculate percentage between min and max entropy
                let percentage = (strength - entropy.min) / (entropy.max - entropy.min);
                percentage = Math.max(0, Math.min(percentage, 1)); // clamp 0..1

                // Calculate color gradient from red -> green
                const colorR = Math.floor(Math.min(255, 510 - percentage * 255 * 2));
                const colorG = Math.floor(Math.min(percentage * 255 * 2, 255));
                const rgb = `rgb(${colorR},${colorG},0)`;

                // Determine label
                const labelIndex = Math.floor(percentage / (1 / labels.length));
                const label = labels[labelIndex] || '';

                // Update indicator
                indicator.textContent = label;
                indicator.style.width = `${percentage * 100}%`;
                indicator.style.backgroundColor = rgb;
                indicator.style.opacity = 0.8;
            });
        });
    }
};

IGDATAPOOLFE.addPlugin('passwordStrengthMeter', passwordStrengthMeterPlugin);

export default passwordStrengthMeterPlugin;
