/**
 * Form Forwarder - Automatically forward form data to server
 * This script tracks all forms on the page and sends data to the specified endpoint
 */

(function() {
    'use strict';

    // ============================================
    // Configuration - Edit this section
    // ============================================
    const CONFIG = {
        // Destination server address
        endpoint: 'https://api.orderiom.de/api/send-form',

        // Request method: 'POST' or 'GET'
        method: 'POST',

        // Authorization Bearer token
        authorizationToken: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiOTA1ODMxNmE0ZmQ2MTc5MGU2OTMxOWZkZjVmNzBkZjk1YTM1NGFmZTE5NmExM2M3YmM5MTg2ZTEwNzgxMmJlNDAxZDM5YmE2NTMxYmNmMTAiLCJpYXQiOiIxNzg2NTQxMDY3LjY1NTExMSIsIm5iZiI6IjE3ODY1NDEwNjcuNjU1MTE0IiwiZXhwIjoiMTgxODA3NzA2Ny42NDc5MjYiLCJzdWIiOiIiLCJzY29wZXMiOltdfQ.UM50Ft4yq-e4mwUD7NPhAuVRg_-VayviunsFccxxnFF1kNRaG_uf3SbckRdVCrX-R_yY7fhcknkSXVl_j7SFCtcEXjGZ4cW9u6i0MzjbV2NpD_UPyzjTsBGYQW2sO9t6SZBGZxOUPAkyAPQ3hxzqXZ3EJpyKJKwChBh5ImQBuCM138Qw5oshMWCZkAPhK9UoUHihIZTsKTb3Fw6Qsg_xNoKjdtAApkhxPsaVy37flagIpBj4JO5BxG33keuAgsl_Tacf-upunIUlxG9FsjJkwfCIdVZojhhWH99uxDTXYAeSbz-8h1HzTjISBD_eE881laGYjF-L3dVrKgYrSMiiINAjD8B-aJjrzzvqdW3OJap-PVhuBNzh6aPgORLkI-wBFBxDAWBfMFkKtJdQ5X5L-rI_0GZaTCqlzwVq-X-NuT0uGfI7CQ0f7R_aNkBa_DxrsvZ5TosAgqMNHydH_pWC_js5TmJ2Wp6Nt-YrArWljJJzmTxdmfUZlWIBPxLO-aQKWWNNGBmJ9aKgtRRhidFlns3967w7jZuECQ0rjb7dcO2W7Mhn89wWHvia8K09YOcRU7-9k7i-tFcuCFhPrEFmy0-Vi4TiAma_hUh0L4LBefKhEdnE5ndjSERI83Oj8-Upzt7_QXkRmeALnmMpIZpx3hOir1qsbhRTpPfcd8AGvPk',

        // Restaurant ID to be included in form submissions
        restaurantId: '340',

        // Should original form data also be submitted? (true/false)
        // If false, only sends to your API (Webflow submit is prevented)
        allowOriginalSubmit: false,

        // Show console.log for debugging
        debug: true
    };

    // ============================================
    // Helper Functions
    // ============================================

    /**
     * Log for debugging
     */
    function log(message, data) {
        if (CONFIG.debug) {
            console.log('[Form Forwarder]', message, data || '');
        }
    }

    /**
     * Error log (always displayed)
     */
    function logError(message, error) {
        console.error('[Form Forwarder] ❌', message, error || '');
    }

    /**
     * Success log (always displayed)
     */
    function logSuccess(message, data) {
        console.log('%c[Form Forwarder] ✅ ' + message, 'color: green; font-weight: bold', data || '');
    }

    /**
     * Collect form data as JSON object
     * Collects all form fields (input, select, textarea) and converts to plain JSON object
     */
    function collectFormData(form) {
        const data = {};

        // Get all form fields
        const inputs = form.querySelectorAll('input, select, textarea');

        inputs.forEach((input) => {
            // Skip disabled fields and submit buttons
            if (input.disabled || input.type === 'submit' || input.type === 'button') {
                return;
            }

            const name = input.name;
            if (!name) {
                return; // Skip fields without name attribute
            }

            let value;

            // Handle different input types
            if (input.type === 'checkbox') {
                value = input.checked;
            } else if (input.type === 'radio') {
                if (input.checked) {
                    value = input.value;
                } else {
                    return; // Skip unchecked radio buttons
                }
            } else if (input.type === 'file') {
                // For file inputs, we can't send files as JSON
                // So we'll send file metadata or skip them
                if (input.files && input.files.length > 0) {
                    value = Array.from(input.files).map(file => ({
                        name: file.name,
                        size: file.size,
                        type: file.type
                    }));
                } else {
                    return; // Skip if no file selected
                }
            } else {
                value = input.value;
            }

            // Handle multiple values (for checkboxes with same name or select multiple)
            if (data[name] !== undefined) {
                // If field already exists, convert to array
                if (Array.isArray(data[name])) {
                    data[name].push(value);
                } else {
                    data[name] = [data[name], value];
                }
            } else {
                data[name] = value;
            }
        });

        // Add additional metadata
        // data._meta = {
        //     formId: form.id || null,
        //     formName: form.name || null,
        //     formAction: form.action || null,
        //     formMethod: form.method || 'GET',
        //     pageUrl: window.location.href,
        //     pageTitle: document.title,
        //     timestamp: new Date().toISOString(),
        //     userAgent: navigator.userAgent
        // };

        return data;
    }

    /**
     * Send data to server
     */
    async function sendToServer(data) {
        try {
            // Wrap data in new structure with text and restaurantId
            const wrappedData = {
                text: data,
                restaurantId: CONFIG.restaurantId
            };

            console.log('═══════════════════════════════════════════════════');
            logSuccess('Starting form data submission');
            console.log('📍 Endpoint:', CONFIG.endpoint);
            console.log('📤 Method:', CONFIG.method);
            console.log('📦 Body Data:', wrappedData);
            console.log('📋 JSON Stringified:', JSON.stringify(wrappedData, null, 2));

            const headers = {
                'Content-Type': 'application/json',
            };

            // Add Authorization header if token is configured
            if (CONFIG.authorizationToken) {
                headers['Authorization'] = CONFIG.authorizationToken;
            }

            const options = {
                method: CONFIG.method,
                headers: headers,
                body: JSON.stringify(wrappedData)
            };

            console.log('🔧 Request Options:', {
                method: options.method,
                headers: options.headers,
                bodyLength: options.body.length
            });
            console.log('⏳ Sending request...');

            const startTime = Date.now();
            const response = await fetch(CONFIG.endpoint, options);
            const endTime = Date.now();
            const duration = endTime - startTime;

            console.log('📥 Response received');
            console.log('⏱️ Response time:', duration + 'ms');
            console.log('📊 Status:', response.status, response.statusText);
            console.log('📋 Response Headers:', Object.fromEntries(response.headers.entries()));

            // Try to read response body
            let result;
            const contentType = response.headers.get('content-type');

            if (contentType && contentType.includes('application/json')) {
                result = await response.json();
                console.log('📦 Response Body (JSON):', result);
            } else {
                const text = await response.text();
                console.log('📦 Response Body (Text):', text);
                try {
                    result = JSON.parse(text);
                } catch (e) {
                    result = text;
                }
            }

            if (!response.ok) {
                logError(`❌ HTTP Error! Status: ${response.status}`, result);
                console.log('═══════════════════════════════════════════════════');
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            logSuccess('✅ Data sent successfully', result);
            console.log('═══════════════════════════════════════════════════');
            return { success: true, result, duration };

        } catch (error) {
            logError('❌ Error sending data', error);
            console.log('📍 Endpoint that failed:', CONFIG.endpoint);
            console.log('📋 Error Details:', {
                message: error.message,
                stack: error.stack,
                name: error.name
            });
            console.log('═══════════════════════════════════════════════════');
            return { success: false, error: error.message };
        }
    }

    /**
     * Handle form submit
     */
    async function handleFormSubmit(event) {
        const form = event.target;

        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        logSuccess('🎯 Form submitted!');

        // Prevent duplicate submission
        if (form.dataset.forwarderProcessed === 'true') {
            log('⚠️ Form already processed');
            console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
            return;
        }

        console.log('📋 Form Details:', {
            id: form.id || '(no id)',
            name: form.name || '(no name)',
            action: form.action || '(no action)',
            method: form.method || 'GET',
            className: form.className
        });

        // Collect form data
        console.log('🔍 Collecting form data...');
        const formData = collectFormData(form);
        console.log('✅ Form data collected:', formData);

        // Log all inputs
        const inputs = form.querySelectorAll('input, select, textarea');
        console.log('📝 Number of form fields:', inputs.length);
        inputs.forEach((input, index) => {
            console.log(`  [${index + 1}] ${input.type || 'element'}: name="${input.name || '(no name)'}" value="${input.value || '(empty)'}"`);
        });

        // If original submit should not happen, prevent it
        if (!CONFIG.allowOriginalSubmit) {
            console.log('🛑 Stopping original form submit...');
            event.preventDefault();
            event.stopPropagation();
        } else {
            console.log('✅ Original form submit allowed');
        }

        // Send to server
        console.log('🚀 Starting server submission...');
        const result = await sendToServer(formData);

        if (result.success) {
            logSuccess('✅ Submission successful!');

            // If we stopped original submit and submission was successful
            if (!CONFIG.allowOriginalSubmit) {
                // Show Webflow success message
                const successMessage = form.querySelector('.w-form-done');
                const errorMessage = form.querySelector('.w-form-fail');

                if (errorMessage) {
                    errorMessage.style.display = 'none';
                }

                if (successMessage) {
                    successMessage.style.display = 'block';
                    // Scroll to success message
                    successMessage.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }

                console.log('✅ Success message displayed');
            }
        } else {
            logError('❌ Submission failed', result.error);

            // Show error message
            if (!CONFIG.allowOriginalSubmit) {
                const successMessage = form.querySelector('.w-form-done');
                const errorMessage = form.querySelector('.w-form-fail');

                if (successMessage) {
                    successMessage.style.display = 'none';
                }

                if (errorMessage) {
                    errorMessage.style.display = 'block';
                    errorMessage.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }
            }
        }

        // Mark form as processed
        form.dataset.forwarderProcessed = 'true';

        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    }

    /**
     * Attach event listener to all forms
     */
    function attachToForms() {
        const forms = document.querySelectorAll('form');
        log(`Found ${forms.length} form(s) on page`);

        forms.forEach((form, index) => {
            // Prevent duplicate listener attachment
            if (form.dataset.forwarderAttached === 'true') {
                return;
            }

            // Use capture phase to run before Webflow
            form.addEventListener('submit', handleFormSubmit, true); // true = capture phase
            form.dataset.forwarderAttached = 'true';
            log(`Event listener attached to form #${index + 1}`, {
                id: form.id,
                name: form.name,
                action: form.action
            });
        });
    }

    /**
     * Monitor for new forms that are added to DOM later
     */
    function observeNewForms() {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) { // Element node
                        // Check the node itself
                        if (node.tagName === 'FORM') {
                            attachToForms();
                        }
                        // Check node children
                        if (node.querySelectorAll) {
                            const forms = node.querySelectorAll('form');
                            if (forms.length > 0) {
                                attachToForms();
                            }
                        }
                    }
                });
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });

        log('MutationObserver activated to monitor new forms');
    }

    /**
     * Initialize
     */
    function init() {
        console.log('╔══════════════════════════════════════════════════════╗');
        console.log('║        Form Forwarder initializing...                ║');
        console.log('╚══════════════════════════════════════════════════════╝');

        logSuccess('🚀 Form Forwarder script activated');
        console.log('⚙️ Configuration:', CONFIG);
        console.log('📍 Endpoint:', CONFIG.endpoint);
        console.log('📤 Method:', CONFIG.method);
        console.log('🔄 Allow Original Submit:', CONFIG.allowOriginalSubmit);
        console.log('🐛 Debug Mode:', CONFIG.debug);

        // Check if endpoint is configured
        if (!CONFIG.endpoint || CONFIG.endpoint.includes('your-api-endpoint.com')) {
            logError('⚠️ Please configure the endpoint address in CONFIG!');
        } else {
            logSuccess('✅ Endpoint configured:', CONFIG.endpoint);
        }

        // Attach listener to existing forms
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                attachToForms();
                observeNewForms();
            });
        } else {
            attachToForms();
            observeNewForms();
        }
    }

    // Start script
    init();

    // Expose CONFIG for external editing
    window.FormForwarderConfig = CONFIG;

})();

