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

{% block title %}{% trans "Complaints Registry" %} - PX360{% endblock %}

{% block extra_css %}
<style>
    /* Page Header Gradient - Matching References Page */
    .page-header-gradient {
        background: linear-gradient(135deg, #005696 0%, #0069a8 50%, #007bbd 100%);
        color: white;
        padding: 1.5rem 2rem;
        border-radius: 1rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
    }
    
    /* Stat Cards */
    .stat-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
    }
    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        border-color: #005696;
    }
    
    /* Section Cards */
    .section-card {
        background: white;
        border-radius: 1rem;
        border: 2px solid #e2e8f0;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        transition: all 0.3s ease;
    }
    .section-card:hover {
        border-color: #005696;
        box-shadow: 0 10px 25px -5px rgba(0, 86, 150, 0.15);
    }
    
    .section-header {
        padding: 1rem 1.5rem;
        border-bottom: 2px solid #e2e8f0;
        background: linear-gradient(to right, #f8fafc, #f1f5f9);
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }
    
    .section-icon {
        width: 40px;
        height: 40px;
        border-radius: 0.75rem;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .filter-btn.active { background-color: #005696; color: white; }
    .filter-btn:not(.active) { background-color: transparent; border: 1px solid #e2e8f0; color: #64748b; }
    .filter-btn:not(.active):hover { background-color: #f8fafc; }
</style>
{% endblock %}

{% block content %}
<!-- Page Header with Gradient -->
<div class="page-header-gradient">
    <div class="flex justify-between items-center">
        <div>
            <h1 class="text-2xl font-bold mb-1">{% trans "Complaints Registry" %}</h1>
            <p class="text-blue-100 text-sm">{% trans "Manage and monitor patient feedback in real-time" %}</p>
        </div>
        <div class="flex items-center gap-3">
            <div class="relative group">
                <i data-lucide="search" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-white/70 group-focus-within:text-navy"></i>
                <input type="text" id="searchInput" placeholder="{% trans 'Search ID, Name or Dept...' %}"
                       class="pl-10 pr-4 py-2.5 bg-white/10 border-2 border-white/30 text-white placeholder-white/70 rounded-xl text-sm outline-none w-64 transition-all focus:bg-white focus:text-navy focus:border-white">
            </div>
            {% if user.is_px_admin or user.is_hospital_admin or user.is_px_employee %}
            <a href="{% url 'core:public_submit_landing' %}" class="inline-flex items-center px-4 py-2.5 bg-white/10 border-2 border-white/30 text-white font-medium rounded-xl hover:bg-white hover:text-navy transition" target="_blank">
                <i data-lucide="external-link" class="w-4 h-4 me-2"></i>{% trans "Public Form" %}
            </a>
            <button onclick="openExportModal()" class="inline-flex items-center px-4 py-2.5 bg-white/10 border-2 border-white/30 text-white font-medium rounded-xl hover:bg-white hover:text-navy transition">
                <i data-lucide="file-spreadsheet" class="w-4 h-4 me-2"></i>{% trans "Export" %}
            </button>
            <a href="{% url 'complaints:complaint_create' %}" class="inline-flex items-center px-4 py-2.5 bg-white text-navy font-medium rounded-xl hover:bg-blue-50 transition">
                <i data-lucide="plus" class="w-4 h-4 me-2"></i>{% trans "New Case" %}
            </a>
            {% endif %}
        </div>
    </div>
</div>

<!-- Statistics Cards -->
<div class="grid grid-cols-4 gap-6 mb-6">
    <div class="stat-card bg-white rounded-2xl border-2 border-slate-200 p-6 flex items-center gap-4">
        <div class="flex-shrink-0">
            <div class="w-14 h-14 bg-navy/10 rounded-xl flex items-center justify-center">
                <i data-lucide="layers" class="w-7 h-7 text-navy"></i>
            </div>
        </div>
        <div>
            <h6 class="text-slate-500 text-sm font-medium mb-1">{% trans "Total Received" %}</h6>
            <h2 class="text-3xl font-bold text-gray-800">{{ stats.total }}</h2>
        </div>
    </div>
    <div class="stat-card bg-white rounded-2xl border-2 border-slate-200 p-6 flex items-center gap-4">
        <div class="flex-shrink-0">
            <div class="w-14 h-14 bg-green-500/10 rounded-xl flex items-center justify-center">
                <i data-lucide="check-circle" class="w-7 h-7 text-green-600"></i>
            </div>
        </div>
        <div>
            <h6 class="text-slate-500 text-sm font-medium mb-1">{% trans "Resolved" %}</h6>
            <h2 class="text-3xl font-bold text-gray-800">{{ stats.resolved }} <span class="text-sm text-green-600">({{ stats.resolved_percentage|floatformat:1 }}%)</span></h2>
        </div>
    </div>
    <div class="stat-card bg-white rounded-2xl border-2 border-slate-200 p-6 flex items-center gap-4">
        <div class="flex-shrink-0">
            <div class="w-14 h-14 bg-yellow-500/10 rounded-xl flex items-center justify-center">
                <i data-lucide="clock" class="w-7 h-7 text-yellow-600"></i>
            </div>
        </div>
        <div>
            <h6 class="text-slate-500 text-sm font-medium mb-1">{% trans "Pending" %}</h6>
            <h2 class="text-3xl font-bold text-gray-800">{{ stats.pending }} <span class="text-sm text-yellow-600">({{ stats.pending_percentage|floatformat:1 }}%)</span></h2>
        </div>
    </div>
    <div class="stat-card bg-white rounded-2xl border-2 border-slate-200 p-6 flex items-center gap-4">
        <div class="flex-shrink-0">
            <div class="w-14 h-14 bg-red-500/10 rounded-xl flex items-center justify-center">
                <i data-lucide="alert-triangle" class="w-7 h-7 text-red-500"></i>
            </div>
        </div>
        <div>
            <h6 class="text-slate-500 text-sm font-medium mb-1">{% trans "TAT Alert" %}</h6>
            <h2 class="text-3xl font-bold text-gray-800">{{ stats.overdue }} <span class="text-sm text-red-500">({{ stats.overdue_percentage|floatformat:1 }}%)</span></h2>
        </div>
    </div>
</div>

<!-- Complaints Section Card -->
<div class="section-card">
    <!-- Section Header with Filters -->
    <div class="section-header flex items-center justify-between">
        <div class="flex items-center gap-3">
            <div class="section-icon bg-red-500/10">
                <i data-lucide="message-square-warning" class="w-5 h-5 text-red-500"></i>
            </div>
            <h5 class="text-lg font-semibold text-gray-800">{% trans "Complaints" %}</h5>
        </div>
        <div class="flex items-center gap-3">
            <a href="?" class="filter-btn px-4 py-1.5 rounded-full text-xs font-semibold transition {% if not status_filter %}active{% endif %}">
                {% trans "All Cases" %}
            </a>
            <a href="?status=open" class="filter-btn px-4 py-1.5 rounded-full text-xs font-semibold transition {% if status_filter == 'open' %}active{% endif %}">
                {% trans "Pending" %}
            </a>
            <a href="?status=in_progress" class="filter-btn px-4 py-1.5 rounded-full text-xs font-semibold transition {% if status_filter == 'in_progress' %}active{% endif %}">
                {% trans "In Progress" %}
            </a>
            <a href="?status=resolved" class="filter-btn px-4 py-1.5 rounded-full text-xs font-semibold transition {% if status_filter == 'resolved' %}active{% endif %}">
                {% trans "Resolved" %}
            </a>
            <div class="h-4 w-[1px] bg-slate-200 mx-2"></div>
            <button onclick="toggleFilters()" class="flex items-center gap-2 text-xs font-bold text-blue uppercase tracking-tight hover:underline">
                <i data-lucide="sliders-horizontal" class="w-3 h-3"></i> {% trans "Advanced" %}
            </button>
        </div>
    </div>
    <p class="px-6 py-2 text-xs font-bold text-slate uppercase bg-slate-50 border-b-2 border-slate-200">
        {% trans "Showing:" %} <span class="text-navy">{{ complaints.start_index|default:0 }}-{{ complaints.end_index|default:0 }} {% trans "of" %} {{ complaints.paginator.count|default:0 }}</span>
    </p>

<!-- Advanced Filters (Hidden by default) -->
<div id="advancedFilters" class="hidden bg-slate-50 px-6 py-4 border-b">
    <form method="get" class="flex flex-wrap gap-4 items-end">
        {% if status_filter %}
        <input type="hidden" name="status" value="{{ status_filter }}">
        {% endif %}
        <div class="flex items-center gap-2">
            <label class="text-xs font-bold text-slate uppercase">{% trans "Priority" %}</label>
            <select name="priority" class="px-3 py-1.5 bg-white border rounded-lg text-xs">
                <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-center gap-2">
            <label class="text-xs font-bold text-slate uppercase">{% trans "Department" %}</label>
            <select name="department" class="px-3 py-1.5 bg-white border rounded-lg text-xs" data-tomselect data-ts-compact>
                <option value="">{% trans "All" %}</option>
                {% for dept in departments %}
                <option value="{{ dept.id }}" {% if department_filter == dept.id|stringformat:'s' %}selected{% endif %}>{{ dept.get_localized_name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="flex items-center gap-2">
            <label class="text-xs font-bold text-slate uppercase">{% trans "Severity" %}</label>
            <select name="severity" class="px-3 py-1.5 bg-white border rounded-lg text-xs">
                <option value="">{% trans "All" %}</option>
                <option value="low" {% if severity_filter == 'low' %}selected{% endif %}>{% trans "Low" %}</option>
                <option value="medium" {% if severity_filter == 'medium' %}selected{% endif %}>{% trans "Medium" %}</option>
                <option value="high" {% if severity_filter == 'high' %}selected{% endif %}>{% trans "High" %}</option>
                <option value="critical" {% if severity_filter == 'critical' %}selected{% endif %}>{% trans "Critical" %}</option>
            </select>
        </div>
        <div class="flex items-center gap-2">
            <label class="text-xs font-bold text-slate uppercase">{% trans "From" %}</label>
            <input type="date" name="date_from" value="{{ date_from }}" class="px-3 py-1.5 bg-white border rounded-lg text-xs">
        </div>
        <div class="flex items-center gap-2">
            <label class="text-xs font-bold text-slate uppercase">{% trans "To" %}</label>
            <input type="date" name="date_to" value="{{ date_to }}" class="px-3 py-1.5 bg-white border rounded-lg text-xs">
        </div>

        <button type="submit" class="px-4 py-1.5 bg-navy text-white rounded-lg text-xs font-bold">{% trans "Apply" %}</button>
        <a href="?" class="px-4 py-1.5 border rounded-lg text-xs font-semibold text-slate hover:bg-white">{% trans "Clear" %}</a>
    </form>
</div>

<!-- Complaints Table -->
<div class="p-0">
    <table class="w-full text-left border-collapse">
        <thead class="bg-slate-50 border-b uppercase text-[10px] font-bold text-slate tracking-wider">
            <tr>
                <th class="px-6 py-4">{% trans "Complaint ID" %}</th>
                <th class="px-6 py-4">{% trans "Patient Name" %}</th>
                <th class="px-6 py-4">{% trans "Description" %}</th>
                <th class="px-6 py-4">{% trans "Source" %}</th>
                <th class="px-6 py-4">{% trans "Department" %}</th>
                <th class="px-6 py-4">{% trans "Status" %}</th>
                <th class="px-6 py-4 text-center">{% trans "SLA" %}</th>
                <th class="px-6 py-4 text-center">{% trans "Severity" %}</th>
                <th class="px-6 py-4 text-center">{% trans "Priority" %}</th>
                <th class="px-6 py-4">{% trans "Assigned" %}</th>
                <th class="px-6 py-4 text-right">{% trans "Actions" %}</th>
            </tr>
        </thead>
        <tbody class="text-sm divide-y divide-slate-100">
            {% for complaint in complaints.object_list %}
            <tr class="hover:bg-light/30 transition-colors cursor-pointer group" onclick="window.location.href='{% url 'complaints:complaint_detail' complaint.pk %}'">
                <td class="px-6 py-4 font-bold text-navy">
                    {{ complaint.reference_number }}
                    {% if complaint.reopened_from_id %}
                    <span class="ml-1 px-1.5 py-0.5 bg-indigo-100 text-indigo-700 text-[9px] font-bold rounded" title="{% trans 'Reopened' %}">R</span>
                    {% endif %}
                    {% if complaint.is_escalated_ovr %}
                    <span class="ml-1 px-1.5 py-0.5 bg-orange-100 text-orange-700 text-[9px] font-bold rounded" title="{% trans 'Escalated OVR' %}">OVR</span>
                    {% endif %}
                </td>
                <td class="px-6 py-4">
                    <div class="font-semibold text-slate-800">{{ complaint.patient.get_full_name|default:complaint.patient_name|default:complaint.contact_name }}</div>
                    {% if complaint.patient %}
                    <div class="text-[10px] text-slate font-medium">{% trans "MRN:" %} {{ complaint.patient.mrn|default:"-" }}</div>
                    {% endif %}
                </td>
                <td class="px-6 py-4 max-w-xs" onclick="event.stopPropagation()">
                    {% if complaint.ai_brief_en %}
                    <span class="inline-block px-2.5 py-1 bg-blue-50 text-blue-700 text-xs font-semibold rounded-md whitespace-nowrap">
                        {{ complaint.ai_brief_ar|default:complaint.ai_brief_en }}
                    </span>
                    <button onclick="showDescriptionModal('{{ complaint.reference_number|escapejs }}', `{{ complaint.description|escapejs }}`)"
                            class="text-slate-400 text-xs hover:text-navy ml-1.5 cursor-pointer inline" title="{% trans 'View description' %}">
                        <i data-lucide="expand" class="w-3 h-3"></i>
                    </button>
                    {% else %}
                    <button onclick="showDescriptionModal('{{ complaint.reference_number|escapejs }}', `{{ complaint.description|escapejs }}`)"
                            class="text-slate-600 text-xs truncate text-left hover:text-navy hover:underline cursor-pointer flex items-center gap-1">
                        {{ complaint.description|truncatewords:10 }}
                        <i data-lucide="expand" class="w-3 h-3 flex-shrink-0 opacity-50"></i>
                    </button>
                    {% endif %}
                </td>
                <td class="px-6 py-4">
                    {% if complaint.source %}
                    <span class="bg-slate-100 px-2 py-0.5 rounded text-[10px] font-bold text-slate-600">{{ complaint.source.get_localized_name }}</span>
                    {% else %}
                    <span class="bg-slate-100 px-2 py-0.5 rounded text-[10px] font-bold text-slate-600">{{ complaint.get_complaint_source_type_display }}</span>
                    {% endif %}
                </td>
                <td class="px-6 py-4 text-slate-600">{{ complaint.department.get_localized_name|default:"-" }}</td>
                <td class="px-6 py-4">
                    <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase
                        {% if complaint.status == 'open' %}bg-yellow-100 text-yellow-700
                        {% elif complaint.status == 'in_progress' %}bg-blue-100 text-blue-700
                        {% elif complaint.status == 'partially_resolved' %}bg-amber-100 text-amber-700
                        {% elif complaint.status == 'resolved' %}bg-green-100 text-green-700
                        {% elif complaint.status == 'closed' %}bg-slate-100 text-slate-600
                        {% elif complaint.status == 'cancelled' %}bg-red-100 text-red-700
                        {% elif complaint.status == 'pending_external' %}bg-cyan-100 text-cyan-700
                        {% elif complaint.status == 'ovr_pending' %}bg-purple-100 text-purple-700
                        {% else %}bg-slate-100 text-slate-600{% endif %}">
                        {{ complaint.get_status_display }}
                    </span>
                    {% if complaint.patient_contact_status == 'contacted' %}
                    <span class="ml-1 px-1.5 py-0.5 rounded-full text-[9px] font-bold uppercase bg-blue-100 text-blue-700">{% trans "Contacted" %}</span>
                    {% elif complaint.patient_contact_status == 'contacted_no_response' %}
                    <span class="ml-1 px-1.5 py-0.5 rounded-full text-[9px] font-bold uppercase bg-orange-100 text-orange-700">{% trans "No Response" %}</span>
                    {% endif %}
                </td>
                <td class="px-6 py-4 text-center">
                    {% if complaint.due_at and complaint.status != 'resolved' and complaint.status != 'closed' and complaint.status != 'cancelled' %}
                    <span class="sla-timer text-[10px] font-bold" data-due-at="{{ complaint.due_at|date:'c' }}" data-overdue="{{ complaint.is_overdue|yesno:'true,false' }}"></span>
                    {% elif complaint.is_overdue %}
                    <span class="text-[10px] font-bold text-red-600">{% trans "Overdue" %}</span>
                    {% else %}
                    <span class="text-[10px] text-slate-400">-</span>
                    {% endif %}
                </td>
                <td class="px-6 py-4 text-center">
                    <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase
                        {% if complaint.severity == 'critical' %}bg-red-500 text-white
                        {% elif complaint.severity == 'high' %}bg-orange-100 text-orange-700
                        {% elif complaint.severity == 'medium' %}bg-yellow-100 text-yellow-700
                        {% else %}bg-green-100 text-green-700{% endif %}">
                        {{ complaint.get_severity_display }}
                    </span>
                </td>
                <td class="px-6 py-4">
                    <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase
                        {% if complaint.priority == 'critical' %}bg-red-500 text-white
                        {% elif complaint.priority == 'high' %}bg-orange-100 text-orange-700
                        {% elif complaint.priority == 'medium' %}bg-yellow-100 text-yellow-700
                        {% else %}bg-green-100 text-green-700{% endif %}">
                        {{ complaint.get_priority_display }}
                    </span>
                </td>
                <td class="px-6 py-4">
                    {% if complaint.assigned_to %}
                    <small class="text-gray-600">{{ complaint.assigned_to.get_full_name }}</small>
                    {% else %}
                    <span class="text-gray-400 italic">{% trans "Unassigned" %}</span>
                    {% endif %}
                </td>
                <td class="px-6 py-4 text-right">
                    <div class="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <a href="{% url 'complaints:complaint_detail' complaint.pk %}" class="p-1.5 text-navy hover:bg-white rounded border border-transparent hover:border-slate-200" title="{% trans 'View' %}">
                            <i data-lucide="eye" class="w-4 h-4"></i>
                        </a>
                        {% if complaint.can_edit %}
                        <a href="{% url 'complaints:complaint_assign' complaint.pk %}" class="p-1.5 text-blue hover:bg-white rounded border border-transparent hover:border-slate-200" title="{% trans 'Assign' %}">
                            <i data-lucide="user-plus" class="w-4 h-4"></i>
                        </a>
                        {% endif %}
                    </div>
                </td>
            </tr>
            {% empty %}
            <tr>
                <td colspan="9" class="px-6 py-12 text-center">
                    <i data-lucide="inbox" class="w-12 h-12 mx-auto text-slate-300 mb-3"></i>
                    <p class="text-slate">{% trans "No complaints found" %}</p>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    
    {% include "partials/pagination.html" %}
</div>
</div>

<!-- Description Modal -->
<div id="descriptionModal" class="fixed inset-0 z-50 hidden items-center justify-center p-4" onclick="closeDescriptionModal(event)">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm"></div>
    <div class="relative bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-[80vh] overflow-hidden" onclick="event.stopPropagation()">
        <div class="flex items-center justify-between px-6 py-4 border-b bg-slate-50">
            <div class="flex items-center gap-3">
                <div class="p-2 bg-navy/10 rounded-lg">
                    <i data-lucide="file-text" class="w-5 h-5 text-navy"></i>
                </div>
                <div>
                    <h3 class="font-bold text-navy">{% trans "Complaint Description" %}</h3>
                    <p id="modalReferenceNumber" class="text-xs text-slate font-mono"></p>
                </div>
            </div>
            <button onclick="closeDescriptionModal()" class="p-2 hover:bg-slate-200 rounded-lg transition">
                <i data-lucide="x" class="w-5 h-5 text-slate-500"></i>
            </button>
        </div>
        <div class="p-6 overflow-y-auto max-h-[60vh]">
            <p id="modalDescription" class="text-slate-700 text-sm leading-relaxed whitespace-pre-wrap"></p>
        </div>
        <div class="px-6 py-4 border-t bg-slate-50 flex justify-end">
            <button onclick="closeDescriptionModal()" class="px-4 py-2 bg-navy text-white rounded-lg text-sm font-bold hover:bg-blue transition">
                {% trans "Close" %}
            </button>
        </div>
    </div>
</div>

<!-- Export Modal -->
<div id="exportModal" class="fixed inset-0 z-50 hidden items-center justify-center p-4" onclick="closeExportModal(event)">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm"></div>
    <div class="relative bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden" onclick="event.stopPropagation()">
        <div class="flex items-center justify-between px-6 py-4 border-b bg-slate-50">
            <div class="flex items-center gap-3">
                <div class="p-2 bg-navy/10 rounded-lg">
                    <i data-lucide="file-spreadsheet" class="w-5 h-5 text-navy"></i>
                </div>
                <div>
                    <h3 class="font-bold text-navy">{% trans "Export Complaints" %}</h3>
                    <p class="text-xs text-slate">{% trans "Select date range for export" %}</p>
                </div>
            </div>
            <button onclick="closeExportModal()" class="p-2 hover:bg-slate-200 rounded-lg transition">
                <i data-lucide="x" class="w-5 h-5 text-slate-500"></i>
            </button>
        </div>
        <form id="exportForm" method="get" action="{% url 'complaints:complaint_export_historical_excel' %}" class="p-6">
            <div class="grid grid-cols-2 gap-4 mb-6">
                <div>
                    <label class="block text-xs font-bold text-slate uppercase mb-2">{% trans "From" %}</label>
                    <input type="date" name="date_start" id="exportDateStart" class="w-full px-3 py-2 bg-white border rounded-lg text-sm">
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate uppercase mb-2">{% trans "To" %}</label>
                    <input type="date" name="date_end" id="exportDateEnd" class="w-full px-3 py-2 bg-white border rounded-lg text-sm">
                </div>
            </div>
            <div class="flex justify-end gap-3">
                <button type="button" onclick="closeExportModal()" class="px-4 py-2 border rounded-lg text-sm font-semibold text-slate hover:bg-slate-50 transition">
                    {% trans "Cancel" %}
                </button>
                <button type="submit" class="px-4 py-2 bg-navy text-white rounded-lg text-sm font-bold hover:bg-blue transition">
                    {% trans "Export" %}
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function toggleFilters() {
    const filters = document.getElementById('advancedFilters');
    filters.classList.toggle('hidden');
}

// Description Modal Functions
function showDescriptionModal(referenceNumber, description) {
    const modal = document.getElementById('descriptionModal');
    const refNumber = document.getElementById('modalReferenceNumber');
    const descEl = document.getElementById('modalDescription');
    
    refNumber.textContent = referenceNumber;
    descEl.textContent = description || '{% trans "No description available" %}';
    
    modal.classList.remove('hidden');
    modal.classList.add('flex');
    document.body.style.overflow = 'hidden';
    
    // Re-initialize lucide icons for the modal
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
}

function closeDescriptionModal(event) {
    if (event && event.target !== event.currentTarget) return;
    
    const modal = document.getElementById('descriptionModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
    document.body.style.overflow = '';
}

// Export Modal Functions
function openExportModal() {
    const modal = document.getElementById('exportModal');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
    document.body.style.overflow = 'hidden';
    
    // Re-initialize lucide icons for the modal
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
}

function closeExportModal(event) {
    if (event && event.target !== event.currentTarget) return;

    const modal = document.getElementById('exportModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
    document.body.style.overflow = '';
}

// Handle export form submission with loading spinner
document.getElementById('exportForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const form = this;
    const submitBtn = form.querySelector('button[type="submit"]');
    const cancelBtn = form.querySelector('button[type="button"]');
    const originalText = submitBtn.innerHTML;

    // Show loading state
    submitBtn.disabled = true;
    cancelBtn.disabled = true;
    submitBtn.innerHTML = '<span class="inline-block w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2"></span>{% trans "Exporting..." %}';

    // Fetch the file
    fetch(form.action + '?' + new URLSearchParams(new FormData(form)))
        .then(response => {
            if (!response.ok) throw new Error('Export failed');
            return response.blob();
        })
        .then(blob => {
            // Trigger download
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'historical_complaints.xlsx';
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);

            // Close modal and reset button
            closeExportModal();
        })
        .catch(error => {
            alert('{% trans "Export failed. Please try again." %}');
        })
        .finally(() => {
            submitBtn.disabled = false;
            cancelBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        });
});

// Close modals on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeDescriptionModal();
        closeExportModal();
    }
});

// Search functionality
document.getElementById('searchInput')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        const value = this.value;
        if (value) {
            window.location.href = '?search=' + encodeURIComponent(value);
        }
    }
});

// SLA Countdown Timers for all rows
(function() {
    var timers = document.querySelectorAll('.sla-timer');
    if (!timers.length) return;

    function updateTimers() {
        var now = Date.now();
        timers.forEach(function(el) {
            var dueAt = new Date(el.dataset.dueAt).getTime();
            var diff = dueAt - now;

            if (diff <= 0) {
                var overMs = Math.abs(diff);
                var overD = Math.floor(overMs / 86400000);
                var overH = Math.floor((overMs % 86400000) / 3600000);
                var overM = Math.floor((overMs % 3600000) / 60000);
                var txt = '{% trans "Overdue" %} ';
                if (overD > 0) txt += overD + 'd ';
                txt += overH + 'h ' + overM + 'm';
                el.textContent = txt;
                el.className = 'sla-timer text-[10px] font-bold text-red-600';
                return;
            }

            var d = Math.floor(diff / 86400000);
            var h = Math.floor((diff % 86400000) / 3600000);
            var m = Math.floor((diff % 3600000) / 60000);

            var parts = [];
            if (d > 0) parts.push(d + 'd');
            parts.push(h + 'h');
            parts.push(m + 'm');
            el.textContent = parts.join(' ');

            if (diff < 21600000) {
                el.className = 'sla-timer text-[10px] font-bold text-red-600';
            } else if (diff < 86400000) {
                el.className = 'sla-timer text-[10px] font-bold text-orange-600';
            } else {
                el.className = 'sla-timer text-[10px] font-bold text-green-600';
            }
        });
    }

    updateTimers();
    setInterval(updateTimers, 30000);
})();
</script>
{% endblock %}
