// Login fix for iframe context
(function() {
    'use strict';
    
    // Check if we're in an iframe
    function isInIframe() {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }
    
    // Fix form submissions in iframe
    function fixFormSubmissions() {
        const forms = document.querySelectorAll('form');
        
        forms.forEach(form => {
            form.addEventListener('submit', function(e) {
                // Add iframe context to form data
                const iframeInput = document.createElement('input');
                iframeInput.type = 'hidden';
                iframeInput.name = 'iframe_context';
                iframeInput.value = 'true';
                form.appendChild(iframeInput);
                
                // Add iframe origin to form data
                const originInput = document.createElement('input');
                originInput.type = 'hidden';
                originInput.name = 'iframe_origin';
                originInput.value = window.location.origin;
                form.appendChild(originInput);
            });
        });
    }
    
    // Fix CSRF token for iframe
    function fixCSRFToken() {
        const csrfToken = document.querySelector('input[name="csrf_test_name"]');
        if (csrfToken) {
            // Ensure CSRF token is properly set for iframe context
            csrfToken.value = csrfToken.value || document.querySelector('meta[name="csrf-token"]')?.content;
        }
    }
    
    // Fix session handling for iframe
    function fixSessionHandling() {
        // Override session storage for iframe context
        const originalSetItem = sessionStorage.setItem;
        sessionStorage.setItem = function(key, value) {
            // Store in both sessionStorage and localStorage for iframe context
            originalSetItem.call(this, key, value);
            localStorage.setItem('iframe_' + key, value);
        };
        
        const originalGetItem = sessionStorage.getItem;
        sessionStorage.getItem = function(key) {
            // Try sessionStorage first, then localStorage
            let value = originalGetItem.call(this, key);
            if (!value) {
                value = localStorage.getItem('iframe_' + key);
            }
            return value;
        };
    }
    
    // Fix cookie handling for iframe
    function fixCookieHandling() {
        // Override document.cookie for iframe context
        const originalCookie = document.cookie;
        
        // Add iframe-specific cookie attributes
        document.cookie = originalCookie + '; SameSite=None; Secure';
    }
    
    // Initialize iframe fixes
    function initIframeFixes() {
        if (isInIframe()) {
            console.log('Initializing iframe login fixes...');
            
            // Apply all fixes
            fixFormSubmissions();
            fixCSRFToken();
            fixSessionHandling();
            fixCookieHandling();
            
            // Monitor for login redirects
            monitorLoginRedirects();
            
            console.log('Iframe login fixes applied');
        }
    }
    
    // Monitor login redirects
    function monitorLoginRedirects() {
        let currentUrl = window.location.href;
        
        // Check for login redirects every 2 seconds
        setInterval(() => {
            const newUrl = window.location.href;
            if (newUrl !== currentUrl) {
                currentUrl = newUrl;
                
                // If redirected back to login page, show error
                if (newUrl.includes('login') && !newUrl.includes('logout')) {
                    console.error('Login failed - redirected back to login page');
                    
                    // Show error message
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'alert alert-danger';
                    errorDiv.innerHTML = 'Login failed. Please check your credentials and try again.';
                    errorDiv.style.position = 'fixed';
                    errorDiv.style.top = '10px';
                    errorDiv.style.right = '10px';
                    errorDiv.style.zIndex = '9999';
                    document.body.appendChild(errorDiv);
                    
                    // Remove error message after 5 seconds
                    setTimeout(() => {
                        if (errorDiv.parentNode) {
                            errorDiv.parentNode.removeChild(errorDiv);
                        }
                    }, 5000);
                }
            }
        }, 2000);
    }
    
    // Start fixes when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initIframeFixes);
    } else {
        initIframeFixes();
    }
    
    // Expose functions globally
    window.iframeLoginFixes = {
        isInIframe: isInIframe,
        fixFormSubmissions: fixFormSubmissions,
        fixCSRFToken: fixCSRFToken
    };
})();
