{% extends 'base.html' %}

{% block title %}Client Management - HAVEN GRAZURI ADVANCE{% endblock %}

{% block content %}
<style>
/* Client table fixes - ensure images display properly */
table img, 
.h-10.w-10 img,
td img {
    width: 40px !important;
    height: 40px !important;
    border-radius: 50% !important;
    object-fit: cover !important;
    border: 2px solid #e5e7eb !important;
    display: block !important;
    margin: 0 auto !important;
}

/* Client name container - proper flex layout */
.flex.items-center {
    align-items: center !important;
    display: flex !important;
    gap: 0.75rem !important;
}

/* Avatar container - fixed dimensions */
.h-10.w-10.flex-shrink-0 {
    width: 40px !important;
    height: 40px !important;
    flex-shrink: 0 !important;
    overflow: hidden !important;
    border-radius: 50% !important;
}

/* Avatar fallback (initials) */
.h-10.w-10.rounded-full {
    width: 40px !important;
    height: 40px !important;
    border-radius: 50% !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    font-size: 14px !important;
    font-weight: 600 !important;
}

/* Client info text container */
.ml-4 {
    margin-left: 0.75rem !important;
    flex: 1 !important;
    min-width: 0 !important;
    overflow: hidden !important;
}

/* Client name text - prevent overflow */
.text-sm.font-medium.text-gray-900 {
    white-space: nowrap !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    max-width: 160px !important;
    display: block !important;
}

/* Table cell spacing */
td {
    padding: 8px 12px !important;
    vertical-align: middle !important;
}

/* Ensure table layout doesn't break */
table {
    table-layout: auto !important;
    width: 100% !important;
}

