/**
 * LOCAL TESTING VERSION - Contact Form Script
 * Includes mock responses for local development
 */

// Copy the entire script.js content here, but with modified submitContactForm function

/**
 * Submit contact form data to API (LOCAL TESTING VERSION)
 */
async function submitContactForm(data) {
    // Detect if we're running locally (file:// protocol or localhost without backend)
    const isLocalTesting = window.location.protocol === 'file:' || 
                          (window.location.hostname === 'localhost' && !window.location.href.includes('/backend/'));
    
    if (isLocalTesting) {
        // Mock local response for testing
        console.log('🧪 LOCAL TESTING MODE - Using mock response');
        console.log('📝 Form data that would be sent:', data);
        
        // Simulate network delay
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // Mock validation
        if (!data.name || !data.email) {
            throw new Error('Name and email are required');
        }
        
        if (!data.email.includes('@')) {
            throw new Error('Invalid email format');
        }
        
        // Mock successful response
        return {
            success: true,
            message: 'Contact inquiry submitted successfully (MOCK RESPONSE)',
            data: {
                inquiry_id: 'mock_' + Date.now(),
                email_sent: true
            }
        };
    }
    
    // Production/server code (same as original)
    const endpoints = [
        '/backend/contact.php',      // Direct PHP file
        '/backend/contact',          // API routing via .htaccess
        '/backend/index.php/contact' // Explicit index.php routing
    ];
    
    const requestData = {
        ...data,
        source: 'website',
        timestamp: new Date().toISOString()
    };
    
    let lastError = null;
    
    // Try each endpoint until one works
    for (const endpoint of endpoints) {
        try {
            console.log(`Trying endpoint: ${endpoint}`);
            
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(requestData)
            });
            
            // Check if response is JSON
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                throw new Error(`Server returned ${contentType} instead of JSON`);
            }
            
            const result = await response.json();
            
            if (!response.ok) {
                throw new Error(result.message || `HTTP error! status: ${response.status}`);
            }
            
            console.log(`✅ Success with endpoint: ${endpoint}`);
            return result;
            
        } catch (error) {
            console.warn(`❌ Failed with endpoint ${endpoint}:`, error.message);
            lastError = error;
            
            // Continue to next endpoint
            continue;
        }
    }
    
    // If all endpoints failed
    console.error('All contact endpoints failed:', lastError);
    throw lastError || new Error('All contact endpoints are unavailable');
}

// Detection function to show local testing info
function showLocalTestingInfo() {
    const isLocalTesting = window.location.protocol === 'file:' || 
                          (window.location.hostname === 'localhost' && !window.location.href.includes('/backend/'));
    
    if (isLocalTesting) {
        console.log(`
🧪 LOCAL TESTING MODE DETECTED
================================
- Contact form will use mock responses
- No actual emails will be sent
- Form validation will still work
- Check console for form data

To test with real server:
1. Upload files to cPanel
2. Visit: https://zenzone.rw/backend/docs.html
3. Or run local server: python3 -m http.server 8000
        `);
    }
}

// Run detection on page load
document.addEventListener('DOMContentLoaded', showLocalTestingInfo); 