// Helper functions for password toggles and validation shared between login, setup, and overlay
window.AuthHelpers = {
    /**
     * Initializes password visibility toggles.
     * @param {HTMLElement} rootEl
     */
    initPasswordToggles(rootEl = document) {
        rootEl.querySelectorAll('.toggle-password').forEach(btn => {
            if (btn.dataset.initialized) return;
            btn.dataset.initialized = 'true';

            btn.addEventListener('click', () => {
                const input = btn.parentElement.querySelector('input');
                if (!input) return;
                
                const isPassword = input.type === 'password';
                input.type = isPassword ? 'text' : 'password';
                
                btn.innerHTML = isPassword 
                    ? '<i data-lucide="eye-off" class="eye-icon"></i>' 
                    : '<i data-lucide="eye" class="eye-icon"></i>';
                
                if (typeof lucide !== 'undefined') {
                    lucide.createIcons({ root: btn });
                }
            });
        });
    },

    /**
     * Performs client-side password validation against complexity rules.
     * @param {string} val 
     * @param {string} confirmVal 
     * @returns {Object}
     */
    validateComplexity(val, confirmVal) {
        const hasLength = val.length >= 8;
        const hasUpper = /[A-Z]/.test(val);
        const hasNumber = /[0-9]/.test(val);
        const hasSpecial = /[^a-zA-Z0-9]/.test(val);
        const matches = val === confirmVal && val.length > 0;

        return {
            hasLength,
            hasUpper,
            hasNumber,
            hasSpecial,
            matches,
            allValid: hasLength && hasUpper && hasNumber && hasSpecial && matches
        };
    },

    /**
     * Updates requirements list checklist UI.
     * @param {HTMLElement} rootEl 
     * @param {Object} statuses 
     */
    updateRequirementsUI(rootEl, statuses) {
        const updateReq = (id, isValid) => {
            const li = rootEl.querySelector(`#${id}`);
            if (!li) return;
            li.className = isValid ? 'valid' : 'invalid';
            
            const holder = li.querySelector('.icon-holder');
            if (holder) {
                holder.innerHTML = isValid 
                    ? '<i data-lucide="check" style="width:14px;height:14px;"></i>' 
                    : '<i data-lucide="x" style="width:14px;height:14px;"></i>';
                if (typeof lucide !== 'undefined') {
                    lucide.createIcons({ root: holder });
                }
            }
        };

        updateReq('req-length', statuses.hasLength);
        updateReq('req-upper', statuses.hasUpper);
        updateReq('req-number', statuses.hasNumber);
        updateReq('req-special', statuses.hasSpecial);
        updateReq('req-match', statuses.matches);
    }
};
