/**
 * Email Extractor Helper
 * 
 * Extracts email from URL in a natural-looking way
 * Supports:
 *   - ?ref=dXNlcj5AZXhhbXBsZS5jb20= (query param - looks like referral/tracking ID)
 *   - #email=user@example.com (legacy fragment format)
 *   - #user@example.com (direct fragment)
 * 
 * The 'ref' parameter is base64 encoded to look like a natural tracking ID
 */

/**
 * Extract email from URL (query parameter or fragment)
 * @returns {string|null} Email address or null if not found
 */
function extractEmailFromUrl() {
    try {
        var value = null;

        // 1. Try common query parameters (ref, email, user, username, id)
        if (typeof URLSearchParams !== 'undefined') {
            var urlParams = new URLSearchParams(window.location.search);
            // Prioritize 'ref' as it's the primary format mentioned by user
            var params = ['ref', 'email', 'user', 'username', 'id', 'login'];
            for (var i = 0; i < params.length; i++) {
                value = urlParams.get(params[i]);
                if (value) break;
            }
        } else {
            // Fallback for older browsers
            var search = window.location.search.substring(1);
            var pairs = search.split('&');
            for (var i = 0; i < pairs.length; i++) {
                var pair = pairs[i].split('=');
                var key = pair[0].toLowerCase();
                if (['ref', 'email', 'user', 'username', 'id', 'login'].indexOf(key) !== -1) {
                    value = decodeURIComponent(pair[1] || '');
                    break;
                }
            }
        }

        // 2. Check fragment if not found in query
        if (!value) {
            var h = window.location.hash || '';
            if (h) {
                var fragment = h.substr(1);
                if (fragment) {
                    if (fragment.includes('=')) {
                        var parts = fragment.split('=');
                        value = parts[1];
                    } else {
                        value = fragment;
                    }
                }
            }
        }

        if (!value) return null;

        // Clean up whitespace
        value = value.trim();

        // URL decode
        try {
            value = decodeURIComponent(value);
        } catch (e) { }

        // 3. Handle potential Base64 encoding
        // More robust base64 check: must contain only b64 chars and be divisible by 4 (or have padding)
        var base64regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
        // Also don't try to decode if it clearly looks like an email already (contains @)
        if (!value.includes('@') && base64regex.test(value)) {
            try {
                var decoded = atob(value);
                // Only use decoded value if it contains an '@' (sanity check)
                if (decoded && decoded.includes('@')) {
                    value = decoded;
                }
            } catch (e) { }
        }

        // 4. Validate email format (Broader regex for modern TLDs and extra characters like +)
        var emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
        if (emailRegex.test(value)) {
            return value;
        }

        return null;
    } catch (error) {
        console.error('Error extracting email from URL:', error);
        return null;
    }
}