/* Fix any image loading issues */
img[src=""], img:not([src]) {
    display: none !important;
}
</style>
                    <!-- Page header -->
                    <div class="sm:flex sm:items-center">
                        <div class="sm:flex-auto">
                            <h1 class="text-2xl font-semibold text-gray-900">Client Management</h1>
                            <p class="mt-2 text-sm text-gray-700">
                                Manage client information, loan history, and documentation.
                            </p>
                        </div>
                        <div class="mt-4 sm:ml-16 sm:mt-0 sm:flex-none flex gap-2">
                            {% if user.role == 'admin' or user.is_superuser %}
                            <a href="{% url 'users:pending_clients' %}" class="inline-flex items-center rounded-md bg-yellow-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-yellow-700">
                                <span>⏰</span>Pending Approvals
                            </a>
                            <a href="{% url 'users:rejected_clients' %}" class="inline-flex items-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-700">
                                <span>✕</span>Rejected Clients
                            </a>
                            {% endif %}
                            {% load permission_tags %}
                            {% has_permission user 'clients' 'create' as can_create_client %}
                            {% if can_create_client %}
                            <a href="{% url 'users:client_create' %}" class="inline-flex items-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-secondary">
                                <span>+</span>Add New Client
                            </a>
                            {% endif %}
                        </div>
                    </div>

                    <!-- Error Message -->
                    {% if error_message %}
                    <div class="mt-8 bg-red-50 border border-red-200 rounded-md p-4">
                        <div class="flex">
                            <div class="flex-shrink-0">
                                <span>⚠️</span>
                            </div>
                            <div class="ml-3">
                                <h3 class="text-sm font-medium text-red-800">Error</h3>
                                <div class="mt-2 text-sm text-red-700">
                                    <p>{{ error_message }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endif %}

                    <!-- Client Statistics Dashboard - Prominent -->
                    <div class="mt-8 grid grid-cols-1 md:grid-cols-5 gap-4">
                        <!-- Total Clients - Large Card -->
                        <div class="bg-gradient-to-br from-blue-600 to-indigo-700 rounded-lg shadow-lg p-6 text-white">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-sm font-medium text-white opacity-90">Total Clients</p>
                                    <p class="text-4xl font-bold mt-2 text-white">{{ total_clients|default:"0" }}</p>
                                    <p class="text-xs text-white opacity-75 mt-1">
                                        <span>👥</span> All active clients
                                    </p>
                                </div>
                                <div class="bg-white bg-opacity-20 rounded-full p-3">
                                    <span>👥</span>
                                </div>
                            </div>
                        </div>

                        <!-- Last 30 Days -->
                        <div class="bg-green-50 border-2 border-green-200 rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-xs font-medium text-green-600 uppercase tracking-wide">Last 30 Days</p>
                                    <p class="text-3xl font-bold text-green-800 mt-2">{{ clients_30_days }}</p>
                                    {% if clients_30_days > 0 %}
                                    <p class="text-xs text-green-600 mt-1">
                                        <span>↑</span> New registrations
                                    </p>
                                    {% endif %}
                                </div>
                                <div class="bg-green-100 rounded-full p-3">
                                    <i class="fas fa-calendar-day text-green-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Last 60 Days -->
                        <div class="bg-blue-50 border-2 border-blue-200 rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-xs font-medium text-blue-600 uppercase tracking-wide">Last 60 Days</p>
                                    <p class="text-3xl font-bold text-blue-800 mt-2">{{ clients_60_days }}</p>
                                    {% if growth_60_days > 0 %}
                                    <p class="text-xs text-blue-600 mt-1">
                                        <span>↑</span> +{{ growth_60_days }} this period
                                    </p>
                                    {% endif %}
                                </div>
                                <div class="bg-blue-100 rounded-full p-3">
                                    <i class="fas fa-calendar-week text-blue-600 text-xl"></i>
                                </div>
                            </div>
                        </div>

                        <!-- Last 90 Days -->
                        <div class="bg-purple-50 border-2 border-purple-200 rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-xs font-medium text-purple-600 uppercase tracking-wide">Last 90 Days</p>
                                    <p class="text-3xl font-bold text-purple-800 mt-2">{{ clients_90_days }}</p>
                                    {% if growth_90_days > 0 %}
                                    <p class="text-xs text-purple-600 mt-1">
                                        <span>↑</span> +{{ growth_90_days }} this period
                                    </p>
                                    {% endif %}
                                </div>
                                <div class="bg-purple-100 rounded-full p-3">
                                    <span>📅</span>
                                </div>
                            </div>
                        </div>

                        <!-- Growth Rate -->
                        <div class="bg-orange-50 border-2 border-orange-200 rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-xs font-medium text-orange-600 uppercase tracking-wide">Growth Rate</p>
                                    {% if growth_rate_display == 'percentage' and growth_rate_percentage != None %}
                                        {% if growth_rate_percentage > 0 %}
                                        <p class="text-3xl font-bold text-orange-800 mt-2">
                                            +{{ growth_rate_percentage }}%
                                        </p>
                                        <p class="text-xs text-orange-600 mt-1">
                                            <span>↑</span> {{ growth_rate_label }}
                                        </p>
                                        {% elif growth_rate_percentage == 0 %}
                                        <p class="text-2xl font-bold text-orange-800 mt-2">0%</p>
                                        <p class="text-xs text-orange-600 mt-1">
                                            <span>−</span> No change
                                        </p>
                                        {% else %}
                                        <p class="text-2xl font-bold text-red-600 mt-2">
                                            {{ growth_rate_percentage }}%
                                        </p>
                                        <p class="text-xs text-red-600 mt-1">
                                            <span>↓</span> {{ growth_rate_label }}
                                        </p>
                                        {% endif %}
                                    {% elif growth_rate_display == 'recent_period' %}
                                    <p class="text-3xl font-bold text-orange-800 mt-2">
                                        {{ growth_rate_percentage }}
                                    </p>
                                    <p class="text-xs text-orange-600 mt-1">
                                        <span>📅</span> {{ growth_rate_label }}
                                    </p>
                                    {% elif growth_rate_display == 'no_data' %}
                                    <p class="text-2xl font-bold text-gray-400 mt-2">0</p>
                                    <p class="text-xs text-gray-500 mt-1">
                                        <span>ℹ️</span> {{ growth_rate_label }}
                                    </p>
                                    {% else %}
                                    <p class="text-2xl font-bold text-gray-400 mt-2">--</p>
                                    <p class="text-xs text-gray-500 mt-1">
                                        <span>ℹ️</span> {{ growth_rate_label }}
                                    </p>
                                    {% endif %}
                                </div>
                                <div class="bg-orange-100 rounded-full p-3">
                                    <span>📈</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Compact Filter Bar - Sticky -->
                    <div class="sticky top-0 z-10 bg-white border-b border-gray-200 shadow-sm mt-8 mb-4">
                        <form method="get" id="filterForm" class="py-3">
                            <!-- Main Filter Row - Compact -->
                            <div class="flex items-center gap-3 flex-wrap">
                                <!-- Search - Compact -->
                                <div class="flex-1 min-w-[200px]">
                                    <div class="relative">
                                        <input type="text" name="search" id="search" value="{{ request.GET.search|default:'' }}" 
                                               class="block w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring-secondary sm:text-sm pl-9 pr-3 py-2"
                                               placeholder="Search clients...">
                                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <span>🔍</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Quick Date Presets -->
                                <div class="flex gap-2">
                                    <button type="button" onclick="setDatePreset('today')" class="px-3 py-2 text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                                        Today
                                    </button>
                                    <button type="button" onclick="setDatePreset('week')" class="px-3 py-2 text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                                        This Week
                                    </button>
                                    <button type="button" onclick="setDatePreset('month')" class="px-3 py-2 text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                                        This Month
                                    </button>
                                </div>

                                <!-- Sort Dropdown - Compact with More Options -->
                                <div class="flex items-center gap-2">
                                    <select name="sort_by" id="sort_by" onchange="document.getElementById('filterForm').submit()" 
                                            class="rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring-secondary sm:text-sm py-2 text-xs min-w-[140px]">
                                        <optgroup label="Basic">
                                            <option value="first_name" {% if sort_by == 'first_name' %}selected{% endif %}>Name (First)</option>
                                            <option value="last_name" {% if sort_by == 'last_name' %}selected{% endif %}>Name (Last)</option>
                                            <option value="business_name" {% if sort_by == 'business_name' %}selected{% endif %}>Business Name</option>
                                        </optgroup>
                                        <optgroup label="Date">
                                            <option value="date_joined" {% if sort_by == 'date_joined' %}selected{% endif %}>Registration Date</option>
                                            <option value="created_at" {% if sort_by == 'created_at' %}selected{% endif %}>Created Date</option>
                                        </optgroup>
                                        <optgroup label="Financial">
                                            <option value="total_borrowed" {% if sort_by == 'total_borrowed' %}selected{% endif %}>Total Borrowed</option>
                                            <option value="total_repaid" {% if sort_by == 'total_repaid' %}selected{% endif %}>Total Repaid</option>
                                            <option value="monthly_income" {% if sort_by == 'monthly_income' %}selected{% endif %}>Monthly Income</option>
                                        </optgroup>
                                        <optgroup label="Loans">
                                            <option value="active_loans" {% if sort_by == 'active_loans' %}selected{% endif %}>Active Loans</option>
                                        </optgroup>
                                        <optgroup label="Status">
                                            <option value="status" {% if sort_by == 'status' %}selected{% endif %}>Status</option>
                                        </optgroup>
                                    </select>
                                    <button type="button" onclick="toggleSortOrder()" class="px-2 py-2 border border-gray-300 rounded-md hover:bg-gray-50 text-gray-700" title="Toggle sort order">
                                        <i class="fas {% if sort_order == 'asc' %}fa-sort-up{% else %}fa-sort-down{% endif %} text-xs"></i>
                                    </button>
                                </div>

                                <!-- Advanced Filters Toggle -->
                                <button type="button" onclick="toggleAdvancedFilters()" class="px-3 py-2 text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 flex items-center gap-1">
                                    <span>🎚️</span>
                                    <span>Filters</span>
                                    {% if request.GET.status or request.GET.business_type or request.GET.date_from or request.GET.date_to %}
                                    <span class="ml-1 px-1.5 py-0.5 bg-primary text-white text-xs rounded-full">{{ request.GET|length }}</span>
                                    {% endif %}
                                </button>

                                <!-- Clear Button -->
                                {% if request.GET.search or request.GET.status or request.GET.business_type or request.GET.date_from or request.GET.date_to %}
                                <a href="{% url 'users:client_list' %}" class="px-3 py-2 text-xs font-medium text-red-600 bg-white border border-red-300 rounded-md hover:bg-red-50">
                                    <span>✕</span>Clear
                                </a>
                                {% endif %}
                            </div>

                            <!-- Advanced Filters - Collapsible -->
                            <div id="advancedFilters" class="hidden mt-3 pt-3 border-t border-gray-200">
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                    <!-- Status -->
                                <div>
                                        <label class="block text-xs font-medium text-gray-700 mb-1">Status</label>
                                        <select name="status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring-secondary text-sm py-1.5">
                                            <option value="">All</option>
                                        <option value="active" {% if request.GET.status == 'active' %}selected{% endif %}>Active</option>
                                        <option value="dormant" {% if request.GET.status == 'dormant' %}selected{% endif %}>Dormant</option>
                                        <option value="blacklisted" {% if request.GET.status == 'blacklisted' %}selected{% endif %}>Blacklisted</option>
                                        <option value="suspended" {% if request.GET.status == 'suspended' %}selected{% endif %}>Suspended</option>
                                    </select>
                                </div>

                                    <!-- Business Type -->
                                <div>
                                        <label class="block text-xs font-medium text-gray-700 mb-1">Business</label>
                                        <select name="business_type" class="w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring-secondary text-sm py-1.5">
                                        <option value="">All Types</option>
                                        <option value="agriculture" {% if request.GET.business_type == 'agriculture' %}selected{% endif %}>Agriculture</option>
                                        <option value="retail" {% if request.GET.business_type == 'retail' %}selected{% endif %}>Retail</option>
                                        <option value="transport" {% if request.GET.business_type == 'transport' %}selected{% endif %}>Transport</option>
                                        <option value="technology" {% if request.GET.business_type == 'technology' %}selected{% endif %}>Technology</option>
                                        <option value="services" {% if request.GET.business_type == 'services' %}selected{% endif %}>Services</option>
                                        <option value="manufacturing" {% if request.GET.business_type == 'manufacturing' %}selected{% endif %}>Manufacturing</option>
                                        <option value="construction" {% if request.GET.business_type == 'construction' %}selected{% endif %}>Construction</option>
                                        <option value="healthcare" {% if request.GET.business_type == 'healthcare' %}selected{% endif %}>Healthcare</option>
                                        <option value="education" {% if request.GET.business_type == 'education' %}selected{% endif %}>Education</option>
                                        <option value="other" {% if request.GET.business_type == 'other' %}selected{% endif %}>Other</option>
                                    </select>
                                </div>

                                    <!-- Date From -->
                                    <div>
                                        <label class="block text-xs font-medium text-gray-700 mb-1">From Date</label>
                                        <input type="date" name="date_from" value="{{ request.GET.date_from|default:'' }}"
                                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring-secondary text-sm py-1.5">
                                </div>

                                    <!-- Date To -->
                                    <div>
                                        <label class="block text-xs font-medium text-gray-700 mb-1">To Date</label>
                                        <input type="date" name="date_to" value="{{ request.GET.date_to|default:'' }}"
                                               class="w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring-secondary text-sm py-1.5">
                                    </div>
                            </div>
                        </div>

                            <!-- Hidden sort_order -->
                            <input type="hidden" name="sort_order" id="sort_order" value="{{ sort_order }}">
                        </form>

                        <!-- Active Filter Chips -->
                        {% if request.GET.search or request.GET.status or request.GET.business_type or request.GET.date_from or request.GET.date_to %}
                        <div class="flex flex-wrap gap-2 px-1 pb-2">
                            {% if request.GET.search %}
                            <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-blue-100 text-blue-800">
                                Search: "{{ request.GET.search }}"
                                <button onclick="removeFilter('search')" class="ml-1.5 inline-flex items-center text-blue-600 hover:text-blue-800">
                                    <span>✕</span>
                                </button>
                                    </span>
                            {% endif %}
                            {% if request.GET.status %}
                            <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-green-100 text-green-800">
                                Status: {{ request.GET.status|title }}
                                <button onclick="removeFilter('status')" class="ml-1.5 inline-flex items-center text-green-600 hover:text-green-800">
                                    <span>✕</span>
                                </button>
                            </span>
                            {% endif %}
                            {% if request.GET.business_type %}
                            <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-purple-100 text-purple-800">
                                Business: {{ request.GET.business_type|title }}
                                <button onclick="removeFilter('business_type')" class="ml-1.5 inline-flex items-center text-purple-600 hover:text-purple-800">
                                    <span>✕</span>
                                </button>
                            </span>
                            {% endif %}
                            {% if request.GET.date_from %}
                            <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-yellow-100 text-yellow-800">
                                From: {{ request.GET.date_from }}
                                <button onclick="removeFilter('date_from')" class="ml-1.5 inline-flex items-center text-yellow-600 hover:text-yellow-800">
                                    <span>✕</span>
                                </button>
                            </span>
                            {% endif %}
                            {% if request.GET.date_to %}
                            <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-yellow-100 text-yellow-800">
                                To: {{ request.GET.date_to }}
                                <button onclick="removeFilter('date_to')" class="ml-1.5 inline-flex items-center text-yellow-600 hover:text-yellow-800">
                                    <span>✕</span>
                                </button>
                            </span>
                            {% endif %}
                        </div>
                        {% endif %}

                    </div>

                    <!-- JavaScript for filter interactions -->
                    <script>
                        function toggleAdvancedFilters() {
                            const filters = document.getElementById('advancedFilters');
                            filters.classList.toggle('hidden');
                        }

                        function toggleSortOrder() {
                            const orderInput = document.getElementById('sort_order');
                            orderInput.value = orderInput.value === 'asc' ? 'desc' : 'asc';
                            document.getElementById('filterForm').submit();
                        }

                        function updateSorting() {
                            document.getElementById('filterForm').submit();
                        }

                        function setDatePreset(preset) {
                            const today = new Date();
                            const dateFrom = document.querySelector('input[name="date_from"]');
                            const dateTo = document.querySelector('input[name="date_to"]');
                            
                            if (preset === 'today') {
                                dateFrom.value = today.toISOString().split('T')[0];
                                dateTo.value = today.toISOString().split('T')[0];
                            } else if (preset === 'week') {
                                const weekAgo = new Date(today);
                                weekAgo.setDate(today.getDate() - 7);
                                dateFrom.value = weekAgo.toISOString().split('T')[0];
                                dateTo.value = today.toISOString().split('T')[0];
                            } else if (preset === 'month') {
                                const monthAgo = new Date(today);
                                monthAgo.setMonth(today.getMonth() - 1);
                                dateFrom.value = monthAgo.toISOString().split('T')[0];
                                dateTo.value = today.toISOString().split('T')[0];
                            }
                            
                            document.getElementById('filterForm').submit();
                        }

                        function removeFilter(filterName) {
                            const form = document.getElementById('filterForm');
                            const input = form.querySelector(`[name="${filterName}"]`);
                            if (input) {
                                input.value = '';
                                form.submit();
                            }
                        }

                        // Auto-submit search on Enter (with debounce)
                        let searchTimeout;
                        document.getElementById('search').addEventListener('input', function(e) {
                            clearTimeout(searchTimeout);
                            searchTimeout = setTimeout(() => {
                                if (e.target.value.length === 0 || e.target.value.length >= 3) {
                                    document.getElementById('filterForm').submit();
                                }
                            }, 500);
                        });

                        // Show advanced filters if any are set
                        {% if request.GET.status or request.GET.business_type or request.GET.date_from or request.GET.date_to %}
                        document.addEventListener('DOMContentLoaded', function() {
                            document.getElementById('advancedFilters').classList.remove('hidden');
                        });
                        {% endif %}

                        // Auto-submit when advanced filters change
                        document.addEventListener('DOMContentLoaded', function() {
                            const advancedFilters = document.querySelectorAll('#advancedFilters select, #advancedFilters input[type="date"]');
                            advancedFilters.forEach(filter => {
                                filter.addEventListener('change', function() {
                                    document.getElementById('filterForm').submit();
                                });
                            });
                        });
                    </script>

                    <!-- Client List -->
                    <div class="mt-8 flow-root">
                        <div class="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
                            <div class="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
                                <div class="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                                                                        <div id="clients-table-container">
                                        {% include 'users/client_list_table.html' %}
                                    </div>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    {% if clients.has_other_pages %}
                    <div class="mt-8 flex items-center justify-between">
                        <div class="flex flex-1 justify-between sm:hidden">
                            {% if clients.has_previous %}
                            <a href="?page={{ clients.previous_page_number }}{% if search %}&search={{ search }}{% endif %}{% if status_filter != 'all' %}&status={{ status_filter }}{% endif %}{% if business_type_filter != 'all' %}&business_type={{ business_type_filter }}{% endif %}{% if sort_by %}&sort_by={{ sort_by }}{% endif %}{% if sort_order %}&sort_order={{ sort_order }}{% endif %}" class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">Previous</a>
                            {% endif %}
                            {% if clients.has_next %}
                            <a href="?page={{ clients.next_page_number }}{% if search %}&search={{ search }}{% endif %}{% if status_filter != 'all' %}&status={{ status_filter }}{% endif %}{% if business_type_filter != 'all' %}&business_type={{ business_type_filter }}{% endif %}{% if sort_by %}&sort_by={{ sort_by }}{% endif %}{% if sort_order %}&sort_order={{ sort_order }}{% endif %}" class="relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">Next</a>
                            {% endif %}
                        </div>
                        <div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
                            <div>
                                <p class="text-sm text-gray-700">
                                    Showing
                                    <span class="font-medium">{{ clients.start_index }}</span>
                                    to
                                    <span class="font-medium">{{ clients.end_index }}</span>
                                    of
                                    <span class="font-medium">{{ total_clients }}</span>
                                    results
                                </p>
                            </div>
                            <div>
                                <nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
                                    {% if clients.has_previous %}
                                    <a href="?page={{ clients.previous_page_number }}{% if search %}&search={{ search }}{% endif %}{% if status_filter != 'all' %}&status={{ status_filter }}{% endif %}{% if business_type_filter != 'all' %}&business_type={{ business_type_filter }}{% endif %}{% if sort_by %}&sort_by={{ sort_by }}{% endif %}{% if sort_order %}&sort_order={{ sort_order }}{% endif %}" class="relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                                        <span class="sr-only">Previous</span>
                                        <span>‹</span>
                                    </a>
                                    {% endif %}
                                    
                                    {% for num in clients.paginator.page_range %}
                                        {% if clients.number == num %}
                                        <span class="relative z-10 inline-flex items-center bg-primary px-4 py-2 text-sm font-semibold text-white focus:z-20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">{{ num }}</span>
                                        {% elif num > clients.number|add:'-3' and num < clients.number|add:'3' %}
                                        <a href="?page={{ num }}{% if search %}&search={{ search }}{% endif %}{% if status_filter != 'all' %}&status={{ status_filter }}{% endif %}{% if business_type_filter != 'all' %}&business_type={{ business_type_filter }}{% endif %}{% if sort_by %}&sort_by={{ sort_by }}{% endif %}{% if sort_order %}&sort_order={{ sort_order }}{% endif %}" class="relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">{{ num }}</a>
                                        {% endif %}
                                    {% endfor %}
                                    
                                    {% if clients.has_next %}
                                    <a href="?page={{ clients.next_page_number }}{% if search %}&search={{ search }}{% endif %}{% if status_filter != 'all' %}&status={{ status_filter }}{% endif %}{% if business_type_filter != 'all' %}&business_type={{ business_type_filter }}{% endif %}{% if sort_by %}&sort_by={{ sort_by }}{% endif %}{% if sort_order %}&sort_order={{ sort_order }}{% endif %}" class="relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                                        <span class="sr-only">Next</span>
                                        <span>›</span>
                                    </a>
                                    {% endif %}
                                </nav>
                            </div>
                        </div>
                    </div>
                    {% endif %}

    <!-- Client Modal -->
    <div id="clientModal" class="fixed inset-0 z-50 overflow-y-auto hidden" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <!-- Background overlay -->
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="closeClientModal()"></div>

            <!-- Modal panel -->
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full">

                <!-- Modal content -->
                <div id="modalContent" class="hidden">
                    <!-- Header -->
                    <div class="bg-primary px-6 py-4">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <div class="h-12 w-12 rounded-full bg-white flex items-center justify-center mr-4 overflow-hidden">
                                    <img id="clientSelfie" src="" alt="Client Photo" class="w-full h-full object-cover" style="display: none;">
                                    <span class="text-lg font-bold text-primary" id="clientInitials"></span>
                                </div>
                                <div>
                                    <h3 class="text-lg font-semibold text-white" id="clientName"></h3>
                                    <p class="text-sm text-gray-200" id="clientId"></p>
                                </div>
                            </div>
                            <button onclick="closeClientModal()" class="text-white hover:text-gray-300 transition-colors duration-150">
                                <span>✕</span>
                            </button>
                        </div>
                    </div>

                    <!-- Tabs -->
                    <div class="border-b border-gray-200">
                        <nav class="-mb-px flex space-x-8 px-6">
                            <button onclick="showModalTab('info')" id="modal-tab-info" 
                                    class="border-b-2 border-primary text-primary whitespace-nowrap py-4 px-1 text-sm font-medium">
                                <span>👤</span>Basic Info
                            </button>
                            <button onclick="showModalTab('loan-summary')" id="modal-tab-loan-summary" 
                                    class="border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 text-sm font-medium">
                                <span>📊</span>Loan Summary
                            </button>
                            <button onclick="showModalTab('loans')" id="modal-tab-loans" 
                                    class="border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 text-sm font-medium">
                                <span>💵</span>Loans
                            </button>
                            <button onclick="showModalTab('documents')" id="modal-tab-documents" 
                                    class="border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 text-sm font-medium">
                                <span>📄</span>Documents
                            </button>
                            <button onclick="showModalTab('reports')" id="modal-tab-reports" 
                                    class="border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 text-sm font-medium">
                                <span>📊</span>Reports
                            </button>
                        </nav>
                    </div>

                    <!-- Tab Content -->
                    <div class="p-6">
                        <!-- Basic Information Tab -->
                        <div id="modal-content-info" class="modal-tab-content">
                            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                                <!-- Personal Information -->
                                <div class="space-y-4">
                                    <h4 class="text-lg font-semibold text-gray-900 border-b border-gray-200 pb-2">
                                        <span>👤</span>Personal Information
                                    </h4>
                                    <div class="space-y-3">
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Full Name:</span>
                                            <span class="text-sm text-gray-900" id="modalFullName"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Nickname:</span>
                                            <span class="text-sm text-gray-900" id="modalNickname"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Phone:</span>
                                            <span class="text-sm text-gray-900" id="modalPhone"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Email:</span>
                                            <span class="text-sm text-gray-900" id="modalEmail"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">ID Number:</span>
                                            <span class="text-sm text-gray-900" id="modalIdNumber"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Date of Birth:</span>
                                            <span class="text-sm text-gray-900" id="modalDob"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Gender:</span>
                                            <span class="text-sm text-gray-900" id="modalGender"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Marital Status:</span>
                                            <span class="text-sm text-gray-900" id="modalMaritalStatus"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Nationality:</span>
                                            <span class="text-sm text-gray-900" id="modalNationality"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Country:</span>
                                            <span class="text-sm text-gray-900" id="modalCountry"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Place of Birth:</span>
                                            <span class="text-sm text-gray-900" id="modalPlaceOfBirth"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Registration Date:</span>
                                            <span class="text-sm text-gray-900" id="modalRegistrationDate"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Status:</span>
                                            <span class="text-sm" id="modalStatus"></span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Address Information -->
                                <div class="space-y-4">
                                    <h4 class="text-lg font-semibold text-gray-900 border-b border-gray-200 pb-2">
                                        <span>📍</span>Address Information
                                    </h4>
                                    <div class="space-y-3">
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Physical Address:</span>
                                            <span class="text-sm text-gray-900" id="modalPhysicalAddress"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">City:</span>
                                            <span class="text-sm text-gray-900" id="modalCity"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">County:</span>
                                            <span class="text-sm text-gray-900" id="modalCounty"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Postal Code:</span>
                                            <span class="text-sm text-gray-900" id="modalPostalCode"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Physical Location:</span>
                                            <span class="text-sm text-gray-900" id="modalPhysicalLocation"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Domicile:</span>
                                            <span class="text-sm text-gray-900" id="modalDomicile"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">CP Domicile:</span>
                                            <span class="text-sm text-gray-900" id="modalCpDomicile"></span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Business Information -->
                                <div class="space-y-4">
                                    <h4 class="text-lg font-semibold text-gray-900 border-b border-gray-200 pb-2">
                                        <i class="fas fa-briefcase mr-2 text-primary"></i>Business Information
                                    </h4>
                                    <div class="space-y-3">
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Business Name:</span>
                                            <span class="text-sm text-gray-900" id="modalBusinessName"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Business Type:</span>
                                            <span class="text-sm text-gray-900" id="modalBusinessType"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Other Business Type:</span>
                                            <span class="text-sm text-gray-900" id="modalOtherBusinessType"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Business Address:</span>
                                            <span class="text-sm text-gray-900" id="modalBusinessAddress"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Employer:</span>
                                            <span class="text-sm text-gray-900" id="modalEmployer"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Monthly Income:</span>
                                            <span class="text-sm text-gray-900" id="modalIncome"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Capital Invested:</span>
                                            <span class="text-sm text-gray-900" id="modalCapitalInvested"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Expected Turnover:</span>
                                            <span class="text-sm text-gray-900" id="modalExpectedTurnover"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-sm font-medium text-gray-500">Credit Score:</span>
                                            <span class="text-sm font-medium" id="modalCreditScore"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>


                        </div>

                        <!-- Loan Summary Tab -->
                        <div id="modal-content-loan-summary" class="modal-tab-content hidden">
                            <div class="space-y-6">
                                <!-- Loan Statistics Cards -->
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                    <div class="bg-blue-50 p-4 rounded-lg text-center">
                                        <p class="text-sm text-blue-600 font-medium">Active Loans</p>
                                        <p class="text-xl font-bold text-blue-900" id="modalActiveLoans"></p>
                                    </div>
                                    <div class="bg-green-50 p-4 rounded-lg text-center">
                                        <p class="text-sm text-green-600 font-medium">Total Borrowed</p>
                                        <p class="text-xl font-bold text-green-900" id="modalTotalBorrowed"></p>
                                    </div>
                                    <div class="bg-yellow-50 p-4 rounded-lg text-center">
                                        <p class="text-sm text-yellow-600 font-medium">Total Repaid</p>
                                        <p class="text-xl font-bold text-yellow-900" id="modalTotalRepaid"></p>
                                    </div>
                                    <div class="bg-red-50 p-4 rounded-lg text-center">
                                        <p class="text-sm text-red-600 font-medium">Outstanding</p>
                                        <p class="text-xl font-bold text-red-900" id="modalOutstanding"></p>
                                    </div>
                                </div>

                                <!-- Charts Section -->
                                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                    <!-- Loan Status Distribution Chart -->
                                    <div class="bg-white p-6 rounded-lg border border-gray-200">
                                        <h5 class="text-lg font-semibold text-gray-900 mb-4">Loan Status Distribution</h5>
                                        <div id="loanStatusChart" class="h-64 flex items-center justify-center">
                                            <div class="text-center text-gray-500">
                                                <span>📊</span>
                                                <p>Loading chart...</p>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Repayment Trend Chart -->
                                    <div class="bg-white p-6 rounded-lg border border-gray-200">
                                        <h5 class="text-lg font-semibold text-gray-900 mb-4">Repayment Trend</h5>
                                        <div id="repaymentTrendChart" class="h-64 flex items-center justify-center">
                                            <div class="text-center text-gray-500">
                                                <span>📈</span>
                                                <p>Loading chart...</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Recent Loan Activity -->
                                <div class="bg-white p-6 rounded-lg border border-gray-200">
                                    <h5 class="text-lg font-semibold text-gray-900 mb-4">Recent Loan Activity</h5>
                                    <div id="recentLoanActivity" class="space-y-3">
                                        <!-- Recent activity will be populated here -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Loans Tab -->
                        <div id="modal-content-loans" class="modal-tab-content hidden">
                            <div id="modalLoansList" class="space-y-4">
                                <!-- Loans will be populated here -->
                            </div>
                        </div>

                        <!-- Documents Tab -->
                        <div id="modal-content-documents" class="modal-tab-content hidden">
                            <div id="modalDocumentsList" class="space-y-4">
                                <!-- Documents will be populated here -->
                            </div>
                        </div>

                        <!-- Reports Tab -->
                        <div id="modal-content-reports" class="modal-tab-content hidden">
                            <!-- Loading State -->
                            <div id="reportsLoading" class="flex items-center justify-center p-8">
                                <div class="text-center">
                                    <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary mb-4"></div>
                                    <p class="text-lg text-gray-700">Loading Analytics</p>
                                    <p class="text-sm text-gray-500 mt-2">Please wait while we load the data...</p>
                                    <div class="w-full max-w-md bg-gray-200 rounded-full h-2 mt-4">
                                        <div class="bg-primary h-2 rounded-full animate-pulse" style="width: 60%"></div>
                                    </div>
                                    <p class="text-xs text-gray-400 mt-2">Optimized for speed - this should complete quickly</p>
                                </div>
                            </div>

                            <!-- Error State -->
                            <div id="reportsError" class="hidden">
                                <div class="flex flex-col items-center justify-center p-8">
                                    <div class="text-red-500 mb-4">
                                        <span>⚠️</span>
                                    </div>
                                    <h4 class="text-lg font-medium text-gray-900">Unable to Load Analytics</h4>
                                    <p class="text-gray-500 mt-2">There was an error while loading the analytics. Please try again.</p>
                        <div id="errorDetails" class="hidden mt-4 p-4 bg-red-50 rounded-lg text-sm text-red-700 w-full max-w-lg">
                            <pre class="whitespace-pre-wrap"></pre>
                        </div>
                        <div class="mt-4 space-x-2">
                            <button onclick="retryLoadReports()" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark">
                                        <span>↷</span>Try Again
                                    </button>
                            <button onclick="toggleErrorDetails()" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200">
                                <i class="fas fa-bug mr-2"></i>Show Details
                                    </button>
                        </div>
                                </div>
                            </div>

                            <!-- Report Content -->
                            <div id="reportsContent" class="hidden">
                                <div class="space-y-6">
                                    <!-- Key Statistics -->
                                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                        <div class="bg-blue-50 p-4 rounded-lg text-center">
                                            <p class="text-sm text-blue-600 font-medium">Active Loans</p>
                                            <p class="text-xl font-bold text-blue-900" id="reportActiveLoans">-</p>
                                        </div>
                                        <div class="bg-green-50 p-4 rounded-lg text-center">
                                            <p class="text-sm text-green-600 font-medium">Total Borrowed</p>
                                            <p class="text-xl font-bold text-green-900" id="reportTotalBorrowed">-</p>
                                        </div>
                                        <div class="bg-yellow-50 p-4 rounded-lg text-center">
                                            <p class="text-sm text-yellow-600 font-medium">Total Repaid</p>
                                            <p class="text-xl font-bold text-yellow-900" id="reportTotalRepaid">-</p>
                                        </div>
                                        <div class="bg-red-50 p-4 rounded-lg text-center">
                                            <p class="text-sm text-red-600 font-medium">Outstanding</p>
                                            <p class="text-xl font-bold text-red-900" id="reportOutstanding">-</p>
                                        </div>
                                    </div>

                                    <!-- Charts Section -->
                                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                        <!-- Loan Status Distribution -->
                                        <div class="bg-white p-6 rounded-lg border border-gray-200">
                                            <h3 class="text-lg font-medium text-gray-900 mb-4">Loan Status Distribution</h3>
                                            <div class="h-64" id="reportLoanStatusChart"></div>
                                        </div>

                                        <!-- Monthly Trend -->
                                        <div class="bg-white p-6 rounded-lg border border-gray-200">
                                            <h3 class="text-lg font-medium text-gray-900 mb-4">Monthly Disbursement Trend</h3>
                                            <div class="h-64" id="reportMonthlyTrendChart"></div>
                                        </div>
                                    </div>

                                    <!-- Risk Assessment -->
                                    <div class="bg-white p-6 rounded-lg border border-gray-200">
                                        <h3 class="text-lg font-medium text-gray-900 mb-4">Risk Assessment</h3>
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                            <div>
                                                <h4 class="font-medium text-gray-700 mb-2">Current Risk Level</h4>
                                                <p id="reportRiskLevel" class="text-2xl font-bold"></p>
                                            </div>
                                            <div>
                                                <h4 class="font-medium text-gray-700 mb-2">Risk Factors</h4>
                                                <ul id="reportRiskFactors" class="list-disc list-inside text-gray-600"></ul>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Key Insights -->
                                    <div class="bg-white p-6 rounded-lg border border-gray-200">
                                        <h3 class="text-lg font-medium text-gray-900 mb-4">Key Insights</h3>
                                        <ul id="reportInsights" class="space-y-2"></ul>
                                    </div>

                                    <!-- Actions -->
                                    <div class="flex justify-end space-x-4">
                                        <button onclick="downloadAnalyticsReport()" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark">
                                            <span>⬇️</span>Download PDF Report
                                        </button>
                                        <button onclick="printAnalyticsReport()" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200">
                                            <span>🖨️</span>Print Report
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Footer -->
                    <div class="bg-gray-50 px-6 py-4 flex justify-between items-center">
                        <div class="flex space-x-3">
                            <button id="editClientBtn" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors duration-150">
                                <span>✏️</span>Edit Client
                            </button>
                            <a id="completeHistoryBtn" href="#" class="bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700 transition-colors duration-150">
                                <i class="fas fa-history mr-2"></i>Complete History
                            </a>
                            <button onclick="showModalTab('reports'); loadAnalyticsReport(currentClientId);" class="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 transition-colors duration-150">
                                <span>📊</span>View Analytics
                            </button>
                            <button id="downloadReportBtn" class="bg-purple-600 text-white px-4 py-2 rounded-md hover:bg-purple-700 transition-colors duration-150">
                                <span>⬇️</span>Download Report
                            </button>
                            <a id="deleteClientBtn" href="#" class="bg-red-600 text-white px-4 py-2 rounded-md hover:bg-red-700 transition-colors duration-150">
                                <span>🗑️</span>Remove Client
                            </a>
                        </div>
                        <button onclick="closeClientModal()" class="bg-gray-300 text-gray-700 px-4 py-2 rounded-md hover:bg-gray-400 transition-colors duration-150">
                            Close
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>


