{% extends "layouts/base.html" %}
{% load i18n %}

{% block title %}{% trans "Physician Ratings Dashboard" %} - PX360{% endblock %}

{% block extra_css %}
<style>
    :root {
        --hh-navy: #005696;
        --hh-blue: #007bbd;
        --hh-light: #eef6fb;
        --hh-slate: #64748b;
        --hh-success: #10b981;
        --hh-warning: #f59e0b;
        --hh-danger: #ef4444;
        --hh-shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --hh-shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        --hh-shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
    }

    /* Page Header */
    .page-header {
        background: linear-gradient(135deg, var(--hh-navy) 0%, #0069a8 50%, var(--hh-blue) 100%);
        color: white;
        padding: 2rem 2.5rem;
        border-radius: 1rem;
        margin-bottom: 2rem;
        box-shadow: var(--hh-shadow-lg);
        position: relative;
        overflow: hidden;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 200px;
        height: 200px;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
        pointer-events: none;
    }

    .page-header h1 {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 0.75rem;
        letter-spacing: -0.025em;
    }

    .page-header p {
        color: rgba(255,255,255,0.9);
        font-size: 1rem;
    }

    /* Stat Cards */
    .stat-card {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        box-shadow: var(--hh-shadow-md);
        border: 1px solid #e2e8f0;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        height: 100%;
        position: relative;
        overflow: hidden;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, var(--hh-navy), var(--hh-blue));
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    .stat-card:hover {
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        border-color: var(--hh-blue);
        transform: translateY(-4px);
    }

    .stat-card:hover::before {
        opacity: 1;
    }

    .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 1rem;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 1rem;
        position: relative;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease;
    }

    .stat-card:hover .stat-icon {
        transform: scale(1.1) rotate(3deg);
    }

    .stat-icon.bg-navy {
        background: linear-gradient(135deg, #005696, #007bbd);
        color: white;
    }

    .stat-icon.bg-yellow {
        background: linear-gradient(135deg, #f59e0b, #fbbf24);
        color: white;
    }

    .stat-icon.bg-green {
        background: linear-gradient(135deg, #10b981, #34d399);
        color: white;
    }

    .stat-icon.bg-purple {
        background: linear-gradient(135deg, #8b5cf6, #a78bfa);
        color: white;
    }

    .stat-value {
        font-size: 2rem;
        font-weight: 800;
        color: #1e293b;
        margin-bottom: 0.25rem;
        line-height: 1;
    }

    .stat-label {
        color: #64748b;
        font-size: 0.875rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }

    /* Chart Cards */
    .chart-card {
        background: white;
        border-radius: 1rem;
        border: 1px solid #e2e8f0;
        overflow: hidden;
        box-shadow: var(--hh-shadow-md);
        transition: all 0.3s ease;
    }

    .chart-card:hover {
        box-shadow: var(--hh-shadow-lg);
    }

    .chart-card .card-header {
        background: linear-gradient(135deg, var(--hh-light), #e0f2fe);
        padding: 1.25rem 1.75rem;
        border-bottom: 1px solid #bae6fd;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .chart-card .card-header h5 {
        color: var(--hh-navy);
        font-weight: 700;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        font-size: 1.1rem;
        margin: 0;
    }

    /* Form Controls */
    .form-select {
        border: 1px solid #cbd5e1;
        border-radius: 0.5rem;
        padding: 0.625rem 0.875rem;
        font-size: 0.875rem;
        transition: all 0.2s;
        background: white;
    }

    .form-select:focus {
        border-color: var(--hh-blue);
        box-shadow: 0 0 0 3px rgba(0, 123, 189, 0.1);
        outline: none;
    }

    /* Loading State */
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.9);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }

    .loading-overlay.active {
        display: flex;
    }

    /* Animations */
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .animate-in {
        animation: fadeIn 0.5s ease-out forwards;
    }
</style>
{% endblock %}

{% block content %}
<div class="px-4 py-6">
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="text-center">
            <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-navy"></div>
            <p class="mt-2 text-gray-600">{% trans "Loading dashboard data..." %}</p>
        </div>
    </div>

    <!-- Page Header -->
    <div class="page-header">
        <h1>
            <i data-lucide="star" class="w-8 h-8 inline-block me-2"></i>
            {% trans "Physician Ratings Dashboard" %}
        </h1>
        <p class="mb-0">{% trans "Comprehensive physician performance analytics and insights" %}</p>
    </div>

    <!-- Filter Panel -->
    <div class="bg-white rounded-2xl shadow-sm border border-slate-100 mb-6">
        <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center">
            <h3 class="font-bold text-gray-800 flex items-center gap-2">
                <i data-lucide="filter" class="w-5 h-5 text-navy"></i>
                {% trans "Filters" %}
            </h3>
            <button type="button" id="toggleFilters" class="text-gray-400 hover:text-gray-600 transition">
                <i data-lucide="chevron-down" class="w-5 h-5"></i>
            </button>
        </div>
        <div id="filterContent" class="px-6 py-4">
            <form id="filterForm" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">{% trans "Year" %}</label>
                    <select name="year" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
                        {% for y in years %}
                        <option value="{{ y }}" {% if filters.year == y|stringformat:"s" %}selected{% endif %}>{{ y }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">{% trans "Month" %}</label>
                    <select name="month" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition">
                        {% for m in "123456789012"|make_list %}
                        <option value="{{ forloop.counter }}" {% if filters.month == forloop.counter|stringformat:"s" %}selected{% endif %}>
                            {{ forloop.counter|stringformat:"02d" }}
                        </option>
                        {% endfor %}
                    </select>
                 </div>
                 <div>
                     <label class="block text-sm font-bold text-gray-700 mb-2">{% trans "Department" %}</label>
                    <select name="department" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-navy/20 focus:border-navy outline-none transition" data-tomselect>
                        <option value="">{% trans "All Departments" %}</option>
                        {% for department in departments %}
                        <option value="{{ department.id }}" {% if filters.department == department.id|stringformat:"s" %}selected{% endif %}>
                            {{ department.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                <div class="flex items-end">
                    <button type="submit" class="w-full px-6 py-2.5 bg-navy text-white rounded-xl font-semibold shadow-md hover:bg-blue transition flex items-center justify-center gap-2">
                        <i data-lucide="search" class="w-4 h-4"></i>
                        {% trans "Apply" %}
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="stat-card animate-in">
            <div class="flex items-start justify-between">
                <div>
                    <p class="stat-label">{% trans "Total Physicians" %}</p>
                    <p class="stat-value" id="totalPhysicians">-</p>
                    <p class="text-sm text-slate mt-1">{% trans "Active ratings" %}</p>
                </div>
                <div class="stat-icon bg-navy">
                    <i data-lucide="users" class="w-6 h-6"></i>
                </div>
            </div>
        </div>

        <div class="stat-card animate-in">
            <div class="flex items-start justify-between">
                <div>
                    <p class="stat-label">{% trans "Average Rating" %}</p>
                    <p class="stat-value text-green-600" id="avgRating">-</p>
                    <p class="text-sm text-slate mt-1">{% trans "Across all physicians" %}</p>
                </div>
                <div class="stat-icon bg-green">
                    <i data-lucide="star" class="w-6 h-6"></i>
                </div>
            </div>
        </div>

        <div class="stat-card animate-in">
            <div class="flex items-start justify-between">
                <div>
                    <p class="stat-label">{% trans "Total Surveys" %}</p>
                    <p class="stat-value" id="totalSurveys">-</p>
                    <p class="text-sm text-slate mt-1">{% trans "This period" %}</p>
                </div>
                <div class="stat-icon bg-purple">
                    <i data-lucide="file-text" class="w-6 h-6"></i>
                </div>
            </div>
        </div>

        <div class="stat-card animate-in">
            <div class="flex items-start justify-between">
                <div>
                    <p class="stat-label">{% trans "Excellent (4.5+)" %}</p>
                    <p class="stat-value text-yellow-600" id="excellentCount">-</p>
                    <p class="text-sm text-slate mt-1">{% trans "Top performers" %}</p>
                </div>
                <div class="stat-icon bg-yellow">
                    <i data-lucide="award" class="w-6 h-6"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Empty State Alert -->
    <div id="emptyStateAlert" class="hidden bg-amber-50 border-2 border-amber-200 rounded-2xl p-6 mb-6">
        <div class="flex items-start gap-4">
            <div class="w-12 h-12 rounded-xl bg-amber-100 flex items-center justify-center flex-shrink-0">
                <i data-lucide="info" class="w-6 h-6 text-amber-600"></i>
            </div>
            <div class="flex-1">
                <h3 class="font-bold text-amber-900 mb-1">{% trans "No Rating Data Available" %}</h3>
                <p class="text-amber-700 text-sm mb-3">
                    {% trans "There are no physician ratings for the selected period. Physician ratings are automatically calculated from patient survey responses." %}
                </p>
                <div class="flex gap-3">
                    <a href="{% url 'physicians:doctor_rating_import' %}" class="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition font-semibold text-sm">
                        <i data-lucide="upload" class="w-4 h-4 inline-block mr-1"></i>
                        {% trans "Import Ratings" %}
                    </a>
                    <a href="{% url 'physicians:leaderboard' %}" class="px-4 py-2 bg-white text-amber-700 border border-amber-300 rounded-lg hover:bg-amber-50 transition font-semibold text-sm">
                        <i data-lucide="trophy" class="w-4 h-4 inline-block mr-1"></i>
                        {% trans "View Leaderboard" %}
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 1 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- Rating Trend -->
        <div class="chart-card">
            <div class="card-header">
                <h5>
                    <i data-lucide="trending-up" class="w-5 h-5"></i>
                    {% trans "Rating Trend (6 Months)" %}
                </h5>
            </div>
            <div class="p-4">
                <div id="ratingTrendChart" style="min-height: 350px;"></div>
            </div>
        </div>

        <!-- Rating Distribution -->
        <div class="chart-card">
            <div class="card-header">
                <h5>
                    <i data-lucide="circle-help" class="w-5 h-5"></i>
                    {% trans "Rating Distribution" %}
                </h5>
            </div>
            <div class="p-4">
                <div id="distributionChart" style="min-height: 350px;"></div>
            </div>
        </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
        <!-- Department Comparison -->
        <div class="chart-card lg:col-span-2">
            <div class="card-header">
                <h5>
                    <i data-lucide="circle-help" class="w-5 h-5"></i>
                    {% trans "Top Departments by Rating" %}
                </h5>
            </div>
            <div class="p-4">
                <div id="departmentChart" style="min-height: 350px;"></div>
            </div>
        </div>

        <!-- Sentiment Breakdown -->
        <div class="chart-card">
            <div class="card-header">
                <h5>
                    <i data-lucide="pie-chart" class="w-5 h-5"></i>
                    {% trans "Sentiment Analysis" %}
                </h5>
            </div>
            <div class="p-4">
                <div id="sentimentChart" style="min-height: 350px;"></div>
            </div>
        </div>
    </div>

    <!-- Top Physicians Table -->
    <div class="chart-card mb-6">
        <div class="card-header">
            <h5>
                <i data-lucide="trophy" class="w-5 h-5"></i>
                {% trans "Top 10 Physicians" %}
            </h5>
            <a href="{% url 'physicians:leaderboard' %}" class="text-sm font-semibold text-navy hover:text-blue transition flex items-center gap-1">
                {% trans "View Full Leaderboard" %}
                <i data-lucide="arrow-right" class="w-4 h-4"></i>
            </a>
        </div>
        <div class="p-0 overflow-x-auto">
            <table class="w-full">
                <thead class="bg-slate-50 border-b border-slate-200">
                    <tr>
                        <th class="px-6 py-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Rank" %}</th>
                        <th class="px-6 py-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Physician" %}</th>
                        <th class="px-6 py-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Specialization" %}</th>
                        <th class="px-6 py-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Department" %}</th>
                        <th class="px-6 py-4 text-left font-bold text-navy text-xs uppercase tracking-wider">{% trans "Hospital" %}</th>
                        <th class="px-6 py-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "Rating" %}</th>
                        <th class="px-6 py-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "Surveys" %}</th>
                        <th class="px-6 py-4 text-center font-bold text-navy text-xs uppercase tracking-wider">{% trans "Actions" %}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100" id="topPhysiciansTable">
                    <tr>
                        <td colspan="8" class="px-6 py-12 text-center">
                            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-navy"></div>
                            <p class="text-slate mt-2">{% trans "Loading..." %}</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // PX360 Theme Colors
    const hhColors = {
        navy: '#005696',
        blue: '#007bbd',
        light: '#eef6fb',
        slate: '#64748b',
        success: '#10b981',
        warning: '#f59e0b',
        danger: '#ef4444',
        purple: '#8b5cf6'
    };

    let charts = {};

    // Initialize dashboard
    document.addEventListener('DOMContentLoaded', function() {
        lucide.createIcons();
        loadDashboardData();

        // Toggle filters
        document.getElementById('toggleFilters').addEventListener('click', function() {
            const content = document.getElementById('filterContent');
            const icon = this.querySelector('i');
            if (content.classList.contains('hidden')) {
                content.classList.remove('hidden');
                icon.setAttribute('data-lucide', 'chevron-down');
            } else {
                content.classList.add('hidden');
                icon.setAttribute('data-lucide', 'chevron-up');
            }
            lucide.createIcons();
        });
    });

    // Load dashboard data
    function loadDashboardData() {
        showLoading();

        const form = document.getElementById('filterForm');
        const formData = new FormData(form);
        const params = new URLSearchParams(formData);

        fetch(`/physicians/api/dashboard/?${params.toString()}`)
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(`HTTP ${response.status}: ${text.substring(0, 200)}`);
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('Dashboard data received:', data);
                updateStatistics(data.statistics);
                updateRatingTrendChart(data.trend);
                updateDistributionChart(data.distribution);
                updateDepartmentChart(data.rating_groups);
                updateSentimentChart(data.sentiment);
                updateTopPhysiciansTable(data.top_physicians);
                hideLoading();
            })
            .catch(error => {
                console.error('Error loading dashboard:', error);
                hideLoading();
                alert(`Error loading dashboard data: ${error.message}\n\nPlease check the browser console for more details.`);
            });
    }

    // Update statistics cards
    function updateStatistics(stats) {
        document.getElementById('totalPhysicians').textContent = stats.total_physicians || 0;
        document.getElementById('avgRating').textContent = Math.round((stats.average_rating || 0) * 10) / 10;
        document.getElementById('totalSurveys').textContent = (stats.total_surveys || 0).toLocaleString();
        document.getElementById('excellentCount').textContent = stats.excellent_count || 0;

        // Show empty state if no data
        const emptyStateAlert = document.getElementById('emptyStateAlert');
        if (stats.total_physicians === 0 || stats.total_surveys === 0) {
            emptyStateAlert.classList.remove('hidden');
        } else {
            emptyStateAlert.classList.add('hidden');
        }
    }

    // Rating Trend Chart
    function updateRatingTrendChart(trendData) {
        const options = {
            series: [{
                name: '{% trans "Average Rating" %}',
                data: trendData.map(item => item.average_rating)
            }],
            chart: {
                type: 'area',
                height: 350,
                fontFamily: 'Inter, sans-serif',
                toolbar: { show: false },
                animations: { enabled: true }
            },
            colors: [hhColors.blue],
            dataLabels: { enabled: true, style: { fontSize: '11px' } },
            stroke: { curve: 'smooth', width: 3 },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.4,
                    opacityTo: 0.1,
                    stops: [0, 100]
                }
            },
            xaxis: {
                categories: trendData.map(item => item.period),
                labels: { style: { fontSize: '12px', colors: hhColors.slate } }
            },
            yaxis: {
                min: 0,
                max: 5,
                labels: {
                    style: { fontSize: '12px', colors: hhColors.slate },
                    formatter: value => Math.round(value * 10) / 10
                }
            },
            grid: {
                borderColor: '#e2e8f0',
                strokeDashArray: 4
            },
            tooltip: {
                theme: 'light',
                y: {
                    formatter: value => Math.round(value * 10) / 10
                }
            }
        };

        if (charts.ratingTrend) {
            charts.ratingTrend.destroy();
        }
        charts.ratingTrend = new ApexCharts(document.querySelector("#ratingTrendChart"), options);
        charts.ratingTrend.render();
    }

    // Distribution Chart
    function updateDistributionChart(distData) {
        const options = {
            series: [
                distData.excellent || 0,
                distData.good || 0,
                distData.average || 0,
                distData.poor || 0
            ],
            chart: {
                type: 'donut',
                height: 350,
                fontFamily: 'Inter, sans-serif',
                toolbar: { show: false }
            },
            labels: ['Excellent (4.5+)', 'Good (3.5-4.5)', 'Average (2.5-3.5)', 'Poor (<2.5)'],
            colors: [hhColors.success, hhColors.blue, hhColors.warning, hhColors.danger],
            plotOptions: {
                pie: {
                    donut: {
                        size: '65%',
                        labels: {
                            show: true,
                            name: { fontSize: '14px', fontWeight: 600 },
                            value: { fontSize: '20px', fontWeight: 700, formatter: val => parseInt(val).toLocaleString() },
                            total: {
                                show: true,
                                label: 'Total',
                                fontSize: '14px',
                                formatter: w => w.globals.seriesTotals.reduce((a, b) => a + b, 0).toLocaleString()
                            }
                        }
                    }
                }
            },
            dataLabels: { enabled: false },
            legend: { position: 'bottom', fontSize: '12px' }
        };

        if (charts.distribution) {
            charts.distribution.destroy();
        }
        charts.distribution = new ApexCharts(document.querySelector("#distributionChart"), options);
        charts.distribution.render();
    }

    // Department Rating Groups (1-5)
    function updateDepartmentChart(ratingGroups) {
        const container = document.querySelector("#departmentChart");
        const ratingColors = {
            5: { bg: '#ecfdf5', border: '#10b981', text: '#065f46', badge: '#10b981' },
            4: { bg: '#eff6ff', border: '#007bbd', text: '#1e3a5f', badge: '#007bbd' },
            3: { bg: '#fffbeb', border: '#f59e0b', text: '#78350f', badge: '#f59e0b' },
            2: { bg: '#fff7ed', border: '#f97316', text: '#7c2d12', badge: '#f97316' },
            1: { bg: '#fef2f2', border: '#ef4444', text: '#7f1d1d', badge: '#ef4444' },
        };

        function renderStars(count) {
            var filled = '<i data-lucide="star" class="w-4 h-4 inline fill-current"></i>';
            var empty = '<i data-lucide="star" class="w-4 h-4 inline"></i>';
            var html = '';
            for (var i = 0; i < 5; i++) {
                html += i < count ? filled : empty;
            }
            return html;
        }

        var hasData = false;
        for (var r = 5; r >= 1; r--) {
            if (ratingGroups[r] && ratingGroups[r].length > 0) hasData = true;
        }

        if (!hasData) {
            container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;min-height:350px;color:#94a3b8;font-size:14px;">{% trans "No department data available for this period" %}</div>';
            return;
        }

        var html = '';
        for (var rating = 5; rating >= 1; rating--) {
            var depts = ratingGroups[rating] || [];
            var colors = ratingColors[rating];
            var countLabel = depts.length === 1 ? '{% trans "department" %}' : '{% trans "departments" %}';
            html += '<div style="background:' + colors.bg + ';border-left:4px solid ' + colors.border + ';border-radius:8px;padding:12px 16px;margin-bottom:10px;">';
            html += '<div style="display:flex;align-items:center;gap:10px;margin-bottom:' + (depts.length > 0 ? '10px' : '0') + ';">';
            html += '<span style="color:' + colors.badge + ';display:flex;align-items:center;gap:2px;">' + renderStars(rating) + '</span>';
            html += '<span style="font-weight:700;font-size:14px;color:' + colors.text + ';">' + rating + '</span>';
            html += '<span style="font-size:12px;color:' + colors.text + ';opacity:0.8;">(' + depts.length + ' ' + countLabel + ')</span>';
            html += '</div>';
            if (depts.length > 0) {
                html += '<div style="display:flex;flex-wrap:wrap;gap:6px;">';
                depts.forEach(function(dept) {
                    html += '<div style="background:white;border-radius:6px;padding:6px 10px;font-size:12px;color:#334155;box-shadow:0 1px 2px rgba(0,0,0,0.05);" title="{% trans "Rating" %}: ' + dept.average_rating + ' | {% trans "Surveys" %}: ' + (dept.total_surveys || 0) + ' | {% trans "Physicians" %}: ' + (dept.physician_count || 0) + '">';
                    html += dept.name;
                    html += ' <span style="color:#64748b;font-weight:500;">' + dept.average_rating + '</span>';
                    html += '</div>';
                });
                html += '</div>';
            }
            html += '</div>';
        }

        container.innerHTML = html;
        lucide.createIcons();
    }

    // Sentiment Chart
    function updateSentimentChart(sentimentData) {
        const options = {
            series: [
                sentimentData.positive || 0,
                sentimentData.neutral || 0,
                sentimentData.negative || 0
            ],
            chart: {
                type: 'pie',
                height: 350,
                fontFamily: 'Inter, sans-serif',
                toolbar: { show: false }
            },
            labels: ['Positive', 'Neutral', 'Negative'],
            colors: [hhColors.success, hhColors.warning, hhColors.danger],
            plotOptions: {
                pie: {
                    expandOnClick: true
                }
            },
            dataLabels: {
                enabled: true,
                formatter: val => val.toFixed(1) + '%'
            },
            legend: { position: 'bottom', fontSize: '12px' },
            tooltip: {
                theme: 'light',
                y: { formatter: val => val.toLocaleString() }
            }
        };

        if (charts.sentiment) {
            charts.sentiment.destroy();
        }
        charts.sentiment = new ApexCharts(document.querySelector("#sentimentChart"), options);
        charts.sentiment.render();
    }

    // Update Top Physicians Table
    function updateTopPhysiciansTable(physicians) {
        const tbody = document.getElementById('topPhysiciansTable');
        
        if (!physicians || physicians.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="8" class="px-6 py-12 text-center">
                        <i data-lucide="inbox" class="w-12 h-12 text-slate-300 mx-auto mb-3"></i>
                        <p class="text-slate">{% trans "No physicians found" %}</p>
                    </td>
                </tr>
            `;
            lucide.createIcons();
            return;
        }

        tbody.innerHTML = physicians.map((physician, index) => {
            const rankClass = index === 0 ? 'bg-yellow-100 text-yellow-700' : 
                             index === 1 ? 'bg-slate-200 text-slate-700' : 
                             index === 2 ? 'bg-orange-100 text-orange-700' : 'bg-light text-navy';
            const rankIcon = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : `#${index + 1}`;
            
            return `
                <tr class="hover:bg-slate-50 transition cursor-pointer" onclick="window.location.href='/physicians/${physician.id}/'">
                    <td class="px-6 py-4">
                        <span class="inline-flex items-center justify-center w-10 h-10 rounded-full font-bold text-sm ${rankClass}">
                            ${rankIcon}
                        </span>
                    </td>
                    <td class="px-6 py-4">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-lg bg-blue/10 flex items-center justify-center">
                                <i data-lucide="user" class="w-5 h-5 text-blue"></i>
                            </div>
                            <div>
                                <p class="font-bold text-navy">${physician.name}</p>
                                <p class="text-xs text-slate">${physician.license_number}</p>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-sm text-slate">${physician.specialization || '-'}</td>
                    <td class="px-6 py-4 text-sm text-slate">${physician.department || '-'}</td>
                    <td class="px-6 py-4 text-sm text-slate">${physician.hospital}</td>
                    <td class="px-6 py-4 text-center">
                        <div class="flex items-center justify-center gap-1">
                            <i data-lucide="star" class="w-4 h-4 text-yellow-500 fill-yellow-500"></i>
                            <span class="font-bold text-lg text-green-600">${Math.round(physician.rating * 10) / 10}</span>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-center">
                        <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-slate-100 text-slate-700">
                            ${physician.surveys.toLocaleString()}
                        </span>
                    </td>
                    <td class="px-6 py-4 text-center">
                        <a href="/physicians/${physician.id}/" class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-blue/10 text-blue hover:bg-blue hover:text-white transition">
                            <i data-lucide="eye" class="w-4 h-4"></i>
                        </a>
                    </td>
                </tr>
            `;
        }).join('');

        lucide.createIcons();
    }

    // Utility functions
    function showLoading() {
        document.getElementById('loadingOverlay').classList.add('active');
    }

    function hideLoading() {
        document.getElementById('loadingOverlay').classList.remove('active');
    }
</script>
{% endblock %}
