{% extends 'layouts/base.html' %}
{% load i18n %}
{% load static %}
{% get_current_language as LANG %}

{% block title %}{{ complaint.reference_number }} - PX360{% endblock %}

{% block extra_css %}
<style>
    .tab-active { 
        border-bottom: 3px solid #005696; 
        color: #005696; 
        font-weight: 700; 
    }
    .tab-inactive {
        color: #64748b;
        font-weight: 500;
    }
    .tab-inactive:hover {
        color: #005696;
    }
    .timeline {
        position: relative;
        padding-left: 30px;
    }
    .timeline::before {
        content: '';
        position: absolute;
        left: 8px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #e5e7eb;
    }
    .timeline-item {
        position: relative;
        padding-bottom: 24px;
    }
    .timeline-item::before {
        content: '';
        position: absolute;
        left: -26px;
        top: 2px;
        width: 14px;
        height: 14px;
        border-radius: 50%;
        background: white;
        border: 3px solid #005696;
        z-index: 1;
    }
    .timeline-item.status_change::before { border-color: #f97316; }
    .timeline-item.assignment::before { border-color: #3b82f6; }
    .timeline-item.escalation::before { border-color: #ef4444; }
    .timeline-item.note::before { border-color: #22c55e; }
    
    .inner-tab-active {
        border-bottom: 2px solid #005696;
        color: #005696;
        font-weight: 700;
        background: white;
    }
    .inner-tab-inactive {
        color: #64748b;
    }
</style>
{% endblock %}

{% block content %}
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">

<!-- Breadcrumb & Header -->
<header class="mb-6">
    <div class="flex items-center gap-2 text-sm text-slate mb-2">
        <a href="{% url 'complaints:complaint_list' %}" class="hover:text-navy">{% trans "Cases" %}</a>
        <i data-lucide="chevron-right" class="w-4 h-4"></i>
        <span class="font-bold text-navy">{{ complaint.reference_number }}</span>
        <span class="ml-2 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider
            {% 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-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-blue-100 text-blue-700">
            <i data-lucide="phone" class="w-3 h-3 inline"></i> {% trans "Patient Contacted" %}
        </span>
        {% elif complaint.patient_contact_status == 'contacted_no_response' %}
        <span class="ml-1 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-orange-100 text-orange-700">
            <i data-lucide="phone-off" class="w-3 h-3 inline"></i> {% trans "No Response" %}
        </span>
        {% endif %}
        {% if not complaint.sent_to_any_department %}
        <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase bg-amber-100 text-amber-700">
            <i data-lucide="alert-circle" class="w-3 h-3 inline"></i> {% trans "Not Sent to Dept" %}
        </span>
        {% endif %}
    </div>
    {% if complaint.source_complaint.exists %}
    {% with sc=complaint.source_complaint.first %}
    <div class="bg-blue-50 border border-blue-200 rounded-xl p-3 mb-4 flex items-center gap-3">
        <i data-lucide="link" class="w-4 h-4 text-blue-600 flex-shrink-0"></i>
        <p class="text-sm text-blue-800">
            {% trans "Converted from source complaint" %}
            <a href="{% url 'px_sources:source_detail' pk=sc.px_source.pk %}" class="font-bold hover:underline">{{ sc.reference_number }}</a>
            {% if sc.px_source %}({{ sc.px_source.get_localized_name }}){% endif %}
        </p>
    </div>
    {% endwith %}
    {% endif %}
    {% if complaint.reopened_from %}
    <div class="bg-amber-50 border border-amber-200 rounded-xl p-3 mb-4 flex items-center gap-3">
        <i data-lucide="rotate-ccw" class="w-4 h-4 text-amber-600 flex-shrink-0"></i>
        <p class="text-sm text-amber-800">
            {% trans "Reopened from complaint" %}
            <a href="{% url 'complaints:complaint_detail' pk=complaint.reopened_from.pk %}" class="font-bold hover:underline">{{ complaint.reopened_from.reference_number|default:complaint.reopened_from.pk }}</a>
        </p>
    </div>
    {% endif %}
    {% if complaint.reopenings.exists %}
    <div class="bg-amber-50 border border-amber-200 rounded-xl p-3 mb-4 flex items-center gap-3">
        <i data-lucide="git-branch" class="w-4 h-4 text-amber-600 flex-shrink-0"></i>
        <p class="text-sm text-amber-800">
            {% trans "This complaint has been reopened as" %}:
            {% for r in complaint.reopenings.all %}
            <a href="{% url 'complaints:complaint_detail' pk=r.pk %}" class="font-bold hover:underline">{{ r.reference_number|default:r.pk }}</a>{% if not forloop.last %}, {% endif %}
            {% endfor %}
        </p>
    </div>
    {% endif %}
    <div class="flex items-center justify-between">
        <h1 class="text-2xl font-bold text-navy">{{ complaint.title }}</h1>
        <div class="flex items-center gap-3">
            {% comment %} <a href="{% url 'complaints:complaint_pdf' complaint.id %}" target="_blank" 
               class="text-slate hover:text-navy px-3 py-2 text-sm font-semibold flex items-center gap-2 border rounded-lg hover:bg-light transition">
                <i data-lucide="printer" class="w-4 h-4"></i> {% trans "PDF View" %}
            </a> {% endcomment %}
            {% if can_edit and complaint.is_active_status and complaint.assigned_to == current_user %}
            <button onclick="showResolveModal()" class="bg-navy text-white px-4 py-2 rounded-lg text-sm font-bold shadow-md hover:bg-blue transition">
                {% trans "Resolve Case" %}
            </button>
            {% endif %}
        </div>
    </div>
</header>

<!-- Tab Navigation -->
<nav class="bg-white px-6 flex gap-6 border-b shadow-sm mb-6 rounded-t-2xl">
    <button class="py-4 text-sm tab-active" onclick="switchTab('details')" id="tab-details">
        {% trans "Details" %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %}" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('departments')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-departments">
        {% trans "Departments" %} ({{ complaint.involved_departments_count }})
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3 inline ml-1"></i>{% endif %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %}" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('staff')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-staff">
        {% trans "Staff" %} ({{ complaint.involved_staff_count }})
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3 inline ml-1"></i>{% endif %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %}" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('timeline')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-timeline">
        {% trans "Timeline" %} ({{ stage_timeline.stages|length }})
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3 inline ml-1"></i>{% endif %}
    </button>
    {% comment %} <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %}" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('attachments')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-attachments">
        {% trans "Attachments" %} ({{ complaint.attachments_count }})
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3 inline ml-1"></i>{% endif %}
    </button> {% endcomment %}
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %}" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('actions')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-actions">
        {% trans "PX Actions" %} ({{ px_actions.count }})
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3 inline ml-1"></i>{% endif %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %} flex items-center gap-2" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('ai')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-ai">
        <i data-lucide="sparkles" class="w-4 h-4 {% if not complaint.assigned_to == current_user and complaint.is_active_status %}text-slate-300{% endif %}"></i> {% trans "AI Analysis" %}
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3"></i>{% endif %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %}" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('explanation')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-explanation">
        {% trans "Explanation" %}
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3 inline ml-1"></i>{% endif %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %}" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('resolution')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-resolution">
        {% trans "Resolution" %}
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3 inline ml-1"></i>{% endif %}
    </button>
    {% comment %} <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %} flex items-center gap-1" 
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('adverse')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-adverse">
        <i data-lucide="shield-alert" class="w-4 h-4 {% if not complaint.assigned_to == current_user and complaint.is_active_status %}text-slate-300{% endif %}"></i>
        {% trans "Adverse Actions" %}
        {% if adverse_actions %}
            <span class="ml-1 px-1.5 py-0.5 bg-red-100 text-red-700 text-xs rounded-full">{{ adverse_actions.count }}</span>
        {% endif %}
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3"></i>{% endif %}
    </button> {% endcomment %}
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %} flex items-center gap-2"
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('rca')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-rca">
        <i data-lucide="search" class="w-4 h-4 {% if not complaint.assigned_to == current_user and complaint.is_active_status %}text-slate-300{% endif %}"></i> {% trans "RCA" %}
        {% if linked_rcas %}
            <span class="ml-1 px-1.5 py-0.5 bg-purple-100 text-purple-700 text-xs rounded-full">{{ linked_rcas.count }}</span>
        {% endif %}
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3"></i>{% endif %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %} flex items-center gap-2"
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('notes')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-notes">
        <i data-lucide="message-square" class="w-4 h-4 {% if not complaint.assigned_to == current_user and complaint.is_active_status %}text-slate-300{% endif %}"></i> {% trans "Notes" %}
        {% if notes_count %}
            <span class="ml-1 px-1.5 py-0.5 bg-slate-100 text-slate-600 text-xs rounded-full">{{ notes_count }}</span>
        {% endif %}
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3"></i>{% endif %}
    </button>
    <button class="py-4 text-sm {% if complaint.assigned_to == current_user or not complaint.is_active_status %}tab-inactive{% else %}text-slate-300 cursor-not-allowed{% endif %} flex items-center gap-2"
        {% if complaint.assigned_to == current_user or not complaint.is_active_status %}onclick="switchTab('pdf')"{% else %}onclick="showActivationRequired()"{% endif %} id="tab-pdf">
        <i data-lucide="file-text" class="w-4 h-4 {% if not complaint.assigned_to == current_user and complaint.is_active_status %}text-slate-300{% endif %}"></i> {% trans "PDF Summary" %}
        {% if not complaint.assigned_to == current_user and complaint.is_active_status %}<i data-lucide="lock" class="w-3 h-3"></i>{% endif %}
    </button>
</nav>

<!-- Main Content Grid -->
<main class="grid grid-cols-12 gap-6">
    
    <!-- Left Column (Content) -->
    <div class="col-span-8 space-y-6">
        
        <!-- Details Tab -->
        <div id="panel-details" class="tab-panel">
            <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
                {% if complaint.description %}
                <div class="bg-slate-50 p-4 rounded-xl border-l-4 border-blue mb-4">
                    <p class="text-sm leading-relaxed text-slate italic">"{{ complaint.description }}"</p>
                </div>
                {% endif %}

                <div class="grid grid-cols-5 gap-4 py-4">
                    <div>
                        <p class="text-[10px] font-bold text-slate uppercase">{% trans "Location" %}</p>
                        <p class="text-sm font-bold text-navy">
                            {% if complaint.legacy_location %}{{ complaint.legacy_location.name_en }}{% else %}-{% endif %}
                        </p>
                        {% if complaint.legacy_main_section %}
                        <p class="text-xs text-slate">{{ complaint.legacy_main_section.name_en }}{% if complaint.legacy_subsection %} &gt; {{ complaint.legacy_subsection.name_en }}{% endif %}</p>
                        {% endif %}
                    </div>
                    <div>
                        <p class="text-[10px] font-bold text-slate uppercase">{% trans "Severity" %}</p>
                        <p class="text-sm font-bold
                            {% if complaint.severity == 'critical' %}text-red-600
                            {% elif complaint.severity == 'high' %}text-orange-600
                            {% elif complaint.severity == 'medium' %}text-yellow-600
                            {% else %}text-green-600{% endif %}">
                            {{ complaint.get_severity_display }}
                        </p>
                    </div>
                    <div>
                        <p class="text-[10px] font-bold text-slate uppercase">{% trans "Classification" %}</p>
                        <p class="text-sm font-bold text-blue-700">
                            {% if complaint.ai_brief_en %}
                                {% if LANG == 'ar' and complaint.ai_brief_ar %}
                                    {{ complaint.ai_brief_ar }}
                                {% else %}
                                    {{ complaint.ai_brief_en }}
                                {% endif %}
                            {% else %}-{% endif %}
                        </p>
                    </div>
                    <div>
                        <p class="text-[10px] font-bold text-slate uppercase">{% trans "Created" %}</p>
                        <p class="text-sm font-bold text-navy">{{ complaint.created_at|date:"d M Y, h:i A" }}</p>
                    </div>
                    <div>
                        <p class="text-[10px] font-bold text-slate uppercase">{% trans "Deadline" %}</p>
                        <p class="text-sm font-bold {% if complaint.is_overdue %}text-red-600{% else %}text-navy{% endif %}">
                            {{ complaint.due_at|date:"d M Y, h:i A" }}
                            {% if complaint.is_overdue %}
                            <span class="ml-1 px-1.5 py-0.5 rounded text-[9px] font-bold bg-red-500 text-white uppercase">{% trans "Overdue" %}</span>
                            {% endif %}
                        </p>
                        {% if complaint.due_at and complaint.status != 'resolved' and complaint.status != 'closed' and complaint.status != 'cancelled' %}
                        <p id="sla-countdown" class="text-xs font-bold mt-1"
                           data-due-at="{{ complaint.due_at|date:'c' }}"
                           data-overdue="{{ complaint.is_overdue|yesno:'true,false' }}">
                        </p>
                        {% elif complaint.sla_is_overdue_display %}
                        <p class="text-xs font-bold text-red-600 mt-1">{{ complaint.sla_is_overdue_display }}</p>
                        {% endif %}
                    </div>
                </div>

                {% if complaint.domain or complaint.category or complaint.subcategory_obj or complaint.classification_obj %}
                <div class="py-3 border-t border-slate-100 flex items-center gap-2 flex-wrap">
                    <span class="text-[10px] font-bold text-slate uppercase">{% trans "Taxonomy" %}:</span>
                    {% if complaint.domain %}<span class="text-sm text-navy font-medium">{{ complaint.domain.get_localized_name }}</span>{% endif %}
                    {% if complaint.category %}<i data-lucide="chevron-right" class="w-3 h-3 text-slate-300"></i><span class="text-sm text-navy font-medium">{{ complaint.category.get_localized_name }}</span>{% endif %}
                    {% if complaint.subcategory_obj %}<i data-lucide="chevron-right" class="w-3 h-3 text-slate-300"></i><span class="text-sm text-navy font-medium">{{ complaint.subcategory_obj.get_localized_name }}</span>{% endif %}
                    {% if complaint.classification_obj %}<i data-lucide="chevron-right" class="w-3 h-3 text-slate-300"></i><span class="text-sm text-navy font-medium">{{ complaint.classification_obj.get_localized_name }}</span>{% endif %}
                </div>
                {% endif %}

                {% if complaint.source %}
                <div class="py-3 border-t border-slate-100 flex items-center gap-2">
                    <span class="text-[10px] font-bold text-slate uppercase">{% trans "Source" %}:</span>
                    <span class="text-sm text-navy font-medium">{{ complaint.source.get_localized_name }}</span>
                </div>
                {% endif %}

                {% if complaint.escalated_at %}
                <div class="mt-3 p-3 bg-orange-50 border border-orange-200 rounded-xl flex items-center gap-3">
                    <i data-lucide="alert-triangle" class="w-5 h-5 text-orange-500 flex-shrink-0"></i>
                    <div>
                        <p class="text-xs font-bold text-orange-700 uppercase">{% trans "Escalated" %}</p>
                        <p class="text-xs text-orange-600">{% trans "Escalated on" %} {{ complaint.escalated_at|date:"d M Y, h:i A" }}</p>
                    </div>
                </div>
                {% endif %}

                {% if complaint.status == 'ovr_pending' %}
                <div class="mt-3 p-4 bg-yellow-50 border-2 border-yellow-200 rounded-xl">
                    <div class="flex items-center gap-2 mb-3">
                        <span class="px-2 py-0.5 text-[9px] font-bold rounded bg-yellow-100 text-yellow-700 uppercase">OVR</span>
                        <span class="text-sm font-bold text-yellow-700">{% trans "Pending Approval" %}</span>
                    </div>
                    <p class="text-xs text-yellow-600 mb-3">{% trans "OVR escalation requested. Please review and approve or reject." %}</p>
                    {% if request.user.is_px_admin or request.user.is_hospital_admin or request.user.is_px_management %}
                    <div class="flex gap-2">
                        <form method="post" action="{% url 'complaints:approve_ovr_escalation' pk=complaint.pk %}">
                            {% csrf_token %}
                            <button type="submit" class="px-4 py-2 bg-green-600 text-white text-sm font-semibold rounded-lg hover:bg-green-700 transition flex items-center gap-2">
                                <i data-lucide="check-circle" class="w-4 h-4"></i> {% trans "Approve" %}
                            </button>
                        </form>
                        <form method="post" action="{% url 'complaints:reject_ovr_escalation' pk=complaint.pk %}">
                            {% csrf_token %}
                            <button type="submit" class="px-4 py-2 bg-red-600 text-white text-sm font-semibold rounded-lg hover:bg-red-700 transition flex items-center gap-2">
                                <i data-lucide="x-circle" class="w-4 h-4"></i> {% trans "Reject" %}
                            </button>
                        </form>
                    </div>
                    {% else %}
                    <p class="text-xs text-yellow-600">{% trans "Waiting for admin approval." %}</p>
                    {% endif %}
                </div>
                {% endif %}

                {% if complaint.expected_result %}
                <div class="mt-3 pt-3 border-t border-slate-100">
                    <p class="text-[10px] font-bold text-slate uppercase mb-1">{% trans "Expected Result" %}</p>
                    <p class="text-sm text-slate">{{ complaint.expected_result }}</p>
                </div>
                {% endif %}

                {% if complaint.patient %}
                <div class="mt-3 pt-3 border-t border-slate-100 flex items-center gap-4 text-sm">
                    <i data-lucide="user" class="w-4 h-4 text-slate flex-shrink-0"></i>
                    <span class="font-bold text-navy">{{ complaint.patient.get_full_name }}</span>
                    <span class="text-slate">|</span>
                    <span class="text-slate">{% trans "MRN:" %} <span class="font-medium text-navy">{{ complaint.patient.mrn|default:"-" }}</span></span>
                    {% if complaint.patient.phone %}
                    <span class="text-slate">|</span>
                    <span class="text-slate">{{ complaint.patient.phone }}</span>
                    {% endif %}
                </div>
                {% endif %}
            </section>
        </div>
        
        <!-- Departments Tab -->
        <div id="panel-departments" class="tab-panel hidden">
            {% include "complaints/partials/departments_panel.html" %}
        </div>
        
        <!-- Staff Tab -->
        <div id="panel-staff" class="tab-panel hidden">
            {% include "complaints/partials/staff_panel.html" %}
        </div>
        
        <!-- Timeline Tab -->
        <div id="panel-timeline" class="tab-panel hidden">
            {% include "complaints/partials/timeline_panel.html" %}
        </div>
        
        <!-- Attachments Tab -->
        <div id="panel-attachments" class="tab-panel hidden">
            {% include "complaints/partials/attachments_panel.html" %}
        </div>
        
        <!-- Actions Tab -->
        <div id="panel-actions" class="tab-panel hidden">
            {% include "complaints/partials/actions_panel.html" %}
        </div>
        
        <!-- AI Analysis Tab -->
        <div id="panel-ai" class="tab-panel hidden">
            {% include "complaints/partials/ai_panel.html" %}
        </div>
        
        <!-- Explanation Tab -->
        <div id="panel-explanation" class="tab-panel hidden">
            {% include "complaints/partials/explanation_panel.html" %}
        </div>
        
        <!-- Resolution Tab -->
        <div id="panel-resolution" class="tab-panel hidden">
            {% include "complaints/partials/resolution_panel.html" %}
        </div>
        
        <!-- Adverse Actions Tab -->
        <div id="panel-adverse" class="tab-panel hidden">
            {% include "complaints/partials/adverse_actions_panel.html" %}
        </div>

        <!-- RCA Tab -->
        <div id="panel-rca" class="tab-panel hidden">
            {% include "complaints/partials/rca_panel.html" %}
        </div>

        <div id="panel-notes" class="tab-panel hidden">
            {% include "partials/notes_panel.html" %}
        </div>

        <div id="panel-pdf" class="tab-panel hidden">
            {% include "complaints/partials/pdf_summary_panel.html" %}
        </div>
    </div>
    
    <!-- Right Column (Sidebar) -->
    <div class="col-span-4 space-y-6">
        
        <!-- Quick Actions -->
        <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
            <h3 class="font-bold text-navy mb-4 text-sm">{% trans "Quick Actions" %}</h3>
            <div class="grid grid-cols-2 gap-3">
                {% if can_edit and complaint.is_active_status %}
                {% if current_user.is_px_admin or current_user.is_hospital_admin or complaint.assigned_to == current_user %}
                <button onclick="showAssignModal()" class="col-span-2 p-2 border border-blue-200 bg-blue-50 rounded-xl hover:bg-blue-100 flex items-center justify-center gap-2 group transition mb-2">
                    <i data-lucide="user-plus" class="w-4 h-4 text-blue"></i>
                    <span class="text-[10px] font-bold text-blue uppercase">
                        {% if complaint.assigned_to %}{% trans "Reassign" %}{% else %}{% trans "Assign" %}{% endif %}
                    </span>
                </button>
                {% endif %}
                <!-- Activate Button - Always show when can edit and status is active -->
                <form method="post" action="{% url 'complaints:complaint_activate' pk=complaint.pk %}" class="contents">
                    {% csrf_token %}
                    <button type="submit"
                        class="p-3 border-blue-200 bg-blue-50 rounded-xl hover:bg-blue-100 flex flex-col items-center gap-2 group transition col-span-2 mb-2"
                        {% if complaint.assigned_to == current_user %}disabled style="opacity: 0.5; cursor: not-allowed;"{% endif %}>
                        <i data-lucide="{% if complaint.assigned_to == current_user %}check-circle{% else %}play-circle{% endif %}" class="w-5 h-5 text-blue"></i>
                        <span class="text-[10px] font-bold text-blue uppercase">
                            {% if complaint.assigned_to == current_user %}{% trans "Activated" %}{% else %}{% trans "Activate" %}{% endif %}
                        </span>
                    </button>
                </form>

                {% if complaint.assigned_to == current_user %}
                <!-- Action buttons only shown when activated -->
                <button onclick="showResolveModal()" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="check-circle-2" class="w-5 h-5 text-slate group-hover:text-green-600"></i>
                    <span class="text-[10px] font-bold uppercase">{% trans "Resolve" %}</span>
                </button>
                <button onclick="showFollowUpModal()" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="clock" class="w-5 h-5 text-slate group-hover:text-orange-500"></i>
                    <span class="text-[10px] font-bold uppercase">{% trans "Follow Up" %}</span>
                </button>
                <button onclick="showEscalateModal()" class="p-3 border-red-100 bg-red-50 rounded-xl hover:bg-red-100 flex flex-col items-center gap-2 group transition">
                    <i data-lucide="alert-triangle" class="w-5 h-5 text-red-500"></i>
                    <span class="text-[10px] font-bold text-red-600 uppercase">{% trans "Escalate" %}</span>
                </button>
                <form method="post" action="{% url 'complaints:toggle_escalated_ovr' pk=complaint.pk %}" class="contents">
                    {% csrf_token %}
                    <button type="submit" name="is_escalated_ovr" value="{% if not complaint.is_escalated_ovr %}on{% endif %}"
                        class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition
                        {% if complaint.is_escalated_ovr %}border-orange-200 bg-orange-50{% endif %}">
                        <i data-lucide="shield-alert" class="w-5 h-5 {% if complaint.is_escalated_ovr %}text-orange-600{% else %}text-slate group-hover:text-orange-500{% endif %}"></i>
                        <span class="text-[10px] font-bold uppercase {% if complaint.is_escalated_ovr %}text-orange-700{% endif %}">
                            {% if complaint.is_escalated_ovr %}{% trans "Remove OVR" %}{% else %}{% trans "OVR Escalate" %}{% endif %}
                        </span>
                    </button>
                </form>
                <!-- Close Button -->
                <button onclick="showCloseModal()" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="circle-check" class="w-5 h-5 text-slate-600 group-hover:text-emerald-600"></i>
                    <span class="text-[10px] font-bold uppercase text-slate-600">{% trans "Close" %}</span>
                </button>
                {% else %}
                <!-- Not yet activated: show Cancel for admins -->
                {% if current_user.is_px_admin or current_user.is_hospital_admin %}
                <form method="post" action="{% url 'complaints:complaint_change_status' pk=complaint.pk %}" class="col-span-2 contents">
                    {% csrf_token %}
                    <input type="hidden" name="status" value="cancelled">
                    <button type="submit" onclick="return confirm('{% trans "Are you sure you want to cancel this complaint?" %}')"
                        class="p-3 border-red-200 bg-red-50 rounded-xl hover:bg-red-100 flex flex-col items-center gap-2 group transition col-span-2">
                        <i data-lucide="x-circle" class="w-5 h-5 text-red-500"></i>
                        <span class="text-[10px] font-bold text-red-600 uppercase">{% trans "Cancel Complaint" %}</span>
                    </button>
                </form>
                {% else %}
                <div class="col-span-2 bg-yellow-50 border border-yellow-200 rounded-xl p-3 text-center">
                    <i data-lucide="lock" class="w-4 h-4 text-yellow-600 mx-auto mb-1"></i>
                    <p class="text-xs text-yellow-700">{% trans "Activate this complaint to perform actions" %}</p>
                </div>
                {% endif %}
                {% endif %}
                {% elif complaint.status == 'resolved' or complaint.status == 'closed' %}
                {% if can_edit %}
                <form method="post" action="{% url 'complaints:complaint_reopen' pk=complaint.pk %}" class="col-span-2 contents">
                    {% csrf_token %}
                    <input type="hidden" name="note" value="Complaint reopened">
                    <button type="submit"
                        class="p-3 border-amber-200 bg-amber-50 rounded-xl hover:bg-amber-100 flex flex-col items-center gap-2 group transition col-span-2">
                        <i data-lucide="rotate-ccw" class="w-5 h-5 text-amber-600"></i>
                        <span class="text-[10px] font-bold text-amber-700 uppercase">{% trans "Reopen" %}</span>
                    </button>
                </form>
                {% if current_user.is_px_admin or current_user.is_hospital_admin or complaint.assigned_to == current_user %}
                <button onclick="showAssignModal()" class="col-span-2 p-2 border border-blue-200 bg-blue-50 rounded-xl hover:bg-blue-100 flex items-center justify-center gap-2 group transition">
                    <i data-lucide="user-plus" class="w-4 h-4 text-blue"></i>
                    <span class="text-[10px] font-bold text-blue uppercase">{% trans "Reassign" %}</span>
                </button>
                {% endif %}
                {% endif %}
                {% else %}
                <div class="col-span-2 text-center py-4 text-slate text-sm">
                    {% trans "No actions available for this status" %}
                </div>
                {% endif %}
                {% if current_user.is_px_admin or current_user.is_hospital_admin %}
                <div class="col-span-2 border-t border-gray-100 pt-3 mt-2">
                    <form method="post" action="{% url 'complaints:complaint_soft_delete' pk=complaint.pk %}" id="delete-form">
                        {% csrf_token %}
                        <button type="button" onclick="if(confirm('{% trans "Are you sure you want to delete this complaint? It can be restored from the trash." %}'))document.getElementById('delete-form').submit()"
                            class="w-full p-2 border border-red-200 bg-red-50 rounded-xl hover:bg-red-100 flex items-center justify-center gap-2 transition">
                            <i data-lucide="trash-2" class="w-4 h-4 text-red-500"></i>
                            <span class="text-xs font-bold text-red-600 uppercase">{% trans "Delete" %}</span>
                        </button>
                    </form>
                </div>
                {% endif %}
            </div>
        </section>
        
        <!-- Update Status -->
        {% if can_edit and available_transitions and complaint.assigned_to == current_user %}
        {% if current_user.is_px_admin or current_user.is_hospital_admin %}
        <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
            <h3 class="font-bold text-navy mb-4 text-sm flex items-center gap-2">
                <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                {% trans "Update Status" %}
            </h3>
            <form method="post" action="{% url 'complaints:complaint_change_status' pk=complaint.pk %}">
                {% csrf_token %}
                <div class="mb-3">
                    <select name="status" class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none">
                        {% for status_value, status_label in available_transitions %}
                        <option value="{{ status_value }}">{{ status_label }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="mb-3">
                    <label class="block text-xs font-semibold text-slate mb-1">{% trans "Note (Optional)" %}</label>
                    <textarea name="note" rows="2" class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none" placeholder="{% trans 'Add a note...' %}"></textarea>
                </div>
                <button type="submit" class="w-full px-4 py-2.5 bg-navy text-white rounded-xl font-semibold hover:bg-blue transition text-sm flex items-center justify-center gap-2">
                    <i data-lucide="check" class="w-4 h-4"></i>
                    {% trans "Update" %}
                </button>
            </form>
        </section>
        {% endif %}
        {% endif %}

        <!-- Closure Delay Reason -->
        {% if complaint.is_active_status and complaint.delay_reason_closure %}
        <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
            <h3 class="font-bold text-navy mb-4 text-sm flex items-center gap-2">
                <i data-lucide="clock-alert" class="w-4 h-4 text-amber-500"></i>
                {% trans "72h Closure Delay Reason" %}
            </h3>
            <div class="bg-amber-50 border border-amber-200 rounded-xl p-3 mb-4">
                <p class="text-sm text-amber-800">{{ complaint.get_delay_reason_closure_display }}</p>
            </div>
            {% if can_edit %}
            <form method="post" action="{% url 'complaints:update_delay_reason_closure' pk=complaint.id %}">
                {% csrf_token %}
                <select name="delay_reason_closure" class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none mb-3">
                    <option value="">{% trans "Select delay reason..." %}</option>
                    <option value="department_no_response" {% if complaint.delay_reason_closure == 'department_no_response' %}selected{% endif %}>{% trans "Department No Response" %}</option>
                    <option value="escalated" {% if complaint.delay_reason_closure == 'escalated' %}selected{% endif %}>{% trans "Escalated" %}</option>
                    <option value="patient_not_satisfied" {% if complaint.delay_reason_closure == 'patient_not_satisfied' %}selected{% endif %}>{% trans "Patient Not Satisfied with Complaint Resolution" %}</option>
                </select>
                <button type="submit" class="w-full px-4 py-2 bg-amber-500 text-white rounded-lg text-sm font-semibold hover:bg-amber-600 transition inline-flex items-center justify-center gap-2">
                    <i data-lucide="save" class="w-4 h-4"></i> {% trans "Save Reason" %}
                </button>
            </form>
            {% endif %}
        </section>
        {% endif %}
        
        <!-- Staff Assignment -->
         {% if complaint.is_activated %}
        <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
            <h3 class="font-bold text-navy mb-4 text-sm">
                {% trans "Staff Assignment" %} ({{ complaint.involved_staff_count }})
            </h3>
            {% if complaint.involved_staff.exists %}
            <div class="space-y-3">
                {% for staff_inv in complaint.involved_staff.all|slice:":3" %}
                <div class="flex items-center gap-3 p-3 bg-light/30 rounded-xl">
                    <div class="w-10 h-10 bg-navy rounded-full flex items-center justify-center text-white font-bold text-sm">
                        {{ staff_inv.staff.first_name|first }}{{ staff_inv.staff.last_name|first }}
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-bold text-navy truncate">{{ staff_inv.staff }}</p>
                        <p class="text-[10px] text-slate">{{ staff_inv.get_role_display }}</p>
                    </div>
                </div>
                {% endfor %}
                {% if complaint.involved_staff_count > 3 %}
                <button onclick="switchTab('staff')" class="text-blue text-xs font-bold hover:underline w-full text-center">
                    {% trans "View all" %} {{ complaint.involved_staff_count }} {% trans "staff" %}
                </button>
                {% endif %}
            </div>
            {% else %}
            <div class="bg-light/30 border-2 border-dashed border-slate-200 rounded-2xl p-6 text-center">
                <div class="w-10 h-10 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-3">
                    <i data-lucide="user" class="text-slate-400 w-6 h-6"></i>
                </div>
                <p class="text-[11px] text-slate font-medium mb-3 tracking-tight">
                    {% trans "No staff assigned to this case yet." %}
                </p>
                {% if can_edit and complaint.is_active_status %}
                <a href="{% url 'complaints:involved_staff_add' complaint_pk=complaint.pk %}" 
                   class="bg-white border text-blue text-[11px] font-bold px-4 py-2 rounded-lg hover:shadow-sm inline-block">
                    {% trans "Select Staff" %}
                </a>
                {% endif %}
            </div>
            {% endif %}
        </section>
        {% endif %}
        
        <!-- Assignment Info -->
         {% if complaint.is_activated %}
        <section class="bg-navy rounded-2xl p-6 shadow-lg text-white">
            <div class="flex items-center gap-3 mb-4">
                <i data-lucide="info" class="w-5 h-5 text-blue"></i>
                <h3 class="font-bold text-sm">{% trans "Assignment Info" %}</h3>
            </div>
            <ul class="space-y-3 text-[11px] opacity-90">
                <li class="flex justify-between border-b border-white/10 pb-2">
                    <span>{% trans "Main Dept:" %}</span>
                    <span class="font-bold">{{ complaint.department.name|default:"-" }}</span>
                </li>
                <li class="flex justify-between border-b border-white/10 pb-2">
                    <span>{% trans "Assigned To:" %}</span>
                    <span class="font-bold">{{ complaint.assigned_to.get_full_name|default:"Unassigned" }}</span>
                </li>
                <li class="flex justify-between border-b border-white/10 pb-2">
                    <span>{% trans "TAT Goal:" %}</span>
                    <span class="font-bold">{{ complaint.due_at|timeuntil }}</span>
                </li>
                <li class="flex justify-between">
                    <span>{% trans "Status:" %}</span>
                    <span class="font-bold uppercase text-blue">{{ complaint.get_status_display }}</span>
                </li>
            </ul>
        </section>
        {%endif%}
        
        <!-- Departments Summary -->
        {% if complaint.involved_departments_count > 0 %}
        <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
            <h3 class="font-bold text-navy mb-4 text-sm">
                {% trans "Involved Departments" %} ({{ complaint.involved_departments_count }})
            </h3>
            <div class="space-y-2">
                {% for dept in complaint.involved_departments.all %}
                <div class="flex items-center gap-2 p-2 rounded-lg {% if dept.is_primary %}bg-light{% else %}bg-slate-50{% endif %}">
                    <i data-lucide="building-2" class="w-4 h-4 {% if dept.is_primary %}text-navy{% else %}text-slate{% endif %}"></i>
                    <span class="text-xs font-medium {% if dept.is_primary %}text-navy font-bold{% else %}text-slate{% endif %}">
                        {{ dept.department.name }}
                    </span>
                    {% if dept.is_primary %}
                    <span class="ml-auto text-[9px] bg-navy text-white px-1.5 py-0.5 rounded">{% trans "PRIMARY" %}</span>
                    {% endif %}
                </div>
                {% endfor %}
            </div>
        </section>
        {% endif %}

        {% if complaint.status != 'open' %}
        <!-- Patient Contact Status -->
        <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
            <h3 class="font-bold text-navy mb-4 text-sm flex items-center gap-2">
                <i data-lucide="phone" class="w-4 h-4"></i>
                {% trans "Patient Contact" %}
            </h3>

            {% if complaint.patient_contact_status and complaint.patient_contact_status != 'not_contacted' %}
            <div class="flex items-center gap-3 mb-3">
                <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold
                    {% if complaint.patient_contact_status == 'contacted' %}bg-blue-100 text-blue-800
                    {% else %}bg-orange-100 text-orange-800{% endif %}">
                    {% if complaint.patient_contact_status == 'contacted' %}
                        <i data-lucide="phone" class="w-3.5 h-3.5"></i>
                    {% else %}
                        <i data-lucide="phone-off" class="w-3.5 h-3.5"></i>
                    {% endif %}
                    {{ complaint.get_patient_contact_status_display }}
                </span>
            </div>
            <div class="text-[10px] text-slate mb-3">
                {% if complaint.patient_contact_status_at %}
                {{ complaint.patient_contact_status_at|date:"Y-m-d H:i" }}
                {% endif %}
                {% if complaint.patient_contact_status_by %}
                &middot; {% trans "by" %} {{ complaint.patient_contact_status_by.get_full_name }}
                {% endif %}
            </div>
            {% endif %}

            {% if can_edit %}
            <form method="post" action="{% url 'complaints:update_patient_contact_status' pk=complaint.pk %}">
                {% csrf_token %}
                <div class="flex flex-wrap gap-2">
                    <button type="submit" name="patient_contact_status" value="contacted"
                        class="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold border-2 transition
                        {% if complaint.patient_contact_status == 'contacted' %}border-blue-500 bg-blue-50 text-blue-700
                        {% else %}border-slate-200 text-slate-600 hover:border-blue-400 hover:bg-blue-50{% endif %}">
                        <i data-lucide="phone" class="w-3.5 h-3.5"></i> {% trans "Contacted" %}
                    </button>
                    <button type="submit" name="patient_contact_status" value="contacted_no_response"
                        class="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold border-2 transition
                        {% if complaint.patient_contact_status == 'contacted_no_response' %}border-orange-500 bg-orange-50 text-orange-700
                        {% else %}border-slate-200 text-slate-600 hover:border-orange-400 hover:bg-orange-50{% endif %}">
                        <i data-lucide="phone-off" class="w-3.5 h-3.5"></i> {% trans "No Response" %}
                    </button>
                    {% if complaint.patient_contact_status != 'not_contacted' %}
                    <button type="submit" name="patient_contact_status" value="not_contacted"
                        class="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold border-2 transition border-slate-200 text-slate-600 hover:border-slate-400 hover:bg-slate-50">
                        <i data-lucide="rotate-ccw" class="w-3.5 h-3.5"></i> {% trans "Reset" %}
                    </button>
                    {% endif %}
                </div>
            </form>
            {% elif not complaint.patient_contact_status or complaint.patient_contact_status == 'not_contacted' %}
            <p class="text-sm text-slate italic">{% trans "Patient has not been contacted yet." %}</p>
            {% endif %}
        </section>
        {% endif %}
    </div>
</main>

<!-- Resolve Modal -->
<div id="resolveModal" style="display:none" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-2xl p-6 w-full max-w-lg mx-4 shadow-2xl">
        <div class="flex items-center gap-3 mb-4">
            <div class="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                <i data-lucide="check-circle" class="w-5 h-5 text-green-600"></i>
            </div>
            <h3 class="text-xl font-bold text-navy">{% trans "Resolve Complaint" %}</h3>
        </div>
        <p class="text-slate mb-4 text-sm">{% trans "Please provide resolution details before marking this complaint as resolved." %}</p>
        <form method="post" action="{% url 'complaints:complaint_change_status' pk=complaint.pk %}">
            {% csrf_token %}
            <input type="hidden" name="status" value="resolved">
            <div class="mb-4">
                <label class="block text-sm font-semibold text-slate mb-2">{% trans "Resolution Notes" %} <span class="text-red-500">*</span></label>
                <textarea name="resolution" rows="4" class="w-full border border-slate-200 rounded-xl p-4 text-sm focus:ring-2 focus:ring-navy/20 outline-none" placeholder="{% trans 'Enter resolution details...' %}" required></textarea>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="closeModal('resolveModal')" class="flex-1 px-4 py-2 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 transition">
                    {% trans "Cancel" %}
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-green-500 text-white rounded-xl font-semibold hover:bg-green-600 transition flex items-center justify-center gap-2">
                    <i data-lucide="check-circle" class="w-4 h-4"></i> {% trans "Mark Resolved" %}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Assign Modal -->
<div id="assignModal" style="display:none" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-2xl p-6 w-full max-w-lg mx-4 shadow-2xl">
        <div class="flex items-center gap-3 mb-4">
            <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                <i data-lucide="user-plus" class="w-5 h-5 text-blue"></i>
            </div>
            <h3 class="text-xl font-bold text-navy">
                {% if complaint.assigned_to %}{% trans "Reassign Complaint" %}{% else %}{% trans "Assign Complaint" %}{% endif %}
            </h3>
        </div>
        <p class="text-slate mb-4 text-sm">{% trans "Select a user to assign this complaint to." %}</p>
        <form method="post" action="{% url 'complaints:complaint_assign' pk=complaint.pk %}">
            {% csrf_token %}
            <div class="mb-4">
                <label class="block text-sm font-semibold text-slate mb-2">{% trans "Assign To" %} <span class="text-red-500">*</span></label>
                <select name="user_id" class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none" required>
                    <option value="">{% trans "Select User" %}</option>
                    {% for user in assignable_users %}
                    <option value="{{ user.id }}">{{ user.get_full_name }} {% if user.department %}({{ user.department.name }}){% endif %}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="closeModal('assignModal')" class="flex-1 px-4 py-2 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 transition">
                    {% trans "Cancel" %}
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-navy text-white rounded-xl font-semibold hover:bg-blue transition flex items-center justify-center gap-2">
                    <i data-lucide="user-plus" class="w-4 h-4"></i> {% trans "Assign" %}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Follow Up Modal -->
<div id="followUpModal" style="display:none" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-2xl p-6 w-full max-w-lg mx-4 shadow-2xl">
        <div class="flex items-center gap-3 mb-4">
            <div class="w-10 h-10 bg-orange-100 rounded-full flex items-center justify-center">
                <i data-lucide="clock" class="w-5 h-5 text-orange-500"></i>
            </div>
            <h3 class="text-xl font-bold text-navy">{% trans "Add Follow Up Note" %}</h3>
        </div>
        <p class="text-slate mb-4 text-sm">{% trans "Add a note or update about this complaint." %}</p>
        <form method="post" action="{% url 'complaints:complaint_add_note' pk=complaint.pk %}">
            {% csrf_token %}
            <div class="mb-4">
                <label class="block text-sm font-semibold text-slate mb-2">{% trans "Note" %} <span class="text-red-500">*</span></label>
                <textarea name="note" rows="4" class="w-full border border-slate-200 rounded-xl p-4 text-sm focus:ring-2 focus:ring-navy/20 outline-none" placeholder="{% trans 'Enter your note...' %}" required></textarea>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="closeModal('followUpModal')" class="flex-1 px-4 py-2 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 transition">
                    {% trans "Cancel" %}
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-orange-500 text-white rounded-xl font-semibold hover:bg-orange-600 transition flex items-center justify-center gap-2">
                    <i data-lucide="plus" class="w-4 h-4"></i> {% trans "Add Note" %}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Escalate Modal -->
<div id="escalateModal" style="display:none" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-2xl p-6 w-full max-w-2xl mx-4 shadow-2xl max-h-[90vh] overflow-y-auto">
        <div class="flex items-center gap-3 mb-4">
            <div class="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
                <i data-lucide="alert-triangle" class="w-5 h-5 text-red-500"></i>
            </div>
            <h3 class="text-xl font-bold text-navy">{% trans "Escalate Complaint" %}</h3>
        </div>
        <form method="post" action="{% url 'complaints:complaint_escalate' pk=complaint.pk %}">
            {% csrf_token %}
            <div class="mb-4">
                <label class="block text-sm font-semibold text-slate mb-2">{% trans "Escalate To" %} <span class="text-red-500">*</span></label>
                <select name="escalate_to" onchange="document.getElementById('escalateSubmitBtn').disabled = !this.value" class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none" required>
                    <option value="">{% trans "Select Person" %}</option>
                    {% regroup escalation_targets by group as target_groups %}
                    {% for group in target_groups %}
                    {% if group.grouper == 'department_roles' %}
                    <optgroup label="{% trans 'Department Roles' %}">
                    {% else %}
                    <optgroup label="{% trans 'Managers & Admins' %}">
                    {% endif %}
                        {% for target in group.list %}
                        <option value="{{ target.staff.id }}" {% if target.staff.id|stringformat:"s" == default_escalation_target %}selected{% endif %}>
                            {{ target.staff.get_full_name }}{% if target.role_label %} ({{ target.role_label }}){% elif target.is_line_manager %} ({% trans "Line Manager" %}){% elif target.is_manager %} ({% trans "Manager" %}){% endif %}
                        </option>
                        {% endfor %}
                    </optgroup>
                    {% endfor %}
                </select>
            </div>
            <div class="border-t border-slate-100 pt-4 mb-4">
                <p class="text-xs font-bold text-slate uppercase mb-3">{% trans "Email Preview" %} <span class="text-slate-400 font-normal normal-case">({% trans "editable" %})</span></p>
                <div class="mb-3">
                    <label class="block text-xs font-semibold text-slate mb-1">{% trans "Subject" %}</label>
                    <input type="text" name="email_subject" value="{{ escalation_email_subject }}"
                        class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate mb-1">{% trans "Body" %}</label>
                    <textarea name="email_body" rows="12"
                        class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none font-mono whitespace-pre">{{ escalation_email_body }}</textarea>
                </div>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="closeModal('escalateModal')" class="flex-1 px-4 py-2 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 transition">
                    {% trans "Cancel" %}
                </button>
                <button type="submit" id="escalateSubmitBtn" disabled class="flex-1 px-4 py-2 bg-red-500 text-white rounded-xl font-semibold hover:bg-red-600 transition flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
                    <i data-lucide="send" class="w-4 h-4"></i> {% trans "Send Escalation Email" %}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Close Modal -->
<div id="closeModal" style="display:none" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-2xl p-6 w-full max-w-lg mx-4 shadow-2xl">
        <div class="flex items-center gap-3 mb-4">
            <div class="w-10 h-10 bg-emerald-100 rounded-full flex items-center justify-center">
                <i data-lucide="circle-check" class="w-5 h-5 text-emerald-600"></i>
            </div>
            <h3 class="text-xl font-bold text-navy">{% trans "Close Complaint" %}</h3>
        </div>
        <p class="text-slate mb-4 text-sm">{% trans "Close this complaint. This will trigger a satisfaction survey." %}</p>
        <form method="post" action="{% url 'complaints:complaint_change_status' pk=complaint.pk %}">
            {% csrf_token %}
            <input type="hidden" name="status" value="closed">
            <div class="mb-4">
                <label class="block text-sm font-semibold text-slate mb-2">{% trans "Closing Note (Optional)" %}</label>
                <textarea name="note" rows="3" class="w-full border border-slate-200 rounded-xl p-4 text-sm focus:ring-2 focus:ring-navy/20 outline-none" placeholder="{% trans 'Enter closing note...' %}"></textarea>
            </div>
            <div class="flex gap-3">
                <button type="button" onclick="closeModal('closeModal')" class="flex-1 px-4 py-2 border border-slate-200 text-slate rounded-xl font-semibold hover:bg-slate-50 transition">
                    {% trans "Cancel" %}
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-emerald-600 text-white rounded-xl font-semibold hover:bg-emerald-700 transition flex items-center justify-center gap-2">
                    <i data-lucide="circle-check" class="w-4 h-4"></i> {% trans "Close Complaint" %}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Tab Switching JavaScript -->
<script>
function showActivationRequired() {
    alert('{% trans "Please activate this complaint first to access this tab." %}');
}

function switchTab(tabName) {
    // Hide all panels
    document.querySelectorAll('.tab-panel').forEach(panel => {
        panel.classList.add('hidden');
    });

    // Show selected panel
    document.getElementById('panel-' + tabName).classList.remove('hidden');

    // Update tab styles
    document.querySelectorAll('main nav button').forEach(tab => {
        tab.classList.remove('tab-active');
        tab.classList.add('tab-inactive');
    });

    document.getElementById('tab-' + tabName).classList.remove('tab-inactive');
    document.getElementById('tab-' + tabName).classList.add('tab-active');

    // Reinitialize icons for newly visible content
    if (window.lucide) {
        lucide.createIcons();
    }
}

// Modal functions
function showResolveModal() {
    document.getElementById('resolveModal').style.display = 'flex';
}

function showAssignModal() {
    document.getElementById('assignModal').style.display = 'flex';
}

function showFollowUpModal() {
    document.getElementById('followUpModal').style.display = 'flex';
}

function showEscalateModal() {
    document.getElementById('escalateModal').style.display = 'flex';
}

function showCloseModal() {
    document.getElementById('closeModal').style.display = 'flex';
}

function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// Close modal when clicking outside
window.onclick = function(event) {
    if (event && event.target) {
        var modals = ['resolveModal', 'assignModal', 'followUpModal', 'escalateModal', 'closeModal'];
        if (modals.indexOf(event.target.id) !== -1) {
            event.target.style.display = 'none';
        }
    }
};

// SLA Countdown Timer
(function() {
    var el = document.getElementById('sla-countdown');
    if (!el || !el.dataset.dueAt) return;

    var dueAt = new Date(el.dataset.dueAt).getTime();
    var isOverdue = el.dataset.overdue === 'true';

    function updateCountdown() {
        var now = Date.now();
        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 by" %} ';
            if (overD > 0) txt += overD + 'd ';
            txt += overH + 'h ' + overM + 'm';
            el.textContent = txt;
            el.className = 'text-xs font-bold mt-1 text-red-600 animate-pulse';
            return;
        }

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

        var parts = [];
        if (d > 0) parts.push(d + 'd');
        parts.push(h + 'h');
        parts.push(m + 'm');
        parts.push(s + 's');
        el.textContent = parts.join(' ') + ' {% trans "remaining" %}';

        if (diff < 21600000) {
            el.className = 'text-xs font-bold mt-1 text-red-600';
        } else if (diff < 86400000) {
            el.className = 'text-xs font-bold mt-1 text-orange-600';
        } else {
            el.className = 'text-xs font-bold mt-1 text-green-600';
        }
    }

    updateCountdown();
    setInterval(updateCountdown, 1000);
})();
</script>

{% include "components/send_to_modal.html" with users=assignable_users departments=hospital_departments %}
{% include "components/department_response_modal.html" %}

{% endblock %}
