{% extends 'base.html' %}
{% load humanize %}

{% block title %}Reports & Statements Dashboard{% endblock %}

{% block extra_css %}
<style>
.metric-card {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%) !important;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
    color: white !important;
}
.metric-card:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3) !important;
}
.metric-card.success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
}
.metric-card.success:hover {
    box-shadow: 0 10px 25px rgba(16, 185, 129, 0.3) !important;
}
.metric-card.warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
}
.metric-card.warning:hover {
    box-shadow: 0 10px 25px rgba(245, 158, 11, 0.3) !important;
}
.metric-card.danger {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
}
.metric-card.danger:hover {
    box-shadow: 0 10px 25px rgba(239, 68, 68, 0.3) !important;
}
.metric-card.info {
    background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%) !important;
}
.metric-card.info:hover {
    box-shadow: 0 10px 25px rgba(6, 182, 212, 0.3) !important;
}
.hover-lift {
    transition: transform 0.2s ease, box-shadow 0.2s ease !important;
}
.hover-lift:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1) !important;
}
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <div class="mb-8">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-900 dark:text-white">Reports & Statements Dashboard</h1>
                <p class="text-gray-600 dark:text-gray-400 mt-1">
                    Comprehensive analytics and reporting for loan management
                    {% if is_admin %}
                        {% if selected_branch_id %}
                            <span class="inline-flex items-center px-2 py-0.5 ml-2 rounded text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">
                                <span>🔍</span>
                                Filtered: {% for branch in all_branches %}{% if selected_branch_id|stringformat:"s" == branch.id|stringformat:"s" %}{{ branch.name }}{% endif %}{% endfor %}
                            </span>
                        {% else %}
                            <span class="inline-flex items-center px-2 py-0.5 ml-2 rounded text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                                <span>🌐</span>
                                All Branches
                            </span>
                        {% endif %}
                    {% endif %}
                </p>
            </div>
            <div class="flex items-center gap-3">
                {% if is_admin %}
                <div class="relative">
                    <label for="branch-filter" class="block text-xs text-gray-600 dark:text-gray-400 mb-1">Filter by Branch</label>
                    <select id="branch-filter" 
                            class="block w-full pl-3 pr-10 py-2 text-sm border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-blue-500 focus:border-blue-500 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                            onchange="filterByBranch(this.value)">
                        <option value="all" {% if not selected_branch_id %}selected{% endif %}>All Branches</option>
                        {% for branch in all_branches %}
                        <option value="{{ branch.id }}" {% if selected_branch_id|stringformat:"s" == branch.id|stringformat:"s" %}selected{% endif %}>
                            {{ branch.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                {% endif %}
                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">Last Updated: {% now "M d, Y H:i" %}</span>
            </div>
        </div>
    </div>

    <!-- First Row: Portfolio Overview, Loans Due Today, Delinquent Loans -->
    <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6 mb-8">
        <!-- Portfolio Overview -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex items-center justify-between mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>📊</span>Portfolio Overview
                </h3>
            </div>
            <div class="grid grid-cols-2 gap-3 flex-1">
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.summary_metrics.total_active_loans|default:0|floatformat:0 }}</div>
                    <div class="text-xs opacity-90">Active Loans</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                    <div class="text-lg font-bold mb-1">KES {{ dashboard_data.summary_metrics.total_portfolio_value|default:0|floatformat:0|intcomma }}</div>
                    <div class="text-xs opacity-90">Portfolio Value</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                    <div class="text-lg font-bold mb-1">KES {{ dashboard_data.summary_metrics.total_outstanding|default:0|floatformat:0|intcomma }}</div>
                    <div class="text-xs opacity-90">Outstanding</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.summary_metrics.collection_rate|default:0|floatformat:1 }}%</div>
                    <div class="text-xs opacity-90">Collection Rate</div>
                </div>
            </div>
        </div>

        <!-- Loans Due Today -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex items-center justify-between mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <i class="fas fa-calendar-day text-red-500 mr-3"></i>Loans Due Today
                </h3>
                <a href="{% url 'reports:enhanced_loans_due_report' %}?today_only=true" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5">
                    <i class="fas fa-eye mr-2"></i> View All
                </a>
            </div>
            <div class="grid grid-cols-2 gap-3 flex-1">
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.summary_metrics.loans_due_today|default:0|floatformat:0 }}</div>
                    <div class="text-xs opacity-90">Due Today</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.summary_metrics.overdue_loans|default:0|floatformat:0 }}</div>
                    <div class="text-xs opacity-90">Overdue</div>
                </div>
                <div class="col-span-2 bg-gray-50 dark:bg-gray-700 rounded-lg p-3 text-center">
                    {% if dashboard_data.loans_due_today.loans %}
                        <p class="text-sm text-gray-600 dark:text-gray-400">{{ dashboard_data.loans_due_today.loans|length }} loans require attention</p>
                        <!-- Repayment Method Breakdown -->
                        <div class="mt-2 grid grid-cols-3 gap-2 text-xs">
                            <div class="bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 px-2 py-1 rounded">
                                <i class="fas fa-calendar-day"></i> Daily: {{ dashboard_data.loans_due_today.daily_count|default:0 }}
                            </div>
                            <div class="bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 px-2 py-1 rounded">
                                <i class="fas fa-calendar-week"></i> Weekly: {{ dashboard_data.loans_due_today.weekly_count|default:0 }}
                            </div>
                            <div class="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 px-2 py-1 rounded">
                                <span>📅</span> Monthly: {{ dashboard_data.loans_due_today.monthly_count|default:0 }}
                            </div>
                        </div>
                    {% else %}
                        <p class="text-sm text-green-600 dark:text-green-400">✓ All loans are up to date!</p>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Delinquent Loans -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex items-center justify-between mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>⚠️</span>Delinquent Loans
                </h3>
                <a href="{% url 'reports:delinquent_loans_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5">
                    <i class="fas fa-eye mr-2"></i> View All
                </a>
            </div>
            <div class="grid grid-cols-1 gap-3 flex-1">
                <div class="text-center p-3 rounded-lg text-white min-h-[60px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.delinquent_loans.summary.mild_delinquent_count|default:0 }}</div>
                    <div class="text-xs opacity-90">1-30 Days Overdue</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[60px] flex flex-col justify-center" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.delinquent_loans.summary.moderate_delinquent_count|default:0 }}</div>
                    <div class="text-xs opacity-90">31-60 Days Overdue</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[60px] flex flex-col justify-center" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.delinquent_loans.summary.severe_delinquent_count|default:0 }}</div>
                    <div class="text-xs opacity-90">60+ Days Overdue</div>
                </div>
                <!-- Critical Daily Payment Alerts -->
                {% if dashboard_data.delinquent_loans.daily_critical_count > 0 %}
                <div class="bg-red-50 dark:bg-red-900 border-2 border-red-200 dark:border-red-700 rounded-lg p-3 text-center animate-pulse">
                    <div class="text-red-800 dark:text-red-200 font-bold text-sm">
                        <span>🔥</span> {{ dashboard_data.delinquent_loans.daily_critical_count }} Daily Payment{{ dashboard_data.delinquent_loans.daily_critical_count|pluralize }} Critical!
                    </div>
                    <div class="text-red-600 dark:text-red-300 text-xs mt-1">
                        Immediate attention required
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Second Row: Processing Fees, Interest Income, Registration Fees, Customer Requests -->
    <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-6 mb-8">
        <!-- Processing Fees -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>🪙</span>Processing Fees (Current Month)
                </h3>
                <a href="{% url 'reports:processing_fees_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📊</span> View Report
                </a>
            </div>
            <div class="grid grid-cols-2 gap-4 flex-1">
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                    <div class="text-xl font-bold mb-1">KES {{ dashboard_data.processing_fees_current_month.summary.total_processing_fees|default:0|floatformat:0|intcomma }}</div>
                    <div class="text-sm opacity-90">Total Fees</div>
                </div>
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.processing_fees_current_month.summary.total_loans_processed|default:0 }}</div>
                    <div class="text-sm opacity-90">Loans Processed</div>
                </div>
            </div>
        </div>

        <!-- Interest Income -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <i class="fas fa-percentage text-blue-500 mr-3"></i>Interest Income (Current Month)
                </h3>
                <a href="{% url 'reports:interest_income_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📈</span> View Report
                </a>
            </div>
            <div class="grid grid-cols-2 gap-4 flex-1">
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);">
                    <div class="text-xl font-bold mb-1">KES {{ dashboard_data.interest_income_current_month.summary.total_interest_income|default:0|floatformat:0|intcomma }}</div>
                    <div class="text-sm opacity-90">Total Interest</div>
                </div>
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.interest_income_current_month.summary.total_loans|default:0 }}</div>
                    <div class="text-sm opacity-90">Interest Bearing Loans</div>
                </div>
            </div>
        </div>

        <!-- Registration Fees -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <i class="fas fa-file-invoice-dollar text-cyan-500 mr-3"></i>Registration Fees
                </h3>
                <div class="flex gap-2 mt-3 sm:mt-0">
                    <a href="{% url 'reports:registration_fees_settings' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 transition-colors">
                        <span>⚙️</span> Settings
                    </a>
                    <a href="{% url 'reports:registration_fees_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5">
                        <span>📊</span> View Report
                    </a>
                </div>
            </div>
            {% if dashboard_data.registration_fees_current_month.summary.total_registration_income > 0 %}
                <div class="grid grid-cols-2 gap-4 flex-1">
                    <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);">
                        <div class="text-xl font-bold mb-1">KES {{ dashboard_data.registration_fees_current_month.summary.total_registration_income|default:0|floatformat:0|intcomma }}</div>
                        <div class="text-sm opacity-90">Total Income</div>
                    </div>
                    <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                        <div class="text-xl font-bold mb-1">{{ dashboard_data.registration_fees_current_month.summary.total_registrations|default:0 }}</div>
                        <div class="text-sm opacity-90">Registrations</div>
                    </div>
                </div>
            {% else %}
                <div class="flex-1 flex items-center justify-center">
                    <div class="text-center text-gray-500 dark:text-gray-400">
                        <span>ℹ️</span>
                        <h4 class="text-lg font-medium mb-2">No Current Month Data</h4>
                        <p class="text-sm">No registration fees found. Add clients with registration fees or view detailed report.</p>
                    </div>
                </div>
            {% endif %}
        </div>

        <!-- Customer Requests -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <i class="fas fa-headset text-yellow-500 mr-3"></i>Customer Requests
                </h3>
                <div class="flex gap-2 mt-3 sm:mt-0">
                    <a href="{% url 'reports:customer_requests_list' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 dark:bg-blue-900 dark:text-blue-200 dark:hover:bg-blue-800 transition-colors">
                        <span>📋</span> Manage
                    </a>
                    <a href="{% url 'reports:customer_requests_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5">
                        <span>📊</span> View Report
                    </a>
                </div>
            </div>
            <div class="grid grid-cols-3 gap-3 flex-1">
                <div class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.customer_requests_current_month.summary.pending_requests|default:0 }}</div>
                    <div class="text-xs opacity-90">Pending</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.customer_requests_current_month.summary.in_progress_requests|default:0 }}</div>
                    <div class="text-xs opacity-90">In Progress</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.customer_requests_current_month.summary.resolved_requests|default:0 }}</div>
                    <div class="text-xs opacity-90">Resolved</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Third Row: View All Due Loans, Loans in Arrears -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- View All Due Loans -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <i class="fas fa-calendar-check text-blue-500 mr-3"></i>View All Due Loans
                </h3>
                <a href="{% url 'reports:enhanced_loans_due_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <i class="fas fa-eye mr-2"></i> View Report
                </a>
            </div>
            <div class="grid grid-cols-2 gap-4 flex-1">
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.summary_metrics.loans_due_today|default:0|floatformat:0 }}</div>
                    <div class="text-sm opacity-90">Due Today</div>
                </div>
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.summary_metrics.overdue_loans|default:0|floatformat:0 }}</div>
                    <div class="text-sm opacity-90">Overdue Loans</div>
                </div>
            </div>
        </div>

        <!-- Loans in Arrears -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>⚠️</span>Loans in Arrears
                </h3>
                <a href="{% url 'reports:loans_in_arrears_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📊</span> View Report
                </a>
            </div>
            <div class="grid grid-cols-2 gap-4 flex-1">
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.delinquent_loans.summary.mild_delinquent_count|default:0 }}</div>
                    <div class="text-sm opacity-90">1-30 Days</div>
                </div>
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.delinquent_loans.summary.severe_delinquent_count|default:0 }}</div>
                    <div class="text-sm opacity-90">60+ Days</div>
                </div>
            </div>
        </div>

    </div>

    <!-- Fourth Row: Missed Payments and Completed Loans -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- Missed Payments -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>⏰</span>Missed Payments
                </h3>
                <a href="{% url 'reports:missed_payments_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-red-600 to-pink-600 rounded-lg hover:from-red-700 hover:to-pink-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📋</span> View Report
                </a>
            </div>
            <div class="grid grid-cols-2 gap-4 flex-1">
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.missed_payments.summary.daily_missed|default:0 }}</div>
                    <div class="text-sm opacity-90">Daily Missed</div>
                </div>
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.missed_payments.summary.weekly_missed|default:0 }}</div>
                    <div class="text-sm opacity-90">Weekly Missed</div>
                </div>
            </div>
        </div>

        <!-- Completed Loans -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>✓</span>Completed Loans
                </h3>
                <a href="{% url 'loans:loans' %}?status=paid" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-green-600 to-emerald-600 rounded-lg hover:from-green-700 hover:to-emerald-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <i class="fas fa-eye mr-2"></i> View All
                </a>
            </div>
            <div class="grid grid-cols-2 gap-4 flex-1">
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.completed_loans.summary.total_completed_loans|default:0 }}</div>
                    <div class="text-sm opacity-90">Total Completed</div>
                </div>
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #14b8a6 0%, #0d9488 100%);">
                    <div class="text-xl font-bold mb-1">{{ dashboard_data.completed_loans.summary.completed_this_month|default:0 }}</div>
                    <div class="text-sm opacity-90">This Month</div>
                </div>
            </div>
            <div class="mt-4 bg-gray-50 dark:bg-gray-700 rounded-lg p-3 text-center">
                <p class="text-sm text-gray-600 dark:text-gray-400">
                    <span class="font-semibold">KES {{ dashboard_data.completed_loans.summary.total_amount_collected|default:0|floatformat:0|intcomma }}</span> collected
                </p>
            </div>
        </div>
    </div>

    <!-- Disbursed Loans & Age/Gender Analytics Row -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- Disbursed Loans Report -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>💸</span>&nbsp;Disbursed Loans
                </h3>
                <a href="{% url 'reports:disbursed_loans_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-indigo-600 rounded-lg hover:from-blue-700 hover:to-indigo-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📊</span>&nbsp;View Report
                </a>
            </div>
            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">Filter disbursed loans by period, status, branch, product and amount range. Export to PDF or Excel.</p>
            <div class="grid grid-cols-3 gap-3 flex-1">
                <a href="{% url 'reports:disbursed_loans_report' %}?period=today" class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center hover:opacity-90 transition-opacity" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);">
                    <div class="text-xs opacity-90 mb-1">Today</div>
                    <div class="text-xs font-medium">View</div>
                </a>
                <a href="{% url 'reports:disbursed_loans_report' %}?period=this_week" class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center hover:opacity-90 transition-opacity" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);">
                    <div class="text-xs opacity-90 mb-1">This Week</div>
                    <div class="text-xs font-medium">View</div>
                </a>
                <a href="{% url 'reports:disbursed_loans_report' %}?period=total" class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center hover:opacity-90 transition-opacity" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);">
                    <div class="text-xs opacity-90 mb-1">All Time</div>
                    <div class="text-xs font-medium">View</div>
                </a>
            </div>
        </div>

        <!-- Age & Gender Analytics Report -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>👥</span>&nbsp;Age &amp; Gender Analytics
                </h3>
                <a href="{% url 'reports:age_gender_analytics_report' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-pink-600 to-rose-600 rounded-lg hover:from-pink-700 hover:to-rose-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📊</span>&nbsp;View Report
                </a>
            </div>
            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">Demographic breakdown of loan applications and approval rates by age group and gender.</p>
            <div class="grid grid-cols-2 gap-3 flex-1">
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #ec4899 0%, #db2777 100%);">
                    <div class="text-sm font-semibold mb-1">By Age Group</div>
                    <div class="text-xs opacity-90">18-25, 26-35, 36-45...</div>
                </div>
                <div class="text-center p-4 rounded-lg text-white min-h-[100px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f43f5e 0%, #e11d48 100%);">
                    <div class="text-sm font-semibold mb-1">By Gender</div>
                    <div class="text-xs opacity-90">Male, Female, Other</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Fifth Row: Overdue Loans Details and Client Growth Analytics -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- Overdue Loans Summary -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>⚠️</span>Overdue Loans Summary
                </h3>
                <a href="{% url 'loans:loans' %}?status=active&overdue=true" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-orange-600 to-red-600 rounded-lg hover:from-orange-700 hover:to-red-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📋</span> View All
                </a>
            </div>
            <div class="grid grid-cols-3 gap-3 flex-1">
                <div class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.overdue_loans.summary.mild_overdue|default:0 }}</div>
                    <div class="text-xs opacity-90">1-30 Days</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center" style="background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.overdue_loans.summary.moderate_overdue|default:0 }}</div>
                    <div class="text-xs opacity-90">31-60 Days</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[90px] flex flex-col justify-center" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.overdue_loans.summary.severe_overdue|default:0 }}</div>
                    <div class="text-xs opacity-90">60+ Days</div>
                </div>
            </div>
            <div class="mt-4 bg-red-50 dark:bg-red-900 rounded-lg p-3">
                <div class="flex justify-between items-center">
                    <span class="text-sm text-red-800 dark:text-red-200">Total Overdue Amount:</span>
                    <span class="text-sm font-bold text-red-900 dark:text-red-100">
                        KES {{ dashboard_data.overdue_loans.summary.total_overdue_amount|default:0|floatformat:0|intcomma }}
                    </span>
                </div>
                <div class="flex justify-between items-center mt-2 pt-2 border-t border-red-200 dark:border-red-700">
                    <span class="text-sm text-red-800 dark:text-red-200">Total Overdue Loans:</span>
                    <span class="text-sm font-bold text-red-900 dark:text-red-100">
                        {{ dashboard_data.overdue_loans.summary.total_overdue_loans|default:0 }}
                    </span>
                </div>
            </div>
        </div>

        <!-- Client Growth Analytics -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 hover-lift h-full flex flex-col">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <span>👥</span>Client Growth Analytics
                </h3>
                <a href="{% url 'users:client_performance_ranking' %}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-gradient-to-r from-purple-600 to-indigo-600 rounded-lg hover:from-purple-700 hover:to-indigo-700 transition-all transform hover:-translate-y-0.5 mt-3 sm:mt-0">
                    <span>📈</span> View Report
                </a>
            </div>
            <div class="grid grid-cols-2 gap-3 flex-1">
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.client_growth.summary.total_clients|default:0 }}</div>
                    <div class="text-xs opacity-90">Total Clients</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #a855f7 0%, #9333ea 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.client_growth.summary.clients_this_week|default:0 }}</div>
                    <div class="text-xs opacity-90">This Week</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #c084fc 0%, #a855f7 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.client_growth.summary.clients_this_month|default:0 }}</div>
                    <div class="text-xs opacity-90">This Month</div>
                </div>
                <div class="text-center p-3 rounded-lg text-white min-h-[80px] flex flex-col justify-center" style="background: linear-gradient(135deg, #d8b4fe 0%, #c084fc 100%);">
                    <div class="text-lg font-bold mb-1">{{ dashboard_data.client_growth.summary.clients_this_year|default:0 }}</div>
                    <div class="text-xs opacity-90">This Year</div>
                </div>
            </div>
            <div class="mt-4 bg-purple-50 dark:bg-purple-900 rounded-lg p-3">
                <div class="flex justify-between items-center text-sm">
                    <span class="text-purple-800 dark:text-purple-200">Growth Rate:</span>
                    <span class="font-bold text-purple-900 dark:text-purple-100">
                        {% if dashboard_data.client_growth.summary.growth_rate >= 0 %}
                            <span>↑</span> {{ dashboard_data.client_growth.summary.growth_rate|floatformat:1 }}%
                        {% else %}
                            <span>↓</span> {{ dashboard_data.client_growth.summary.growth_rate|floatformat:1 }}%
                        {% endif %}
                    </span>
                </div>
                <div class="flex justify-between items-center text-xs mt-2 pt-2 border-t border-purple-200 dark:border-purple-700">
                    <span class="text-purple-700 dark:text-purple-300">Best Month:</span>
                    <span class="font-semibold text-purple-900 dark:text-purple-100">
                        {{ dashboard_data.client_growth.summary.best_month|default:"N/A" }} ({{ dashboard_data.client_growth.summary.best_month_count|default:0 }})
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Branch filter function for admins
function filterByBranch(branchId) {
    console.log('Filtering by branch:', branchId);
    const url = new URL(window.location.href);
    url.searchParams.set('branch_filter', branchId);
    console.log('Redirecting to:', url.toString());
    window.location.href = url.toString();
}

