// Function to log to localStorage
function logToStorage(type, data) {
    const logs = JSON.parse(localStorage.getItem('apiLogs') || '[]');
    logs.push({ timestamp: new Date().toISOString(), type: type, data: data });
    localStorage.setItem('apiLogs', JSON.stringify(logs));
}

// Function to get URL parameters
function getUTMParameters() {  // Changed from getUrlParameters to getUTMParameters
    const urlParams = new URLSearchParams(window.location.search);
    return {
        utm_campaign: urlParams.get('utm_campaign') || 'not_set',
        utm_content: urlParams.get('utm_content') || 'not_set',
        utm_medium: urlParams.get('utm_medium') || 'not_set',
        utm_source: urlParams.get('utm_source') || 'not_set',
        subid: urlParams.get('subid') || 'not_set'
    };
}

// Debt amount mapping based on product codes
const debtMapping = {
    2466: 'over_20k',  // ≥ $250k
    2465: 'over_20k',  // $150k-$249,999
    2464: 'over_20k',  // $75k-$149,999
    2463: 'over_20k',  // $50k-$74,999
    2462: 'over_20k',  // $40k-$49,999
    2069: 'over_20k',  // $30k-$39,999
    2068: 'over_20k',  // $20k-$29,999
    2650: 'over_10k',  // $15k-$19,999
    2658: 'over_10k',  // $10k-$14,999
    2657: 'below_10k', // $5k-$9,999
    2656: 'below_10k', // $2k-$4,999
    2064: 'below_10k'  // < $2k (thin file)
};


$(document).ready(function () {
    console.log("URL Parameters:", getUTMParameters());
    
    $('#debtReliefForm').on('submit', function(e) {
        e.preventDefault();
        
        const paymentStatus = $('#paymentStatus').val();
        const selfReportedDebt = $('#selfReportedDebt').val();
        
        // Validate payment status is selected
        if (!paymentStatus) {
            alert('Please select whether you are currently making payments on your debts.');
            $('#paymentStatus').focus();
            return;
        }
        
        // Validate self-reported debt is selected
        if (!selfReportedDebt) {
            alert('Please select how much debt you currently have.');
            $('#selfReportedDebt').focus();
            return;
        }
        
        // Immediately hide form and show loading to prevent multiple clicks
        $('#debtReliefForm').hide();
        $('#loading').show();
        
        const phone = $('#phone').val().replace(/\D/g, '');
        
        const formData = {
            firstName: $('#firstName').val(),
            lastName: $('#lastName').val(),
            phone: phone,
            streetName: $('#streetName').val(),
            city: $('#city').val(),
            state: $('#state').val(),
            zip: $('#zip').val()
        };
        
        // Get TrustedForm cert URL
        const trustedFormCertUrl = document.querySelector('input[name="xxTrustedFormCertUrl"]')?.value || '';
        
        // Post to GHL immediately (in parallel)
        const ghlData = {
            ...formData,
            pay: paymentStatus,
            debt_amount: selfReportedDebt === 'under_10k' ? '-10k' : selfReportedDebt === '10k_to_20k' ? '10k' : '20k',
            xxTrustedFormCertUrl: trustedFormCertUrl
        };
        
        fetch('https://services.leadconnectorhq.com/hooks/hDuW5BJtfaLU5bTBefY8/webhook-trigger/871b6846-9e55-472e-990e-77e0de4b5b5d', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(ghlData)
        })
        .then(response => {
            console.log('GHL webhook response:', response.status);
            logToStorage('GHL_WEBHOOK_SUCCESS', { status: response.status });
        })
        .catch(error => {
            console.error('GHL webhook error:', error);
            logToStorage('GHL_WEBHOOK_ERROR', { error: error.message });
        });
        
        console.log('REQUEST DATA:', formData);
        console.log('REQUEST BODY:', JSON.stringify(formData));
        
        // Test if we can reach the API at all
        console.log('Testing API connection...');
        
        // Call the debt API through proxy
        fetch('proxy.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
        .then(response => {
            console.log('Response status:', response.status);
            console.log('Response headers:', response.headers);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('RESPONSE DATA:', data);
            
            // Log to localStorage
            logToStorage('API_RESPONSE', { data: data, formData: formData });
            
            if (!data.ok || !data.productCodes || data.productCodes.length === 0) {
                console.log('No product codes found, using self-reported debt');
                logToStorage('NO_PRODUCT_CODES', { data: data, selfReportedDebt: selfReportedDebt });
                handleRedirect('failed', selfReportedDebt);
                return;
            }
            
            let pulledDebt = 'below_10k'; // default
            
            // Check debt levels in priority order
            for (const code of data.productCodes) {
                if (debtMapping[code] === 'over_20k') {
                    pulledDebt = 'over_20k';
                    break;
                } else if (debtMapping[code] === 'over_10k' && pulledDebt === 'below_10k') {
                    pulledDebt = 'over_10k';
                }
            }
            
            console.log('Determined debt amount:', pulledDebt);
            logToStorage('DEBT_DETERMINATION', { pulledDebt: pulledDebt, productCodes: data.productCodes, selfReportedDebt: selfReportedDebt });
            
            handleRedirect(pulledDebt, selfReportedDebt);
        })
        .catch(error => {
            console.error('CREDIT PULL API ERROR:', error);
            logToStorage('CREDIT_PULL_API_ERROR', { error: error.message, formData: formData });
            // Still redirect even if credit pull fails
            handleRedirect('failed', selfReportedDebt);
        });
    });
});

function handleRedirect(pulledDebt, selfReportedDebt) {
    const params = getUTMParameters();
    const paymentStatus = $('#paymentStatus').val();
    
    // Determine final debt amount based on credit pull and self-reported debt
    let finalDebtAmount = pulledDebt;
    
    // If credit shows $0 but consumer self-reported higher debt, use self-reported
    if (pulledDebt === 'below_10k' || pulledDebt === 'failed') {
        if (selfReportedDebt === '10k_to_20k') {
            finalDebtAmount = 'over_10k';
        } else if (selfReportedDebt === 'over_20k') {
            finalDebtAmount = 'over_20k';
        }
    }
    
    // Map debt amount for URL parameter
    const debtAmountParam = finalDebtAmount === 'over_20k' ? '20k' : 
                           finalDebtAmount === 'over_10k' ? '10k' : '-10k';
    
    const queryString = Object.entries({
        ...params, 
        pd: finalDebtAmount,
        pay: paymentStatus || 'not_set',
        debt_amount: debtAmountParam
    })
        .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
        .join('&');
    window.location.href = `https://help.resolve-your-debts.com/base2.php?${queryString}`;
}