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

{% block title %}My Dashboard - PX360{% endblock %}

{% block content %}
<div class="space-y-6">
    <!-- Page Header -->
    <header class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-2">
        <div>
            <h1 class="text-2xl font-bold text-navy flex items-center gap-3">
                <i data-lucide="layout-dashboard" class="w-7 h-7"></i>
                {% trans "My Dashboard" %}
            </h1>
            <p class="text-sm text-slate mt-1">{% trans "Overview of your assigned items and tasks" %}</p>
            {% if selected_hospital %}
            <div class="mt-2 inline-flex items-center gap-2 px-3 py-1.5 bg-blue-50 border border-blue-200 rounded-lg">
                <i data-lucide="building-2" class="w-4 h-4 text-blue"></i>
                <span class="text-sm font-medium text-blue">{{ selected_hospital.name }}</span>
                <span class="text-xs text-blue/70">({% trans "filtered" %})</span>
            </div>
            {% endif %}
        </div>
        <div>
            <a href="{% url 'dashboard:my_performance' %}" class="inline-flex items-center gap-2 px-4 py-2.5 bg-navy text-white rounded-xl font-bold text-sm hover:bg-blue transition">
                <i data-lucide="bar-chart-3" class="w-4 h-4"></i>
                {% trans "My Performance" %}
            </a>
        </div>
    </header>

    <!-- Summary Cards -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        <!-- Total Items -->
        <div class="bg-white rounded-lg border border-slate-200 shadow-sm hover:shadow-lg transition cursor-pointer">
            <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="p-2 bg-navy/10 rounded-lg">
                        <i data-lucide="inbox" class="w-5 h-5 text-navy"></i>
                    </div>
                </div>
                <h3 class="text-sm font-medium text-slate mb-1">{% trans "Total Items" %}</h3>
                <p class="text-3xl font-bold text-navy">{{ total_stats.total }}</p>
            </div>
        </div>
        
        <!-- Open -->
        <div class="bg-white rounded-lg border border-slate-200 shadow-sm hover:shadow-lg transition cursor-pointer">
            <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="p-2 bg-yellow-50 rounded-lg">
                        <i data-lucide="mail-open" class="w-5 h-5 text-yellow-500"></i>
                    </div>
                </div>
                <h3 class="text-sm font-medium text-slate mb-1">{% trans "Open" %}</h3>
                <p class="text-3xl font-bold text-navy">{{ total_stats.open }}</p>
            </div>
        </div>
        
        <!-- In Progress -->
        <div class="bg-white rounded-lg border border-slate-200 shadow-sm hover:shadow-lg transition cursor-pointer">
            <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="p-2 bg-blue-50 rounded-lg">
                        <i data-lucide="hourglass" class="w-5 h-5 text-blue"></i>
                    </div>
                </div>
                <h3 class="text-sm font-medium text-slate mb-1">{% trans "In Progress" %}</h3>
                <p class="text-3xl font-bold text-navy">{{ total_stats.in_progress }}</p>
            </div>
        </div>
        
        <!-- Resolved -->
        <div class="bg-white rounded-lg border border-slate-200 shadow-sm hover:shadow-lg transition cursor-pointer">
            <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="p-2 bg-green-50 rounded-lg">
                        <i data-lucide="check-circle" class="w-5 h-5 text-green-500"></i>
                    </div>
                </div>
                <h3 class="text-sm font-medium text-slate mb-1">{% trans "Resolved" %}</h3>
                <p class="text-3xl font-bold text-navy">{{ total_stats.resolved }}</p>
            </div>
        </div>
        
        <!-- Closed -->
        <div class="bg-white rounded-lg border border-slate-200 shadow-sm hover:shadow-lg transition cursor-pointer">
            <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="p-2 bg-slate-100 rounded-lg">
                        <i data-lucide="x-circle" class="w-5 h-5 text-slate"></i>
                    </div>
                </div>
                <h3 class="text-sm font-medium text-slate mb-1">{% trans "Closed" %}</h3>
                <p class="text-3xl font-bold text-navy">{{ total_stats.closed }}</p>
            </div>
        </div>
        
        <!-- Overdue -->
        <div class="bg-white rounded-lg border border-slate-200 shadow-sm hover:shadow-lg transition cursor-pointer">
            <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                    <div class="p-2 bg-red-50 rounded-lg">
                        <i data-lucide="alert-triangle" class="w-5 h-5 text-red-500"></i>
                    </div>
                </div>
                <h3 class="text-sm font-medium text-slate mb-1">{% trans "Overdue" %}</h3>
                <p class="text-3xl font-bold text-red-500">{{ total_stats.overdue }}</p>
            </div>
        </div>
    </div>

    <!-- Chart Row -->
    <div class="bg-white rounded-lg border border-slate-200 shadow-sm">
        <div class="card-header">
            <h3 class="card-title flex items-center gap-2">
                <i data-lucide="trending-up" class="w-5 h-5 text-navy"></i>
                {% trans "Completion Trend (Last 30 Days)" %}
            </h3>
        </div>
        <div class="p-6">
            <div id="completionTrendChart" class="h-[350px]"></div>
        </div>
    </div>

    <!-- Filter Bar -->
    <div class="bg-white rounded-lg border border-slate-200 shadow-sm">
        <div class="p-6">
            <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                <div>
                    <label class="block text-sm font-bold text-slate mb-2">{% trans "Date Range" %}</label>
                    <select name="date_range" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 focus:border-navy focus:ring-2 focus:ring-navy/20 outline-none transition bg-white">
                        <option value="7" {% if date_range == 7 %}selected{% endif %}>{% trans "Last 7 days" %}</option>
                        <option value="30" {% if date_range == 30 %}selected{% endif %}>{% trans "Last 30 days" %}</option>
                        <option value="90" {% if date_range == 90 %}selected{% endif %}>{% trans "Last 90 days" %}</option>
                        <option value="-1" {% if date_range == -1 %}selected{% endif %}>{% trans "All time" %}</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate mb-2">{% trans "Search" %}</label>
                    <input type="text" name="search" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 focus:border-navy focus:ring-2 focus:ring-navy/20 outline-none transition" value="{{ search_query }}" placeholder="{% trans 'Search...' %}">
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate mb-2">{% trans "Status" %}</label>
                    <select name="status" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 focus:border-navy focus:ring-2 focus:ring-navy/20 outline-none transition bg-white">
                        <option value="">{% trans "All" %}</option>
                        <option value="open" {% if status_filter == 'open' %}selected{% endif %}>{% trans "Open" %}</option>
                        <option value="in_progress" {% if status_filter == 'in_progress' %}selected{% endif %}>{% trans "In Progress" %}</option>
                        <option value="resolved" {% if status_filter == 'resolved' %}selected{% endif %}>{% trans "Resolved" %}</option>
                        <option value="closed" {% if status_filter == 'closed' %}selected{% endif %}>{% trans "Closed" %}</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate mb-2">{% trans "Priority/Severity" %}</label>
                    <select name="priority" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 focus:border-navy focus:ring-2 focus:ring-navy/20 outline-none transition bg-white">
                        <option value="">{% trans "All" %}</option>
                        <option value="low" {% if priority_filter == 'low' %}selected{% endif %}>{% trans "Low" %}</option>
                        <option value="medium" {% if priority_filter == 'medium' %}selected{% endif %}>{% trans "Medium" %}</option>
                        <option value="high" {% if priority_filter == 'high' %}selected{% endif %}>{% trans "High" %}</option>
                        <option value="critical" {% if priority_filter == 'critical' %}selected{% endif %}>{% trans "Critical" %}</option>
                    </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-bold hover:bg-blue transition flex items-center justify-center gap-2">
                        <i data-lucide="filter" class="w-4 h-4"></i>
                        {% trans "Apply Filters" %}
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Tabs -->
    <div class="bg-white rounded-lg border border-slate-200 shadow-sm">
        <div class="border-b border-slate-100">
            <nav class="flex gap-1 p-2 overflow-x-auto" id="dashboardTabs">
                <button class="px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition {% if active_tab == 'complaints' %}bg-navy text-white{% else %}text-slate hover:bg-light{% endif %}" data-tab="complaints">
                    <i data-lucide="alert-triangle" class="w-4 h-4"></i>
                    {% trans "Complaints" %}
                    <span class="px-2 py-0.5 rounded-lg text-xs font-bold {% if active_tab == 'complaints' %}bg-white/20 text-white{% else %}bg-red-100 text-red-600{% endif %}">{{ stats.complaints.total }}</span>
                </button>
                <button class="px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition {% if active_tab == 'inquiries' %}bg-navy text-white{% else %}text-slate hover:bg-light{% endif %}" data-tab="inquiries">
                    <i data-lucide="help-circle" class="w-4 h-4"></i>
                    {% trans "Inquiries" %}
                    <span class="px-2 py-0.5 rounded-lg text-xs font-bold {% if active_tab == 'inquiries' %}bg-white/20 text-white{% else %}bg-blue-100 text-blue-600{% endif %}">{{ stats.inquiries.total }}</span>
                </button>
                <button class="px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition {% if active_tab == 'observations' %}bg-navy text-white{% else %}text-slate hover:bg-light{% endif %}" data-tab="observations">
                    <i data-lucide="eye" class="w-4 h-4"></i>
                    {% trans "Observations" %}
                    <span class="px-2 py-0.5 rounded-lg text-xs font-bold {% if active_tab == 'observations' %}bg-white/20 text-white{% else %}bg-yellow-100 text-yellow-600{% endif %}">{{ stats.observations.total }}</span>
                </button>
                <button class="px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition {% if active_tab == 'actions' %}bg-navy text-white{% else %}text-slate hover:bg-light{% endif %}" data-tab="actions">
                    <i data-lucide="clipboard-check" class="w-4 h-4"></i>
                    {% trans "PX Actions" %}
                    <span class="px-2 py-0.5 rounded-lg text-xs font-bold {% if active_tab == 'actions' %}bg-white/20 text-white{% else %}bg-orange-100 text-orange-600{% endif %}">{{ stats.actions.total }}</span>
                </button>
                <button class="px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition {% if active_tab == 'tasks' %}bg-navy text-white{% else %}text-slate hover:bg-light{% endif %}" data-tab="tasks">
                    <i data-lucide="list-todo" class="w-4 h-4"></i>
                    {% trans "Tasks" %}
                    <span class="px-2 py-0.5 rounded-lg text-xs font-bold {% if active_tab == 'tasks' %}bg-white/20 text-white{% else %}bg-slate-100 text-slate{% endif %}">{{ stats.tasks.total }}</span>
                </button>
                <button class="px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition {% if active_tab == 'feedback' %}bg-navy text-white{% else %}text-slate hover:bg-light{% endif %}" data-tab="feedback">
                    <i data-lucide="message-square" class="w-4 h-4"></i>
                    {% trans "Feedback" %}
                    <span class="px-2 py-0.5 rounded-lg text-xs font-bold {% if active_tab == 'feedback' %}bg-white/20 text-white{% else %}bg-green-100 text-green-600{% endif %}">{{ stats.feedback.total }}</span>
                </button>
                <button class="px-5 py-2.5 rounded-xl font-bold flex items-center gap-2 transition {% if active_tab == 'activity' %}bg-navy text-white{% else %}text-slate hover:bg-light{% endif %}" data-tab="activity">
                    <i data-lucide="activity" class="w-4 h-4"></i>
                    {% trans "Activity" %}
                </button>
            </nav>
        </div>

        <!-- Tab Content -->
        <div class="p-6">
            <!-- Complaints Tab -->
            <div class="tab-content {% if active_tab == 'complaints' %}block{% else %}hidden{% endif %}" id="complaints-tab">
                {% include 'dashboard/partials/complaints_table.html' with data=paginated_data.complaints stats=stats.complaints %}
            </div>

            <!-- Inquiries Tab -->
            <div class="tab-content {% if active_tab == 'inquiries' %}block{% else %}hidden{% endif %}" id="inquiries-tab">
                {% include 'dashboard/partials/inquiries_table.html' with data=paginated_data.inquiries stats=stats.inquiries %}
            </div>

            <!-- Observations Tab -->
            <div class="tab-content {% if active_tab == 'observations' %}block{% else %}hidden{% endif %}" id="observations-tab">
                {% include 'dashboard/partials/observations_table.html' with data=paginated_data.observations stats=stats.observations %}
            </div>

            <!-- Actions Tab -->
            <div class="tab-content {% if active_tab == 'actions' %}block{% else %}hidden{% endif %}" id="actions-tab">
                {% include 'dashboard/partials/actions_table.html' with data=paginated_data.actions stats=stats.actions %}
            </div>

            <!-- Tasks Tab -->
            <div class="tab-content {% if active_tab == 'tasks' %}block{% else %}hidden{% endif %}" id="tasks-tab">
                {% include 'dashboard/partials/tasks_table.html' with data=paginated_data.tasks stats=stats.tasks %}
            </div>

            <!-- Feedback Tab -->
            <div class="tab-content {% if active_tab == 'feedback' %}block{% else %}hidden{% endif %}" id="feedback-tab">
                {% include 'dashboard/partials/feedback_table.html' with data=paginated_data.feedback stats=stats.feedback %}
            </div>
            <div class="tab-content {% if active_tab == 'activity' %}block{% else %}hidden{% endif %}" id="activity-tab">
                <div class="p-6">
                    <h3 class="text-lg font-bold text-navy mb-4 flex items-center gap-2">
                        <i data-lucide="activity" class="w-5 h-5"></i>
                        {% trans "My Recent Activity" %}
                    </h3>
                    {% if activity_logs %}
                    <div class="space-y-3">
                        {% for log in activity_logs %}
                        <div class="flex items-start gap-3 p-3 rounded-lg border border-slate-100 hover:bg-slate-50 transition">
                            <div class="flex-shrink-0 w-9 h-9 rounded-full flex items-center justify-center text-xs font-bold
                                {% if log.activity_type == 'create' %}bg-green-100 text-green-700
                                {% elif log.activity_type == 'update' %}bg-blue-100 text-blue-700
                                {% elif log.activity_type == 'delete' %}bg-red-100 text-red-700
                                {% elif log.activity_type == 'login' or log.activity_type == 'logout' %}bg-slate-100 text-slate-700
                                {% elif log.activity_type == 'send' %}bg-purple-100 text-purple-700
                                {% elif log.activity_type == 'resolve' %}bg-emerald-100 text-emerald-700
                                {% elif log.activity_type == 'assign' %}bg-amber-100 text-amber-700
                                {% else %}bg-slate-100 text-slate{% endif %}">
                                {% if log.activity_type == 'create' %}<i data-lucide="plus" class="w-4 h-4"></i>
                                {% elif log.activity_type == 'update' %}<i data-lucide="edit-2" class="w-4 h-4"></i>
                                {% elif log.activity_type == 'delete' %}<i data-lucide="trash-2" class="w-4 h-4"></i>
                                {% elif log.activity_type == 'login' %}<i data-lucide="log-in" class="w-4 h-4"></i>
                                {% elif log.activity_type == 'logout' %}<i data-lucide="log-out" class="w-4 h-4"></i>
                                {% elif log.activity_type == 'send' %}<i data-lucide="send" class="w-4 h-4"></i>
                                {% elif log.activity_type == 'resolve' %}<i data-lucide="check-circle" class="w-4 h-4"></i>
                                {% elif log.activity_type == 'assign' %}<i data-lucide="user-plus" class="w-4 h-4"></i>
                                {% else %}<i data-lucide="circle" class="w-4 h-4"></i>{% endif %}
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm text-slate-800">{{ log.description }}</p>
                                <div class="flex items-center gap-2 mt-1">
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold uppercase
                                        {% if log.activity_type == 'create' %}bg-green-50 text-green-600
                                        {% elif log.activity_type == 'update' %}bg-blue-50 text-blue-600
                                        {% elif log.activity_type == 'delete' %}bg-red-50 text-red-600
                                        {% elif log.activity_type == 'login' or log.activity_type == 'logout' %}bg-slate-50 text-slate-600
                                        {% else %}bg-slate-50 text-slate{% endif %}">
                                        {{ log.get_activity_type_display }}
                                    </span>
                                    {% if log.module %}
                                    <span class="text-[10px] text-slate-400 uppercase">{{ log.module }}</span>
                                    {% endif %}
                                </div>
                            </div>
                            <div class="flex-shrink-0 text-xs text-slate-400 whitespace-nowrap">
                                {{ log.created_at|date:"M d, Y H:i" }}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <div class="text-center py-12 text-slate">
                        <i data-lucide="inbox" class="w-12 h-12 mx-auto mb-3 text-slate-300"></i>
                        <p class="text-sm">{% trans "No activity recorded yet" %}</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Action Modal -->
