<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Loan Application - Haven Grazuri Investment Limited</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#1E3A8A',
                        accent: '#F59E0B',
                        success: '#10B981',
                        warning: '#F59E0B',
                        error: '#EF4444',
                    },
                    animation: {
                        'fade-in': 'fadeIn 0.5s ease-in-out',
                        'slide-up': 'slideUp 0.3s ease-out',
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                    }
                }
            }
        }
    </script>
    <style>
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .glass-effect {
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.9);
        }
        .step-active {
            background: linear-gradient(135deg, #3B82F6, #1E3A8A);
        }
        .input-focus:focus {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(59, 130, 246, 0.15);
        }
        .hover-lift:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Header with gradient background -->
    <div class="gradient-bg text-white py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-file-contract text-2xl"></i>
                    </div>
                    <div>
                        <h1 class="text-3xl font-bold">Add Loan to System</h1>
                        <p class="text-blue-100 mt-1">Record existing loans in the system</p>
                    </div>
                </div>
                <button onclick="goBack()" class="bg-white bg-opacity-20 hover:bg-opacity-30 px-6 py-3 rounded-lg transition-all duration-200 flex items-center space-x-2">
                    <span>←</span>
                    <span>Back</span>
                </button>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <!-- Progress Steps -->
        <div class="mb-8">
            <div class="flex items-center justify-center space-x-4 mb-6">
                <div class="flex items-center">
                    <div id="step1" class="step-active w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm">1</div>
                    <span class="ml-2 text-sm font-medium text-gray-700">Client & Product</span>
                </div>
                <div class="w-16 h-1 bg-gray-300 rounded">
                    <div id="progress1" class="h-full bg-primary rounded transition-all duration-300" style="width: 100%"></div>
                </div>
                <div class="flex items-center">
                    <div id="step2" class="w-10 h-10 rounded-full flex items-center justify-center bg-gray-300 text-gray-600 font-bold text-sm">2</div>
                    <span class="ml-2 text-sm font-medium text-gray-500">Loan Details</span>
                </div>
                <div class="w-16 h-1 bg-gray-300 rounded">
                    <div id="progress2" class="h-full bg-primary rounded transition-all duration-300" style="width: 0%"></div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Main Form -->
            <div class="lg:col-span-2">
                <div class="glass-effect rounded-2xl shadow-xl border border-white border-opacity-20">
                    <div class="p-8">
                        <form id="loanForm" class="space-y-8" method="POST" action="{% url 'loans:new_application' %}" enctype="multipart/form-data">
                            {% csrf_token %}
                            <input type="hidden" name="loan_product" id="loan_product">
                            <!-- Step 1: Client Selection & Product -->
                            <div id="step-1" class="animate-fade-in">
                                <!-- Client Search with Enhanced UI -->
                                <div class="mb-8">
                                    <label class="block text-lg font-semibold text-gray-800 mb-4">
                                        <span>👤</span>
                                        Select Client
                                    </label>
                                    <div class="relative">
                                        <input type="text" id="client_search" 
                                               class="w-full px-6 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-primary focus:ring-4 focus:ring-primary focus:ring-opacity-20 input-focus transition-all duration-200"
                                               placeholder="Search by name, email, or phone number..." 
                                               autocomplete="off">
                                        <div class="absolute right-4 top-1/2 transform -translate-y-1/2">
                                            <span>🔍</span>
                                        </div>
                                    </div>
                                    <select id="client_id" name="client_id" required
                                            class="mt-4 w-full px-6 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-primary focus:ring-4 focus:ring-primary focus:ring-opacity-20 input-focus transition-all duration-200">
                                        <option value="">Select a client</option>
                                    </select>
                                    <!-- Client Info Card -->
                                    <div id="client_info" class="hidden mt-4 p-4 bg-blue-50 border-2 border-blue-200 rounded-xl">
                                        <div class="flex items-center space-x-4">
                                            <div class="w-12 h-12 bg-primary rounded-full flex items-center justify-center">
                                                <span>👤</span>
                                            </div>
                                            <div>
                                                <h4 id="client_name" class="font-semibold text-gray-800"></h4>
                                                <p id="client_details" class="text-sm text-gray-600"></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Loan Product Selection with Enhanced UI -->
                                <div class="mb-8">
                                    <label class="block text-lg font-semibold text-gray-800 mb-4">
                                        <span>📦</span>
                                        Choose Loan Product
                                    </label>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4" id="product_cards">
                                        <!-- Product cards will be populated here -->
                                    </div>
                                </div>

                                <div class="flex justify-end">
                                    <button type="button" onclick="nextStep(1)" class="bg-primary hover:bg-secondary text-white px-8 py-3 rounded-xl font-semibold transition-all duration-200 hover-lift disabled:opacity-50 disabled:cursor-not-allowed">
                                        Next Step <span>→</span>
                                    </button>
                                </div>
                            </div>

                            <!-- Step 2: Loan Details -->
                            <div id="step-2" class="hidden">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">
                                    <!-- Amount Input with Slider -->
                                    <div>
                                        <label class="block text-lg font-semibold text-gray-800 mb-4">
                                            <span>💵</span>
                                            Loan Amount
                                        </label>
                                        <div class="space-y-4">
                                            <div class="relative">
                                                <input type="range" id="amount_slider" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer" 
                                                       min="10000" max="1000000" step="5000" value="50000">
                                                <div class="text-center mt-2">
                                                    <span class="text-3xl font-bold text-primary">KES <span id="amount_display">50,000</span></span>
                                                </div>
                                            </div>
                                            <input type="number" id="amount" name="amount" 
                                                   class="w-full px-6 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-primary focus:ring-4 focus:ring-primary focus:ring-opacity-20 input-focus transition-all duration-200"
                                                   value="50000">
                                        </div>
                                    </div>

                                    <!-- Duration Selection -->
                                    <div>
                                        <label class="block text-lg font-semibold text-gray-800 mb-4">
                                            <span>📅</span>
                                            Loan Duration
                                        </label>
                                        <div class="grid grid-cols-3 gap-2 mb-4">
                                            <button type="button" onclick="setDuration(30)" class="duration-btn px-4 py-3 border-2 border-gray-200 rounded-lg hover:border-primary hover:bg-primary hover:text-white transition-all duration-200">
                                                30 Days
                                            </button>
                                            <button type="button" onclick="setDuration(60)" class="duration-btn px-4 py-3 border-2 border-gray-200 rounded-lg hover:border-primary hover:bg-primary hover:text-white transition-all duration-200">
                                                60 Days
                                            </button>
                                            <button type="button" onclick="setDuration(90)" class="duration-btn px-4 py-3 border-2 border-gray-200 rounded-lg hover:border-primary hover:bg-primary hover:text-white transition-all duration-200">
                                                90 Days
                                            </button>
                                        </div>
                                        <input type="number" id="duration" name="duration" 
                                               class="w-full px-6 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-primary focus:ring-4 focus:ring-primary focus:ring-opacity-20 input-focus transition-all duration-200"
                                               value="30" placeholder="Custom duration in days">
                                    </div>

                                    <!-- Disbursement Date -->
                                    <div>
                                        <label class="block text-lg font-semibold text-gray-800 mb-4">
                                            <i class="fas fa-calendar-check mr-2 text-success"></i>
                                            Disbursement Date
                                        </label>
                                        <input type="date" id="disbursement_date" name="disbursement_date" 
                                               class="w-full px-6 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-primary focus:ring-4 focus:ring-primary focus:ring-opacity-20 input-focus transition-all duration-200"
                                               value="{{ today|date:'Y-m-d' }}">
                                        <p class="text-sm text-gray-600 mt-2">
                                            <span>ℹ️</span>
                                            Select the actual date when the loan was/will be disbursed
                                        </p>
                                    </div>
                                </div>

                                <!-- Repayment Method -->
                                <div class="mb-8">
                                    <label class="block text-lg font-semibold text-gray-800 mb-4">
                                        <span>💳</span>
                                        Repayment Method
                                    </label>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                        <div class="repayment-option border-2 border-gray-200 rounded-xl p-4 cursor-pointer hover:border-primary transition-all duration-200" data-method="monthly" onclick="selectRepayment('monthly')">
                                            <div class="flex items-center space-x-3">
                                                <span>📅</span>
                                                <div>
                                                    <h4 class="font-semibold">Monthly</h4>
                                                    <p class="text-sm text-gray-600">Regular monthly payments</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="repayment-option border-2 border-gray-200 rounded-xl p-4 cursor-pointer hover:border-primary transition-all duration-200" data-method="weekly" onclick="selectRepayment('weekly')">
                                            <div class="flex items-center space-x-3">
                                                <span>⏰</span>
                                                <div>
                                                    <h4 class="font-semibold">Weekly</h4>
                                                    <p class="text-sm text-gray-600">Weekly installments</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="repayment-option border-2 border-gray-200 rounded-xl p-4 cursor-pointer hover:border-primary transition-all duration-200" data-method="daily" onclick="selectRepayment('daily')">
                                            <div class="flex items-center space-x-3">
                                                <i class="fas fa-calendar-day text-primary text-xl"></i>
                                                <div>
                                                    <h4 class="font-semibold">Daily</h4>
                                                    <p class="text-sm text-gray-600">Daily repayments</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <input type="hidden" id="repayment_method" name="repayment_method">
                                </div>

                                <!-- Loan Purpose -->
                                <div class="mb-8">
                                    <label class="block text-lg font-semibold text-gray-800 mb-4">
                                        <i class="fas fa-bullseye mr-2 text-primary"></i>
                                        Loan Purpose
                                    </label>
                                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
                                        <button type="button" onclick="setPurpose('Business Expansion')" class="purpose-btn px-4 py-3 border-2 border-gray-200 rounded-lg hover:border-primary hover:bg-primary hover:text-white transition-all duration-200 text-sm">
                                            <span>📈</span><br>Business Expansion
                                        </button>
                                        <button type="button" onclick="setPurpose('Equipment Purchase')" class="purpose-btn px-4 py-3 border-2 border-gray-200 rounded-lg hover:border-primary hover:bg-primary hover:text-white transition-all duration-200 text-sm">
                                            <span>🛠️</span><br>Equipment Purchase
                                        </button>
                                        <button type="button" onclick="setPurpose('Working Capital')" class="purpose-btn px-4 py-3 border-2 border-gray-200 rounded-lg hover:border-primary hover:bg-primary hover:text-white transition-all duration-200 text-sm">
                                            <span>🪙</span><br>Working Capital
                                        </button>
                                        <button type="button" onclick="setPurpose('Inventory')" class="purpose-btn px-4 py-3 border-2 border-gray-200 rounded-lg hover:border-primary hover:bg-primary hover:text-white transition-all duration-200 text-sm">
                                            <span>📦</span><br>Inventory
                                        </button>
                                    </div>
                                    <textarea id="purpose" name="purpose" rows="4" 
                                              class="w-full px-6 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-primary focus:ring-4 focus:ring-primary focus:ring-opacity-20 input-focus transition-all duration-200"
                                              placeholder="Describe the specific purpose for this loan..."></textarea>
                                </div>

                                <div class="flex justify-between">
                                    <button type="button" onclick="prevStep(2)" class="bg-gray-500 hover:bg-gray-600 text-white px-8 py-3 rounded-xl font-semibold transition-all duration-200">
                                        <span>←</span> Previous
                                    </button>
                                    <button type="submit" class="bg-success hover:bg-green-600 text-white px-8 py-3 rounded-xl font-semibold transition-all duration-200 hover-lift">
                                        <span>✈️</span> Submit Application
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Sidebar with Loan Summary -->
            <div class="lg:col-span-1">
                <div class="sticky top-8">
                    <!-- Loan Calculator -->
                    <div class="glass-effect rounded-2xl shadow-xl border border-white border-opacity-20 p-6 mb-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-6 flex items-center">
                            <span>🧮</span>
                            Loan Summary
                        </h3>
                        
                        <div class="space-y-4">
                            <div class="flex justify-between items-center p-4 bg-blue-50 rounded-xl">
                                <span class="text-gray-600">Principal Amount</span>
                                <span class="font-bold text-lg text-primary" id="summary_amount">KES 50,000</span>
                            </div>
                            <div class="flex justify-between items-center p-4 bg-yellow-50 rounded-xl">
                                <span class="text-gray-600">Interest Rate</span>
                                <span class="font-bold text-lg text-warning" id="summary_rate">5.0% /month</span>
                            </div>
                            <div class="flex justify-between items-center p-4 bg-green-50 rounded-xl">
                                <span class="text-gray-600">Duration</span>
                                <span class="font-bold text-lg text-success" id="summary_duration">30 days</span>
                            </div>
                            <div class="flex justify-between items-center p-4 bg-purple-50 rounded-xl">
                                <span class="text-gray-600">Processing Fee</span>
                                <span class="font-bold text-lg text-purple-600" id="summary_processing">KES 500</span>
                            </div>

                            <div class="flex justify-between items-center p-4 bg-gray-100 rounded-xl">
                                <span class="text-lg font-semibold text-gray-800">Total Repayment</span>
                                <span class="font-bold text-xl text-gray-800" id="summary_total">KES 52,500</span>
                            </div>
                            <div id="summary_breakdown" class="mt-4 p-4 bg-gray-50 rounded-xl">
                                <!-- Breakdown will be populated here -->
                            </div>
                        </div>
                    </div>

                    <!-- Quick Tips -->
                    <div class="glass-effect rounded-2xl shadow-xl border border-white border-opacity-20 p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                            <span>💡</span>
                            Quick Tips
                        </h3>
                        <ul class="space-y-3 text-sm text-gray-600">
                            <li class="flex items-start space-x-2">
                                <span>✓</span>
                                <span>Ensure all information is accurate to speed up processing</span>
                            </li>
                            <li class="flex items-start space-x-2">
                                <span>✓</span>
                                <span>Upload clear, readable documents for faster approval</span>
                            </li>
                            <li class="flex items-start space-x-2">
                                <span>✓</span>
                                <span>Applications are typically reviewed within 24 hours</span>
                            </li>
                            <li class="flex items-start space-x-2">
                                <span>✓</span>
                                <span>You'll receive SMS and email updates on your application status</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Success Modal -->
    <div id="successModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-2xl p-8 max-w-md mx-4 text-center animate-slide-up">
            <div class="w-16 h-16 bg-success rounded-full flex items-center justify-center mx-auto mb-6">
                <span>✓</span>
            </div>
            <h3 class="text-2xl font-bold text-gray-800 mb-4">Loan Added Successfully!</h3>
            <p class="text-gray-600 mb-6">The loan has been successfully recorded in the system.</p>
            <button onclick="closeSuccessModal()" class="bg-success hover:bg-green-600 text-white px-8 py-3 rounded-xl font-semibold transition-all duration-200 w-full">
                View Loans List
            </button>
        </div>
    </div>

    <script>
        let currentStep = 1;
        let selectedProduct = null;
        // Get clients from Django template context (safer approach)
        let clients = {{ clients_json|safe }};
        
        // Fallback if clients_json is not available
        if (!clients || clients.length === 0) {
            clients = [
                {% if clients %}
                    {% for client in clients %}
                    {
                        id: "{{ client.id }}",
                        full_name: "{{ client.get_full_name|escapejs }}",
                        first_name: "{{ client.first_name|default:''|escapejs }}",
                        last_name: "{{ client.last_name|default:''|escapejs }}",
                        email: "{{ client.email|default:'No email'|escapejs }}",
                        phone_number: "{{ client.phone_number|default:'No phone'|escapejs }}",
                        business_name: "{{ client.business_name|default:''|escapejs }}",
                        id_number: "{{ client.id_number|default:''|escapejs }}",
                        status: "{{ client.status|default:'active'|escapejs }}"
                    }{% if not forloop.last %},{% endif %}
                    {% endfor %}
                {% endif %}
            ];
        }
        
        // Get loan products with current settings from Django context
        let loanProducts = {{ loan_products_json|safe }};

        // Initialize the application
        document.addEventListener('DOMContentLoaded', function() {
            initializeProductCards();
            setupEventListeners();
            updateLoanSummary();
        });

        function initializeProductCards() {
            const container = document.getElementById('product_cards');
            container.innerHTML = '';
            
            loanProducts.forEach(product => {
                const card = document.createElement('div');
                card.className = 'product-card border-2 border-gray-200 rounded-xl p-6 cursor-pointer hover:border-primary hover:shadow-lg transition-all duration-200';
                card.onclick = () => selectProduct(product);
                
                // Format repayment methods for display
                const repaymentMethods = product.available_repayment_methods.map(method => 
                    method.charAt(0).toUpperCase() + method.slice(1)
                ).join(', ');
                
                card.innerHTML = `
                    <div class="flex items-start justify-between mb-4">
                        <h4 class="font-bold text-lg text-gray-800">${product.name}</h4>
                        <div class="w-6 h-6 border-2 border-gray-300 rounded-full flex items-center justify-center">
                            <span>✓</span>
                        </div>
                    </div>
                    <p class="text-gray-600 mb-4">${product.description}</p>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-gray-500">Duration:</span>
                            <span class="font-semibold">${product.duration_months} month(s)</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">Interest:</span>
                            <span class="font-semibold text-primary">${product.interest_rate}% per month</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">Amount Range:</span>
                            <span class="font-semibold">KES ${parseFloat(product.min_amount).toLocaleString()} - ${parseFloat(product.max_amount).toLocaleString()}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">Repayment:</span>
                            <span class="font-semibold">${repaymentMethods}</span>
                        </div>
                    </div>
                `;
                
                container.appendChild(card);
            });
        }

        function selectProduct(product) {
            selectedProduct = product;
            document.getElementById('loan_product').value = product.id;
            
            // Update UI
            document.querySelectorAll('.product-card').forEach(card => {
                card.classList.remove('border-primary', 'bg-blue-50');
                card.classList.add('border-gray-200');
                card.querySelector('.fa-check').parentElement.classList.remove('bg-primary', 'border-primary');
                card.querySelector('.fa-check').parentElement.classList.add('border-gray-300');
                card.querySelector('.fa-check').classList.add('hidden');
            });
            
            event.target.closest('.product-card').classList.add('border-primary', 'bg-blue-50');
            const checkIcon = event.target.closest('.product-card').querySelector('.fa-check');
            checkIcon.parentElement.classList.remove('border-gray-300');
            checkIcon.parentElement.classList.add('bg-primary', 'border-primary');
            checkIcon.classList.remove('hidden');
            
            // Update amount slider constraints
            const amountSlider = document.getElementById('amount_slider');
            const amountInput = document.getElementById('amount');
            amountSlider.min = parseFloat(product.min_amount);
            amountSlider.max = parseFloat(product.max_amount);
            amountSlider.value = parseFloat(product.min_amount);
            amountInput.value = parseFloat(product.min_amount);
            amountInput.min = parseFloat(product.min_amount);
            amountInput.max = parseFloat(product.max_amount);
            
            // Update duration constraints
            const durationInput = document.getElementById('duration');
            durationInput.min = product.min_duration;
            durationInput.max = product.max_duration;
            durationInput.value = product.min_duration;
            
            // Update available repayment methods
            document.querySelectorAll('.repayment-option').forEach(option => {
                const method = option.getAttribute('data-method');
                if (product.available_repayment_methods.includes(method)) {
                    option.classList.remove('opacity-50', 'cursor-not-allowed');
                    option.onclick = () => selectRepayment(method);
                } else {
                    option.classList.add('opacity-50', 'cursor-not-allowed');
                    option.onclick = null;
                }
            });
            
            updateAmountDisplay();
            updateLoanSummary();
        }

        function setupEventListeners() {
            // Client search functionality
            const clientSearch = document.getElementById('client_search');
            const clientSelect = document.getElementById('client_id');
            let searchTimeout;
            
            // Populate all clients initially
            populateClientSelect(clients);
            
            clientSearch.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                const query = this.value.trim().toLowerCase();
                
                // Always show all clients if search is empty
                if (query.length === 0) {
                    populateClientSelect(clients);
                    hideClientInfo();
                    return;
                }
                
                searchTimeout = setTimeout(() => {
                    // Filter clients locally
                    const filteredClients = clients.filter(client => {
                        const searchFields = [
                            client.full_name,
                            client.email,
                            client.phone_number,
                            client.business_name,
                            client.id_number
                        ].filter(Boolean); // Remove null/undefined values
                        
                        return searchFields.some(field => 
                            field.toLowerCase().includes(query)
                        );
                    });
                    
                    populateClientSelect(filteredClients);
                    
                    // If there's only one result, auto-select it
                    if (filteredClients.length === 1) {
                        clientSelect.value = filteredClients[0].id;
                        showClientInfo(filteredClients[0]);
                    } else {
                        hideClientInfo();
                    }
                }, 300);
            });
            
            clientSelect.addEventListener('change', function() {
                const selectedClient = clients.find(c => c.id === this.value);
                if (selectedClient) {
                    showClientInfo(selectedClient);
                    // Update search box to match selection
                    clientSearch.value = selectedClient.full_name;
                } else {
                    hideClientInfo();
                }
            });
            
            // Amount slider and input synchronization
            const amountSlider = document.getElementById('amount_slider');
            const amountInput = document.getElementById('amount');
            
            amountSlider.addEventListener('input', function() {
                amountInput.value = this.value;
                updateAmountDisplay();
                updateLoanSummary();
            });
            
            amountInput.addEventListener('input', function() {
                amountSlider.value = this.value;
                updateAmountDisplay();
                updateLoanSummary();
            });
            
            // Duration input listener
            document.getElementById('duration').addEventListener('input', updateLoanSummary);
            
            // Form submission
            document.getElementById('loanForm').addEventListener('submit', handleFormSubmit);
            
            // File upload handlers
            // document.getElementById('business_plan').addEventListener('change', handleFileUpload);
            // document.getElementById('financial_statements').addEventListener('change', handleFileUpload);
        }

        // Function to populate client select dropdown
        function populateClientSelect(clientList) {
            const clientSelect = document.getElementById('client_id');
            clientSelect.innerHTML = '<option value="">Select a client</option>';
            
            if (clientList.length === 0) {
                const option = document.createElement('option');
                option.value = "";
                option.textContent = "No clients found";
                option.disabled = true;
                clientSelect.appendChild(option);
                return;
            }
            
            clientList.forEach(client => {
                const option = document.createElement('option');
                option.value = client.id;
                let displayText = client.full_name;
                
                // Add additional identifiers
                const identifiers = [];
                if (client.email && client.email !== 'No email') identifiers.push(client.email);
                if (client.phone_number) identifiers.push(client.phone_number);
                if (client.business_name) identifiers.push(client.business_name);
                if (client.id_number) identifiers.push(`ID: ${client.id_number}`);
                
                if (identifiers.length > 0) {
                    displayText += ` (${identifiers.join(' • ')})`;
                }
                
                // Add status indicator and disable if not active
                if (client.status && client.status !== 'active') {
                    displayText += ` [${client.status.toUpperCase()}]`;
                    option.disabled = true;
                    option.style.color = '#9CA3AF';
                    option.style.fontStyle = 'italic';
                }
                
                option.textContent = displayText;
                clientSelect.appendChild(option);
            });
        }

        function showClientInfo(client) {
            const clientInfo = document.getElementById('client_info');
            const clientName = document.getElementById('client_name');
            const clientDetails = document.getElementById('client_details');
            
            // Handle different client object structures
            const fullName = client.full_name || `${client.first_name || ''} ${client.last_name || ''}`.trim();
            const email = client.email || 'No email provided';
            const phone = client.phone_number || client.phone || 'No phone provided';
            
            clientName.textContent = fullName;
            clientDetails.textContent = `${email} • ${phone}`;
            
            // Add additional client info if available
            if (client.business_name) {
                clientDetails.textContent += ` • ${client.business_name}`;
            }
            
            clientInfo.classList.remove('hidden');
            clientInfo.classList.add('animate-fade-in');
        }

        function hideClientInfo() {
            document.getElementById('client_info').classList.add('hidden');
        }

        function updateAmountDisplay() {
            const amount = document.getElementById('amount').value;
            document.getElementById('amount_display').textContent = parseInt(amount).toLocaleString();
        }

        function setDuration(days) {
            document.getElementById('duration').value = days;
            
            // Update button states
            document.querySelectorAll('.duration-btn').forEach(btn => {
                btn.classList.remove('bg-primary', 'text-white', 'border-primary');
                btn.classList.add('border-gray-200');
            });
            
            event.target.classList.remove('border-gray-200');
            event.target.classList.add('bg-primary', 'text-white', 'border-primary');
            
            updateLoanSummary();
        }

        function selectRepayment(method) {
            document.getElementById('repayment_method').value = method;
            
            // Update UI
            document.querySelectorAll('.repayment-option').forEach(option => {
                option.classList.remove('border-primary', 'bg-blue-50');
                option.classList.add('border-gray-200');
            });
            
            event.target.closest('.repayment-option').classList.remove('border-gray-200');
            event.target.closest('.repayment-option').classList.add('border-primary', 'bg-blue-50');
        }

        function setPurpose(purpose) {
            document.getElementById('purpose').value = purpose;
            
            // Update button states
            document.querySelectorAll('.purpose-btn').forEach(btn => {
                btn.classList.remove('bg-primary', 'text-white', 'border-primary');
                btn.classList.add('border-gray-200');
            });
            
            event.target.classList.remove('border-gray-200');
            event.target.classList.add('bg-primary', 'text-white', 'border-primary');
        }

        function updateLoanSummary() {
            const amount = parseFloat(document.getElementById('amount').value) || 0;
            const duration = parseInt(document.getElementById('duration').value) || 30;
            
            if (selectedProduct && amount > 0) {
                const interestRate = selectedProduct.interest_rate;
                const processingFeeRate = selectedProduct.processing_fee;
                const durationMonths = Math.ceil(duration / 30); // Convert days to months
                
                const interestAmount = (amount * interestRate / 100) * durationMonths;
                const processingFee = amount * processingFeeRate / 100;
                const totalRepayment = amount + interestAmount + processingFee;
                
                // Update summary display
                document.getElementById('summary_amount').textContent = `KES ${amount.toLocaleString()}`;
                document.getElementById('summary_rate').textContent = `${interestRate}% /month`;
                document.getElementById('summary_duration').textContent = `${duration} days (${durationMonths} month${durationMonths > 1 ? 's' : ''})`;
                document.getElementById('summary_processing').textContent = `KES ${processingFee.toLocaleString()} (${processingFeeRate}%)`;
                document.getElementById('summary_total').textContent = `KES ${totalRepayment.toLocaleString()}`;
                
                // Add breakdown of charges
                const breakdownHtml = `
                    <div class="mt-4 p-4 bg-gray-50 rounded-xl">
                        <h4 class="font-semibold mb-2">Payment Breakdown:</h4>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span>Principal Amount:</span>
                                <span>KES ${amount.toLocaleString()}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Interest (${interestRate}% × ${durationMonths} months):</span>
                                <span>KES ${interestAmount.toLocaleString()}</span>
                            </div>
                            <div class="flex justify-between">
                                <span>Processing Fee (${processingFeeRate}%):</span>
                                <span>KES ${processingFee.toLocaleString()}</span>
                            </div>
                        </div>
                    </div>
                `;
                document.getElementById('summary_breakdown').innerHTML = breakdownHtml;
            } else {
                // Reset summary if no product selected
                document.getElementById('summary_amount').textContent = 'KES 0';
                document.getElementById('summary_rate').textContent = '0% /month';
                document.getElementById('summary_duration').textContent = '0 days';
                document.getElementById('summary_processing').textContent = 'KES 0';
                document.getElementById('summary_total').textContent = 'KES 0';
                document.getElementById('summary_breakdown').innerHTML = '';
            }
        }

        function nextStep(step) {
            if (validateStep(step)) {
                currentStep = step + 1;
                updateStepDisplay();
            }
        }

        function prevStep(step) {
            currentStep = step - 1;
            updateStepDisplay();
        }

        function validateStep(step) {
            switch(step) {
                case 1:
                    const clientSelected = document.getElementById('client_id').value;
                    if (!clientSelected || clientSelected === '') {
                        showError('Please select a client from the dropdown');
                        return false;
                    }
                    
                    // Check if selected client exists and is valid
                    const selectedClient = clients.find(c => c.id === clientSelected);
                    if (!selectedClient) {
                        showError('Selected client not found. Please refresh the page and try again.');
                        return false;
                    }
                    
                    // Check client status
                    if (selectedClient.status && selectedClient.status !== 'active') {
                        if (selectedClient.status === 'blacklisted') {
                            showError(`Cannot create loan application for blacklisted client: ${selectedClient.full_name}`);
                            return false;
                        } else if (selectedClient.status === 'suspended') {
                            showError(`Cannot create loan application for suspended client: ${selectedClient.full_name}`);
                            return false;
                        } else if (selectedClient.status === 'inactive') {
                            showError(`Cannot create loan application for inactive client: ${selectedClient.full_name}. Please contact an administrator.`);
                            return false;
                        }
                    }
                    
                    if (!selectedProduct) {
                        showError('Please select a loan product');
                        return false;
                    }
                    return true;
                    
                default:
                    return true;
            }
        }

        function updateStepDisplay() {
            // Hide all steps
            for (let i = 1; i <= 2; i++) {
                document.getElementById(`step-${i}`).classList.add('hidden');
                const stepIndicator = document.getElementById(`step${i}`);
                stepIndicator.classList.remove('step-active');
                stepIndicator.classList.add('bg-gray-300', 'text-gray-600');
                stepIndicator.nextElementSibling.classList.remove('text-gray-700');
                stepIndicator.nextElementSibling.classList.add('text-gray-500');
            }
            
            // Show current step
            document.getElementById(`step-${currentStep}`).classList.remove('hidden');
            document.getElementById(`step-${currentStep}`).classList.add('animate-fade-in');
            
            // Update step indicators
            for (let i = 1; i <= currentStep; i++) {
                const stepIndicator = document.getElementById(`step${i}`);
                stepIndicator.classList.remove('bg-gray-300', 'text-gray-600');
                stepIndicator.classList.add('step-active');
                stepIndicator.nextElementSibling.classList.remove('text-gray-500');
                stepIndicator.nextElementSibling.classList.add('text-gray-700');
                
                if (i < currentStep) {
                    document.getElementById(`progress${i}`).style.width = '100%';
                }
            }
        }

        function handleFormSubmit(event) {
            event.preventDefault();
            
            // Show loading state
            const submitBtn = event.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<span>⟳</span> Processing...';
            submitBtn.disabled = true;
            
            // Validate all required fields before submission
            const requiredFields = {
                'client_id': 'Please select a client from the dropdown',
                'loan_product': 'Please select a loan product',
                'amount': 'Please enter a loan amount',
                'duration': 'Please enter a loan duration',
                'repayment_method': 'Please select a repayment method',
                'purpose': 'Please enter the loan purpose'
            };

            for (const [fieldName, errorMessage] of Object.entries(requiredFields)) {
                const field = document.querySelector(`[name="${fieldName}"]`);
                if (!field || !field.value || field.value.trim() === '') {
                    showError(errorMessage);
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                    return;
                }
            }
            
            // Additional validation for client selection
            const clientId = document.querySelector('[name="client_id"]').value;
            const selectedClient = clients.find(c => c.id === clientId);
            if (!selectedClient) {
                showError('Selected client is invalid. Please select a client from the dropdown.');
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
                return;
            }

            // Get CSRF token
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
            
            // Create form data
            const formData = new FormData(event.target);
            
            // Submit the form using fetch
            fetch(event.target.action, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': csrfToken
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // Show success message
                    document.getElementById('successModal').classList.remove('hidden');
                    document.getElementById('successModal').classList.add('flex');
                    
                    // Redirect to loans page after 2 seconds
                    setTimeout(() => {
                        window.location.href = '{% url "loans:loans" %}';
                    }, 2000);
                } else {
                    // Show error message
                    showError(data.message);
                }
            })
            .catch(error => {
                console.error('Form submission error:', error);
                showError(error.message || 'An error occurred during form submission');
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        }

        function showError(message) {
            console.error('Error:', message); // Add logging
            // Create and show error toast
            const toast = document.createElement('div');
            toast.className = 'fixed top-4 right-4 bg-error text-white px-6 py-4 rounded-lg shadow-lg z-50 animate-slide-up max-w-md';
            toast.innerHTML = `
                <div class="flex items-center space-x-3">
                    <span>⚠️</span>
                    <div>
                        <h4 class="font-semibold">Error</h4>
                        <p class="text-sm">${message}</p>
                    </div>
                </div>
            `;
            document.body.appendChild(toast);
            
            // Remove after 5 seconds
            setTimeout(() => {
                toast.classList.add('opacity-0');
                setTimeout(() => toast.remove(), 300);
            }, 5000);
        }

        function showSuccessModal() {
            document.getElementById('successModal').classList.remove('hidden');
            document.getElementById('successModal').classList.add('flex');
        }

        function closeSuccessModal() {
            document.getElementById('successModal').classList.add('hidden');
            document.getElementById('successModal').classList.remove('flex');
            // Redirect to loans page
            window.location.href = '{% url "loans:loans" %}';
        }

        function goBack() {
            if (confirm('Are you sure you want to leave? Your progress will be lost.')) {
                window.history.back();
            }
        }

        // Initialize amount display
        updateAmountDisplay();
    </script>
</body>
</html>