// Load client analytics on page load
document.addEventListener('DOMContentLoaded', function() {
    loadClientAnalytics();
});

function loadClientAnalytics() {
    // Values are already loaded from template, but update if API has newer data
    fetch('{% url "users:acquisition_trends_api" %}')
        .then(response => response.json())
        .then(data => {
            if (data.total_clients !== undefined) {
                const elem = document.getElementById('total-clients-count');
                if (elem) elem.textContent = data.total_clients;
            }
            if (data.new_clients_this_month !== undefined) {
                const elem = document.getElementById('new-clients-this-month');
                if (elem) elem.textContent = data.new_clients_this_month;
            }
        })
        .catch(error => {
            console.error('Error loading client analytics:', error);
        });
    
    // Load officer count and portfolio distribution
    fetch('{% url "users:officer_performance_api" %}')
        .then(response => response.json())
        .then(data => {
            if (data.officers) {
                const officersElem = document.getElementById('active-loan-officers');
                if (officersElem) officersElem.textContent = data.officers.length;
                
                const totalClients = data.officers.reduce((sum, officer) => sum + (officer.total_clients || 0), 0);
                const avgClients = data.officers.length > 0 ? (totalClients / data.officers.length).toFixed(1) : 0;
                const avgElem = document.getElementById('avg-clients-per-officer');
                if (avgElem) avgElem.textContent = avgClients;
                
                // Display portfolio distribution
                const distributionDiv = document.getElementById('portfolio-distribution');
                if (distributionDiv && data.officers.length > 0) {
                    distributionDiv.innerHTML = data.officers.slice(0, 6).map(officer => `
                        <div class="bg-gray-100 dark:bg-gray-700 rounded px-2 py-1 flex justify-between items-center">
                            <span class="font-medium text-xs text-gray-700 dark:text-gray-300">${officer.officer_name || 'Unknown'}</span>
                            <span class="bg-purple-500 text-white px-2 py-0.5 rounded text-xs">${officer.total_clients || 0}</span>
                        </div>
                    `).join('');
                } else if (distributionDiv) {
                    distributionDiv.innerHTML = '<div class="text-gray-500 text-xs">No officers found</div>';
                }
            }
        })
        .catch(error => {
            console.error('Error loading officer data:', error);
        });
}
</script>
{% endblock %}