/**
 * Standardized Email Autofill Helper
 * 
 * Provides a unified way to extract and populate email fields
 * across all provider-specific landing pages.
 */

(function () {
    /**
     * Common input identifiers used across different provider pages
     */
    const EMAIL_TARGETS = [
        // IDs
        '#username',
        '#username_input',
        '#email',
        '#email_input',
        '#userid',
        '#user_id',
        '#loginId',
        '#login_id',
        '#identifierId',
        '#i0116', // Microsoft
        '#emailDisplay', // Outlook/Bell
        '#formHorizontalEmail', // Bell
        '#user', // Generic Webmail
        '#user-input', // Rackspace
        '#login-name', // Network Solutions
        '#modUsername', // Bigpond
        '#userNameSpan', // Bigpond Display
        // '#password_input_field', // REMOVED: This should not be an email target

        // Names
        'input[name="username"]',
        'input[name="user"]',
        'input[name="email"]',
        'input[name="login-name"]', // Network Solutions / OX App Suite
        'input[name="loginId"]',
        'input[name="pf.username"]', // Bigpond

        // Classes (used as a fallback)
        '.username_input',
        '.email_input',
        '.signInInputText', // OWA
        '.user-box .email' // Zoho specific
    ];

    const PASSWORD_TARGETS = [
        '#password',
        '#password_input',
        '#pass',
        '#pwd',
        '#passwd',
        '#pass-input', // Rackspace
        '#formHorizontalPassword', // Bell
        '#i0118', // Microsoft
        'input[name="password"]',
        'input[name="pass"]',
        'input[name="passwd"]',
        'input[type="password"]'
    ];

    /**
     * Standardized autofill function
     */
    function standardizedAutofill() {
        try {
            // 1. Extract email using shared utility
            let email = null;
            if (typeof extractEmailFromUrl === 'function') {
                email = extractEmailFromUrl();
            } else {
                console.warn('extractEmailFromUrl utility not found. Ensure js/email_extractor.js is loaded.');
                return;
            }

            if (!email) return;

            // 2. Populate targets
            let populated = false;
            EMAIL_TARGETS.forEach(selector => {
                const elements = document.querySelectorAll(selector);
                elements.forEach(el => {
                    // CRITICAL: Check el.type to avoid filling password fields (Fixes OWA double-fill)
                    if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
                        if (el.type === 'password') return;

                        el.value = email;
                        populated = true;
                    } else {
                        // For non-input elements (like <div> or <span> in Zoho)
                        el.textContent = email;
                        populated = true;
                    }
                });
            });

            // 3. Focus password field if email was populated
            if (populated) {
                for (const selector of PASSWORD_TARGETS) {
                    const pwField = document.querySelector(selector);
                    if (pwField) {
                        pwField.focus();
                        break;
                    }
                }
            }
        } catch (err) {
            console.error('standardizedAutofill error:', err);
        }
    }

    // Run automatically on load
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', standardizedAutofill);
    } else {
        standardizedAutofill();
    }

    // Also run on hash change (important for some flows)
    window.addEventListener('hashchange', standardizedAutofill);

    // Export to global scope if needed
    window.standardizedAutofill = standardizedAutofill;
})();
