// Loan Request Page JavaScript
// This handles all loan application functionality

document.addEventListener('DOMContentLoaded', function() {
    console.log('Loan request page loaded - initializing...');
    initLoanRequestPage();
});

function initLoanRequestPage() {
    console.log('Initializing loan request page...');
    
    // Initialize form validation
    initFormValidation();
    
    // Initialize loan calculation
    initLoanCalculation();
    
    // Initialize form interactions
    initFormInteractions();
    
    console.log('Loan request page initialization complete');
}

function initFormValidation() {
    const form = document.getElementById('loanForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            if (!validateForm()) {
                e.preventDefault();
                showErrorMessage('Please fill in all required fields correctly.');
            }
        });
    }
}

function validateForm() {
    const requiredFields = ['loan_type', 'amount', 'purpose', 'repayment_period', 'monthly_income'];
    let isValid = true;
    
    requiredFields.forEach(field => {
        const element = document.getElementById(field);
        if (element && !element.value.trim()) {
            isValid = false;
            element.classList.add('error');
        } else if (element) {
            element.classList.remove('error');
        }
    });
    
    // Validate amount
    const amount = parseFloat(document.getElementById('amount')?.value || 0);
    if (amount < 100 || amount > 100000) {
        isValid = false;
        document.getElementById('amount')?.classList.add('error');
    }
    
    // Validate repayment period
    const period = parseInt(document.getElementById('repayment_period')?.value || 0);
    if (period < 3 || period > 60) {
        isValid = false;
        document.getElementById('repayment_period')?.classList.add('error');
    }
    
    // Validate monthly income
    const income = parseFloat(document.getElementById('monthly_income')?.value || 0);
    if (income < 1000) {
        isValid = false;
        document.getElementById('monthly_income')?.classList.add('error');
    }
    
    return isValid;
}

function initLoanCalculation() {
    // Add event listeners for calculation triggers
    const amountInput = document.getElementById('amount');
    const periodInput = document.getElementById('repayment_period');
    
    if (amountInput) {
        amountInput.addEventListener('input', function() {
            if (this.value && periodInput.value) {
                calculateLoan();
            }
        });
    }
    
    if (periodInput) {
        periodInput.addEventListener('change', function() {
            if (this.value && amountInput.value) {
                calculateLoan();
            }
        });
    }
}

function initFormInteractions() {
    // Add real-time validation feedback
    const inputs = document.querySelectorAll('.loan-application-form input, .loan-application-form select, .loan-application-form textarea');
    
    inputs.forEach(input => {
        input.addEventListener('blur', function() {
            validateField(this);
        });
        
        input.addEventListener('input', function() {
            if (this.classList.contains('error')) {
                this.classList.remove('error');
            }
        });
    });
}

function validateField(field) {
    const value = field.value.trim();
    
    switch (field.name) {
        case 'amount':
            const amount = parseFloat(value);
            if (amount < 100 || amount > 100000) {
                field.classList.add('error');
                showFieldError(field, 'Amount must be between $100 and $100,000');
            } else {
                field.classList.remove('error');
                clearFieldError(field);
            }
            break;
            
        case 'repayment_period':
            const period = parseInt(value);
            if (period < 3 || period > 60) {
                field.classList.add('error');
                showFieldError(field, 'Repayment period must be between 3 and 60 months');
            } else {
                field.classList.remove('error');
                clearFieldError(field);
            }
            break;
            
        case 'monthly_income':
            const income = parseFloat(value);
            if (income < 1000) {
                field.classList.add('error');
                showFieldError(field, 'Monthly income must be at least $1,000');
            } else {
                field.classList.remove('error');
                clearFieldError(field);
            }
            break;
            
        case 'purpose':
            if (value.length < 10) {
                field.classList.add('error');
                showFieldError(field, 'Please provide a detailed purpose (at least 10 characters)');
            } else {
                field.classList.remove('error');
                clearFieldError(field);
            }
            break;
    }
}

function showFieldError(field, message) {
    // Remove existing error message
    clearFieldError(field);
    
    // Create error message element
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error';
    errorDiv.textContent = message;
    errorDiv.style.color = '#dc3545';
    errorDiv.style.fontSize = '0.8rem';
    errorDiv.style.marginTop = '5px';
    
    // Insert after the field
    field.parentNode.appendChild(errorDiv);
}

function clearFieldError(field) {
    const existingError = field.parentNode.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
}

function calculateLoan() {
    console.log('Calculating loan...');
    
    const amount = parseFloat(document.getElementById('amount')?.value || 0);
    const period = parseInt(document.getElementById('repayment_period')?.value || 0);
    
    if (amount < 100 || period < 3) {
        showErrorMessage('Please enter valid amount and repayment period to calculate loan.');
        return;
    }
    
    // Calculate loan details (12% annual interest rate)
    const interestRate = 0.12;
    const monthlyRate = interestRate / 12;
    const totalInterest = amount * interestRate * (period / 12);
    const totalAmount = amount + totalInterest;
    const monthlyPayment = totalAmount / period;
    
    // Update preview
    document.getElementById('previewAmount').textContent = formatCurrency(amount);
    document.getElementById('previewPeriod').textContent = period + ' months';
    document.getElementById('previewMonthly').textContent = formatCurrency(monthlyPayment);
    document.getElementById('previewInterest').textContent = formatCurrency(totalInterest);
    document.getElementById('previewTotal').textContent = formatCurrency(totalAmount);
    
    // Show preview
    document.getElementById('loanPreview').style.display = 'block';
    
    // Scroll to preview
    document.getElementById('loanPreview').scrollIntoView({ 
        behavior: 'smooth', 
        block: 'center' 
    });
    
    console.log('Loan calculation complete:', {
        amount,
        period,
        monthlyPayment,
        totalInterest,
        totalAmount
    });
}

// Utility functions
function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(amount);
}

function formatNumber(number) {
    return new Intl.NumberFormat('en-US').format(number);
}

// Show success message
function showSuccessMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-success';
    alertDiv.innerHTML = `
        <i class="fas fa-check-circle"></i>
        ${message}
    `;
    
    const pageHeader = document.querySelector('.page-header');
    if (pageHeader) {
        pageHeader.parentNode.insertBefore(alertDiv, pageHeader.nextSibling);
        
        // Remove after 5 seconds
        setTimeout(() => {
            alertDiv.remove();
        }, 5000);
    }
}

// Show error message
function showErrorMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-error';
    alertDiv.innerHTML = `
        <i class="fas fa-exclamation-circle"></i>
        ${message}
    `;
    
    const pageHeader = document.querySelector('.page-header');
    if (pageHeader) {
        pageHeader.parentNode.insertBefore(alertDiv, pageHeader.nextSibling);
        
        // Remove after 5 seconds
        setTimeout(() => {
            alertDiv.remove();
        }, 5000);
    }
}

// Confirm action
function confirmAction(message) {
    return confirm(message);
}

// Debug logging
console.log('Loan request JS loaded successfully');
console.log('Available functions:', Object.keys(window).filter(key => typeof window[key] === 'function' && key.startsWith('calculate')));