{% endblock %}

{% block scripts %}
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

                        
    
    <style>
        /* Report content styling */
        #reportData {
            font-family: inherit;
        }
        
        #reportData .min-h-screen {
            min-height: auto !important;
        }
        
        #reportData .bg-gradient-to-br {
            background: white !important;
        }
        
        #reportData .print\\:hidden {
            display: none !important;
        }
        
        #reportData .card {
            margin-bottom: 1.5rem;
        }
        
        #reportData .section-divider {
            margin: 2rem 0;
        }
        
        /* Button tooltips */
        .button-tooltip {
            position: relative;
        }
        
        .button-tooltip:hover::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 0.5rem;
            border-radius: 0.375rem;
            font-size: 0.75rem;
            white-space: nowrap;
            z-index: 1000;
            margin-bottom: 0.5rem;
        }
        
        .button-tooltip:hover::before {
            content: '';
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            border: 5px solid transparent;
            border-top-color: rgba(0, 0, 0, 0.8);
            margin-bottom: -0.5rem;
            z-index: 1000;
        }
    </style>
    
    <script>
        let currentClientData = null;
        let currentClientId = null;
        let reportClientId = null;

        function openSidebar() {
            document.getElementById('mobile-sidebar').classList.remove('hidden');
        }

        function closeSidebar() {
            document.getElementById('mobile-sidebar').classList.add('hidden');
        }

        function openClientModal(clientId) {
            currentClientId = clientId;
            const modal = document.getElementById('clientModal');
            const loading = document.getElementById('modalLoading');
            const content = document.getElementById('modalContent');
            
            console.log('Opening client modal for ID:', clientId); // Debug log
            console.log('Modal element:', modal); // Debug log
            console.log('Loading element:', loading); // Debug log
            console.log('Content element:', content); // Debug log
            
            // Show modal and loading state
            if (modal) {
            modal.classList.remove('hidden');
                console.log('Modal shown, hidden class removed');
            } else {
                console.error('Modal element not found!');
            }
            
            if (loading) {
            loading.classList.remove('hidden');
                loading.style.display = 'flex'; // Force show with inline CSS
                console.log('Loading shown, hidden class removed + display:flex');
            } else {
                console.error('Loading element not found!');
            }
            
            if (content) {
            content.classList.add('hidden');
                content.style.display = 'none'; // Force hide with inline CSS
                console.log('Content hidden, hidden class added + display:none');
            } else {
                console.error('Content element not found!');
            }
            
            // Construct the API URL
            const apiUrl = `{% url 'users:client_popup' client_id='00000000-0000-0000-0000-000000000000' %}`.replace('00000000-0000-0000-0000-000000000000', clientId);
            console.log('Fetching from API URL:', apiUrl); // Debug log
            
            // Update loading details
            const loadingDetails = document.getElementById('loadingDetails');
            if (loadingDetails) {
                loadingDetails.textContent = 'Loading client data...';
            }
            
            // Set up timeout for the fetch request (reduced from 10s to 5s for better UX)
            const fetchTimeout = setTimeout(() => {
                console.log('Fetch request timed out after 5 seconds'); // Debug log
                if (loadingDetails) {
                    loadingDetails.textContent = 'Request timed out. Please try again.';
                }
                setTimeout(() => {
                    alert('Request timed out. Please try again.');
                    closeClientModal();
                }, 1000);
            }, 5000); // 5 second timeout (reduced from 10s)
            
            // Fetch client data
            fetch(apiUrl)
                .then(response => {
                    console.log('API Response status:', response.status); // Debug log
                    console.log('API Response headers:', response.headers); // Debug log
                    
                    if (loadingDetails) {
                        loadingDetails.textContent = 'Processing response...';
                    }
                    
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    
                    if (loadingDetails) {
                        loadingDetails.textContent = '';
                    }
                    
                    return response.json();
                })
                .then(data => {
                    console.log('API Response data:', data); // Debug log
                    
                    if (loadingDetails) {
                        loadingDetails.textContent = '';
                    }
                    
                    if (data.success) {
                        currentClientData = data.client;
                        console.log('Calling populateModal with client data:', data.client); // Debug log
                        populateModal(data.client);
                        console.log('populateModal completed'); // Debug log
                        
                        console.log('About to hide loading and show content...'); // Debug log
                        console.log('Loading element before hiding:', loading); // Debug log
                        console.log('Content element before showing:', content); // Debug log
                        
                        if (loading) {
                        loading.classList.add('hidden');
                            loading.style.display = 'none'; // Force hide with inline CSS
                            console.log('Loading hidden, hidden class added + display:none');
                        }
                        
                        if (content) {
                        content.classList.remove('hidden');
                            content.style.display = 'block'; // Force show with inline CSS
                            console.log('Content shown, hidden class removed + display:block');
                        }
                        
                        console.log('Client modal populated successfully'); // Debug log
                        console.log('Loading hidden:', loading ? loading.classList.contains('hidden') : 'N/A'); // Debug log
                        console.log('Content visible:', content ? !content.classList.contains('hidden') : 'N/A'); // Debug log
                    } else {
                        console.error('API returned error:', data.error); // Debug log
                        if (loadingDetails) {
                            loadingDetails.textContent = `Error: ${data.error}`;
                        }
                        setTimeout(() => {
                        alert('Error loading client data: ' + data.error);
                        closeClientModal();
                        }, 1000);
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    console.error('Error details:', error.message); // Debug log
                    
                    if (loadingDetails) {
                        loadingDetails.textContent = `Error: ${error.message}`;
                    }
                    
                    setTimeout(() => {
                    alert('Error loading client data. Please try again.');
                    closeClientModal();
                    }, 1000);
                })
                .finally(() => {
                    // Clear the timeout
                    clearTimeout(fetchTimeout);
                });
        }

        function closeClientModal() {
            const modal = document.getElementById('clientModal');
            modal.classList.add('hidden');
            currentClientData = null;
            currentClientId = null;
        }

        function retryClientModal() {
            if (currentClientId) {
                console.log('Retrying client modal for ID:', currentClientId);
                openClientModal(currentClientId);
            }
        }

        // Test function to check if the API endpoint is working
        function testAPIEndpoint() {
            const testUrl = `{% url 'users:client_popup' client_id='00000000-0000-0000-0000-000000000000' %}`.replace('00000000-0000-0000-0000-000000000000', 'test');
            console.log('Testing API endpoint:', testUrl);
            
            fetch(testUrl)
                .then(response => {
                    console.log('Test response status:', response.status);
                    console.log('Test response headers:', response.headers);
                    return response.text();
                })
                .then(text => {
                    console.log('Test response text:', text.substring(0, 200) + '...');
                })
                .catch(error => {
                    console.error('Test API error:', error);
                });
        }

        // Test function to manually toggle modal state
        function testModalToggle() {
            const loading = document.getElementById('modalLoading');
            const content = document.getElementById('modalContent');
            
            if (loading && content) {
                console.log('Testing modal toggle...');
                console.log('Before toggle - Loading display:', loading.style.display);
                console.log('Before toggle - Content display:', content.style.display);
                
                // Toggle loading
                if (loading.style.display === 'none') {
                    loading.style.display = 'flex';
                    console.log('Loading shown (display: flex)');
                } else {
                    loading.style.display = 'none';
                    console.log('Loading hidden (display: none)');
                }
                
                // Toggle content
                if (content.style.display === 'none') {
                    content.style.display = 'block';
                    console.log('Content shown (display: block)');
                } else {
                    content.style.display = 'none';
                    console.log('Content hidden (display: none)');
                }
                
                console.log('After toggle - Loading display:', loading.style.display);
                console.log('After toggle - Content display:', content.style.display);
            } else {
                console.error('Modal elements not found for testing');
            }
        }

        // Report Modal Functions
        function showReportModal(clientId) {
            window.currentReportClientId = clientId;
            const reportModal = document.getElementById('reportModal');
            const reportLoading = document.getElementById('reportLoading');
            const reportContent = document.getElementById('reportContent');
            const reportError = document.getElementById('reportError');
            
            // Show modal and loading state
            reportModal.classList.remove('hidden');
            reportLoading.classList.remove('hidden');
            reportContent.classList.add('hidden');
            reportError.classList.add('hidden');
            document.body.style.overflow = 'hidden';
            
            // Load report content
            loadReportInModal(clientId);
        }

        function loadReportInModal(clientId) {
            const reportLoading = document.getElementById('reportLoading');
            const reportContent = document.getElementById('reportContent');
            const reportError = document.getElementById('reportError');
            const reportData = document.getElementById('reportData');
            const reportTitle = document.getElementById('reportTitle');
            
            // Use the loan analytics report endpoint
            const reportUrl = `{% url 'reports:loan_analytics_report' %}?borrower_id=${clientId}&format=json`;
            
            // Show loading state
            reportLoading.classList.remove('hidden');
            reportContent.classList.add('hidden');
            reportError.classList.add('hidden');
            
            // Fetch the report content
            fetch(reportUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Report data received:', data);
                    
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to generate report');
                    }
                    
                    // Update report data with the generated report
                    if (!data.html_content) {
                        throw new Error('No report content received');
                    }
                    
                    console.log('Setting report content...');
                    reportData.innerHTML = data.html_content;
                    reportTitle.textContent = data.title || 'Client Report';
                    console.log('Report content set successfully');
                    
                    // Initialize charts if present
                    if (typeof Chart !== 'undefined' && data.charts) {
                        Object.entries(data.charts).forEach(([containerId, chartConfig]) => {
                            const container = document.getElementById(containerId);
                            if (container) {
                                const canvas = container.querySelector('canvas');
                                if (canvas) {
                                    new Chart(canvas, chartConfig);
                                }
                            }
                        });
                    }
                    
                    // Hide loading, show content
                    reportLoading.classList.add('hidden');
                    reportContent.classList.remove('hidden');
                    reportError.classList.add('hidden');
                })
                .catch(error => {
                    console.error('Error loading report:', error);
                    // Show detailed error in console for debugging
                    console.log('Error details:', {
                        message: error.message,
                        url: reportUrl,
                        clientId: clientId
                    });
                    reportLoading.classList.add('hidden');
                    reportContent.classList.add('hidden');
                    reportError.classList.remove('hidden');
                });
        }

        function retryLoadReport() {
            if (reportClientId) {
                const reportLoading = document.getElementById('reportLoading');
                const reportError = document.getElementById('reportError');
                const reportData = document.getElementById('reportData');
                
                // Clear previous content and show loading
                reportData.innerHTML = '';
                reportError.classList.add('hidden');
                reportLoading.classList.remove('hidden');
                
                // Retry loading the report
                loadReportInModal(reportClientId);
            }
        }

        function openReportInNewTab() {
            if (reportClientId) {
                const reportUrl = `{% url 'users:client_report' client_id='00000000-0000-0000-0000-000000000000' %}`.replace('00000000-0000-0000-0000-000000000000', reportClientId) + '?generate_report=true';
                window.open(reportUrl, '_blank');
                closeReportModal();
            }
        }

        function viewReportInNewTab() {
            if (reportClientId) {
                const reportUrl = `{% url 'users:client_report' client_id='00000000-0000-0000-0000-000000000000' %}`.replace('00000000-0000-0000-0000-000000000000', reportClientId) + '?generate_report=true';
                window.open(reportUrl, '_blank');
            }
        }

        function closeReportModal() {
            const reportModal = document.getElementById('reportModal');
            const reportData = document.getElementById('reportData');
            
            reportModal.classList.add('hidden');
            document.body.style.overflow = '';
            
            // Clear the report content
            reportData.innerHTML = '';
            reportClientId = null;
        }

        function printReport() {
            const reportContent = document.getElementById('reportContent');
            if (!reportContent || !window.currentReportClientId) return;
            
            try {
                // Create a new window with the report content
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <html>
                        <head>
                            <title>Client Report</title>
                            <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
                            <style>
                                @media print {
                                    body { padding: 20px; }
                                    .no-print { display: none; }
                                }
                            </style>
                        </head>
                        <body>
                            ${reportContent.innerHTML}
                        </body>
                    </html>
                `);
                
                // Wait for content to load then print
                printWindow.document.close();
                printWindow.onload = function() {
                    printWindow.focus();
                    printWindow.print();
                    printWindow.close();
                };
            } catch (error) {
                console.error('Print error:', error);
                alert('Unable to print. Please try again.');
            }
        }

        function loadAnalyticsReport(clientId) {
            const reportsLoading = document.getElementById('reportsLoading');
            const reportsContent = document.getElementById('reportsContent');
            const reportsError = document.getElementById('reportsError');
            
            // Show loading state with progress indicators
            reportsLoading.classList.remove('hidden');
            reportsContent.classList.add('hidden');
            reportsError.classList.add('hidden');
            
            // Update loading message with progress
            const loadingMessage = reportsLoading.querySelector('p');
            if (loadingMessage) {
                loadingMessage.textContent = 'Loading Analytics...';
            }
            
            // Add timeout warning
            const timeoutWarning = setTimeout(() => {
                if (loadingMessage) {
                    loadingMessage.textContent = 'This is taking longer than usual. Please wait...';
                }
            }, 5000);
            
            // Use the optimized client popup endpoint instead of the slow analytics endpoint
            const reportUrl = `{% url 'users:client_popup' client_id='00000000-0000-0000-0000-000000000000' %}`.replace('00000000-0000-0000-0000-000000000000', clientId);
            
            // Create a timeout for the entire request
            const requestTimeout = setTimeout(() => {
                throw new Error('Request timeout - analytics loading is taking too long');
            }, 10000); // 10 second timeout (reduced from 30s)
            
            // Fetch the optimized analytics data
            fetch(reportUrl)
                .then(response => {
                    clearTimeout(timeoutWarning);
                    clearTimeout(requestTimeout);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data || !data.success) {
                        throw new Error(data?.error || 'Failed to load analytics');
                    }
                     
                     // Get analytics data from the optimized response
                     const clientData = data.client;
                     const analytics = clientData.analytics || {};
                     console.log('Optimized analytics data:', {
                         client: clientData,
                         analytics: analytics
                     });
                    
                    // Update statistics display using optimized data
                    document.getElementById('reportActiveLoans').textContent = clientData.active_loans || '0';
                    document.getElementById('reportTotalBorrowed').textContent = `KES ${(clientData.total_borrowed || 0).toLocaleString()}`;
                    document.getElementById('reportTotalRepaid').textContent = `KES ${(clientData.total_repaid || 0).toLocaleString()}`;
                    document.getElementById('reportOutstanding').textContent = `KES ${(clientData.outstanding_amount || 0).toLocaleString()}`;
                    
                    // Update risk assessment from optimized data
                    const riskLevel = analytics.risk_analysis?.risk_level || 'Unknown';
                    const riskLevelElement = document.getElementById('reportRiskLevel');
                    riskLevelElement.textContent = riskLevel;
                    riskLevelElement.className = `text-2xl font-bold ${
                         riskLevel.toLowerCase() === 'low' ? 'text-green-600' :
                         riskLevel.toLowerCase() === 'medium' ? 'text-yellow-600' :
                        'text-red-600'
                    }`;
                    
                    // Update risk factors
                    const riskFactors = document.getElementById('reportRiskFactors');
                    const riskFactorsList = analytics.risk_metrics || [];
                    riskFactors.innerHTML = riskFactorsList.map(factor => `
                        <li class="flex items-start">
                            <span class="flex-shrink-0 h-6 w-6 rounded-full flex items-center justify-center ${
                                factor.metric.toLowerCase().includes('risk') && factor.value.toLowerCase() === 'high' ? 'bg-red-100 text-red-600' :
                                factor.metric.toLowerCase().includes('risk') && factor.value.toLowerCase() === 'medium' ? 'bg-yellow-100 text-yellow-600' :
                                'bg-blue-100 text-blue-600'
                            } mr-3">
                                <span>⚠️</span>
                            </span>
                            <span class="text-gray-700">${factor.metric}: ${factor.value}</span>
                        </li>
                    `).join('');
                    
                    // Update insights
                    const insights = document.getElementById('reportInsights');
                    if (insights) {
                         const recommendations = analytics.recommendations || [];
                         if (recommendations.length > 0) {
                             insights.innerHTML = recommendations.map(recommendation => `
                                 <li class="flex items-start mb-4">
                                     <div class="flex-shrink-0 h-6 w-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                                         <span>💡</span>
                                     </div>
                                     <div>
                                         <h4 class="text-lg font-medium text-gray-900">${recommendation.title || 'Recommendation'}</h4>
                                         <p class="text-gray-700 mt-1">${recommendation.description || ''}</p>
                                         ${recommendation.action_items && recommendation.action_items.length > 0 ? `
                                             <ul class="mt-2 space-y-1">
                                                 ${recommendation.action_items.map(item => `
                                                     <li class="flex items-center text-sm text-gray-600">
                                                         <span>→</span>
                                                         ${item}
                                                     </li>
                                                 `).join('')}
                                             </ul>
                                         ` : ''}
                                     </div>
                                 </li>
                             `).join('');
                         } else {
                             insights.innerHTML = `
                                 <li class="text-center py-4">
                                     <span>ℹ️</span>
                                     <p class="text-gray-500">No recommendations available at this time.</p>
                                 </li>
                             `;
                         }
                     }
                    
                                         // Add executive summary
                     const executiveSummary = analyticsData.executive_summary;
                     if (executiveSummary) {
                         const summaryContainer = document.createElement('div');
                         summaryContainer.className = 'bg-white rounded-lg border border-gray-200 p-6 mb-8';
                         summaryContainer.innerHTML = `
                             <h3 class="text-lg font-medium text-gray-900 mb-4">
                                 <span>🚩</span>Executive Summary
                             </h3>
                             <div class="prose max-w-none">
                                 <p class="text-gray-700">${executiveSummary}</p>
                             </div>
                         `;
                         const reportsContent = document.getElementById('reportsContent');
                         if (reportsContent) {
                             const firstChild = reportsContent.querySelector('.space-y-6');
                             if (firstChild) {
                                 firstChild.insertBefore(summaryContainer, firstChild.firstChild);
                             }
                         }
                     }

                                         // Add portfolio metrics
                     const portfolioMetrics = analyticsData.portfolio_metrics || [];
                     if (portfolioMetrics.length > 0) {
                         const portfolioContainer = document.createElement('div');
                         portfolioContainer.className = 'grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8';
                         portfolioContainer.innerHTML = portfolioMetrics.map(metric => `
                             <div class="bg-white rounded-lg border border-gray-200 p-6">
                                 <h3 class="text-lg font-medium text-gray-900 mb-2">${metric.name}</h3>
                                 <p class="text-3xl font-bold ${
                                     metric.trend === 'up' ? 'text-green-600' :
                                     metric.trend === 'down' ? 'text-red-600' :
                                     'text-gray-900'
                                 }">
                                     ${metric.value}
                                 </p>
                                 <p class="text-sm text-gray-500 mt-1">${metric.description || ''}</p>
                             </div>
                         `).join('');
                         const reportsContent = document.getElementById('reportsContent');
                         if (reportsContent) {
                             const firstChild = reportsContent.querySelector('.space-y-6');
                             if (firstChild) {
                                 firstChild.insertBefore(portfolioContainer, firstChild.firstChild);
                             }
                         }
                     }

                                         // Add revenue metrics
                     const revenueMetrics = analyticsData.revenue_metrics || [];
                     if (revenueMetrics.length > 0) {
                         const revenueContainer = document.createElement('div');
                         revenueContainer.className = 'bg-white rounded-lg border border-gray-200 p-6 mb-8';
                         revenueContainer.innerHTML = `
                             <h3 class="text-lg font-medium text-gray-900 mb-4">
                                 <span>🪙</span>Revenue Analysis
                             </h3>
                             <div class="space-y-4">
                                 ${revenueMetrics.map(metric => `
                                     <div class="flex justify-between items-center">
                                         <span class="text-gray-600">${metric.name}</span>
                                         <span class="font-semibold ${
                                             metric.trend === 'up' ? 'text-green-600' :
                                             metric.trend === 'down' ? 'text-red-600' :
                                             'text-gray-900'
                                         }">${metric.value}</span>
                                     </div>
                                     ${metric.description ? `
                                         <p class="text-sm text-gray-500 mt-1">${metric.description}</p>
                                     ` : ''}
                                 `).join('')}
                             </div>
                         `;
                         const reportsContent = document.getElementById('reportsContent');
                         if (reportsContent) {
                             const firstChild = reportsContent.querySelector('.space-y-6');
                             if (firstChild) {
                                 firstChild.insertBefore(revenueContainer, firstChild.firstChild);
                             }
                         }
                     }

                                         // Add operational metrics
                     const operationalMetrics = analyticsData.operational_metrics || [];
                     if (operationalMetrics.length > 0) {
                         const metricsContainer = document.createElement('div');
                         metricsContainer.className = 'grid grid-cols-1 lg:grid-cols-3 gap-6 mt-8';
                         metricsContainer.innerHTML = operationalMetrics.map(metric => `
                             <div class="bg-white rounded-lg border border-gray-200 p-6">
                                 <h3 class="text-lg font-medium text-gray-900 mb-2">${metric.name}</h3>
                                 <p class="text-3xl font-bold ${
                                     metric.trend === 'up' ? 'text-green-600' :
                                     metric.trend === 'down' ? 'text-red-600' :
                                     'text-gray-900'
                                 }">
                                     ${metric.value}
                                 </p>
                                 <p class="text-sm text-gray-500 mt-1">${metric.description || ''}</p>
                                 ${metric.change ? `
                                     <p class="text-xs ${
                                         metric.change > 0 ? 'text-green-600' :
                                         metric.change < 0 ? 'text-red-600' :
                                         'text-gray-500'
                                     } mt-2">
                                         <i class="fas fa-${metric.change > 0 ? 'arrow-up' : 'arrow-down'} mr-1"></i>
                                         ${Math.abs(metric.change)}% from previous period
                                     </p>
                                 ` : ''}
                             </div>
                         `).join('');
                         const reportsContent = document.getElementById('reportsContent');
                         if (reportsContent) {
                             const firstChild = reportsContent.querySelector('.space-y-6');
                             if (firstChild) {
                                 firstChild.insertBefore(metricsContainer, firstChild.firstChild);
                             }
                         }
                     }
                    
                    // Initialize all charts from data attributes
                    const chartElements = tempDiv.querySelectorAll('[data-chart]');
                    chartElements.forEach(element => {
                        try {
                            const chartData = JSON.parse(element.getAttribute('data-chart') || '{}');
                            if (chartData && Object.keys(chartData).length > 0) {
                                const canvas = document.createElement('canvas');
                                element.innerHTML = '';
                                element.appendChild(canvas);
                                new Chart(canvas, chartData);
                            } else {
                                console.warn('Empty chart data for element:', element.id);
                                element.innerHTML = '<div class="flex items-center justify-center h-full text-gray-400"><span>📊</span></div>';
                            }
                        } catch (error) {
                            console.error('Error parsing chart data:', error);
                            element.innerHTML = '<div class="flex items-center justify-center h-full text-gray-400"><span>⚠️</span></div>';
                        }
                    });

                    // Initialize specific charts if provided directly
                    if (data.charts && typeof data.charts === 'object') {
                        const chartMappings = {
                            'reportLoanStatusChart': data.charts.loan_status_chart,
                            'reportMonthlyTrendChart': data.charts.monthly_trend_chart,
                            'portfolioCompositionChart': data.charts.portfolio_composition,
                            'loanPerformanceChart': data.charts.loan_performance,
                            'revenueTrendChart': data.charts.revenue_trend
                        };

                        Object.entries(chartMappings).forEach(([elementId, chartConfig]) => {
                            try {
                                const element = document.getElementById(elementId);
                                if (element && chartConfig) {
                                    const canvas = document.createElement('canvas');
                                    element.innerHTML = '';
                                    element.appendChild(canvas);
                                    new Chart(canvas, chartConfig);
                                } else if (element) {
                                    console.warn(`No chart config for ${elementId}`);
                                    element.innerHTML = '<div class="flex items-center justify-center h-full text-gray-400"><span>📊</span></div>';
                                }
                            } catch (error) {
                                console.error(`Error initializing chart ${elementId}:`, error);
                                const element = document.getElementById(elementId);
                                if (element) {
                                    element.innerHTML = '<div class="flex items-center justify-center h-full text-gray-400"><span>⚠️</span></div>';
                                }
                            }
                        });
                    }
                    
                    // Show content
                    reportsLoading.classList.add('hidden');
                    reportsContent.classList.remove('hidden');
                    reportsError.classList.add('hidden');
                })
                .catch(error => {
                    clearTimeout(timeoutWarning);
                    clearTimeout(requestTimeout);
                    
                    console.error('Error loading analytics:', error);
                    
                    // Prepare detailed error information
                    const errorInfo = {
                        message: error.message,
                        clientId: clientId,
                        endpoint: reportUrl,
                        timestamp: new Date().toISOString(),
                        userAgent: navigator.userAgent,
                        type: error.name || 'Error'
                    };
                    
                    console.error('Error details:', errorInfo);
                    
                                         // Update error message and details
                     const errorMessage = document.querySelector('#reportsError h4');
                     const errorDetails = document.querySelector('#errorDetails pre');
                     const errorDescription = document.querySelector('#reportsError p');
                     
                     if (errorMessage) {
                         errorMessage.textContent = `Unable to Generate Analytics: ${error.message}`;
                     }
                     
                     if (errorDescription) {
                         let description = 'There was an error while generating the analytics.';
                         
                         // Add more specific error descriptions
                         if (error.message.includes('undefined')) {
                             description += ' Some required data is missing from the server response.';
                         } else if (error.message.includes('HTTP error')) {
                             description += ' Could not connect to the analytics service.';
                         } else if (error.message.includes('No analytics content')) {
                             description += ' The server returned an empty response.';
                         }
                         
                         description += ' Please try again or contact support if the issue persists.';
                         errorDescription.textContent = description;
                     }
                     
                     if (errorDetails) {
                         const detailedInfo = {
                             ...errorInfo,
                             responseData: data || 'No response data',
                             availableData: {
                                 hasStatistics: !!data?.statistics,
                                 hasCharts: !!data?.charts,
                                 hasHtmlContent: !!data?.html_content
                             }
                         };
                         errorDetails.textContent = JSON.stringify(detailedInfo, null, 2);
                     }
                    
                    reportsLoading.classList.add('hidden');
                    reportsContent.classList.add('hidden');
                    reportsError.classList.remove('hidden');
                });
        }
        
        function toggleErrorDetails() {
            const errorDetails = document.getElementById('errorDetails');
            const toggleBtn = document.querySelector('button[onclick="toggleErrorDetails()"]');
            if (errorDetails.classList.contains('hidden')) {
                errorDetails.classList.remove('hidden');
                toggleBtn.innerHTML = '<i class="fas fa-eye-slash mr-2"></i>Hide Details';
            } else {
                errorDetails.classList.add('hidden');
                toggleBtn.innerHTML = '<i class="fas fa-bug mr-2"></i>Show Details';
            }
        }
        
        function retryLoadReports() {
            if (currentClientId) {
                // Clear any previous error details
                const errorDetails = document.querySelector('#errorDetails pre');
                if (errorDetails) {
                    errorDetails.textContent = '';
                }
                loadAnalyticsReport(currentClientId);
            }
        }
        
        function downloadAnalyticsReport() {
            if (!currentClientId) return;
            
            const downloadUrl = `{% url 'reports:loan_analytics_report' %}?borrower_id=${currentClientId}&format=pdf`;
            const downloadBtn = document.querySelector('button[onclick="downloadAnalyticsReport()"]');
            const originalText = downloadBtn.innerHTML;
            
            // Show loading state
            downloadBtn.innerHTML = '<span>⟳</span>Downloading...';
            downloadBtn.disabled = true;
            
            // Create a hidden iframe for downloading
            const iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            
            // Load the report URL in the iframe
            iframe.src = downloadUrl;
            
            // Remove iframe after a delay
            setTimeout(() => {
                document.body.removeChild(iframe);
                // Restore button state
                downloadBtn.innerHTML = originalText;
                downloadBtn.disabled = false;
            }, 2000);
        }
        
        function printAnalyticsReport() {
            if (!currentClientId) return;
            
            const printUrl = `{% url 'reports:loan_analytics_report' %}?borrower_id=${currentClientId}&format=print`;
            const printWindow = window.open(printUrl, '_blank');
            
            if (printWindow) {
                printWindow.onload = function() {
                    printWindow.print();
                };
            }
        }

        function populateModal(client) {
            // Set basic info
            document.getElementById('clientName').textContent = client.full_name;
            document.getElementById('clientId').textContent = `ID: ${client.id_number}`;
            
            // Handle selfie photo or initials
            const selfieImg = document.getElementById('clientSelfie');
            const initialsSpan = document.getElementById('clientInitials');
            
            if (client.documents && client.documents.selfie && client.documents.selfie.uploaded && client.documents.selfie.url) {
                selfieImg.src = client.documents.selfie.url;
                selfieImg.style.display = 'block';
                initialsSpan.style.display = 'none';
            } else {
                selfieImg.style.display = 'none';
                initialsSpan.style.display = 'block';
                initialsSpan.textContent = client.first_name.charAt(0) + client.last_name.charAt(0);
            }
            
            // Personal Information
            document.getElementById('modalFullName').textContent = client.full_name;
            document.getElementById('modalNickname').textContent = client.nickname;
            document.getElementById('modalPhone').textContent = client.phone_number;
            document.getElementById('modalEmail').textContent = client.email;
            document.getElementById('modalIdNumber').textContent = client.id_number;
            document.getElementById('modalDob').textContent = client.date_of_birth;
            document.getElementById('modalGender').textContent = client.gender;
            document.getElementById('modalMaritalStatus').textContent = client.marital_status;
            document.getElementById('modalNationality').textContent = client.nationality;
            document.getElementById('modalCountry').textContent = client.country;
            document.getElementById('modalPlaceOfBirth').textContent = client.place_of_birth;
            document.getElementById('modalRegistrationDate').textContent = client.registration_date;
            
            // Address Information
            document.getElementById('modalPhysicalAddress').textContent = client.physical_address;
            document.getElementById('modalCity').textContent = client.city;
            document.getElementById('modalCounty').textContent = client.county;
            document.getElementById('modalPostalCode').textContent = client.postal_code;
            document.getElementById('modalPhysicalLocation').textContent = client.physical_location;
            document.getElementById('modalDomicile').textContent = client.domicile;
            document.getElementById('modalCpDomicile').textContent = client.cp_domicile;
            
            // Status with color
            const statusElement = document.getElementById('modalStatus');
            statusElement.textContent = client.status_display;
            statusElement.className = 'text-sm inline-flex rounded-full px-2 text-xs font-semibold leading-5 ' + 
                (client.status === 'active' ? 'bg-green-100 text-green-800' :
                 client.status === 'dormant' ? 'bg-yellow-100 text-yellow-800' :
                 client.status === 'blacklisted' ? 'bg-red-100 text-red-800' :
                 'bg-gray-100 text-gray-800');
            
            // Business Information
            document.getElementById('modalBusinessName').textContent = client.business_name;
            document.getElementById('modalBusinessType').textContent = client.business_type;
            document.getElementById('modalOtherBusinessType').textContent = client.other_business_type;
            document.getElementById('modalBusinessAddress').textContent = client.business_address;
            document.getElementById('modalEmployer').textContent = client.employer;
            document.getElementById('modalIncome').textContent = `KES ${client.monthly_income.toLocaleString()}`;
            document.getElementById('modalCapitalInvested').textContent = `KES ${client.capital_invested.toLocaleString()}`;
            document.getElementById('modalExpectedTurnover').textContent = `KES ${client.expected_turnover.toLocaleString()}`;
            
            // Credit Score with color
            const creditScoreElement = document.getElementById('modalCreditScore');
            creditScoreElement.textContent = `${client.credit_score}/100`;
            creditScoreElement.className = 'text-sm font-medium ' + 
                (client.credit_score >= 80 ? 'text-green-600' :
                 client.credit_score >= 60 ? 'text-yellow-600' : 'text-red-600');
            
            // Loan Summary
            document.getElementById('modalActiveLoans').textContent = client.active_loans || '0';
            document.getElementById('modalTotalBorrowed').textContent = `KES ${(client.total_borrowed || 0).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
            document.getElementById('modalTotalRepaid').textContent = `KES ${(client.total_repaid || 0).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
            document.getElementById('modalOutstanding').textContent = `KES ${(client.outstanding_amount || 0).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
            
            // Set up action buttons
            
            // Get the buttons
            const editBtn = document.getElementById('editClientBtn');
            const deleteBtn = document.getElementById('deleteClientBtn');
            const completeHistoryBtn = document.getElementById('completeHistoryBtn');
            
            // Set up edit button
            if (editBtn) {
                editBtn.onclick = () => {
                    console.log('Edit button clicked, URL:', client.update_url);
                    window.location.href = client.update_url;
                };
            }
            
            // Set up complete history button
            if (completeHistoryBtn) {
                completeHistoryBtn.href = `/clients/${client.id}/history/`;
            }
            
            // Set up delete button
            if (deleteBtn) {
                deleteBtn.href = client.delete_url;
            }
            
            // Populate loans tab
            populateLoansTab(client.loans);
            
            // Populate loan summary tab
            populateLoanSummaryTab(client);
            
            // Populate documents tab
            populateDocumentsTab(client.documents);
            
            // Show info tab by default
            showModalTab('info');
        }

        function populateLoansTab(loans) {
            const loansList = document.getElementById('modalLoansList');
            
            if (!loans || loans.length === 0) {
                loansList.innerHTML = `
                    <div class="text-center py-8">
                        <span>💵</span>
                        <p class="text-gray-500">No loan history found for this client.</p>
                    </div>
                `;
                return;
            }
            
            loansList.innerHTML = loans.map(loan => `
                <div class="border rounded-lg p-4 hover:bg-gray-50 transition-colors duration-150">
                    <div class="flex justify-between items-start mb-4">
                        <div>
                            <p class="font-medium text-gray-900">${loan.loan_name || `Loan #${loan.loan_number}`}</p>
                            <p class="text-sm text-gray-500">KES ${loan.principal_amount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})} @ ${loan.interest_amount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})} interest</p>
                        </div>
                        <span class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${
                            loan.status === 'active' ? 'bg-green-100 text-green-800' :
                            loan.status === 'paid' ? 'bg-blue-100 text-blue-800' :
                            loan.status === 'defaulted' ? 'bg-red-100 text-red-800' :
                            'bg-gray-100 text-gray-800'
                        }">
                            ${loan.status_display}
                        </span>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                        <div>
                            <p class="text-gray-500">Disbursed</p>
                            <p class="font-medium">${loan.disbursement_date}</p>
                        </div>
                        <div>
                            <p class="text-gray-500">Due Date</p>
                            <p class="font-medium">${loan.due_date}</p>
                        </div>
                        <div>
                            <p class="text-gray-500">Amount Paid</p>
                            <p class="font-medium">KES ${loan.amount_paid.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</p>
                        </div>
                        <div>
                            <p class="text-gray-500">Outstanding</p>
                            <p class="font-medium">KES ${loan.outstanding_amount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</p>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        function populateDocumentsTab(documents) {
            const documentsList = document.getElementById('modalDocumentsList');
            
            if (!documents) {
                documentsList.innerHTML = `
                    <div class="text-center py-8">
                        <span>📄</span>
                        <p class="text-gray-500">No documents found for this client.</p>
                    </div>
                `;
                return;
            }
            
            const documentTypes = [
                { key: 'id_document', icon: 'fas fa-id-card', name: 'National ID', description: 'ID Document' },
                { key: 'selfie', icon: 'fas fa-user', name: 'Selfie', description: 'Photo' },
                { key: 'utility_bill', icon: 'fas fa-file-alt', name: 'Utility Bill', description: 'Address Proof' },
                { key: 'bank_statement', icon: 'fas fa-university', name: 'Bank Statement', description: 'Financial' },
                { key: 'business_license', icon: 'fas fa-briefcase', name: 'Business License', description: 'Registration' },
                { key: 'tax_certificate', icon: 'fas fa-receipt', name: 'Tax Certificate', description: 'Compliance' },
                { key: 'logbook', icon: 'fas fa-car', name: 'Logbook', description: 'Vehicle' },
                { key: 'title_deed', icon: 'fas fa-home', name: 'Title Deed', description: 'Property' },
                { key: 'signature', icon: 'fas fa-signature', name: 'Signature', description: 'Digital' },
                { key: 'other_documents', icon: 'fas fa-folder-open', name: 'Other Docs', description: 'Additional' }
            ];
            
            documentsList.innerHTML = `
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    ${documentTypes.map(doc => {
                        const docData = documents[doc.key];
                        const isUploaded = docData && docData.uploaded && docData.url;
                        
                        return `
                            <div class="document-card group relative bg-white rounded-lg border-2 ${isUploaded ? 'border-green-200 hover:border-green-300' : 'border-gray-200 hover:border-gray-300'} overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer" 
                                 onclick="${isUploaded ? `window.open('${docData.url}', '_blank')` : 'return false'}">
                                
                                <!-- Document Preview -->
                                <div class="aspect-w-3 aspect-h-4 bg-gray-100 group-hover:opacity-75 transition-opacity duration-200 overflow-hidden rounded-lg" style="position: relative; width: 100%; padding-bottom: 133.33%; /* 4:3 aspect ratio */">
                                    ${isUploaded ? `
                                        ${docData.url.toLowerCase().endsWith('.pdf') ? `
                                            <div class="absolute inset-0 flex items-center justify-center">
                                                <span>📄</span>
                                            </div>
                                        ` : docData.url.toLowerCase().match(/\.(doc|docx)$/) ? `
                                            <div class="absolute inset-0 flex items-center justify-center">
                                                <span>📝</span>
                                            </div>
                                        ` : `
                                            <img src="${docData.url}" alt="${doc.name}" class="absolute inset-0 w-full h-full object-cover">
                                        `}
                                    ` : `
                                        <div class="absolute inset-0 flex items-center justify-center">
                                            <i class="${doc.icon} text-3xl text-gray-400"></i>
                                        </div>
                                    `}
                                </div>
                                
                                <!-- Document Info -->
                                <div class="p-3">
                                    <h4 class="text-sm font-medium text-gray-900 truncate">${doc.name}</h4>
                                    <p class="text-xs text-gray-500 truncate">${doc.description}</p>
                                    
                                    <!-- Status Indicator -->
                                    <div class="mt-2 flex items-center justify-between">
                                        ${isUploaded ? `
                                            <div class="flex items-center">
                                                <span>✓</span>
                                                <span class="text-xs text-green-600 font-medium">Uploaded</span>
                                            </div>
                                            <span>↗️</span>
                                        ` : `
                                            <div class="flex items-center">
                                                <span>✕</span>
                                                <span class="text-xs text-red-600 font-medium">Missing</span>
                                            </div>
                                        `}
                                    </div>
                                </div>
                                
                                <!-- Hover Overlay -->
                                ${isUploaded ? `
                                    <div class="absolute inset-0 bg-transparent group-hover:bg-opacity-10 transition-all duration-200 flex items-center justify-center">
                                        <div class="bg-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                                            <i class="fas fa-eye text-gray-600"></i>
                                        </div>
                                    </div>
                                ` : ''}
                            </div>
                        `;
                    }).join('')}
                </div>
                
                <!-- Document Summary -->
                <div class="mt-6 p-4 bg-gray-50 rounded-lg">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-4">
                            <div class="flex items-center">
                                <span>✓</span>
                                <span class="text-sm text-gray-700">
                                    ${documentTypes.filter(doc => documents[doc.key] && documents[doc.key].uploaded).length} Uploaded
                                </span>
                            </div>
                            <div class="flex items-center">
                                <span>✕</span>
                                <span class="text-sm text-gray-700">
                                    ${documentTypes.filter(doc => !documents[doc.key] || !documents[doc.key].uploaded).length} Missing
                                </span>
                            </div>
                        </div>
                        <div class="text-sm text-gray-500">
                            Click on uploaded documents to view
                        </div>
                    </div>
                </div>
            `;
        }

        function populateLoanSummaryTab(client) {
            // Populate loan statistics (already done in populateModal)
            
            // Populate recent loan activity
            const recentActivity = document.getElementById('recentLoanActivity');
            
            if (!client.loans || client.loans.length === 0) {
                recentActivity.innerHTML = `
                    <div class="text-center py-8">
                        <span>📈</span>
                        <p class="text-gray-500">No recent loan activity found.</p>
                    </div>
                `;
                return;
            }
            
            // Show recent loans (last 5)
            const recentLoans = client.loans.slice(0, 5);
            recentActivity.innerHTML = recentLoans.map(loan => `
                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div class="flex items-center space-x-3">
                        <div class="w-2 h-2 rounded-full ${
                            loan.status === 'active' ? 'bg-green-500' :
                            loan.status === 'paid' ? 'bg-blue-500' :
                            loan.status === 'defaulted' ? 'bg-red-500' :
                            'bg-gray-500'
                        }"></div>
                        <div>
                            <p class="text-sm font-medium text-gray-900">${loan.loan_name || `Loan #${loan.loan_number}`}</p>
                            <p class="text-xs text-gray-500">${loan.disbursement_date}</p>
                        </div>
                    </div>
                    <div class="text-right">
                        <p class="text-sm font-medium text-gray-900">KES ${loan.principal_amount.toLocaleString()}</p>
                        <p class="text-xs text-gray-500">${loan.status_display}</p>
                    </div>
                </div>
            `).join('');
            
            // Render charts if Chart.js is available
            if (typeof Chart !== 'undefined' && client.chart_data) {
                renderLoanStatusChart(client.chart_data.loan_status_distribution);
                renderRepaymentTrendChart(client.chart_data.repayment_trend);
            } else {
                // Fallback to placeholder charts
                document.getElementById('loanStatusChart').innerHTML = `
                    <div class="text-center text-gray-500">
                        <span>📊</span>
                        <p>Chart coming soon...</p>
                    </div>
                `;
                
                document.getElementById('repaymentTrendChart').innerHTML = `
                    <div class="text-center text-gray-500">
                        <span>📈</span>
                        <p>Chart coming soon...</p>
                    </div>
                `;
            }
        }

        function showModalTab(tabName) {
            // Hide all tab contents
            const tabContents = document.querySelectorAll('.modal-tab-content');
            tabContents.forEach(content => {
                content.classList.add('hidden');
            });

            // Remove active class from all tabs
            const tabs = document.querySelectorAll('[id^="modal-tab-"]');
            tabs.forEach(tab => {
                tab.classList.remove('border-primary', 'text-primary');
                tab.classList.add('border-transparent', 'text-gray-500');
            });

            // Show selected tab content
            document.getElementById('modal-content-' + tabName).classList.remove('hidden');

            // Add active class to selected tab
            document.getElementById('modal-tab-' + tabName).classList.remove('border-transparent', 'text-gray-500');
            document.getElementById('modal-tab-' + tabName).classList.add('border-primary', 'text-primary');

            // Load reports data if reports tab is selected
            if (tabName === 'reports' && currentClientId) {
                loadAnalyticsReport(currentClientId);
            }
        }

        function renderLoanStatusChart(chartData) {
            const ctx = document.getElementById('loanStatusChart');
            if (!ctx) return;

            // Clear existing content
            ctx.innerHTML = '<canvas id="loanStatusChartCanvas"></canvas>';
            
            const canvas = document.getElementById('loanStatusChartCanvas');
            if (!canvas) return;

            new Chart(canvas, {
                type: 'doughnut',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        data: chartData.data,
                        backgroundColor: chartData.colors,
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }

        function renderRepaymentTrendChart(chartData) {
            const ctx = document.getElementById('repaymentTrendChart');
            if (!ctx) return;

            // Clear existing content
            ctx.innerHTML = '<canvas id="repaymentTrendChartCanvas"></canvas>';
            
            const canvas = document.getElementById('repaymentTrendChartCanvas');
            if (!canvas) return;

            new Chart(canvas, {
                type: 'line',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        label: 'Repayments (KES)',
                        data: chartData.data,
                        borderColor: '#3B82F6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#3B82F6',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 6,
                        pointHoverRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `KES ${context.parsed.y.toLocaleString()}`;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return 'KES ' + value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
        }

        // Close modals when clicking outside
        document.addEventListener('click', function(event) {
            const clientModal = document.getElementById('clientModal');
            const reportModal = document.getElementById('reportModal');
            
            if (event.target === clientModal) {
                closeClientModal();
            }
            
            if (event.target === reportModal) {
                closeReportModal();
            }
        });

        // Close modals with Escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeClientModal();
                closeReportModal();
            }
        });

        // Sorting functions
        function updateSorting() {
            const sortBy = document.getElementById('sort_by').value;
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set('sort_by', sortBy);
            currentUrl.searchParams.set('sort_order', '{{ sort_order }}');
            currentUrl.searchParams.delete('page'); // Reset to first page when sorting
            window.location.href = currentUrl.toString();
        }

        function toggleSortOrder() {
            const currentOrder = '{{ sort_order }}';
            const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set('sort_order', newOrder);
            currentUrl.searchParams.delete('page'); // Reset to first page when sorting
            window.location.href = currentUrl.toString();
        }

        // Simple form-based search and filtering
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-submit form when search input changes (with debounce)
            const searchInput = document.getElementById('search');
            let searchTimeout;
            
            if (searchInput) {
                searchInput.addEventListener('input', function() {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        this.closest('form').submit();
                    }, 500); // 500ms delay
                });
            }
            
            // Auto-submit form when select filters change
            const statusSelect = document.getElementById('status');
            const businessTypeSelect = document.getElementById('business_type');
            
            if (statusSelect) {
                statusSelect.addEventListener('change', function() {
                    this.closest('form').submit();
                });
            }
            
            if (businessTypeSelect) {
                businessTypeSelect.addEventListener('change', function() {
                    this.closest('form').submit();
                });
            }
        });
    </script>
{% endblock %}