<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>Loans in Arrears - Advanced Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary: #4f46e5;
            --primary-dark: #4338ca;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --info: #3b82f6;
            --dark: #1e293b;
            --light: #f8fafc;
            --text: #475569;
            --border: #e2e8f0;
            --shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
            --shadow-sm: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            position: relative;
            overflow-x: hidden;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="%23ffffff" fill-opacity="0.03" d="M0,224L48,213.3C96,203,192,181,288,186.7C384,192,480,224,576,229.3C672,235,768,213,864,186.7C960,160,1056,128,1152,133.3C1248,139,1344,181,1392,202.7L1440,224L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>') no-repeat;
            background-size: cover;
            pointer-events: none;
            z-index: 0;
        }

        .container {
            position: relative;
            z-index: 1;
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }

        /* Animated Background Particles */
        @keyframes float {
            0%, 100% { 
                transform: translateY(0) rotate(0deg); 
                opacity: 0.3; 
            }
            33% { 
                transform: translateY(-100px) rotate(120deg); 
                opacity: 0.6; 
            }
            66% { 
                transform: translateY(-50px) rotate(240deg); 
                opacity: 0.3; 
            }
        }

        .particle {
            position: fixed;
            width: 60px;
            height: 60px;
            background: radial-gradient(circle, rgba(255,255,255,0.4) 0%, rgba(255,255,255,0.1) 50%, transparent 70%);
            border-radius: 50%;
            animation: float 20s infinite;
            z-index: 0;
            pointer-events: none;
        }

        /* Header */
        .header {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border-radius: 24px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: var(--shadow);
            border: 1px solid rgba(255, 255, 255, 0.2);
            animation: slideDown 0.6s ease-out;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1.5rem;
        }

        .header h1 {
            font-size: 2rem;
            font-weight: 800;
            background: linear-gradient(135deg, var(--primary) 0%, var(--danger) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .header p {
            color: var(--text);
            margin-top: 0.5rem;
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 12px;
            border: none;
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            position: relative;
            overflow: hidden;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.3);
            transform: translate(-50%, -50%);
            transition: width 0.5s, height 0.5s;
        }

        .btn:hover::before {
            width: 300px;
            height: 300px;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, var(--success) 0%, #059669 100%);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, var(--danger) 0%, #dc2626 100%);
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
        }

        /* Filter Section */
        .filter-card {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: var(--shadow-sm);
            animation: fadeInUp 0.8s ease-out 0.2s both;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-top: 1.5rem;
        }

        .form-group label {
            display: block;
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 0.5rem;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid var(--border);
            border-radius: 12px;
            font-size: 0.9rem;
            transition: all 0.3s;
            background: white;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
        }

        /* Metric Cards */
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .metric-card {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            cursor: pointer;
            border: 1px solid rgba(255, 255, 255, 0.2);
            animation: fadeInUp 0.8s ease-out both;
        }

        .metric-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.12);
        }

        .metric-card.clickable {
            cursor: pointer;
            user-select: none;
        }

        .metric-card.clickable:hover {
            background: rgba(79, 70, 229, 0.05);
            border-color: var(--primary);
        }

        .metric-card.clickable:active {
            transform: translateY(-4px) scale(0.98);
        }

        .metric-card.clickable::after {
            content: 'Click to filter';
            position: absolute;
            bottom: 0.5rem;
            right: 0.5rem;
            font-size: 0.75rem;
            color: var(--primary);
            opacity: 0;
            transition: opacity 0.3s;
        }

        .metric-card.clickable:hover::after {
            opacity: 1;
        }

        .metric-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary) 0%, var(--info) 100%);
        }

        .metric-card.danger::before {
            background: linear-gradient(90deg, var(--danger) 0%, var(--warning) 100%);
        }

        .metric-card.success::before {
            background: linear-gradient(90deg, var(--success) 0%, var(--info) 100%);
        }

        .metric-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.12);
        }

        .metric-icon {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--info) 100%);
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }

        .metric-card.danger .metric-icon {
            background: linear-gradient(135deg, var(--danger) 0%, var(--warning) 100%);
        }

        .metric-card.success .metric-icon {
            background: linear-gradient(135deg, var(--success) 0%, var(--info) 100%);
        }

        .metric-value {
            font-size: 2rem;
            font-weight: 800;
            color: var(--dark);
            line-height: 1;
            margin-bottom: 0.5rem;
        }

        .metric-label {
            font-size: 0.875rem;
            color: var(--text);
            font-weight: 500;
        }

        .metric-change {
            position: absolute;
            top: 1.5rem;
            right: 1.5rem;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .metric-change.positive {
            background: rgba(16, 185, 129, 0.1);
            color: var(--success);
        }

        .metric-change.negative {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
        }

        /* Charts Section */
        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .chart-card {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 1.5rem;
            box-shadow: var(--shadow-sm);
            animation: fadeInUp 0.8s ease-out 0.4s both;
            position: relative;
            height: 400px;
        }

        .chart-container {
            position: relative;
            height: 300px;
            width: 100%;
        }

        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .chart-title {
            font-size: 1.125rem;
            font-weight: 700;
            color: var(--dark);
        }

        /* Data Table */
        .table-card {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            overflow: hidden;
            box-shadow: var(--shadow);
            animation: fadeInUp 0.8s ease-out 0.6s both;
        }

        .table-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            padding: 1.5rem;
            color: white;
        }

        .table-header h3 {
            font-size: 1.25rem;
            font-weight: 700;
        }

        .table-wrapper {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead th {
            background: var(--light);
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            color: var(--dark);
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 2px solid var(--border);
        }

        tbody tr {
            transition: all 0.3s;
            border-bottom: 1px solid var(--border);
        }

        tbody tr:hover {
            background: rgba(79, 70, 229, 0.05);
            transform: scale(1.01);
        }

        tbody td {
            padding: 1rem;
            color: var(--text);
        }

        .borrower-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .borrower-avatar {
            width: 40px;
            height: 40px;
            border-radius: 12px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--info) 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
        }

        .severity-badge {
            padding: 0.375rem 0.875rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            display: inline-block;
        }

        /* Enhanced Alert Animations */
        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.05); opacity: 0.8; }
            100% { transform: scale(1); opacity: 1; }
        }

        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0.3; }
        }

        .alert-badge.critical {
            animation: pulse 2s infinite;
            box-shadow: 0 0 20px rgba(239, 68, 68, 0.5);
        }

        .alert-badge.high {
            animation: blink 3s infinite;
        }

        /* Product-specific styling */
        .product-info {
            text-align: center;
        }

        .repayment-method-info {
            text-align: center;
        }

        .payment-schedule-info {
            text-align: center;
            padding: 0.5rem;
            background: rgba(99, 102, 241, 0.05);
            border-radius: 8px;
            border: 1px solid rgba(99, 102, 241, 0.1);
        }

        .missed-periods-container {
            text-align: center;
        }

        .days-overdue-info {
            text-align: center;
        }

        .alert-level-container {
            text-align: center;
            min-width: 120px;
        }

        /* Enhanced row highlighting for critical alerts */
        tr[data-repayment-method="daily"] .alert-badge.critical {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
            box-shadow: 0 0 25px rgba(239, 68, 68, 0.7);
        }

        tr[data-repayment-method="weekly"] .alert-badge.critical {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
            box-shadow: 0 0 25px rgba(245, 158, 11, 0.7);
        }

        tr[data-repayment-method="monthly"] .alert-badge.critical {
            background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%) !important;
            box-shadow: 0 0 25px rgba(59, 130, 246, 0.7);
        }

        .severity-low {
            background: rgba(16, 185, 129, 0.1);
            color: var(--success);
        }

        .severity-medium {
            background: rgba(245, 158, 11, 0.1);
            color: var(--warning);
        }

        .severity-high {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
        }

        .severity-critical {
            background: var(--danger);
            color: white;
        }

        .product-badge, .repayment-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            display: inline-block;
        }

        .product-badge {
            background: rgba(79, 70, 229, 0.1);
            color: var(--primary);
        }

        .product-badge.product-boost {
            background: rgba(16, 185, 129, 0.1);
            color: var(--success);
        }

        .product-badge.product-boost_plus {
            background: rgba(59, 130, 246, 0.1);
            color: var(--info);
        }

        .product-badge.product-mwamba {
            background: rgba(245, 158, 11, 0.1);
            color: var(--warning);
        }

        .product-badge.product-imara {
            background: rgba(139, 92, 246, 0.1);
            color: #8b5cf6;
        }

        .repayment-badge {
            background: rgba(107, 114, 128, 0.1);
            color: #6b7280;
        }

        .repayment-badge.repayment-daily {
            background: rgba(16, 185, 129, 0.1);
            color: var(--success);
        }

        .repayment-badge.repayment-weekly {
            background: rgba(59, 130, 246, 0.1);
            color: var(--info);
        }

        .repayment-badge.repayment-monthly {
            background: rgba(245, 158, 11, 0.1);
            color: var(--warning);
        }

        .product-badge:hover, .repayment-badge:hover {
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            transition: all 0.2s ease;
        }

        .action-icons {
            display: flex;
            gap: 0.5rem;
        }

        .action-icon {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            background: var(--light);
            color: var(--text);
        }

        .action-icon:hover {
            background: var(--primary);
            color: white;
            transform: scale(1.1);
        }

        /* Loading Animation */
        .loading {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 9999;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-top: 4px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            100% { transform: rotate(360deg); }
        }

        /* Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }

            .header h1 {
                font-size: 1.5rem;
            }

            .metrics-grid {
                grid-template-columns: 1fr;
            }

            .charts-grid {
                grid-template-columns: 1fr;
            }

            .chart-card {
                height: 350px;
            }

            .chart-container {
                height: 250px;
            }

            .filter-grid {
                grid-template-columns: 1fr;
            }

            .action-buttons {
                flex-direction: column;
                width: 100%;
            }

            .btn {
                width: 100%;
                justify-content: center;
            }

            .table-wrapper {
                font-size: 0.875rem;
            }

            .borrower-info {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }

            .action-icons {
                flex-wrap: wrap;
            }
        }

        @media (max-width: 480px) {
            .chart-card {
                height: 300px;
            }

            .chart-container {
                height: 200px;
            }

            .metric-value {
                font-size: 1.5rem;
            }

            .table-wrapper {
                font-size: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <!-- Animated Background Particles -->
    <div class="particle" style="left: 10%; top: 20%; animation-delay: 0s;"></div>
    <div class="particle" style="left: 70%; top: 60%; animation-delay: 5s;"></div>
    <div class="particle" style="left: 30%; top: 80%; animation-delay: 10s;"></div>
    <div class="particle" style="left: 90%; top: 10%; animation-delay: 15s;"></div>
    <div class="particle" style="left: 50%; top: 30%; animation-delay: 3s;"></div>
    <div class="particle" style="left: 20%; top: 70%; animation-delay: 8s;"></div>
    <div class="particle" style="left: 80%; top: 40%; animation-delay: 12s;"></div>
    <div class="particle" style="left: 60%; top: 90%; animation-delay: 18s;"></div>

    <!-- Loading Spinner -->
    <div class="loading" id="loadingSpinner">
        <div class="loading-spinner"></div>
    </div>

    <div class="container">
        <!-- Header -->
        <div class="header">
            <div class="header-content">
                <div>
                    <h1>
                        <span>📈</span>
                        Loans in Arrears Dashboard
                    </h1>
                    <p>Real-time monitoring and advanced analytics for overdue loans</p>
                </div>
                <div class="action-buttons">
                    <button class="btn btn-success" onclick="exportData('excel')">
                        <span>📊</span> Export Excel
                    </button>
                    <button class="btn btn-danger" onclick="exportData('pdf')">
                        <span>📄</span> Export PDF
                    </button>
                    <button class="btn btn-primary" onclick="refreshDashboard()">
                        <span>🔄</span> Refresh
                    </button>
                    <button class="btn" style="background: var(--text); color: white;" onclick="clearAllFilters()">
                        <span>✕</span> Clear Filters
                    </button>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="filter-card">
            <h3 style="color: var(--dark); margin-bottom: 1rem;">
                <span>🔍</span>
                Advanced Filters
            </h3>
            <div class="filter-grid">
                <div class="form-group">
                    <label>Risk Level</label>
                    <select class="form-control" id="riskFilter" onchange="applyFilters()">
                        <option value="all" {% if request.GET.arrears_filter == 'all' or not request.GET.arrears_filter %}selected{% endif %}>All Risk Levels</option>
                        <option value="under_10k" {% if request.GET.arrears_filter == 'under_10k' %}selected{% endif %}>Low Risk (< KSh 10k)</option>
                        <option value="10k_50k" {% if request.GET.arrears_filter == '10k_50k' %}selected{% endif %}>Medium Risk (10k-50k)</option>
                        <option value="over_50k" {% if request.GET.arrears_filter == 'over_50k' %}selected{% endif %}>High Risk (> KSh 50k)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Sort By</label>
                    <select class="form-control" id="sortBy" onchange="applyFilters()">
                        <option value="amount_desc" {% if request.GET.sort_by == 'amount_desc' or not request.GET.sort_by %}selected{% endif %}>Amount (High to Low)</option>
                        <option value="amount_asc" {% if request.GET.sort_by == 'amount_asc' %}selected{% endif %}>Amount (Low to High)</option>
                        <option value="days_overdue_desc" {% if request.GET.sort_by == 'days_overdue_desc' %}selected{% endif %}>Days Overdue (Most)</option>
                        <option value="days_overdue_asc" {% if request.GET.sort_by == 'days_overdue_asc' %}selected{% endif %}>Days Overdue (Least)</option>
                        <option value="borrower" {% if request.GET.sort_by == 'borrower' %}selected{% endif %}>Borrower Name</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Start Date</label>
                    <input type="date" class="form-control" id="startDate" value="{{ request.GET.start_date|default:'' }}" onchange="applyFilters()">
                </div>
                <div class="form-group">
                    <label>End Date</label>
                    <input type="date" class="form-control" id="endDate" value="{{ request.GET.end_date|default:'' }}" onchange="applyFilters()">
                </div>
            </div>
        </div>

        <!-- Key Metrics -->
        <div class="metrics-grid">
            <div class="metric-card clickable" style="animation-delay: 0.1s;" onclick="filterByMetric('total_loans')" data-metric="total_loans">
                <div class="metric-icon">
                    <span>⚠️</span>
                </div>
                <div class="metric-value">{{ report_data.summary.total_loans_in_arrears|default:0 }}</div>
                <div class="metric-label">Total Loans in Arrears</div>
            </div>

            <div class="metric-card danger clickable" style="animation-delay: 0.2s;" onclick="filterByMetric('total_amount')" data-metric="total_amount">
                <div class="metric-icon">
                    <span>💵</span>
                </div>
                <div class="metric-value">KSh {{ report_data.summary.total_arrears_amount|floatformat:0|default:0 }}</div>
                <div class="metric-label">Total Arrears Amount</div>
            </div>

            <div class="metric-card clickable" style="animation-delay: 0.3s;" onclick="filterByMetric('average_amount')" data-metric="average_amount">
                <div class="metric-icon" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);">
                    <span>📈</span>
                </div>
                <div class="metric-value">KSh {{ report_data.summary.average_arrears_amount|floatformat:0|default:0 }}</div>
                <div class="metric-label">Average Arrears</div>
            </div>

            <div class="metric-card success clickable" style="animation-delay: 0.4s;" onclick="filterByMetric('recovery_rate')" data-metric="recovery_rate">
                <div class="metric-icon">
                    <i class="fas fa-percentage"></i>
                </div>
                <div class="metric-value">{{ report_data.summary.recovery_rate|floatformat:1|default:0 }}%</div>
                <div class="metric-label">Recovery Rate</div>
            </div>
        </div>

        {% if error %}
        <div class="filter-card" style="background: rgba(239, 68, 68, 0.1); border-left: 4px solid var(--danger);">
            <h3 style="color: var(--danger); margin-bottom: 1rem;">
                <span>⚠️</span>
                Error Loading Report
            </h3>
            <p style="color: var(--text);">{{ error }}</p>
        </div>
        {% endif %}

        <!-- Risk Distribution -->
        <div class="metrics-grid">
            <div class="metric-card success clickable" style="animation-delay: 0.5s;" onclick="filterByRisk('low')" data-risk="low">
                <div class="metric-icon">
                    <i class="fas fa-shield-alt"></i>
                </div>
                <div class="metric-value">{{ report_data.severity_breakdown.low_risk_count|default:0 }}</div>
                <div class="metric-label">Low Risk (< KSh 10k)</div>
            </div>

            <div class="metric-card clickable" style="animation-delay: 0.6s; border-top: 4px solid var(--warning);" onclick="filterByRisk('medium')" data-risk="medium">
                <div class="metric-icon" style="background: linear-gradient(135deg, var(--warning) 0%, #d97706 100%);">
                    <span>⚠️</span>
                </div>
                <div class="metric-value">{{ report_data.severity_breakdown.medium_risk_count|default:0 }}</div>
                <div class="metric-label">Medium Risk (10k-50k)</div>
            </div>

            <div class="metric-card danger clickable" style="animation-delay: 0.7s;" onclick="filterByRisk('high')" data-risk="high">
                <div class="metric-icon">
                    <span>🔥</span>
                </div>
                <div class="metric-value">{{ report_data.severity_breakdown.high_risk_count|default:0 }}</div>
                <div class="metric-label">High Risk (> 50k)</div>
            </div>

            <div class="metric-card danger clickable" style="animation-delay: 0.8s;" onclick="filterByRisk('critical')" data-risk="critical">
                <div class="metric-icon">
                    <i class="fas fa-skull-crossbones"></i>
                </div>
                <div class="metric-value">{{ report_data.severity_breakdown.critical_count|default:0 }}</div>
                <div class="metric-label">Critical (> 90 days)</div>
            </div>
        </div>

        <!-- Charts -->
        <div class="charts-grid">
            <div class="chart-card">
                <div class="chart-header">
                    <h3 class="chart-title">Arrears Trend Analysis</h3>
                    <select class="form-control" id="trendPeriod" style="width: 120px;" onchange="updateTrendChart()">
                        <option value="7">Last 7 days</option>
                        <option value="30">Last 30 days</option>
                        <option value="90">Last 90 days</option>
                    </select>
                </div>
                <div class="chart-container">
                    <canvas id="trendChart"></canvas>
                </div>
            </div>

            <div class="chart-card">
                <div class="chart-header">
                    <h3 class="chart-title">Risk Distribution</h3>
                    <button class="btn btn-primary" style="padding: 0.5rem 1rem; font-size: 0.875rem;">
                        <span>⬇️</span>
                    </button>
                </div>
                <div class="chart-container">
                    <canvas id="riskChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Data Table -->
        <div class="table-card">
            <div class="table-header">
                <h3><i class="fas fa-table" style="margin-right: 0.5rem;"></i>Detailed Arrears List</h3>
            </div>
            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>Borrower</th>
                            <th>Loan Details</th>
                            <th style="text-align: center;">Product</th>
                            <th style="text-align: center;">Repayment Method</th>
                            <th style="text-align: center;">Payment Schedule</th>
                            <th style="text-align: right;">Expected Payment</th>
                            <th style="text-align: right;">Arrears Amount</th>
                            <th style="text-align: center;">Missed Periods</th>
                            <th style="text-align: center;">Days Overdue</th>
                            <th style="text-align: center;">Alert Level</th>
                            <th>Last Payment</th>
                            <th style="text-align: center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="loansTableBody">
                        {% for loan in report_data.loans %}
                        <tr data-loan-id="{{ loan.id }}" 
                            data-product-type="{{ loan.product_type|default:'unknown' }}" 
                            data-repayment-method="{{ loan.repayment_method|default:'monthly' }}" 
                            data-severity="{{ loan.severity_level }}" 
                            data-amount="{{ loan.arrears_amount|default:0 }}"
                            data-days-overdue="{{ loan.days_overdue|default:0 }}">
                            <td>
                                <div class="borrower-info">
                                    <div class="borrower-avatar">
                                        {{ loan.borrower_name|first|upper }}
                                    </div>
                                    <div>
                                        <div style="font-weight: 600; color: var(--dark);">{{ loan.borrower_name }}</div>
                                        <div style="font-size: 0.875rem; color: var(--text);">{{ loan.borrower_phone|default:"N/A" }}</div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div style="font-weight: 600; color: var(--dark);">{{ loan.loan_number }}</div>
                                <div style="font-size: 0.875rem; color: var(--text);">Due: {{ loan.due_date|date:"M d, Y" }}</div>
                            </td>
                            <td style="text-align: center;">
                                <div class="product-info">
                                    <span class="product-badge product-{{ loan.product_type|default:'unknown' }}" 
                                          onclick="filterByProduct('{{ loan.product_type|default:'unknown' }}')" 
                                          style="cursor: pointer; display: block; margin-bottom: 0.25rem;" 
                                          title="Click to filter by {{ loan.loan_product|default:'Unknown' }}">
                                        {{ loan.loan_product|default:'Unknown' }}
                                    </span>
                                    <div style="font-size: 0.7rem; color: #6b7280; font-weight: 500;">
                                        {% if loan.product_type == 'boost' %}
                                            <span>⚡</span> 1 Month
                                        {% elif loan.product_type == 'boost_plus' %}
                                            <i class="fas fa-rocket" style="color: #f59e0b;"></i> 2 Months
                                        {% elif loan.product_type == 'mwamba' %}
                                            <i class="fas fa-mountain" style="color: #3b82f6;"></i> 3 Months
                                        {% elif loan.product_type == 'imara' %}
                                            <i class="fas fa-shield-alt" style="color: #8b5cf6;"></i> 6 Months
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                            <td style="text-align: center;">
                                <div class="repayment-method-info">
                                    <span class="repayment-badge repayment-{{ loan.repayment_method|default:'monthly' }}" 
                                          onclick="filterByRepaymentMethod('{{ loan.repayment_method|default:'monthly' }}')" 
                                          style="cursor: pointer; display: block; margin-bottom: 0.25rem;" 
                                          title="Click to filter by {{ loan.repayment_method|default:'Monthly'|title }} repayment">
                                        {{ loan.repayment_method|default:'Monthly'|title }}
                                    </span>
                                    <div style="font-size: 0.7rem; color: #6b7280; font-weight: 500;">
                                        {% if loan.repayment_method == 'daily' %}
                                            <i class="fas fa-calendar-day" style="color: #10b981;"></i> Every Day
                                        {% elif loan.repayment_method == 'weekly' %}
                                            <i class="fas fa-calendar-week" style="color: #f59e0b;"></i> Every Week
                                        {% else %}
                                            <span>📅</span> Every Month
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                            <td style="text-align: center;">
                                <div class="payment-schedule-info">
                                    <div style="font-size: 0.75rem; font-weight: 600; color: #374151; margin-bottom: 0.25rem;">
                                        {% if loan.repayment_method == 'daily' %}
                                            Daily: KES {{ loan.expected_payment_amount|floatformat:0 }}
                                        {% elif loan.repayment_method == 'weekly' %}
                                            Weekly: KES {{ loan.expected_payment_amount|floatformat:0 }}
                                        {% else %}
                                            Monthly: KES {{ loan.expected_payment_amount|floatformat:0 }}
                                        {% endif %}
                                    </div>
                                    <div style="font-size: 0.7rem; color: #6b7280;">
                                        {% if loan.repayment_method == 'daily' %}
                                            <span>⏰</span> Due Every Day
                                        {% elif loan.repayment_method == 'weekly' %}
                                            <span>⏰</span> Due Every 7 Days
                                        {% else %}
                                            <span>⏰</span> Due Every 30 Days
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                            <td style="text-align: right; font-weight: 600; color: var(--info);">
                                KSh {{ loan.expected_payment_amount|floatformat:0 }}
                            </td>
                            <td style="text-align: right; font-weight: 600; color: var(--danger);">
                                KSh {{ loan.arrears_amount|floatformat:0 }}
                            </td>
                            <td style="text-align: center;">
                                <div class="missed-periods-container">
                                    <span class="missed-periods-badge" 
                                          style="background: {% if loan.missed_periods_count > 3 %}var(--danger){% elif loan.missed_periods_count > 1 %}var(--warning){% else %}var(--success){% endif %}; 
                                                 color: white; padding: 0.25rem 0.5rem; border-radius: 12px; font-size: 0.75rem; font-weight: 600; display: block; margin-bottom: 0.25rem;"
                                          title="Number of missed payment periods">
                                        {{ loan.missed_periods_count|default:0 }} Missed
                                    </span>
                                    <div style="font-size: 0.7rem; color: #6b7280;">
                                        {% if loan.repayment_method == 'daily' %}
                                            {% if loan.missed_periods_count > 0 %}
                                                <span>⚠️</span> {{ loan.missed_periods_count }} Day{{ loan.missed_periods_count|pluralize }} Overdue
                                            {% endif %}
                                        {% elif loan.repayment_method == 'weekly' %}
                                            {% if loan.missed_periods_count > 0 %}
                                                <span>⚠️</span> {{ loan.missed_periods_count }} Week{{ loan.missed_periods_count|pluralize }} Overdue
                                            {% endif %}
                                        {% else %}
                                            {% if loan.missed_periods_count > 0 %}
                                                <span>⚠️</span> {{ loan.missed_periods_count }} Month{{ loan.missed_periods_count|pluralize }} Overdue
                                            {% endif %}
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                            <td style="text-align: center;">
                                <div class="days-overdue-info">
                                    <span style="font-weight: 600; color: {% if loan.days_overdue > 90 %}var(--danger){% elif loan.days_overdue > 30 %}var(--warning){% else %}var(--success){% endif %}; display: block; margin-bottom: 0.25rem;">
                                        {{ loan.days_overdue }} days
                                    </span>
                                    <div style="font-size: 0.7rem; color: #6b7280;">
                                        {% if loan.repayment_method == 'daily' %}
                                            {% if loan.days_overdue >= 7 %}
                                                <span>🔥</span> Critical
                                            {% elif loan.days_overdue >= 3 %}
                                                <span>⚠️</span> High Risk
                                            {% elif loan.days_overdue >= 1 %}
                                                <span>⚠️</span> Medium Risk
                                            {% endif %}
                                        {% elif loan.repayment_method == 'weekly' %}
                                            {% if loan.days_overdue >= 21 %}
                                                <span>🔥</span> Critical
                                            {% elif loan.days_overdue >= 14 %}
                                                <span>⚠️</span> High Risk
                                            {% elif loan.days_overdue >= 7 %}
                                                <span>⚠️</span> Medium Risk
                                            {% endif %}
                                        {% else %}
                                            {% if loan.days_overdue >= 90 %}
                                                <span>🔥</span> Critical
                                            {% elif loan.days_overdue >= 60 %}
                                                <span>⚠️</span> High Risk
                                            {% elif loan.days_overdue >= 30 %}
                                                <span>⚠️</span> Medium Risk
                                            {% endif %}
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                            <td style="text-align: center;">
                                <div class="alert-level-container">
                                    {% if loan.repayment_method == 'daily' %}
                                        {% if loan.days_overdue >= 7 %}
                                            <span class="alert-badge critical" style="background: #ef4444; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem; animation: pulse 2s infinite;">
                                                <span>🔥</span> CRITICAL
                                            </span>
                                            <div style="font-size: 0.7rem; color: #ef4444; font-weight: 600;">
                                                Daily Payment Overdue!
                                            </div>
                                        {% elif loan.days_overdue >= 3 %}
                                            <span class="alert-badge high" style="background: #f59e0b; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                                <span>⚠️</span> HIGH ALERT
                                            </span>
                                            <div style="font-size: 0.7rem; color: #f59e0b; font-weight: 600;">
                                                Multiple Days Overdue
                                            </div>
                                        {% elif loan.days_overdue >= 1 %}
                                            <span class="alert-badge medium" style="background: #3b82f6; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                                <span>⚠️</span> ALERT
                                            </span>
                                            <div style="font-size: 0.7rem; color: #3b82f6; font-weight: 600;">
                                                Daily Payment Missed
                                            </div>
                                        {% endif %}
                                    {% elif loan.repayment_method == 'weekly' %}
                                        {% if loan.days_overdue >= 21 %}
                                            <span class="alert-badge critical" style="background: #ef4444; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem; animation: pulse 2s infinite;">
                                                <span>🔥</span> CRITICAL
                                            </span>
                                            <div style="font-size: 0.7rem; color: #ef4444; font-weight: 600;">
                                                Multiple Weeks Overdue!
                                            </div>
                                        {% elif loan.days_overdue >= 14 %}
                                            <span class="alert-badge high" style="background: #f59e0b; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                                <span>⚠️</span> HIGH ALERT
                                            </span>
                                            <div style="font-size: 0.7rem; color: #f59e0b; font-weight: 600;">
                                                Weekly Payment Overdue
                                            </div>
                                        {% elif loan.days_overdue >= 7 %}
                                            <span class="alert-badge medium" style="background: #3b82f6; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                                <span>⚠️</span> ALERT
                                            </span>
                                            <div style="font-size: 0.7rem; color: #3b82f6; font-weight: 600;">
                                                Weekly Payment Missed
                                            </div>
                                        {% endif %}
                                    {% else %}
                                        {% if loan.days_overdue >= 90 %}
                                            <span class="alert-badge critical" style="background: #ef4444; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem; animation: pulse 2s infinite;">
                                                <span>🔥</span> CRITICAL
                                            </span>
                                            <div style="font-size: 0.7rem; color: #ef4444; font-weight: 600;">
                                                Multiple Months Overdue!
                                            </div>
                                        {% elif loan.days_overdue >= 60 %}
                                            <span class="alert-badge high" style="background: #f59e0b; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                                <span>⚠️</span> HIGH ALERT
                                            </span>
                                            <div style="font-size: 0.7rem; color: #f59e0b; font-weight: 600;">
                                                Monthly Payment Overdue
                                            </div>
                                        {% elif loan.days_overdue >= 30 %}
                                            <span class="alert-badge medium" style="background: #3b82f6; color: white; padding: 0.4rem 0.8rem; border-radius: 12px; font-size: 0.7rem; font-weight: 700; display: block; margin-bottom: 0.25rem;">
                                                <span>⚠️</span> ALERT
                                            </span>
                                            <div style="font-size: 0.7rem; color: #3b82f6; font-weight: 600;">
                                                Monthly Payment Missed
                                            </div>
                                        {% endif %}
                                    {% endif %}
                                </div>
                            </td>
                            <td>
                                {% if loan.last_payment_date %}
                                    <div style="font-weight: 600; color: var(--dark);">{{ loan.last_payment_date|date:"M d, Y" }}</div>
                                    <div style="font-size: 0.875rem; color: var(--text);">KSh {{ loan.last_payment_amount|floatformat:0 }}</div>
                                {% else %}
                                    <span style="color: var(--text); font-style: italic;">No payments</span>
                                {% endif %}
                            </td>
                            <td style="text-align: center;">
                                <div class="action-icons">
                                    <button class="action-icon" title="View Details" onclick="viewLoanDetails('{{ loan.id }}')">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="action-icon" title="Contact Borrower" onclick="contactBorrower('{{ loan.borrower_phone }}')">
                                        <span>📞</span>
                                    </button>
                                    <button class="action-icon" title="Record Payment" onclick="recordPaymentArrears('{{ loan.id }}')">
                                        <span>+</span>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="9" style="text-align: center; padding: 2rem; color: var(--text);">
                                <span>✓</span>
                                <div>No loans in arrears found</div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <script>
        // Version: 2024-01-15-v2 - Enhanced Loans in Arrears Report
        // Real data from Django template
        const reportData = {
            summary: {
                total_loans_in_arrears: {{ report_data.summary.total_loans_in_arrears|default:0 }},
                total_arrears_amount: {{ report_data.summary.total_arrears_amount|default:0 }},
                average_arrears_amount: {{ report_data.summary.average_arrears_amount|default:0 }},
                recovery_rate: {{ report_data.summary.recovery_rate|default:0 }}
            },
            severity_breakdown: {
                low_risk_count: {{ report_data.severity_breakdown.low_risk_count|default:0 }},
                medium_risk_count: {{ report_data.severity_breakdown.medium_risk_count|default:0 }},
                high_risk_count: {{ report_data.severity_breakdown.high_risk_count|default:0 }},
                critical_count: {{ report_data.severity_breakdown.critical_count|default:0 }}
            },
            loans: [
                {% for loan in report_data.loans %}
                {
                    id: "{{ loan.id }}",
                    loan_number: "{{ loan.loan_number }}",
                    borrower_name: "{{ loan.borrower_name }}",
                    borrower_phone: "{{ loan.borrower_phone|default:'' }}",
                    due_date: "{{ loan.due_date|date:'Y-m-d' }}",
                    arrears_amount: {{ loan.arrears_amount|default:0 }},
                    days_overdue: {{ loan.days_overdue|default:0 }},
                    severity_level: "{{ loan.severity_level }}",
                    severity_label: "{{ loan.severity_label }}",
                    last_payment_date: {% if loan.last_payment_date %}"{{ loan.last_payment_date|date:'Y-m-d' }}"{% else %}null{% endif %},
                    last_payment_amount: {{ loan.last_payment_amount|default:0 }}
                }{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            recovery_trend: {
                labels: {{ report_data.recovery_trend.labels|default:"[]"|safe }},
                data: {{ report_data.recovery_trend.data|default:"[]"|safe }}
            },
            performance_chart: {
                labels: {{ report_data.performance_chart.labels|default:"[]"|safe }},
                datasets: {{ report_data.performance_chart.datasets|default:"[]"|safe }}
            }
        };

        // Generate trend data based on current loans
        function generateTrendData() {
            const period = document.getElementById('trendPeriod') ? document.getElementById('trendPeriod').value : 7;
            const days = parseInt(period);
            
            // Generate labels for the period
            const labels = [];
            const data = [];
            const today = new Date();
            
            for (let i = days - 1; i >= 0; i--) {
                const date = new Date(today);
                date.setDate(date.getDate() - i);
                labels.push(date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
                
                // Generate sample data based on current loans
                // In a real implementation, this would come from the server
                const baseAmount = reportData.summary.total_arrears_amount || 0;
                const variation = (Math.random() - 0.5) * 0.2; // ±10% variation
                const amount = Math.max(0, baseAmount * (1 + variation));
                data.push(Math.round(amount));
            }
            
            return { labels, data };
        }

        // Initialize Charts
        let trendChart, riskChart;

        function initCharts() {
            // Check if Chart.js is loaded
            if (typeof Chart === 'undefined') {
                console.error('Chart.js is not loaded');
                return;
            }

            // Initialize trend chart
            initTrendChart();
            
            // Initialize risk chart
            initRiskChart();
        }

        function initTrendChart() {
            const trendCanvas = document.getElementById('trendChart');
            if (!trendCanvas) {
                console.error('Trend chart canvas not found');
                return;
            }
            
            const trendCtx = trendCanvas.getContext('2d');
            
            // Generate trend data based on current loans
            const trendData = generateTrendData();
            
            if (trendData.labels.length === 0 || trendData.data.length === 0) {
                trendCanvas.parentElement.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: var(--text); font-style: italic;">No trend data available</div>';
                return;
            }

            trendChart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: trendData.labels,
                    datasets: [{
                        label: 'Total Arrears (KSh)',
                        data: trendData.data,
                        borderColor: '#4f46e5',
                        backgroundColor: 'rgba(79, 70, 229, 0.2)',
                        tension: 0.4,
                        fill: true,
                        pointBackgroundColor: '#4f46e5',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 4,
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#ffffff',
                            bodyColor: '#ffffff',
                            borderColor: '#4f46e5',
                            borderWidth: 1
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#6b7280'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)'
                            },
                            ticks: {
                                color: '#6b7280',
                                callback: function(value) {
                                    return 'KSh ' + value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });

        }

        function initRiskChart() {
            const riskCanvas = document.getElementById('riskChart');
            if (!riskCanvas) {
                console.error('Risk chart canvas not found');
                return;
            }
            
            const riskCtx = riskCanvas.getContext('2d');
            riskChart = new Chart(riskCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Low Risk', 'Medium Risk', 'High Risk', 'Critical'],
                    datasets: [{
                        data: [
                            reportData.severity_breakdown.low_risk_count || 0,
                            reportData.severity_breakdown.medium_risk_count || 0,
                            reportData.severity_breakdown.high_risk_count || 0,
                            reportData.severity_breakdown.critical_count || 0
                        ],
                        backgroundColor: [
                            '#10b981',
                            '#f59e0b',
                            '#ef4444',
                            '#dc2626'
                        ],
                        borderWidth: 0,
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '60%',
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#ffffff',
                            bodyColor: '#ffffff',
                            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 = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }

        // Filter and sort functionality
        function applyFilters() {
            const riskFilter = document.getElementById('riskFilter').value;
            const sortBy = document.getElementById('sortBy').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            console.log('Applying filters:', { riskFilter, sortBy, startDate, endDate });
            
            // Build URL with filters
            const params = new URLSearchParams();
            if (riskFilter && riskFilter !== 'all') params.append('arrears_filter', riskFilter);
            if (sortBy && sortBy !== 'amount_desc') params.append('sort_by', sortBy);
            if (startDate) params.append('start_date', startDate);
            if (endDate) params.append('end_date', endDate);
            
            // Reload page with filters
            const newUrl = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
            console.log('Redirecting to:', newUrl);
            showNotification('Applying filters...', 'info');
            window.location.href = newUrl;
        }

        // Clear all filters
        function clearAllFilters() {
            // Show all rows
            const rows = document.querySelectorAll('#loansTableBody tr[data-loan-id]');
            rows.forEach(row => {
                row.style.display = '';
            });
            
            // Reset filter controls
            document.getElementById('riskFilter').value = '';
            document.getElementById('sortBy').value = 'amount_desc';
            document.getElementById('startDate').value = '';
            document.getElementById('endDate').value = '';
            
            showNotification('All filters cleared', 'success');
        }

        // Filter by product type
        function filterByProduct(productType) {
            console.log('Filtering by product type:', productType);
            
            const rows = document.querySelectorAll('#loansTableBody tr[data-loan-id]');
            let visibleCount = 0;
            
            rows.forEach(row => {
                const rowProductType = row.dataset.productType;
                const shouldShow = productType === 'all' || rowProductType === productType;
                
                if (shouldShow) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
            
            showNotification(`Showing ${visibleCount} ${productType === 'all' ? 'all' : productType} loans`, 'success');
        }

        // Filter by repayment method
        function filterByRepaymentMethod(method) {
            console.log('Filtering by repayment method:', method);
            
            const rows = document.querySelectorAll('#loansTableBody tr[data-loan-id]');
            let visibleCount = 0;
            
            rows.forEach(row => {
                const rowMethod = row.dataset.repaymentMethod;
                const shouldShow = method === 'all' || rowMethod === method;
                
                if (shouldShow) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
            
            showNotification(`Showing ${visibleCount} ${method === 'all' ? 'all' : method} repayment loans`, 'success');
        }

        // Filter by metric card click
        function filterByMetric(metric) {
            console.log('Filtering by metric:', metric);
            
            // Show notification
            showNotification('Applying filter...', 'info');
            
            // Apply client-side filtering
            const rows = document.querySelectorAll('#loansTableBody tr[data-loan-id]');
            let visibleCount = 0;
            
            rows.forEach(row => {
                const amount = parseFloat(row.dataset.amount) || 0;
                const daysOverdue = parseInt(row.dataset.daysOverdue) || 0;
                let shouldShow = true;
                
                switch(metric) {
                    case 'total_loans':
                        // Show all loans
                        shouldShow = true;
                        break;
                    case 'total_amount':
                        // Show high value loans (>50k)
                        shouldShow = amount >= 50000;
                        break;
                    case 'average_amount':
                        // Show medium risk loans (10k-50k)
                        shouldShow = amount >= 10000 && amount < 50000;
                        break;
                    case 'recovery_rate':
                        // Show all loans, prioritize by days overdue
                        shouldShow = true;
                        break;
                }
                
                if (shouldShow) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
            
            // Update the filter controls
            const riskFilter = document.getElementById('riskFilter');
            const sortBy = document.getElementById('sortBy');
            
            switch(metric) {
                case 'total_loans':
                    riskFilter.value = '';
                    sortBy.value = 'amount_desc';
                    break;
                case 'total_amount':
                    riskFilter.value = 'over_50k';
                    sortBy.value = 'amount_desc';
                    break;
                case 'average_amount':
                    riskFilter.value = '10k_50k';
                    sortBy.value = 'amount_asc';
                    break;
                case 'recovery_rate':
                    riskFilter.value = '';
                    sortBy.value = 'days_desc';
                    break;
            }
            
            // Show result count
            showNotification(`Showing ${visibleCount} loans`, 'success');
        }

        // Filter by risk level card click
        function filterByRisk(riskLevel) {
            console.log('Filtering by risk level:', riskLevel);
            
            // Show notification
            showNotification('Filtering by ' + riskLevel + ' risk...', 'info');
            
            // Apply client-side filtering
            const rows = document.querySelectorAll('#loansTableBody tr[data-loan-id]');
            let visibleCount = 0;
            
            rows.forEach(row => {
                const amount = parseFloat(row.dataset.amount) || 0;
                const daysOverdue = parseInt(row.dataset.daysOverdue) || 0;
                const severity = row.dataset.severity;
                let shouldShow = true;
                
                switch(riskLevel) {
                    case 'low':
                        // Low risk: amount < 10k
                        shouldShow = amount < 10000;
                        break;
                    case 'medium':
                        // Medium risk: 10k-50k
                        shouldShow = amount >= 10000 && amount < 50000;
                        break;
                    case 'high':
                        // High risk: amount >= 50k
                        shouldShow = amount >= 50000;
                        break;
                    case 'critical':
                        // Critical: > 90 days overdue
                        shouldShow = daysOverdue > 90;
                        break;
                }
                
                if (shouldShow) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
            
            // Update the filter controls
            const riskFilter = document.getElementById('riskFilter');
            const sortBy = document.getElementById('sortBy');
            
            switch(riskLevel) {
                case 'low':
                    riskFilter.value = 'under_10k';
                    sortBy.value = 'amount_asc';
                    break;
                case 'medium':
                    riskFilter.value = '10k_50k';
                    sortBy.value = 'amount_desc';
                    break;
                case 'high':
                    riskFilter.value = 'over_50k';
                    sortBy.value = 'amount_desc';
                    break;
                case 'critical':
                    riskFilter.value = '';
                    sortBy.value = 'days_desc';
                    break;
            }
            
            // Show result count
            showNotification(`Showing ${visibleCount} ${riskLevel} risk loans`, 'success');
        }

        // Show notification
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'info' ? 'var(--primary)' : type === 'success' ? 'var(--success)' : 'var(--danger)'};
                color: white;
                padding: 1rem 1.5rem;
                border-radius: 8px;
                box-shadow: var(--shadow);
                z-index: 10000;
                font-weight: 500;
                animation: slideInRight 0.3s ease-out;
            `;
            notification.textContent = message;
            
            // Add animation keyframes
            if (!document.getElementById('notification-styles')) {
                const style = document.createElement('style');
                style.id = 'notification-styles';
                style.textContent = `
                    @keyframes slideInRight {
                        from { transform: translateX(100%); opacity: 0; }
                        to { transform: translateX(0); opacity: 1; }
                    }
                `;
                document.head.appendChild(style);
            }
            
            document.body.appendChild(notification);
            
            // Remove after 3 seconds
            setTimeout(() => {
                notification.style.animation = 'slideInRight 0.3s ease-out reverse';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }

        // Export functions
        function exportToExcel() {
            showNotification('Preparing Excel export...', 'info');
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set('export', 'excel');
            window.location.href = currentUrl.toString();
        }

        function exportToPDF() {
            showNotification('Preparing PDF export...', 'info');
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set('export', 'pdf');
            window.location.href = currentUrl.toString();
        }

        // Update trend chart based on period selection
        function updateTrendChart() {
            const period = document.getElementById('trendPeriod').value;
            console.log('Updating trend chart for period:', period);
            
            // Destroy existing chart if it exists
            if (trendChart) {
                trendChart.destroy();
            }
            
            // Show loading message
            const trendCanvas = document.getElementById('trendChart');
            if (trendCanvas) {
                trendCanvas.parentElement.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: var(--text); font-style: italic;">Loading trend data for last ' + period + ' days...</div>';
                
                // Regenerate the chart with new data
                setTimeout(() => {
                    // Recreate the canvas element
                    trendCanvas.parentElement.innerHTML = '<canvas id="trendChart"></canvas>';
                    initTrendChart();
                }, 500);
            }
        }

        // Export functionality
        function exportData(format) {
            const params = new URLSearchParams(window.location.search);
            params.append('export', format);
            window.location.href = window.location.pathname + '?' + params.toString();
        }

        // Refresh dashboard
        function refreshDashboard() {
            showLoading();
            window.location.reload();
        }

        // Show loading spinner
        function showLoading() {
            document.getElementById('loadingSpinner').style.display = 'block';
        }

        // Hide loading spinner
        function hideLoading() {
            document.getElementById('loadingSpinner').style.display = 'none';
        }

        // Action functions
        function viewLoanDetails(loanId) {
            // Navigate to loan details page
            window.location.href = `/loans/${loanId}/`;
        }

        function contactBorrower(phoneNumber) {
            if (phoneNumber && phoneNumber !== 'N/A') {
                // Open phone dialer or copy to clipboard
                if (navigator.userAgent.match(/iPhone|iPad|iPod|Android/i)) {
                    window.location.href = `tel:${phoneNumber}`;
                } else {
                    navigator.clipboard.writeText(phoneNumber).then(() => {
                        alert('Phone number copied to clipboard: ' + phoneNumber);
                    });
                }
            } else {
                alert('No phone number available for this borrower');
            }
        }

        function recordPaymentArrears(loanId) {
            // Navigate to payment recording page
            console.log('Navigating to payment page for loan:', loanId);
            window.location.href = `/loans/${loanId}/repay/`;
        }

        // Initialize everything when page loads
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM loaded, initializing charts...');
            console.log('Report data:', reportData);
            
            // Wait a bit for Chart.js to fully load
            setTimeout(function() {
                try {
                    initCharts();
                    console.log('Charts initialized successfully');
                } catch (error) {
                    console.error('Error initializing charts:', error);
                    // Show a message if charts fail to load
                    const trendChart = document.getElementById('trendChart');
                    const riskChart = document.getElementById('riskChart');
                    if (trendChart) {
                        trendChart.style.display = 'none';
                        trendChart.parentElement.innerHTML += '<p style="text-align: center; color: var(--text); padding: 2rem;">Chart data unavailable</p>';
                    }
                    if (riskChart) {
                        riskChart.style.display = 'none';
                        riskChart.parentElement.innerHTML += '<p style="text-align: center; color: var(--text); padding: 2rem;">Chart data unavailable</p>';
                    }
                }
                hideLoading();
            }, 100);
        });
    </script>
</body>
</html>