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

{% block title %}Complaint #{{ complaint.id|slice:":8" }} - PX360{% endblock %}

{% block extra_css %}
<style>
    .complaint-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 30px;
        border-radius: 12px;
        margin-bottom: 30px;
    }
    .sla-countdown {
        background: rgba(255,255,255,0.2);
        padding: 15px;
        border-radius: 8px;
        text-align: center;
    }
    .sla-countdown.overdue {
        background: #d32f2f;
    }
    .status-badge {
        padding: 6px 16px;
        border-radius: 20px;
        font-size: 0.9rem;
        font-weight: 600;
    }
    .status-open { background: #e3f2fd; color: #1976d2; }
    .status-in_progress { background: #fff3e0; color: #f57c00; }
    .status-resolved { background: #e8f5e9; color: #388e3c; }
    .status-closed { background: #f5f5f5; color: #616161; }
    .status-cancelled { background: #ffebee; color: #d32f2f; }

    .severity-badge {
        padding: 6px 16px;
        border-radius: 20px;
        font-size: 0.9rem;
        font-weight: 600;
    }
    .severity-low { background: #e8f5e9; color: #388e3c; }
    .severity-medium { background: #fff3e0; color: #f57c00; }
    .severity-high { background: #ffebee; color: #d32f2f; }
    .severity-critical { background: #880e4f; color: #fff; }

    .timeline {
        position: relative;
        padding-left: 30px;
    }
    .timeline::before {
        content: '';
        position: absolute;
        left: 8px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #dee2e6;
    }
    .timeline-item {
        position: relative;
        padding-bottom: 30px;
    }
    .timeline-item::before {
        content: '';
        position: absolute;
        left: -26px;
        top: 5px;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: #fff;
        border: 3px solid #667eea;
        z-index: 1;
    }
    .timeline-item.status_change::before {
        border-color: #f57c00;
    }
    .timeline-item.assignment::before {
        border-color: #1976d2;
    }
    .timeline-item.escalation::before {
        border-color: #d32f2f;
    }
    .timeline-item.note::before {
        border-color: #388e3c;
    }

    .action-card {
        border-left: 4px solid #667eea;
        transition: transform 0.2s;
    }
    .action-card:hover {
        transform: translateX(5px);
    }

    .info-label {
        font-weight: 600;
        color: #6c757d;
        font-size: 0.85rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .info-value {
        font-size: 1rem;
        color: #212529;
        margin-top: 4px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Back Button -->
    <div class="mb-3">
        <a href="{% url 'complaints:complaint_list' %}" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-left me-1"></i> {{ _("Back to Complaints")}}
        </a>
    </div>

    <!-- Complaint Header -->
    <div class="card p-3">
        <div class="row align-items-center">
            <div class="col-md-8">
                <div class="d-flex align-items-center mb-2">
                    <h3 class="mb-0 me-3">{{ complaint.title }}</h3>
                    <span class="status-badge status-{{ complaint.status }}">
                        {{ complaint.get_status_display }}
                    </span>
                    <span class="severity-badge severity-{{ complaint.severity }} ms-2">
                        {{ complaint.get_severity_display }}
                    </span>
                </div>
                <p class="mb-2">
                    <i class="bi bi-hash me-1"></i>
                    <strong>{{ _("ID") }}:</strong> {{ complaint.id|slice:":8" }}
                    <span class="mx-2">|</span>
                    <i class="bi bi-person-fill me-1"></i>
                    <strong>{{ _("Patient") }}:</strong> {{ complaint.patient.get_full_name }} ({{ _("MRN") }}: {{ complaint.patient.mrn }})
                </p>
                <p class="mb-0">
                    <i class="bi bi-hospital me-1"></i>
                    <strong>{{ _("Hospital") }}:</strong> {{ complaint.hospital.name_en }}
                    {% if complaint.department %}
                    <span class="mx-2">|</span>
                    <i class="bi bi-building me-1"></i>
                    <strong>{{ _("Department") }}:</strong> {{ complaint.department.name_en }}
                    {% endif %}
                </p>
            </div>
            <div class="col-md-4">
                <div class="sla-countdown {% if complaint.is_overdue %}overdue{% endif %}">
                    <div class="mb-1">
                        <i class="bi bi-clock-history me-1"></i>
                        <strong>{{ _("SLA Deadline")}}</strong>
                    </div>
                    <h4 class="mb-0">{{ complaint.due_at|date:"M d, Y H:i" }}</h4>
                    {% if complaint.is_overdue %}
                    <div class="mt-2">
                        <i class="bi bi-exclamation-triangle-fill me-1"></i>
                        <strong>{{ _("OVERDUE") }}</strong>
                    </div>
                    {% else %}
                    <small>{{ complaint.due_at|timeuntil }} {{ _("remaining") }}</small>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Main Content -->
        <div class="col-lg-8">
            <!-- Tabs -->
            <ul class="nav nav-tabs mb-3" id="complaintTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="details-tab" data-bs-toggle="tab"
                            data-bs-target="#details" type="button" role="tab">
                        <i class="bi bi-info-circle me-1"></i> {{ _("Details") }}
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="timeline-tab" data-bs-toggle="tab"
                            data-bs-target="#timeline" type="button" role="tab">
                        <i class="bi bi-clock-history me-1"></i> {{ _("Timeline") }} ({{ timeline.count }})
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="attachments-tab" data-bs-toggle="tab"
                            data-bs-target="#attachments" type="button" role="tab">
                        <i class="bi bi-paperclip me-1"></i> {{ _("Attachments") }} ({{ attachments.count }})
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="actions-tab" data-bs-toggle="tab"
                            data-bs-target="#actions" type="button" role="tab">
                        <i class="bi bi-lightning-fill me-1"></i> {{ _("PX Actions")}} ({{ px_actions.count }})
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="explanation-tab" data-bs-toggle="tab"
                            data-bs-target="#explanation" type="button" role="tab">
                        <i class="bi bi-chat-quote me-1"></i> {{ _("Explanation")}}
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="pdf-tab" data-bs-toggle="tab"
                            data-bs-target="#pdf" type="button" role="tab">
                        <i class="bi bi-file-earmark-pdf me-1"></i> {{ _("PDF View")}}
                    </button>
                </li>
            </ul>

            <!-- Tab Content -->
            <div class="tab-content" id="complaintTabsContent">
                <!-- Details Tab -->
                <div class="tab-pane fade show active" id="details" role="tabpanel">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title mb-4">{% trans "Complaint Details" %}</h5>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <div class="info-label">{{ _("Category") }}</div>
                                    <div class="info-value">
                                        <span class="badge bg-secondary">{{ complaint.get_category_display }}</span>
                                        {% if complaint.subcategory %}
                                        <span class="text-muted ms-2">/ {{ complaint.subcategory }}</span>
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="info-label">{{ _("Source") }}</div>
                                    <div class="info-value">{{ complaint.get_source_display }}</div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <div class="info-label">{{ _("Priority") }}</div>
                                    <div class="info-value">
                                        <span class="badge bg-info">{{ complaint.get_priority_display }}</span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="info-label">{{ _("Encounter ID")}}</div>
                                    <div class="info-value">
                                        {% if complaint.encounter_id %}
                                        {{ complaint.encounter_id }}
                                        {% else %}
                                        <span class="text-muted">{{ _("N/A")}}</span>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>


                            {% if complaint.department %}
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <div class="info-label">{{ _("Department") }}</div>
                                    <div class="info-value">
                                        <div class="d-flex align-items-center">
                                            <i class="bi bi-building me-2"></i>
                                            <div>
                                                <strong>{{ complaint.department.name_en }}</strong>
                                                {% if complaint.department.name_ar %}
                                                <span class="text-muted ms-2">({{ complaint.department.name_ar }})</span>
                                                {% endif %}
                                            </div>
                                            {% if complaint.metadata.ai_analysis.old_department %}
                                            <span class="badge bg-info ms-auto">
                                                <i class="bi bi-robot me-1"></i>{{ _("AI Mapped")}}
                                            </span>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            {% if complaint.staff %}
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <div class="info-label">{{ _("Staff Member") }}</div>
                                    <div class="info-value">
                                        <div class="d-flex align-items-center">
                                            <i class="bi bi-person-badge me-2"></i>
                                            <div>
                                                <strong>{{ complaint.staff.first_name }} {{ complaint.staff.last_name }}</strong>
                                                {% if complaint.staff.first_name_ar or complaint.staff.last_name_ar %}
                                                <span class="text-muted ms-2">({{ complaint.staff.first_name_ar }} {{ complaint.staff.last_name_ar }})</span>
                                                {% endif %}
                                                {% if complaint.staff.job_title %}
                                                <div class="text-muted">{{ complaint.staff.job_title }}</div>
                                                {% endif %}
                                            </div>
                                            <span class="badge bg-success ms-auto">
                                                <i class="bi bi-robot me-1"></i>{{ _("AI Matched")}}
                                            </span>
                                        </div>
                                        {% if complaint.metadata.ai_analysis.extracted_staff_name %}
                                        <small class="text-muted mt-1 d-block">
                                            <i class="bi bi-lightning me-1"></i>
                                            {{ _("Extracted from complaint")}}: "{{ complaint.metadata.ai_analysis.extracted_staff_name }}"
                                            {% if complaint.metadata.ai_analysis.staff_confidence %}
                                            ({{ _("confidence") }}: {{ complaint.metadata.ai_analysis.staff_confidence|floatformat:0 }}%)
                                            {% endif %}
                                        </small>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            <!-- Staff Suggestions Section -->
                            {% if complaint.metadata.ai_analysis.staff_matches and user.is_px_admin %}
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <div class="info-label">
                                        <i class="bi bi-people me-1"></i>
                                        {{ _("Staff Suggestions")}}
                                        {% if complaint.metadata.ai_analysis.needs_staff_review %}
                                        <span class="badge bg-warning ms-2">{{ _("Needs Review")}}</span>
                                        {% endif %}
                                    </div>
                                    <div class="info-value">
                                        {% if complaint.metadata.ai_analysis.extracted_staff_name %}
                                        <p class="text-muted mb-2">
                                            {{ _("AI extracted name")}}: <strong>"{{ complaint.metadata.ai_analysis.extracted_staff_name }}"</strong>
                                            ({% if complaint.metadata.ai_analysis.staff_match_count %}{{ complaint.metadata.ai_analysis.staff_match_count }}{{ _("potential match")}}{{ complaint.metadata.ai_analysis.staff_match_count|pluralize }}{% else %}{{ _("No matches found")}}{% endif %})
                                        </p>
                                        {% endif %}

                                        <div class="list-group">
                                            {% for staff_match in complaint.metadata.ai_analysis.staff_matches %}
                                            <div class="list-group-item list-group-item-action {% if complaint.staff and staff_match.id == complaint.staff.id|stringformat:"s" %}list-group-item-primary{% endif %}">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <div class="d-flex align-items-center">
                                                            <i class="bi bi-person me-2 text-primary"></i>
                                                            <strong>{{ staff_match.name_en }}</strong>
                                                            {% if staff_match.name_ar %}
                                                            <span class="text-muted ms-2">({{ staff_match.name_ar }})</span>
                                                            {% endif %}
                                                        </div>
                                                        {% if staff_match.job_title %}
                                                        <small class="text-muted">{{ staff_match.job_title }}</small>
                                                        {% endif %}
                                                        {% if staff_match.specialization %}
                                                        <small class="text-muted"> • {{ staff_match.specialization }}</small>
                                                        {% endif %}
                                                        {% if staff_match.department %}
                                                        <small class="text-muted"> • {{ staff_match.department }}</small>
                                                        {% endif %}
                                                    </div>
                                                    <div class="text-end">
                                                        <span class="badge {% if staff_match.confidence >= 0.7 %}bg-success{% elif staff_match.confidence >= 0.5 %}bg-warning{% else %}bg-danger{% endif %}">
                                                            {{ staff_match.confidence|mul:100|floatformat:0 }}% {{ _("confidence") }}
                                                        </span>
                                                        {% if complaint.staff and staff_match.id == complaint.staff.id|stringformat:"s" %}
                                                        <div class="small text-success mt-1">
                                                            <i class="bi bi-check-circle-fill"></i> {{ _("Currently assigned")}}
                                                        </div>
                                                        {% elif not complaint.staff %}
                                                        <button class="btn btn-sm btn-outline-primary mt-1" onclick="assignStaff('{{ staff_match.id }}', '{{ staff_match.name_en }}')">
                                                            <i class="bi bi-person-plus"></i> {{ _("Select") }}
                                                        </button>
                                                        {% endif %}
                                                    </div>
                                                </div>
                                            </div>
                                            {% endfor %}
                                        </div>

                                        <div class="mt-3">
                                            <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#staffSelectionModal">
                                                <i class="bi bi-search me-1"></i> {{ _("Search All Staff")}}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            <hr>

                            <div class="mb-3">
                                <div class="info-label">{{ _("Description") }}</div>
                                <div class="info-value mt-2">
                                    <p class="mb-0">{{ complaint.description|linebreaks }}</p>
                                </div>
                            </div>

                            <!-- AI Analysis Section -->
                            {% if complaint.short_description_ar or complaint.suggested_action_ar %}
                            <hr>
                            <div class="mb-3">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="info-label mb-0 me-2">
                                        <i class="bi bi-robot me-1"></i>{{ _("AI Analysis")}}
                                    </div>
                                    <span class="badge bg-info">{{ _("AI Generated")}}</span>
                                </div>

                                <!-- Emotion Analysis -->
                                {% if complaint.emotion %}
                                <div class="mb-3">
                                    <div class="info-label" style="font-size: 0.8rem;">{{ _("Emotion Analysis")}}</div>
                                    <div class="card mb-0" style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-left: 4px solid #6c757d;">
                                        <div class="card-body py-2">
                                            <div class="row align-items-center mb-2">
                                                <div class="col-md-6">
                                                    <span class="badge bg-{{ complaint.get_emotion_badge_class }} me-2">
                                                        <i class="bi bi-emoji-frown me-1"></i>{{ complaint.get_emotion_display }}
                                                    </span>
                                                </div>
                                                <div class="col-md-6 text-md-end">
                                                    <small class="text-muted">{{ _("Confidence") }}: {{ complaint.emotion_confidence|mul:100|floatformat:0 }}%</small>
                                                </div>
                                            </div>
                                            <div class="mb-1">
                                                <div class="d-flex justify-content-between mb-1">
                                                    <small class="text-muted">{{ _("Intensity") }}</small>
                                                    <small>{{ complaint.emotion_intensity|floatformat:2 }} / 1.0</small>
                                                </div>
                                                <div class="progress" style="height: 6px;">
                                                    {% if complaint.emotion == 'anger' %}
                                                    <div class="progress-bar bg-danger" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
                                                    {% elif complaint.emotion == 'sadness' %}
                                                    <div class="progress-bar bg-primary" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
                                                    {% elif complaint.emotion == 'confusion' %}
                                                    <div class="progress-bar bg-warning" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
                                                    {% elif complaint.emotion == 'fear' %}
                                                    <div class="progress-bar bg-info" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
                                                    {% else %}
                                                    <div class="progress-bar bg-secondary" role="progressbar" style="width: {{ complaint.emotion_intensity|mul:100 }}%"></div>
                                                    {% endif %}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                {% endif %}

                                {% if complaint.short_description_ar %}
                                <div class="mb-3">
                                    <div class="info-label" style="font-size: 0.8rem;">{{ _("Summary") }}</div>
                                    <div class="alert alert-light border-info mb-0" style="background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);">
                                        <i class="bi bi-info-circle me-1 text-info"></i>
                                        <small>{{ complaint.short_description_ar }}</small>
                                    </div>
                                </div>
                                {% endif %}

                                {% if complaint.suggested_action_ar %}
                                <div class="mb-0">
                                    <div class="info-label" style="font-size: 0.8rem;">{{ _("Suggested Action")}}</div>
                                    <div class="alert alert-success mb-0" style="background: linear-gradient(135deg, #e8f5e9 0%, #e1f5fe 100%); border-color: #4caf50;">
                                        <i class="bi bi-lightning me-1 text-success"></i>
                                        <small>{{ complaint.suggested_action_ar }}</small>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#createActionModal">
                                        <i class="bi bi-plus-circle me-1"></i> {{ _("Create PX Action")}}
                                    </button>
                                </div>
                                {% endif %}
                            </div>
                            {% endif %}

                            {% if complaint.resolution %}
                            <hr>
                            <div class="mb-3">
                                <div class="info-label">{{ _("Resolution") }}</div>
                                <div class="info-value mt-2">
                                    <div class="alert alert-success">
                                        <p class="mb-2">{{ complaint.resolution|linebreaks }}</p>
                                        <small class="text-muted">
                                            {{ _("Resolved by")}} {{ complaint.resolved_by.get_full_name }}
                                            {{ _("on") }} {{ complaint.resolved_at|date:"M d, Y H:i" }}
                                        </small>
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            <hr>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="info-label">{{ _("Created") }}</div>
                                    <div class="info-value">{{ complaint.created_at|date:"M d, Y H:i" }}</div>
                                </div>
                                <div class="col-md-6">
                                    <div class="info-label">{{ _("Last Updated")}}</div>
                                    <div class="info-value">{{ complaint.updated_at|date:"M d, Y H:i" }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Timeline Tab -->
                <div class="tab-pane fade" id="timeline" role="tabpanel">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title mb-4">{% trans "Activity Timeline" %}</h5>

                            {% if timeline %}
                            <div class="timeline">
                                {% for update in timeline %}
                                <div class="timeline-item {{ update.update_type }}">
                                    <div class="card mb-3">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <div>
                                                    <span class="badge bg-primary">{{ update.get_update_type_display }}</span>
                                                    {% if update.created_by %}
                                                    <span class="text-muted ms-2">
                                                        by {{ update.created_by.get_full_name }}
                                                    </span>
                                                    {% endif %}
                                                </div>
                                                <small class="text-muted">
                                                    {{ update.created_at|date:"M d, Y H:i" }}
                                                </small>
                                            </div>
                                            <p class="mb-0">{{ update.message }}</p>
                                            {% if update.old_status and update.new_status %}
                                            <div class="mt-2">
                                                <span class="status-badge status-{{ update.old_status }}">
                                                    {{ update.old_status }}
                                                </span>
                                                <i class="bi bi-arrow-right mx-2"></i>
                                                <span class="status-badge status-{{ update.new_status }}">
                                                    {{ update.new_status }}
                                                </span>
                                            </div>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-5">
                                <i class="bi bi-clock-history" style="font-size: 3rem; color: #ccc;"></i>
                                <p class="text-muted mt-3">{{ _("No timeline entries yet")}}</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- Attachments Tab -->
                <div class="tab-pane fade" id="attachments" role="tabpanel">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title mb-4">{% trans "Attachments" %}</h5>

                            {% if attachments %}
                            <div class="list-group">
                                {% for attachment in attachments %}
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <i class="bi bi-file-earmark me-2"></i>
                                            <strong>{{ attachment.filename }}</strong>
                                            <br>
                                            <small class="text-muted">
                                                Uploaded by {{ attachment.uploaded_by.get_full_name }}
                                                on {{ attachment.created_at|date:"M d, Y H:i" }}
                                                ({{ attachment.file_size|filesizeformat }})
                                            </small>
                                            {% if attachment.description %}
                                            <br>
                                            <small>{{ attachment.description }}</small>
                                            {% endif %}
                                        </div>
                                        <a href="{{ attachment.file.url }}" class="btn btn-sm btn-outline-primary"
                                           target="_blank" download>
                                            <i class="bi bi-download"></i>
                                        </a>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="text-center py-5">
                                <i class="bi bi-paperclip" style="font-size: 3rem; color: #ccc;"></i>
                                <p class="text-muted mt-3">{{ _("No attachments")}}</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- Explanation Tab -->
                <div class="tab-pane fade" id="explanation" role="tabpanel">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title mb-4">{% trans "Staff Explanation" %}</h5>

                            {% if complaint.explanation %}
                            <!-- Existing Explanation -->
                            <div class="alert alert-info">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <h6 class="mb-2">
                                            <i class="bi bi-chat-quote me-2"></i>
                                            {% trans "Explanation Received" %}
                                        </h6>
                                        <p class="mb-2">{{ complaint.explanation.explanation|linebreaks }}</p>
                                        {% if complaint.explanation.staff_name %}
                                        <p class="mb-0 text-muted">
                                            <small>
                                                <strong>{% trans "Staff:" %}</strong> {{ complaint.explanation.staff_name }}
                                            </small>
                                        </p>
                                        {% endif %}
                                    </div>
                                    <span class="badge bg-success">
                                        <i class="bi bi-check-circle"></i>
                                        {% trans "Submitted" %}
                                    </span>
                                </div>
                                <hr class="my-2">
                                <small class="text-muted">
                                    <i class="bi bi-clock me-1"></i>
                                    {{ complaint.explanation.responded_at|date:"M d, Y H:i" }}
                                    {% if complaint.explanation.attachment_count > 0 %}
                                    <span class="mx-2">|</span>
                                    <i class="bi bi-paperclip me-1"></i>
                                    {{ complaint.explanation.attachment_count }} {% trans "attachment(s)" %}
                                    {% endif %}
                                </small>
                                {% if complaint.explanation.attachments %}
                                <div class="mt-3">
                                    <h6 class="small text-muted">{% trans "Attachments:" %}</h6>
                                    {% for attachment in complaint.explanation.attachments %}
                                    <a href="{{ attachment.file.url }}" class="btn btn-sm btn-outline-secondary me-2" download>
                                        <i class="bi bi-download"></i> {{ attachment.filename }}
                                    </a>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>

                            {% if complaint.explanation and complaint.explanation.token %}
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-outline-primary" onclick="copyExplanationLink()">
                                    <i class="bi bi-link-45deg me-1"></i> {% trans "Copy Link" %}
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="resendExplanation()">
                                    <i class="bi bi-envelope me-1"></i> {% trans "Resend Email" %}
                                </button>
                            </div>
                            {% endif %}

                            <div class="mt-3">
                                <div class="card bg-light">
                                    <div class="card-body py-2">
                                        <small class="text-muted">
                                            <i class="bi bi-info-circle me-1"></i>
                                            {% trans "Explanation ID:" %} {{ complaint.explanation.id }} |
                                            {% trans "Token:" %} {{ complaint.explanation.token|slice:":8" }}...
                                        </small>
                                    </div>
                                </div>
                            </div>

                            {% else %}
                            <!-- No Explanation Yet -->
                            <div class="text-center py-5">
                                <i class="bi bi-chat-quote" style="font-size: 3rem; color: #ccc;"></i>
                                <p class="text-muted mt-3">{% trans "No explanation has been submitted yet." %}</p>

                                {% if can_edit %}
                                <div class="card border-info mt-4">
                                    <div class="card-body">
                                        <h6 class="card-title">
                                            <i class="bi bi-lightning-charge me-2"></i>
                                            {% trans "Request Explanation" %}
                                        </h6>
                                        <p class="card-text text-muted">
                                            {% trans "Send a link to the assigned staff member requesting their explanation about this complaint." %}
                                        </p>

                                        {% if complaint.staff %}
                                        <div class="alert alert-success mb-3">
                                            <i class="bi bi-person-badge me-1"></i>
                                            <strong>{% trans "Will be sent to:" %}</strong>
                                            {{ complaint.staff.get_full_name }}
                                            {% if complaint.staff.user %}
                                            <br><small class="text-muted">{{ complaint.staff.user.email }}</small>
                                            {% elif complaint.staff.email %}
                                            <br><small class="text-muted">{{ complaint.staff.email }}</small>
                                            {% else %}
                                            <br><small class="text-danger"><i class="bi bi-exclamation-triangle"></i> {% trans "No email configured" %}</small>
                                            {% endif %}
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">{% trans "Custom Message (Optional)" %}</label>
                                            <textarea id="explanationMessage" class="form-control" rows="3"
                                                      placeholder="{% trans 'Add a custom message to include in the email...' %}"></textarea>
                                        </div>

                                        <button type="button" class="btn btn-primary" onclick="requestExplanation()">
                                            <i class="bi bi-send me-1"></i> {% trans "Request Explanation" %}
                                        </button>

                                        {% else %}
                                        <div class="alert alert-warning mb-3">
                                            <i class="bi bi-exclamation-triangle me-1"></i>
                                            {% trans "Please assign a staff member to this complaint before requesting an explanation." %}
                                        </div>
                                        {% endif %}
                                    </div>
                                </div>
                                {% endif %}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- PX Actions Tab -->
                <div class="tab-pane fade" id="actions" role="tabpanel">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title mb-4">{% trans "Related PX Actions" %}</h5>

                            {% if px_actions %}
                            {% for action in px_actions %}
                            <div class="card action-card mb-3">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6 class="mb-1">{{ action.title }}</h6>
                                            <p class="text-muted mb-2">{{ action.description|truncatewords:20 }}</p>
                                            <div>
                                                <span class="badge bg-{{ action.status }}">{{ action.get_status_display }}</span>
                                                <span class="badge bg-secondary ms-1">{{ action.get_priority_display }}</span>
                                            </div>
                                        </div>
                                        <a href="{% url 'actions:action_detail' action.id %}"
                                           class="btn btn-sm btn-outline-primary">
                                            {{ _("View") }} <i class="bi bi-arrow-right ms-1"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                            {% else %}
                            <div class="text-center py-5">
                                <i class="bi bi-lightning" style="font-size: 3rem; color: #ccc;"></i>
                                <p class="text-muted mt-3">{{ _("No PX actions created yet")}}</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- PDF View Tab -->
                <div class="tab-pane fade" id="pdf" role="tabpanel">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title mb-4">
                                <i class="bi bi-file-earmark-pdf me-2"></i>{% trans "PDF View" %}
                            </h5>

                            <div class="text-center mb-4">
                                <a href="{% url 'complaints:complaint_pdf' complaint.id %}"
                                   class="btn btn-primary btn-lg"
                                   target="_blank">
                                    <i class="bi bi-download me-2"></i>{% trans "Download PDF" %}
                                </a>
                                <div class="mt-3 text-muted">
                                    <small>
                                        <i class="bi bi-info-circle me-1"></i>
                                        {% trans "This will generate a professionally formatted PDF with all complaint details, including AI analysis, staff assignment, and resolution information." %}
                                    </small>
                                </div>
                            </div>

                            <hr>

                            <div class="alert alert-info">
                                <h6 class="alert-heading">
                                    <i class="bi bi-file-text me-2"></i>{% trans "PDF Contents" %}
                                </h6>
                                <ul class="mb-0">
                                    <li><strong>{% trans "Header:" %}</strong> Complaint title, ID, status, severity, patient info</li>
                                    <li><strong>{% trans "Basic Information:" %}</strong> Category, source, priority, encounter ID, dates</li>
                                    <li><strong>{% trans "Description:" %}</strong> Full complaint details</li>
                                    <li><strong>{% trans "Staff Assignment:" %}</strong> Assigned staff member (if any)</li>
                                    <li><strong>{% trans "AI Analysis:" %}</strong> Emotion analysis, summary, suggested action (if available)</li>
                                    <li><strong>{% trans "Resolution:" %}</strong> Resolution details (if resolved)</li>
                                </ul>
                            </div>

                            <div class="alert alert-warning">
                                <h6 class="alert-heading">
                                    <i class="bi bi-exclamation-triangle me-2"></i>{% trans "Note" %}
                                </h6>
                                <p class="mb-0">
                                    {% trans "PDF generation requires WeasyPrint to be installed. If you see an error message, please contact your system administrator." %}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sidebar Actions -->
        <div class="col-lg-4">
            <!-- Quick Actions -->
            {% if can_edit %}
            <div class="card mb-3">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0"><i class="bi bi-lightning-fill me-2"></i>{% trans "Quick Actions" %}</h6>
                </div>
                <div class="card-body">
                    {% if user.is_px_admin %}
                    <!-- Change Staff (PX Admin only) -->
                    <div class="mb-3">
                        <label class="form-label">{% trans "Change Staff" %}</label>
                        <button type="button" class="btn btn-outline-info w-100" data-bs-toggle="modal" data-bs-target="#staffSelectionModal">
                            <i class="bi bi-person-badge me-1"></i> {{ _("Assign/Change Staff")}}
                        </button>
                        {% if complaint.metadata.ai_analysis.needs_staff_review %}
                        <small class="text-warning">
                            <i class="bi bi-exclamation-triangle me-1"></i>
                            This complaint needs staff review
                        </small>
                        {% endif %}
                    </div>
                    <hr>
                    {% endif %}

                    <!-- Change Department -->
                    {% if can_edit and hospital_departments %}
                    <form method="post" action="{% url 'complaints:complaint_change_department' complaint.id %}" class="mb-3">
                        {% csrf_token %}
                        <label class="form-label">{% trans "Change Department" %}</label>
                        <div class="input-group">
                            <select name="department_id" class="form-select" required>
                                <option value="">{{ _("Select department...")}}</option>
                                {% for dept in hospital_departments %}
                                <option value="{{ dept.id }}"
                                        {% if complaint.department and complaint.department.id == dept.id %}selected{% endif %}>
                                    {% if LANGUAGE_CODE == 'ar' %}
                                        {{ dept.name_ar|default:dept.name }}
                                    {% else %}
                                        {{ dept.name }}
                                    {% endif %}
                                </option>
                                {% endfor %}
                            </select>
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-building"></i>
                            </button>
                        </div>
                    </form>
                    {% endif %}

                    <!-- Assign -->
                    <form method="post" action="{% url 'complaints:complaint_assign' complaint.id %}" class="mb-3">
                        {% csrf_token %}
                        <label class="form-label">{% trans "Assign To" %}</label>
                        <div class="input-group">
                            <select name="user_id" class="form-select" required>
                                <option value="">{{ _("Select user...")}}</option>
                                {% for user_obj in assignable_users %}
                                <option value="{{ user_obj.id }}"
                                        {% if complaint.assigned_to and complaint.assigned_to.id == user_obj.id %}selected{% endif %}>
                                    {{ user_obj.get_full_name }}
                                </option>
                                {% endfor %}
                            </select>
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-person-check"></i>
                            </button>
                        </div>
                    </form>

                    <!-- Change Status -->
                    <form method="post" action="{% url 'complaints:complaint_change_status' complaint.id %}" class="mb-3">
                        {% csrf_token %}
                        <label class="form-label">{% trans "Change Status" %}</label>
                        <select name="status" class="form-select mb-2" required>
                            {% for value, label in status_choices %}
                            <option value="{{ value }}" {% if complaint.status == value %}selected{% endif %}>
                                {{ label }}
                            </option>
                            {% endfor %}
                        </select>
                        <textarea name="note" class="form-control mb-2" rows="2"
                                  placeholder="{% trans 'Optional note...' %}"></textarea>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-arrow-repeat me-1"></i> {{ _("Update Status")}}
                        </button>
                    </form>

                    <!-- Request Explanation -->
                    <button type="button" class="btn btn-info w-100 mb-2" onclick="switchToExplanationTab()">
                        <i class="bi bi-chat-quote me-1"></i> {{ _("Request Explanation") }}
                    </button>

                    <!-- Send Notification -->
                    <button type="button" class="btn btn-outline-info w-100 mb-2" data-bs-toggle="modal"
                            data-bs-target="#sendNotificationModal">
                        <i class="bi bi-envelope me-1"></i> {{ _("Send Notification") }}
                    </button>

                    <!-- Escalate -->
                    <button type="button" class="btn btn-danger w-100" data-bs-toggle="modal"
                            data-bs-target="#escalateModal">
                        <i class="bi bi-exclamation-triangle me-1"></i> {{ _("Escalate") }}
                    </button>
                </div>
            </div>
            {% endif %}

            <!-- Add Note -->
            <div class="card mb-3">
                <div class="card-header bg-success text-white">
                    <h6 class="mb-0"><i class="bi bi-chat-left-text me-2"></i>{% trans "Add Note" %}</h6>
                </div>
                <div class="card-body">
                    <form method="post" action="{% url 'complaints:complaint_add_note' complaint.id %}">
                        {% csrf_token %}
                        <textarea name="note" class="form-control mb-2" rows="3"
                                  placeholder="{% trans 'Enter your note...' %}" required></textarea>
                        <button type="submit" class="btn btn-success w-100">
                            <i class="bi bi-plus-circle me-1"></i> {{ _("Add Note")}}
                        </button>
                    </form>
                </div>
            </div>

            <!-- Assignment Info -->
            <div class="card mb-3">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-info-circle me-2"></i>{% trans "Assignment Info" %}</h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="info-label">{{ _("Assigned To")}}</div>
                        <div class="info-value">
                            {% if complaint.assigned_to %}
                            {{ complaint.assigned_to.get_full_name }}
                            <br>
                            <small class="text-muted">
                                Assigned {{ complaint.assigned_at|date:"M d, Y H:i" }}
                            </small>
                            {% else %}
                            <span class="text-muted">{{ _("Unassigned") }}</span>
                            {% endif %}
                        </div>
                    </div>

                    {% if complaint.resolved_by %}
                    <div class="mb-3">
                        <div class="info-label">{{ _("Resolved By")}}</div>
                        <div class="info-value">
                            {{ complaint.resolved_by.get_full_name }}
                            <br>
                            <small class="text-muted">
                                {{ complaint.resolved_at|date:"M d, Y H:i" }}
                            </small>
                        </div>
                    </div>
                    {% endif %}

                    {% if complaint.closed_by %}
                    <div class="mb-0">
                        <div class="info-label">{{ _("Closed By")}}</div>
                        <div class="info-value">
                            {{ complaint.closed_by.get_full_name }}
                            <br>
                            <small class="text-muted">
                                {{ complaint.closed_at|date:"M d, Y H:i" }}
                            </small>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- Resolution Survey -->
            {% if complaint.resolution_survey %}
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="bi bi-clipboard-check me-2"></i>{% trans "Resolution Survey" %}</h6>
                </div>
                <div class="card-body">
                    <p class="mb-2">
                        <strong>{{ _("Status") }}:</strong>
                        <span class="badge bg-{{ complaint.resolution_survey.status }}">
                            {{ complaint.resolution_survey.get_status_display }}
                        </span>
                    </p>
                    {% if complaint.resolution_survey.score %}
                    <p class="mb-2">
                        <strong>{{ _("Score") }}:</strong> {{ complaint.resolution_survey.score }}/100
                    </p>
                    {% endif %}
                    <a href="{% url 'surveys:survey_instance_detail' complaint.resolution_survey.id %}"
                       class="btn btn-sm btn-outline-info">
                        {{ _("View Survey")}} <i class="bi bi-arrow-right ms-1"></i>
                    </a>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Escalate Modal -->
<div class="modal fade" id="escalateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" action="{% url 'complaints:complaint_escalate' complaint.id %}">
                {% csrf_token %}
                <div class="modal-header">
                    <h5 class="modal-title">{% trans "Escalate Complaint" %}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        {{ _("This will escalate")}} {{ _("complaint to higher management")}}}}.
                    </div>
                    <div class="mb-3">
                        <label class="form-label">{% trans "Reason for Escalation" %}</label>
                        <textarea name="reason" class="form-control" rows="3"
                                  placeholder="{% trans 'Explain why this complaint needs escalation...' %}" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Cancel" %}</button>
                    <button type="submit" class="btn btn-danger">
                        <i class="bi bi-exclamation-triangle me-1"></i> {{ _("Escalate") }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Create PX Action Modal -->
<div class="modal fade" id="createActionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-lightning-fill me-2"></i>{{ _("Create PX Action from AI Suggestion")}}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    {{ _("This will create a PX Action based on the AI-suggested action for this complaint")}}.
                </div>

                <div class="mb-3">
                    <label class="form-label">{{ _("Auto-mapped Category")}}</label>
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="bi bi-tag"></i>
                        </span>
                        <input type="text" id="autoMappedCategory" class="form-control" readonly
                               value="{% if complaint.category %}{{ complaint.category.name_en }}{% else %}Other{% endif %}">
                    </div>
                    <small class="text-muted">{{ _("Category automatically mapped from complaint category")}}</small>
                </div>

                <div class="mb-3">
                    <label class="form-label">{{ _("Assign To (Optional)")}}</label>
                    <select id="actionAssignTo" class="form-select">
                        <option value="">{{ _("Leave unassigned")}}</option>
                        {% for user_obj in assignable_users %}
                        <option value="{{ user_obj.id }}">{{ user_obj.get_full_name }}</option>
                        {% endfor %}
                    </select>
                    <small class="text-muted">{{ _("If left unassigned, you can assign the action later")}}.</small>
                </div>

                <div class="mb-0">
                    <label class="form-label">{{ _("Action Description")}}</label>
                    <div class="alert alert-success mb-0">
                        <small>{{ complaint.suggested_action }}</small>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ _("Cancel") }}</button>
                <button type="button" id="createActionBtn" class="btn btn-primary" onclick="createAction()">
                    <i class="bi bi-plus-circle me-1"></i>{{ _("Create Action")}}
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Staff Selection Modal -->
<div class="modal fade" id="staffSelectionModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-person-badge me-2"></i>{{ _("Select Staff Member")}}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- Department Filter -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">{{ _("Filter by Department")}}</label>
                        <select id="staffDepartmentFilter" class="form-select">
                            <option value="">{{ _("All Departments")}}</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">{{ _("Search Staff")}}</label>
                        <input type="text" id="staffSearchInput" class="form-control" placeholder="Search by name or job title...">
                    </div>
                </div>

                <!-- Staff List -->
                <div id="staffListContainer" class="border rounded" style="max-height: 400px; overflow-y: auto;">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">{{ _("Loading...")}}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="assignSelectedStaffBtn" class="btn btn-primary" onclick="assignSelectedStaff()" disabled>
                    <i class="bi bi-person-check me-1"></i>Assign Selected Staff
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Send Notification Modal -->
<div class="modal fade" id="sendNotificationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-envelope me-2"></i>{{ _("Send Complaint Notification")}}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- AI Summary (EDITABLE) -->
                <div class="mb-3">
                    <label class="form-label">
                        <i class="bi bi-robot me-1"></i>
                        {{ _("AI Summary")}}
                        <small class="text-muted">({{ _("you can edit this before sending")}})</small>
                    </label>
                    <textarea id="emailMessage" class="form-control" rows="5"
                              placeholder="Enter message to send...">{{ complaint.short_description }}</textarea>
                    <small class="text-muted">
                        {{ _("This is AI-generated summary. You can edit it before sending")}}.
                    </small>
                </div>

                <!-- Recipient Information -->
                <div class="card mb-3">
                    <div class="card-body">
                        <h6 class="card-title">
                            <i class="bi bi-person-check me-1"></i>{{ _("Recipient") }}
                        </h6>

                        {% if complaint.staff %}
                        <!-- Staff is assigned - always the primary recipient -->
                        {% if complaint.staff.user %}
                        <!-- Staff has user account -->
                        <div class="alert alert-success mb-2">
                            <i class="bi bi-check-circle-fill me-1"></i>
                            <strong>Primary Recipient (Assigned Staff with User Account):</strong> {{ complaint.staff.get_full_name }}
                            {% if complaint.staff.job_title %}
                            <br><small class="text-muted">{{ complaint.staff.job_title }}</small>
                            {% endif %}
                            {% if complaint.staff.department %}
                            <br><small class="text-muted">{{ complaint.staff.department.name_en }}</small>
                            {% endif %}
                            <hr class="my-2">
                            <small class="text-success"><i class="bi bi-envelope me-1"></i>Email will be sent to: {{ complaint.staff.user.email }}</small>
                        </div>
                        {% elif complaint.staff.email %}
                        <!-- Staff has email but no user account -->
                        <div class="alert alert-warning mb-2">
                            <i class="bi bi-exclamation-triangle-fill me-1"></i>
                            <strong>Primary Recipient (Assigned Staff - Email):</strong> {{ complaint.staff.get_full_name }}
                            {% if complaint.staff.job_title %}
                            <br><small class="text-muted">{{ complaint.staff.job_title }}</small>
                            {% endif %}
                            {% if complaint.staff.department %}
                            <br><small class="text-muted">{{ complaint.staff.department.name_en }}</small>
                            {% endif %}
                            <hr class="my-2">
                            <small class="text-warning"><i class="bi bi-envelope me-1"></i>Email will be sent to: {{ complaint.staff.email }}</small>
                        </div>
                        {% else %}
                        <!-- Staff has no user account and no email -->
                        <div class="alert alert-warning mb-2">
                            <i class="bi bi-exclamation-triangle-fill me-1"></i>
                            <strong>Assigned Staff:</strong> {{ complaint.staff.get_full_name }}
                            {% if complaint.staff.job_title %}
                            <br><small class="text-muted">{{ complaint.staff.job_title }}</small>
                            {% endif %}
                            {% if complaint.staff.department %}
                            <br><small class="text-muted">{{ complaint.staff.department.name_en }}</small>
                            {% endif %}
                            <hr class="my-2">
                            <small class="text-danger"><i class="bi bi-x-circle me-1"></i>No email configured for this staff member</small>
                        </div>
                        {% endif %}

                        {% if not complaint.staff.user and not complaint.staff.email %}
                        <!-- Staff has no user account and no email - show fallback -->
                        {% if complaint.department and complaint.department.manager %}
                        <div class="alert alert-info mb-0">
                            <i class="bi bi-person-badge me-1"></i>
                            <strong>Actual Recipient:</strong> {{ complaint.department.manager.get_full_name }}
                            <br><small class="text-muted">{{ _("Department Head of")}} {{ complaint.department.name_en }}</small>
                            <i class="bi bi-info-circle-fill me-1"></i>
                            <strong>Fallback Recipient (Department Head):</strong> {{ complaint.department.manager.get_full_name }}
                            {% if complaint.department.manager.email %}
                            <br><small class="text-info"><i class="bi bi-envelope me-1"></i>Email will be sent to: {{ complaint.department.manager.email }}</small>
                            {% else %}
                            <br><small class="text-danger"><i class="bi bi-exclamation-triangle me-1"></i>Department head has no email address</small>
                            {% endif %}
                        </div>
                        {% else %}
                        <div class="alert alert-danger mb-0">
                            <i class="bi bi-x-circle-fill me-1"></i>
                            <strong>{{ _("No recipient available")}}</strong>
                            <br><small>{{ _("The assigned staff has no user account and no department manager is set")}}.</small>
                        </div>
                        {% endif %}
                        {% endif %}

                        {% elif complaint.department and complaint.department.manager %}
                        <!-- No staff assigned, but department manager exists -->
                        <div class="alert alert-info mb-0">
                            <i class="bi bi-person-badge me-1"></i>
                            <strong>Recipient (Department Head):</strong> {{ complaint.department.manager.get_full_name }}
                            {% if complaint.department %}
                            <br><small class="text-muted">Manager of {{ complaint.department.name_en }}</small>
                            {% endif %}
                        </div>

                        {% else %}
                        <!-- No recipient at all -->
                        <div class="alert alert-danger mb-0">
                            <i class="bi bi-exclamation-triangle-fill me-1"></i>
                            <strong>{{ _("No recipient available")}}</strong>
                            <br><small>{{ _("No staff or department manager assigned to this complaint")}}.</small>
                        </div>
                        {% endif %}
                    </div>
                </div>

                <!-- Optional Additional Message -->
                <div class="mb-3">
                    <label class="form-label">
                        {{ _("Additional Message (Optional)")}}
                    </label>
                    <textarea id="additionalMessage" class="form-control" rows="3"
                              placeholder="Add any additional notes to send..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    {{ _("Cancel") }}
                </button>
                <button type="button" id="sendNotificationBtn" class="btn btn-primary"
                        onclick="sendNotification()">
                    <i class="bi bi-send me-1"></i>{{ _("Send Email")}}
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let selectedStaffId = null;
let allHospitalStaff = [];
let currentLanguage = document.documentElement.lang || 'en';

// Load hospital staff when modal opens
document.getElementById('staffSelectionModal').addEventListener('shown.bs.modal', function() {
    loadHospitalDepartments();
    loadHospitalStaff();
});

// Load hospital departments
function loadHospitalDepartments() {
    const hospitalId = '{{ complaint.hospital.id }}';
    const departmentSelect = document.getElementById('staffDepartmentFilter');

    fetch(`/organizations/api/departments/?hospital=${hospitalId}`, {
        credentials: 'same-origin'
    })
        .then(response => response.json())
        .then(data => {
            // Clear existing options except the first one
            departmentSelect.innerHTML = '<option value="">All Departments</option>';

            // Populate with departments
            data.results.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept.id;
                const deptName = currentLanguage === 'ar' && dept.name_ar ? dept.name_ar : dept.name_en;
                option.textContent = deptName;
                departmentSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error loading departments:', error);
        });
}

// Load hospital staff from API
function loadHospitalStaff(departmentId = null, search = '') {
    const container = document.getElementById('staffListContainer');
    let url = `/complaints/api/complaints/{{ complaint.id }}/hospital_staff/`;

    const params = new URLSearchParams();
    if (departmentId) params.append('department_id', departmentId);
    if (search) params.append('search', search);

    if (params.toString()) {
        url += '?' + params.toString();
    }

    container.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>
    `;

    fetch(url, {
        credentials: 'same-origin',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => response.json())
    .then(data => {
        allHospitalStaff = data.staff || [];
        renderStaffList(allHospitalStaff);
    })
    .catch(error => {
        console.error('Error loading staff:', error);
        container.innerHTML = `
            <div class="alert alert-danger m-3">
                <i class="bi bi-exclamation-triangle me-2"></i>
                Failed to load staff. Please try again.
            </div>
        `;
    });
}

// Render staff list
function renderStaffList(staffList) {
    const container = document.getElementById('staffListContainer');

    if (!staffList || staffList.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="bi bi-people" style="font-size: 3rem;"></i>
                <p class="mt-3">No staff found</p>
            </div>
        `;
        return;
    }

    let html = '<div class="list-group list-group-flush">';

    // Group by department
    const grouped = {};
    staffList.forEach(staff => {
        const dept = staff.department || 'No Department';
        if (!grouped[dept]) grouped[dept] = [];
        grouped[dept].push(staff);
    });

    // Render groups
    for (const [department, staffMembers] of Object.entries(grouped)) {
        html += `<div class="list-group-item bg-light fw-bold"><i class="bi bi-building me-2"></i>${department}</div>`;

        staffMembers.forEach(staff => {
            html += `
                <div class="list-group-item list-group-item-action staff-item"
                     data-staff-id="${staff.id}"
                     data-staff-name="${staff.name_en}"
                     onclick="selectStaff('${staff.id}', '${staff.name_en.replace(/'/g, "\\'")}')">
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="selectedStaff"
                               id="staff_${staff.id}" value="${staff.id}"
                               ${selectedStaffId === staff.id ? 'checked' : ''}>
                        <label class="form-check-label w-100 cursor-pointer" for="staff_${staff.id}">
                            <div>
                                <strong>${staff.name_en}</strong>
                                ${staff.name_ar ? `<span class="text-muted ms-2">(${staff.name_ar})</span>` : ''}
                            </div>
                            <small class="text-muted">
                                ${staff.job_title || ''}
                                ${staff.specialization ? '• ' + staff.specialization : ''}
                            </small>
                        </label>
                    </div>
                </div>
            `;
        });
    }

    html += '</div>';
    container.innerHTML = html;
}

// Select staff from list
function selectStaff(staffId, staffName) {
    selectedStaffId = staffId;

    // Update radio buttons
    document.querySelectorAll('input[name="selectedStaff"]').forEach(radio => {
        radio.checked = (radio.value === staffId);
    });

    // Enable assign button
    document.getElementById('assignSelectedStaffBtn').disabled = false;
}

// Assign staff directly from suggestions
function assignStaff(staffId, staffName) {
    if (!confirm(`Assign ${staffName} to this complaint?`)) {
        return;
    }

    const data = {
        staff_id: staffId,
        reason: 'Selected from AI suggestions'
    };

    fetch(`/complaints/api/complaints/{{ complaint.id }}/assign_staff/`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.message) {
            alert('Staff assigned successfully!');
            location.reload();
        } else {
            alert('Error: ' + (result.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to assign staff. Please try again.');
    });
}

// Assign selected staff from modal
function assignSelectedStaff() {
    if (!selectedStaffId) {
        alert('Please select a staff member first.');
        return;
    }

    const staffName = document.querySelector(`input[name="selectedStaff"]:checked`)?.closest('.staff-item')?.dataset?.staffName || 'selected staff';
    const reason = prompt('Reason for assignment (optional):', 'Manual selection from hospital staff list');

    const data = {
        staff_id: selectedStaffId,
        reason: reason || 'Manual selection from hospital staff list'
    };

    const btn = document.getElementById('assignSelectedStaffBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Assigning...';

    fetch(`/complaints/api/complaints/{{ complaint.id }}/assign_staff/`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.message) {
            alert('Staff assigned successfully!');
            location.reload();
        } else {
            alert('Error: ' + (result.error || 'Unknown error'));
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-person-check me-1"></i>Assign Selected Staff';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to assign staff. Please try again.');
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-person-check me-1"></i>Assign Selected Staff';
    });
}

// Department filter change handler
document.getElementById('staffDepartmentFilter')?.addEventListener('change', function(e) {
    const departmentId = e.target.value || null;
    const search = document.getElementById('staffSearchInput').value.trim();
    loadHospitalStaff(departmentId, search);
});

// Search input handler (debounced)
let searchTimeout;
document.getElementById('staffSearchInput')?.addEventListener('input', function(e) {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        const departmentId = document.getElementById('staffDepartmentFilter').value || null;
        const search = e.target.value.trim();
        loadHospitalStaff(departmentId, search);
    }, 300);
});

function createAction() {
    const assignTo = document.getElementById('actionAssignTo').value;
    const btn = document.getElementById('createActionBtn');

    const data = {};

    if (assignTo) {
        data.assigned_to = assignTo;
    }

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Creating...';

    fetch(`/complaints/api/complaints/{{ complaint.id }}/create_action_from_ai/`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.action_id) {
            // Redirect to action detail page
            window.location.href = `/actions/${data.action_id}/`;
        } else {
            alert('Error: ' + (data.error || 'Unknown error'));
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-plus-circle me-1"></i>Create Action';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to create action. Please try again.');
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-plus-circle me-1"></i>Create Action';
    });
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function switchToExplanationTab() {
    const explanationTab = document.getElementById('explanation-tab');
    if (explanationTab) {
        explanationTab.click();
    }
}

function requestExplanation() {
    const message = document.getElementById('explanationMessage')?.value || '';

    if (!confirm('{% trans "Are you sure you want to request an explanation?" %}')) {
        return;
    }

    const btn = event.target;
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';

    fetch(`/complaints/api/complaints/{{ complaint.id }}/request_explanation/`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            message: message
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('{% trans "Explanation request sent successfully!" %}');
            location.reload();
        } else {
            alert('{% trans "Error:" %} ' + (data.error || '{% trans "Unknown error" %}'));
            btn.disabled = false;
            btn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{% trans "Failed to send explanation request. Please try again." %}');
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
}

{% if complaint.explanation and complaint.explanation.token %}
function copyExplanationLink() {
    const link = `{% if request.is_secure %}https{% else %}http{% endif %}://{{ request.get_host }}{% url 'complaints:complaint_explanation_form' complaint.id complaint.explanation.token %}`;

    navigator.clipboard.writeText(link).then(() => {
        alert('{% trans "Link copied to clipboard!" %}');
    }).catch(() => {
        // Fallback
        const textarea = document.createElement('textarea');
        textarea.value = link;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        alert('{% trans "Link copied to clipboard!" %}');
    });
}

function resendExplanation() {
    if (!confirm('{% trans "Resend explanation request email?" %}')) {
        return;
    }

    fetch(`/complaints/api/complaints/{{ complaint.id }}/resend_explanation_email/`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('{% trans "Email resent successfully!" %}');
        } else {
            alert('{% trans "Error:" %} ' + (data.error || '{% trans "Unknown error" %}'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{% trans "Failed to resend email. Please try again." %}');
    });
}
{% endif %}

function sendNotification() {
    const btn = document.getElementById('sendNotificationBtn');
    const emailMessage = document.getElementById('emailMessage').value;
    const additionalMessage = document.getElementById('additionalMessage').value;

    // Validate email message is not empty
    if (!emailMessage.trim()) {
        alert('Please enter a message to send.');
        return;
    }

    // Disable button and show loading
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';

    // Get CSRF token
    const csrftoken = getCookie('csrftoken');

    fetch(`/complaints/api/complaints/{{ complaint.id }}/send_notification/`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken
        },
        body: JSON.stringify({
            email_message: emailMessage,
            additional_message: additionalMessage
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Email sent successfully!');
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('sendNotificationModal'));
            modal.hide();
            // Reload page to show timeline entry
            location.reload();
        } else {
            alert('Error: ' + (data.error || 'Unknown error'));
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-send me-1"></i>Send Email';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to send email. Please try again.');
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-send me-1"></i>Send Email';
    });
}
</script>
{% endblock %}
