/**
 * Comprehensive Signup Debugging Script
 * 
 * This script will help identify exactly what happens when you click signup
 * by injecting detailed logging into the signup form processing.
 */

// First, let's check if we're on the right page
console.log('🔍 Debugging Signup Process');
console.log('Current URL:', window.location.href);

// Check if AuthForm component is loaded properly
const authFormExists = typeof window.AuthForm !== 'undefined';
console.log('AuthForm component available:', authFormExists);

// Inject detailed logging into the signup form submission
console.log('🔧 Setting up form interceptors...');

// Wait for DOM to be ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', setupFormMonitoring);
} else {
    setupFormMonitoring();
}

function setupFormMonitoring() {
    console.log('🎯 Monitoring form submissions...');
    
    // Find all forms on the page
    const forms = document.querySelectorAll('form');
    console.log(`Found ${forms.length} form(s)`);
    
    forms.forEach((form, index) => {
        console.log(`Form ${index + 1}:`, {
            action: form.action,
            method: form.method,
            id: form.id,
            className: form.className
        });
        
        // Add detailed submit monitoring
        form.addEventListener('submit', function(e) {
            console.log('📋 FORM SUBMIT DETECTED');
            console.log('Form element:', this);
            console.log('Event:', e);
            console.log('Preventing default to test');
            
            // Prevent default to let us see what happens
            e.preventDefault();
            
            // Collect form data
            const formData = new FormData(this);
            const data = {};
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            console.log('Form data to be submitted:', data);
            
            // Check if we have the correct form fields
            const emailInput = this.querySelector('input[name="email"]');
            const passwordInput = this.querySelector('input[name="password"]');
            
            console.log('Email field:', emailInput ? 'FOUND' : 'MISSING');
            console.log('Password field:', passwordInput ? 'FOUND' : 'MISSING');
            
            if (emailInput && passwordInput) {
                console.log('Field values:');
                console.log('- Email:', emailInput.value);
                console.log('- Password:', passwordInput.value ? '*'.repeat(passwordInput.value.length) : '');
                
                // Try the fetch manually to see what happens
                console.log('📡 Attempting manual fetch to /api/auth/signup');
                
                const fetchPromise = fetch('/api/auth/signup', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        email: emailInput.value,
                        password: passwordInput.value
                    })
                });
                
                fetchPromise.then(response => {
                    console.log('Fetch response:', response);
                    return response.json().then(data => {
                        console.log('Response data:', data);
                    });
                }).catch(error => {
                    console.error('Fetch error:', error);
                });
            }
        }, true); // Use capture to intercept early
    });
    
    // Also monitor network requests
    const originalFetch = window.fetch;
    window.fetch = function(...args) {
        console.log('📡 FETCH CALL:', {
            url: args[0],
            init: args[1]
        });
        return originalFetch.apply(this, args);
    };
    
    // Monitor for JavaScript errors
    window.addEventListener('error', function(e) {
        console.error('🚨 JavaScript Error:', {
            message: e.error?.message,
            filename: e.filename,
            lineno: e.lineno,
            colno: e.colno,
            error: e.error
        });
    });
    
    // Monitor console for any hidden output
    const originalConsole = {
        log: console.log,
        error: console.error,
        warn: console.warn
    };
    
    console.log = function(...args) {
        originalConsole.log.apply(console, args);
        // Log to a special div if we can
        try {
            const debugDiv = document.getElementById('debug-output');
            if (debugDiv) {
                debugDiv.innerHTML += '<div>' + args.join(' ') + '</div>';
            }
        } catch (e) {
            // Ignore errors in debug logging
        }
    };
    
    console.error = function(...args) {
        originalConsole.error.apply(console, args);
        try {
            const debugDiv = document.getElementById('debug-output');
            if (debugDiv) {
                debugDiv.innerHTML += '<div style="color:red;">ERROR: ' + args.join(' ') + '</div>';
            }
        } catch (e) {
            // Ignore errors in debug logging
        }
    };
    
    console.log('📝 Debug monitoring initialized. Try submitting the form now.');
}