<div id="bulkActionModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-2xl w-full max-w-md mx-4 shadow-2xl">
        <div class="flex justify-between items-center p-6 border-b border-slate-100">
            <h3 class="text-xl font-bold text-navy">{% trans "Bulk Action" %}</h3>
            <button onclick="closeBulkActionModal()" class="p-2 hover:bg-light rounded-xl transition">
                <i data-lucide="x" class="w-5 h-5 text-slate"></i>
            </button>
        </div>
        <div class="p-6">
            <input type="hidden" id="bulkActionTab">
            <div class="mb-4">
                <label class="block text-sm font-bold text-slate mb-2">{% trans "Select Action" %}</label>
                <select id="bulkActionType" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 focus:border-navy focus:ring-2 focus:ring-navy/20 outline-none transition bg-white">
                    <option value="bulk_status">{% trans "Change Status" %}</option>
                    <option value="bulk_assign">{% trans "Assign to User" %}</option>
                </select>
            </div>
            <div class="mb-4" id="bulkStatusContainer">
                <label class="block text-sm font-bold text-slate mb-2">{% trans "New Status" %}</label>
                <select id="bulkStatus" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 focus:border-navy focus:ring-2 focus:ring-navy/20 outline-none transition bg-white">
                    <option value="open">{% trans "Open" %}</option>
                    <option value="in_progress">{% trans "In Progress" %}</option>
                    <option value="resolved">{% trans "Resolved" %}</option>
                    <option value="closed">{% trans "Closed" %}</option>
                </select>
            </div>
            <div class="mb-4 hidden" id="bulkAssignContainer">
                <label class="block text-sm font-bold text-slate mb-2">{% trans "Assign To" %}</label>
                <select id="bulkAssignUser" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 focus:border-navy focus:ring-2 focus:ring-navy/20 outline-none transition bg-white">
                    <!-- Users will be loaded dynamically -->
                </select>
            </div>
        </div>
        <div class="flex gap-3 p-6 border-t border-slate-100">
            <button onclick="closeBulkActionModal()" class="flex-1 px-6 py-2.5 border-2 border-slate-200 text-slate rounded-xl font-bold hover:bg-light transition">
                {% trans "Cancel" %}
            </button>
            <button id="executeBulkAction" class="flex-1 px-6 py-2.5 bg-navy text-white rounded-xl font-bold hover:bg-blue transition">
                {% trans "Execute" %}
            </button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Lucide icons
    lucide.createIcons();

    // Tab switching
    const tabs = document.querySelectorAll('#dashboardTabs button[data-tab]');
    const contents = document.querySelectorAll('.tab-content');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.dataset.tab;
            
            // Update tab buttons
            tabs.forEach(t => {
                t.classList.remove('bg-navy', 'text-white');
                t.classList.add('text-slate', 'hover:bg-light');
                const badge = t.querySelector('span');
                if (badge) {
                    badge.classList.remove('bg-white/20', 'text-white');
                    badge.classList.add('bg-' + getBadgeColor(tabName) + '-100', 'text-' + getBadgeColor(tabName) + '-600');
                }
            });
            this.classList.remove('text-slate', 'hover:bg-light');
            this.classList.add('bg-navy', 'text-white');
            const currentBadge = this.querySelector('span');
            if (currentBadge) {
                currentBadge.classList.remove('bg-' + getBadgeColor(tabName) + '-100', 'text-' + getBadgeColor(tabName) + '-600');
                currentBadge.classList.add('bg-white/20', 'text-white');
            }
            
            // Show/hide content
            contents.forEach(content => {
                if (content.id === `${tabName}-tab`) {
                    content.classList.remove('hidden');
                    content.classList.add('block');
                } else {
                    content.classList.remove('block');
                    content.classList.add('hidden');
                }
            });

            // Update URL
            const url = new URL(window.location);
            url.searchParams.set('tab', tabName);
            window.history.pushState({}, '', url);
        });
    });

    function getBadgeColor(tabName) {
        const colors = {
            'complaints': 'red',
            'inquiries': 'blue',
            'observations': 'yellow',
            'actions': 'orange',
            'tasks': 'slate',
            'feedback': 'green'
        };
        return colors[tabName] || 'slate';
    }

    // Completion Trend Chart - ApexCharts
    const chartElement = document.getElementById('completionTrendChart');
    if (chartElement) {
        const completionData = {{ chart_data.completion_trend|safe }};
        
        var options = {
            series: [{
                name: '{% trans "Completed Items" %}',
                data: completionData.data
            }],
            chart: {
                type: 'bar',
                height: 350,
                toolbar: {
                    show: false
                },
                fontFamily: 'Inter, sans-serif'
            },
            plotOptions: {
                bar: {
                    borderRadius: 8,
                    columnWidth: '60%'
                }
            },
            colors: ['#005696'],
            xaxis: {
                categories: completionData.labels,
                labels: {
                    style: {
                        fontSize: '12px',
                        fontFamily: 'Inter, sans-serif',
                        colors: ['#64748b']
                    }
                },
                axisBorder: {
                    show: false
                },
                axisTicks: {
                    show: false
                }
            },
            yaxis: {
                min: 0,
                forceNiceScale: true,
                labels: {
                    style: {
                        fontSize: '12px',
                        fontFamily: 'Inter, sans-serif',
                        colors: ['#64748b']
                    }
                }
            },
            grid: {
                borderColor: '#f1f5f9',
                strokeDashArray: 5
            },
            tooltip: {
                theme: 'light',
                style: {
                    fontSize: '12px',
                    fontFamily: 'Inter, sans-serif'
                }
            },
            dataLabels: {
                enabled: false
            }
        };
        
        var chart = new ApexCharts(chartElement, options);
        chart.render();
    }

    // Bulk action handling
    let selectedItems = [];

    document.querySelectorAll('.bulk-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                if (!selectedItems.includes(this.value)) {
                    selectedItems.push(this.value);
                }
            } else {
                selectedItems = selectedItems.filter(id => id !== this.value);
            }
            updateBulkActionButtons();
        });
    });

    function updateBulkActionButtons() {
        const buttons = document.querySelectorAll('.bulk-action-btn');
        buttons.forEach(btn => {
            btn.disabled = selectedItems.length === 0;
        });
    }

    document.querySelectorAll('.bulk-action-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const tab = this.dataset.tab;
            document.getElementById('bulkActionTab').value = tab;
            openBulkActionModal();
        });
    });

    function openBulkActionModal() {
        const modal = document.getElementById('bulkActionModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closeBulkActionModal() {
        const modal = document.getElementById('bulkActionModal');
        modal.classList.remove('flex');
        modal.classList.add('hidden');
    }

    document.getElementById('bulkActionType').addEventListener('change', function() {
        if (this.value === 'bulk_status') {
            document.getElementById('bulkStatusContainer').classList.remove('hidden');
            document.getElementById('bulkAssignContainer').classList.add('hidden');
        } else if (this.value === 'bulk_assign') {
            document.getElementById('bulkStatusContainer').classList.add('hidden');
            document.getElementById('bulkAssignContainer').classList.remove('hidden');
            // Load users dynamically
            // This is a placeholder - you'd fetch users from an API endpoint
        }
    });

    document.getElementById('executeBulkAction').addEventListener('click', function() {
        const tab = document.getElementById('bulkActionTab').value;
        const actionType = document.getElementById('bulkActionType').value;
        
        let data = {
            action: actionType,
            tab: tab,
            item_ids: selectedItems
        };
        
        if (actionType === 'bulk_status') {
            data.new_status = document.getElementById('bulkStatus').value;
        } else if (actionType === 'bulk_assign') {
            data.user_id = document.getElementById('bulkAssignUser').value;
        }
        
        fetch('{% url "dashboard:bulk_action" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                alert('{% trans "Successfully processed" %} ' + result.updated_count + ' {% trans "items" %}');
                location.reload();
            } else {
                alert('{% trans "Error" %}: ' + result.error);
            }
        })
        .catch(error => {
            alert('{% trans "Error" %}: ' + error.message);
        });
    });
});
</script>
{% endblock %}