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

{% block title %}Enhanced Portfolio Analytics{% endblock %}

{% block extra_css %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    .metric-card {
        transition: all 0.3s ease;
    }
    .metric-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    }
    .chart-container {
        position: relative;
        height: 300px;
    }
    .risk-alert {
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.7; }
        100% { opacity: 1; }
    }
    .performance-badge {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
    }
    .performance-excellent { background-color: #dcfce7; color: #166534; }
    .performance-good { background-color: #dbeafe; color: #1e40af; }
    .performance-average { background-color: #fef3c7; color: #92400e; }
    .performance-poor { background-color: #fee2e2; color: #991b1b; }
</style>
{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50">
    <!-- Enhanced Header with Real-time Updates -->
    <div class="bg-gradient-to-r from-purple-600 to-blue-600 text-white py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>📈</span>
                    </div>
                    <div>
                        <h1 class="text-3xl font-bold">Enhanced Portfolio Analytics</h1>
                        <p class="text-purple-100 mt-1">Advanced performance analysis with risk assessment and benchmarking</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <!-- Date Range Filter -->
                    <div class="bg-blue-100 bg-opacity-20 rounded-lg p-3">
                        <select id="dateRange" class="bg-transparent text-white border-none focus:outline-none" onchange="updateAnalytics()">
                            <option value="7">Last 7 days</option>
                            <option value="30" selected>Last 30 days</option>
                            <option value="90">Last 90 days</option>
                            <option value="365">Last year</option>
                        </select>
                    </div>
                    <!-- Client Performance Link -->
                    <a href="{% url 'users:client_performance_ranking' %}" class="bg-blue-100 bg-opacity-20 hover:bg-opacity-30 px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2">
                        <span>👥</span>
                        <span>Client Performance</span>
                    </a>
                    <!-- Benchmarking Link -->
                    <a href="{% url 'users:portfolio_benchmarking_dashboard' %}" class="bg-blue-100 bg-opacity-20 hover:bg-opacity-30 px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2">
                        <i class="fas fa-bullseye"></i>
                        <span>Benchmarking</span>
                    </a>
                    <!-- Export Button -->
                    <button onclick="exportAnalytics()" class="bg-blue-100 bg-opacity-20 hover:bg-opacity-30 px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2">
                        <span>⬇️</span>
                        <span>Export</span>
                    </button>
                    <!-- Refresh Button -->
                    <button onclick="refreshData()" class="bg-blue-100 bg-opacity-20 hover:bg-opacity-30 px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2">
                        <span>🔄</span>
                        <span>Refresh</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <!-- Risk Alerts Section -->
        {% if risk_alerts %}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-xl font-semibold text-gray-800 flex items-center">
                    <span>⚠️</span>
                    Risk Alerts & Notifications
                </h2>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {% for alert in risk_alerts %}
                    <div class="risk-alert border-l-4 {% if alert.type == 'danger' %}border-red-500 bg-red-50{% elif alert.type == 'warning' %}border-yellow-500 bg-yellow-50{% else %}border-blue-500 bg-blue-50{% endif %} p-4 rounded-r-lg">
                        <div class="flex items-start">
                            <div class="flex-shrink-0">
                                {% if alert.type == 'danger' %}
                                <span>⚠️</span>
                                {% elif alert.type == 'warning' %}
                                <span>⚠️</span>
                                {% else %}
                                <span>ℹ️</span>
                                {% endif %}
                            </div>
                            <div class="ml-3">
                                <h4 class="text-sm font-semibold {% if alert.type == 'danger' %}text-red-800{% elif alert.type == 'warning' %}text-yellow-800{% else %}text-blue-800{% endif %}">
                                    {{ alert.title }}
                                </h4>
                                <p class="text-sm {% if alert.type == 'danger' %}text-red-700{% elif alert.type == 'warning' %}text-yellow-700{% else %}text-blue-700{% endif %} mt-1">
                                    {{ alert.message }}
                                </p>
                                <div class="mt-2">
                                    <a href="{% url 'users:portfolio_manager_detail' alert.manager_id %}" 
                                       class="text-xs font-medium {% if alert.type == 'danger' %}text-red-600 hover:text-red-800{% elif alert.type == 'warning' %}text-yellow-600 hover:text-yellow-800{% else %}text-blue-600 hover:text-blue-800{% endif %}">
                                        View Details →
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Enhanced Key Metrics with Benchmarking -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="metric-card bg-gradient-to-br from-blue-500 to-blue-600 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-blue-100 text-sm font-medium">Total Portfolio Value</div>
                        <div class="text-2xl font-bold" id="portfolioValue">KES {{ total_portfolio_value|floatformat:0|default:"0" }}</div>
                        <div class="text-xs text-blue-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>📈</span>
                                {% if benchmarking_data.efficiency_metrics %}
                                Avg: KES {{ benchmarking_data.efficiency_metrics.avg_portfolio_per_manager|floatformat:0 }}
                                {% endif %}
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>💵</span>
                    </div>
                </div>
            </div>

            <div class="metric-card bg-gradient-to-br from-green-500 to-green-600 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-green-100 text-sm font-medium">Collection Rate</div>
                        <div class="text-2xl font-bold" id="collectionRate">{{ avg_collection_rate|floatformat:1|default:"0" }}%</div>
                        <div class="text-xs text-green-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>↑</span>
                                {% if portfolio_comparison.industry_benchmarks %}
                                Industry Avg: {{ portfolio_comparison.industry_benchmarks.avg_collection_rate|floatformat:1 }}%
                                {% endif %}
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <i class="fas fa-percentage text-xl"></i>
                    </div>
                </div>
            </div>

            <div class="metric-card bg-gradient-to-br from-purple-500 to-purple-600 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-purple-100 text-sm font-medium">Active Managers</div>
                        <div class="text-2xl font-bold" id="totalManagers">{{ total_managers|default:"0" }}</div>
                        <div class="text-xs text-purple-200 mt-1">
                            <span class="inline-flex items-center">
                                <span>👥</span>
                                {% if benchmarking_data.efficiency_metrics %}
                                Avg {{ benchmarking_data.efficiency_metrics.avg_clients_per_manager|floatformat:0 }} clients each
                                {% endif %}
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>👥</span>
                    </div>
                </div>
            </div>

            <div class="metric-card bg-gradient-to-br from-orange-500 to-red-500 text-white rounded-xl p-6 shadow-lg">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-orange-100 text-sm font-medium">Risk Level</div>
                        <div class="text-2xl font-bold" id="riskLevel">
                            {% if portfolio_comparison.risk_distribution %}
                            {{ portfolio_comparison.risk_distribution.high_risk }}
                            {% else %}0{% endif %}
                        </div>
                        <div class="text-xs text-orange-200 mt-1">
                            <span class="inline-flex items-center">
                                <i class="fas fa-shield-alt mr-1"></i>High risk managers
                            </span>
                        </div>
                    </div>
                    <div class="bg-white bg-opacity-20 p-3 rounded-full">
                        <span>⚠️</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance Trends Charts -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Collection Rate Trends -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <span>📈</span>
                        Collection Rate Trends
                    </h3>
                    <div class="flex space-x-2">
                        <button onclick="toggleChartType('collection')" class="text-sm text-gray-500 hover:text-gray-700">
                            <i class="fas fa-exchange-alt"></i>
                        </button>
                    </div>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="collectionTrendChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Risk Assessment Dashboard -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-shield-alt mr-3 text-red-500"></i>
                        Risk Assessment
                    </h3>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="riskAssessmentChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Client Performance Ranking and Analysis -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-xl font-semibold text-gray-800 flex items-center">
                    <span>🏆</span>
                    Portfolio Manager Performance Ranking
                </h2>
            </div>
            <div class="p-6">
                {% if manager_rankings %}
                <div class="space-y-4">
                    {% for manager in manager_rankings %}
                    <div class="flex items-center p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                        <!-- Enhanced Rank Badge -->
                        <div class="flex-shrink-0 mr-4">
                            {% if forloop.counter == 1 %}
                            <div class="w-12 h-12 bg-gradient-to-r from-yellow-400 to-yellow-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                <i class="fas fa-crown text-lg"></i>
                            </div>
                            {% elif forloop.counter == 2 %}
                            <div class="w-12 h-12 bg-gradient-to-r from-gray-400 to-gray-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                2
                            </div>
                            {% elif forloop.counter == 3 %}
                            <div class="w-12 h-12 bg-gradient-to-r from-orange-400 to-orange-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                3
                            </div>
                            {% else %}
                            <div class="w-12 h-12 bg-gradient-to-r from-blue-400 to-blue-500 rounded-full flex items-center justify-center text-white font-bold shadow-lg">
                                {{ forloop.counter }}
                            </div>
                            {% endif %}
                        </div>

                        <!-- Manager Info with Performance Badge -->
                        <div class="flex-1">
                            <div class="flex items-center justify-between">
                                <div>
                                    <div class="flex items-center space-x-3">
                                        <h3 class="font-semibold text-gray-900">{{ manager.manager.get_full_name }}</h3>
                                        {% if manager.performance_score >= 85 %}
                                        <span class="performance-badge performance-excellent">Excellent</span>
                                        {% elif manager.performance_score >= 70 %}
                                        <span class="performance-badge performance-good">Good</span>
                                        {% elif manager.performance_score >= 50 %}
                                        <span class="performance-badge performance-average">Average</span>
                                        {% else %}
                                        <span class="performance-badge performance-poor">Needs Improvement</span>
                                        {% endif %}
                                    </div>
                                    <p class="text-sm text-gray-600">{{ manager.manager.get_role_display }} • Risk Level: {{ manager.risk_level|title }}</p>
                                </div>
                                <div class="text-right">
                                    <div class="text-2xl font-bold text-gray-900">{{ manager.performance_score|floatformat:1 }}</div>
                                    <div class="text-sm text-gray-600">Performance Score</div>
                                </div>
                            </div>

                            <!-- Enhanced Performance Metrics Grid -->
                            <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mt-4">
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-blue-600">{{ manager.total_clients }}</div>
                                    <div class="text-xs text-gray-600">Clients</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-green-600">{{ manager.active_loans }}</div>
                                    <div class="text-xs text-gray-600">Active Loans</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-purple-600">{{ manager.collection_rate|floatformat:1 }}%</div>
                                    <div class="text-xs text-gray-600">Collection Rate</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold {% if manager.default_rate > 5 %}text-red-600{% else %}text-orange-600{% endif %}">{{ manager.default_rate|floatformat:1 }}%</div>
                                    <div class="text-xs text-gray-600">Default Rate</div>
                                </div>
                                <div class="text-center">
                                    <div class="text-lg font-semibold text-indigo-600">KES {{ manager.total_outstanding|floatformat:0 }}</div>
                                    <div class="text-xs text-gray-600">Outstanding</div>
                                </div>
                            </div>

                            <!-- Performance Progress Bars -->
                            <div class="grid grid-cols-2 gap-4 mt-4">
                                <div>
                                    <div class="flex justify-between text-sm mb-1">
                                        <span class="text-gray-600">Collection Rate</span>
                                        <span class="font-semibold">{{ manager.collection_rate|floatformat:1 }}%</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-green-500 h-2 rounded-full" style="width: {{ manager.collection_rate }}%"></div>
                                    </div>
                                </div>
                                <div>
                                    <div class="flex justify-between text-sm mb-1">
                                        <span class="text-gray-600">Performance Score</span>
                                        <span class="font-semibold">{{ manager.performance_score|floatformat:1 }}</span>
                                    </div>
                                    <div class="w-full bg-gray-200 rounded-full h-2">
                                        <div class="bg-blue-500 h-2 rounded-full" style="width: {{ manager.performance_score }}%"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Action Button -->
                        <div class="flex-shrink-0 ml-4">
                            <a href="{% url 'users:portfolio_manager_detail' manager.manager.id %}" 
                               class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-colors">
                                View Details
                            </a>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="text-center py-12">
                    <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <span>📈</span>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900 mb-2">No Analytics Data</h3>
                    <p class="text-gray-600">No portfolio manager data available for analysis.</p>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- Portfolio Comparison and Benchmarking -->
        {% if portfolio_comparison and benchmarking_data %}
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Performance Distribution -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <span>📊</span>
                        Performance Distribution
                    </h3>
                </div>
                <div class="p-6">
                    <div class="chart-container">
                        <canvas id="performanceDistributionChart"></canvas>
                    </div>
                    <div class="grid grid-cols-2 gap-4 mt-4">
                        <div class="text-center">
                            <div class="text-2xl font-bold text-green-600">{{ portfolio_comparison.performance_distribution.excellent }}</div>
                            <div class="text-sm text-gray-600">Excellent (95%+)</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-blue-600">{{ portfolio_comparison.performance_distribution.good }}</div>
                            <div class="text-sm text-gray-600">Good (85-94%)</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-yellow-600">{{ portfolio_comparison.performance_distribution.average }}</div>
                            <div class="text-sm text-gray-600">Average (70-84%)</div>
                        </div>
                        <div class="text-center">
                            <div class="text-2xl font-bold text-red-600">{{ portfolio_comparison.performance_distribution.poor }}</div>
                            <div class="text-sm text-gray-600">Poor (<70%)</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Benchmarking Insights -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-bullseye mr-3 text-indigo-500"></i>
                        Benchmarking Insights
                    </h3>
                </div>
                <div class="p-6 space-y-6">
                    <!-- Top Performers -->
                    {% if benchmarking_data.top_performers %}
                    <div>
                        <h4 class="font-semibold text-gray-800 mb-3 flex items-center">
                            <span>⭐</span>
                            Top Performers
                        </h4>
                        <div class="space-y-2">
                            {% for performer in benchmarking_data.top_performers %}
                            <div class="flex items-center justify-between p-2 bg-green-50 rounded-lg">
                                <span class="text-sm font-medium text-gray-900">{{ performer.manager.get_full_name }}</span>
                                <span class="text-sm font-bold text-green-600">{{ performer.performance_score|floatformat:1 }}</span>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}

                    <!-- Improvement Opportunities -->
                    {% if benchmarking_data.improvement_opportunities %}
                    <div>
                        <h4 class="font-semibold text-gray-800 mb-3 flex items-center">
                            <span>↑</span>
                            Improvement Opportunities
                        </h4>
                        <div class="space-y-2">
                            {% for opportunity in benchmarking_data.improvement_opportunities|slice:":3" %}
                            <div class="flex items-center justify-between p-2 bg-blue-50 rounded-lg">
                                <span class="text-sm font-medium text-gray-900">{{ opportunity.manager.get_full_name }}</span>
                                <span class="text-sm font-bold text-blue-600">{{ opportunity.collection_rate|floatformat:1 }}%</span>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}

                    <!-- Risk Managers -->
                    {% if benchmarking_data.risk_managers %}
                    <div>
                        <h4 class="font-semibold text-gray-800 mb-3 flex items-center">
                            <span>⚠️</span>
                            High Risk Portfolios
                        </h4>
                        <div class="space-y-2">
                            {% for risk_manager in benchmarking_data.risk_managers|slice:":3" %}
                            <div class="flex items-center justify-between p-2 bg-red-50 rounded-lg">
                                <span class="text-sm font-medium text-gray-900">{{ risk_manager.manager.get_full_name }}</span>
                                <span class="text-sm font-bold text-red-600">{{ risk_manager.default_rate|floatformat:1 }}%</span>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Performance Comparison Chart -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                    <span>📊</span>
                    Manager Performance Comparison
                </h3>
            </div>
            <div class="p-6">
                <div class="chart-container" style="height: 400px;">
                    <canvas id="performanceChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Global chart instances
let collectionChart, riskChart, distributionChart, performanceChart, performanceDistributionChart;

// Get real data from Django context
const chartData = {{ chart_data|safe }};
const portfolioComparison = {{ portfolio_comparison|safe }};

document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    setupEventListeners();
});

function initializeCharts() {
    // Collection Rate Trends Chart
    const collectionCtx = document.getElementById('collectionTrendChart').getContext('2d');
    collectionChart = new Chart(collectionCtx, {
        type: 'line',
        data: {
            labels: chartData.manager_names,
            datasets: [{
                label: 'Collection Rate (%)',
                data: chartData.collection_rates,
                borderColor: 'rgb(34, 197, 94)',
                backgroundColor: 'rgba(34, 197, 94, 0.1)',
                tension: 0.4,
                fill: true,
                pointBackgroundColor: 'rgb(34, 197, 94)',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    min: 0,
                    max: 100,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.1)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            }
        }
    });

    // Risk Assessment Chart
    const riskCtx = document.getElementById('riskAssessmentChart').getContext('2d');
    riskChart = new Chart(riskCtx, {
        type: 'doughnut',
        data: {
            labels: ['Low Risk', 'Medium Risk', 'High Risk'],
            datasets: [{
                data: [
                    portfolioComparison.risk_distribution?.low_risk || 0,
                    portfolioComparison.risk_distribution?.medium_risk || 0,
                    portfolioComparison.risk_distribution?.high_risk || 0
                ],
                backgroundColor: [
                    'rgb(34, 197, 94)',
                    'rgb(251, 191, 36)',
                    'rgb(239, 68, 68)'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // Performance Distribution Chart
    const perfDistCtx = document.getElementById('performanceDistributionChart').getContext('2d');
    performanceDistributionChart = new Chart(perfDistCtx, {
        type: 'pie',
        data: {
            labels: ['Excellent', 'Good', 'Average', 'Poor'],
            datasets: [{
                data: [
                    portfolioComparison.performance_distribution?.excellent || 0,
                    portfolioComparison.performance_distribution?.good || 0,
                    portfolioComparison.performance_distribution?.average || 0,
                    portfolioComparison.performance_distribution?.poor || 0
                ],
                backgroundColor: [
                    'rgb(34, 197, 94)',
                    'rgb(59, 130, 246)',
                    'rgb(251, 191, 36)',
                    'rgb(239, 68, 68)'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });

    // Performance Comparison Chart
    const performanceCtx = document.getElementById('performanceChart').getContext('2d');
    performanceChart = new Chart(performanceCtx, {
        type: 'bar',
        data: {
            labels: chartData.manager_names,
            datasets: [{
                label: 'Collection Rate (%)',
                data: chartData.collection_rates,
                backgroundColor: 'rgba(34, 197, 94, 0.8)',
                borderColor: 'rgb(34, 197, 94)',
                borderWidth: 1
            }, {
                label: 'Performance Score',
                data: chartData.performance_scores,
                backgroundColor: 'rgba(59, 130, 246, 0.8)',
                borderColor: 'rgb(59, 130, 246)',
                borderWidth: 1,
                yAxisID: 'y1'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top'
                }
            },
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    beginAtZero: true,
                    max: 100,
                    title: {
                        display: true,
                        text: 'Collection Rate (%)'
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    beginAtZero: true,
                    max: 100,
                    title: {
                        display: true,
                        text: 'Performance Score'
                    },
                    grid: {
                        drawOnChartArea: false,
                    },
                }
            }
        }
    });
}

function setupEventListeners() {
    // Date range change listener
    document.getElementById('dateRange').addEventListener('change', updateAnalytics);
}

function updateAnalytics() {
    const dateRange = document.getElementById('dateRange').value;
    
    // Show loading state
    showLoadingState();
    
    // In a real implementation, make AJAX call to update data
    // For now, simulate loading
    setTimeout(() => {
        hideLoadingState();
    }, 1000);
}

function toggleChartType(chartType) {
    if (chartType === 'collection') {
        collectionChart.config.type = collectionChart.config.type === 'line' ? 'bar' : 'line';
        collectionChart.update();
    }
}

function refreshData() {
    const refreshIcon = document.getElementById('refreshIcon');
    refreshIcon.classList.add('fa-spin');
    
    updateAnalytics();
    
    setTimeout(() => {
        refreshIcon.classList.remove('fa-spin');
    }, 2000);
}

function exportAnalytics() {
    // Create comprehensive export data
    const exportData = {
        timestamp: new Date().toISOString(),
        metrics: {
            portfolioValue: document.getElementById('portfolioValue').textContent,
            totalManagers: document.getElementById('totalManagers').textContent,
            collectionRate: document.getElementById('collectionRate').textContent,
            riskLevel: document.getElementById('riskLevel').textContent
        },
        chartData: chartData,
        portfolioComparison: portfolioComparison
    };
    
    // Download as JSON
    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `enhanced_portfolio_analytics_${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
}

function showLoadingState() {
    document.querySelectorAll('.metric-card').forEach(card => {
        card.style.opacity = '0.7';
    });
}

function hideLoadingState() {
    document.querySelectorAll('.metric-card').forEach(card => {
        card.style.opacity = '1';
    });
}
</script>
{% endblock %}