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

{% block title %}{% trans "Inquiry" %} #{{ inquiry.reference_number|truncatechars:15 }} - 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;
    }
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    .spinner {
        display: inline-block;
        width: 1rem;
        height: 1rem;
        border: 2px solid rgba(255,255,255,0.3);
        border-top-color: white;
        border-radius: 50%;
        animation: spin 0.6s linear infinite;
    }
    .spinner-dark {
        border-color: rgba(0,86,150,0.2);
        border-top-color: #005696;
    }
    .ai-suggestion-card {
        border: 2px dashed #bae6fd;
        border-radius: 0.75rem;
        padding: 1rem;
        background: #eef6fb;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .ai-suggestion-card:hover {
        border-color: #007bbd;
        background: #e0f2fe;
    }
    .ai-suggestion-card.selected {
        border-style: solid;
        border-color: #005696;
        background: #e0f2fe;
        box-shadow: 0 0 0 2px #005696;
    }
    .lang-tab {
        padding: 0.5rem 1rem;
        font-size: 0.8rem;
        font-weight: 600;
        border-radius: 0.5rem 0.5rem 0 0;
        cursor: pointer;
        border: 1px solid #e2e8f0;
        border-bottom: none;
        background: #f1f5f9;
        color: #64748b;
        transition: all 0.2s ease;
    }
    .lang-tab.active {
        background: white;
        color: #005696;
        border-color: #bae6fd;
    }
</style>
{% endblock %}

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

<header class="mb-6">
    <div class="flex items-center gap-2 text-sm text-slate mb-2">
        {% if source_user %}
        <a href="{% url 'px_sources:source_user_inquiry_list' %}" class="hover:text-navy">{% trans "My Inquiries" %}</a>
        {% else %}
        <a href="{% url 'inquiries:inquiry_list' %}" class="hover:text-navy">{% trans "Inquiries" %}</a>
        {% endif %}
        <i data-lucide="chevron-right" class="w-4 h-4"></i>
        <span class="font-bold text-navy">{{ inquiry.reference_number|truncatechars:15 }}</span>
        <span class="ml-2 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider
            {% if inquiry.status == 'open' %}bg-yellow-100 text-yellow-700
            {% elif inquiry.status == 'in_progress' %}bg-blue-100 text-blue-700
            {% elif inquiry.status == 'resolved' %}bg-green-100 text-green-700
            {% elif inquiry.status == 'closed' %}bg-slate-100 text-slate-600
            {% else %}bg-slate-100 text-slate-600{% endif %}">
            {{ inquiry.get_status_display }}
        </span>
        {% if inquiry.priority %}
        <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase
            {% if inquiry.priority == 'critical' %}bg-red-500 text-white
            {% elif inquiry.priority == 'high' %}bg-orange-100 text-orange-700
            {% elif inquiry.priority == 'medium' %}bg-yellow-100 text-yellow-700
            {% elif inquiry.priority == 'low' %}bg-green-100 text-green-700
            {% else %}bg-slate-100 text-slate-600{% endif %}">
            {{ inquiry.get_priority_display }}
        </span>
        {% endif %}
        {% if not inquiry.sent_to_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>
    <div class="flex items-center justify-between">
        <h1 class="text-2xl font-bold text-navy">{{ inquiry.subject }}</h1>
        <div class="flex items-center gap-3">
            <span class="text-slate text-sm">
                <i data-lucide="calendar" class="w-3 h-3 inline-block mr-1"></i>{{ inquiry.created_at|date:"Y-m-d" }}
            </span>
            {% if can_respond %}
            <button onclick="showRespondModal()" class="bg-navy text-white px-4 py-2 rounded-lg text-sm font-bold shadow-md hover:bg-blue transition inline-flex items-center gap-2">
                <i data-lucide="message-square" class="w-4 h-4"></i>{% trans "Respond" %}
            </button>
            {% endif %}
        </div>
    </div>
</header>

<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 tab-inactive" onclick="switchTab('timeline')" id="tab-timeline">{% trans "Timeline" %}</button>
    <button class="py-4 text-sm tab-inactive" onclick="switchTab('department')" id="tab-department">{% trans "Department Response" %}</button>
    <button class="py-4 text-sm tab-inactive" onclick="switchTab('rca')" id="tab-rca">{% trans "RCA" %}</button>
    <button class="py-4 text-sm tab-inactive" onclick="switchTab('notes')" id="tab-notes">
        {% 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 %}
    </button>
</nav>

<main class="grid grid-cols-12 gap-6">
    <div class="col-span-8 space-y-6">

        <div id="panel-details" class="tab-panel">
            <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
                <div class="bg-slate-50 p-4 rounded-xl border-l-4 border-cyan-500 mb-4">
                    <p class="text-sm leading-relaxed text-slate">{{ inquiry.message|linebreaks }}</p>
                </div>

                {% if inquiry.short_description_en or inquiry.emotion %}
                <div class="pt-3 border-t border-slate-100">
                    <div class="flex items-center justify-between mb-2">
                        <div class="flex items-center gap-2">
                            <i data-lucide="sparkles" class="w-4 h-4 text-blue-600"></i>
                            <span class="text-[10px] font-bold text-slate uppercase">{% trans "AI Analysis" %}</span>
                        </div>
                        {% if can_respond and not inquiry.short_description_en %}
                        <button id="reanalyzeBtn" onclick="reanalyzeAI()" class="inline-flex items-center gap-1 px-2 py-1 bg-white border border-slate-200 rounded-lg text-[10px] font-semibold text-navy hover:bg-slate-50 transition">
                            <i data-lucide="refresh-cw" class="w-3 h-3"></i> {% trans "Re-analyze" %}
                        </button>
                        {% endif %}
                    </div>

                    {% if inquiry.emotion and inquiry.emotion != 'neutral' %}
                    <div class="flex items-center gap-3 mb-3">
                        <span class="px-2.5 py-1 bg-navy/10 rounded-lg text-xs font-bold text-navy flex items-center gap-1.5">
                            <i data-lucide="frown" class="w-3 h-3"></i> {{ inquiry.get_emotion_display }}
                        </span>
                        <span class="text-xs text-slate">{% trans "Confidence" %}: {{ inquiry.emotion_confidence_percent|floatformat:0 }}%</span>
                        <span class="text-xs text-slate">·</span>
                        <span class="text-xs text-slate">{% trans "Intensity" %}: {{ inquiry.emotion_intensity|floatformat:2 }}/1.0</span>
                    </div>
                    {% endif %}

                    <div id="aiAnalysisContent">
                        {% if inquiry.short_description_en %}
                        <p class="text-sm text-slate-700 mb-2">{{ inquiry.short_description_en }}</p>
                        {% if inquiry.short_description_ar %}
                        <p class="text-sm text-slate-700" dir="rtl">{{ inquiry.short_description_ar }}</p>
                        {% endif %}
                        {% else %}
                        <div class="flex items-center gap-2 py-2">
                            <i data-lucide="loader" class="w-4 h-4 text-slate-300 animate-spin"></i>
                            <p class="text-slate text-sm">{% trans "AI analysis is running. Please refresh the page shortly." %}</p>
                        </div>
                        {% endif %}
                    </div>
                </div>
                {% endif %}
            </section>

            <div class="grid grid-cols-2 gap-6 mt-6">
                <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="user" class="w-4 h-4"></i>
                        {% trans "Contact Information" %}
                    </h3>
                    <ul class="space-y-3 text-[11px]">
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Name" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.contact_name|default:"-" }}</span>
                        </li>
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Phone" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.contact_phone|default:"-" }}</span>
                        </li>
                        <li class="flex justify-between">
                            <span class="text-slate font-semibold">{% trans "Email" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.contact_email|default:"-" }}</span>
                        </li>
                    </ul>
                </section>

                <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="building-2" class="w-4 h-4"></i>
                        {% trans "Organization" %}
                    </h3>
                    <ul class="space-y-3 text-[11px]">
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Hospital" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.hospital.name }}</span>
                        </li>
                        {% if inquiry.department %}
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Department" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.department.name }}</span>
                        </li>
                        {% endif %}
                        {% if inquiry.legacy_location %}
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Location" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.legacy_location.name }}</span>
                        </li>
                        {% endif %}
                        {% if inquiry.legacy_main_section %}
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Section" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.legacy_main_section.name }}</span>
                        </li>
                        {% endif %}
                        {% if inquiry.legacy_subsection %}
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Subsection" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.legacy_subsection.name }}</span>
                        </li>
                        {% endif %}
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Category" %}</span>
                            <span class="text-navy font-bold">{{ inquiry.get_category_display|default:"-" }}</span>
                        </li>
                        {% if inquiry.taxonomy_domain or inquiry.taxonomy_category or inquiry.taxonomy_subcategory or inquiry.taxonomy_classification %}
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "SHCT Taxonomy" %}</span>
                            <span class="text-navy font-bold text-right max-w-[60%]">
                                {{ inquiry.taxonomy_domain.name_en|default:"" }}
                                {% if inquiry.taxonomy_category %} > {{ inquiry.taxonomy_category.name_en }}{% endif %}
                                {% if inquiry.taxonomy_subcategory %} > {{ inquiry.taxonomy_subcategory.name_en }}{% endif %}
                                {% if inquiry.taxonomy_classification %} > {{ inquiry.taxonomy_classification.name_en }}{% endif %}
                            </span>
                        </li>
                        {% endif %}
                        {% if inquiry.outgoing_department %}
                        <li class="flex justify-between border-b border-slate-100 pb-2">
                            <span class="text-slate font-semibold">{% trans "Transferred Dept" %}</span>
                            <span class="flex items-center gap-1">
                                <span class="text-navy font-bold">{{ inquiry.outgoing_department.get_localized_name }}</span>
                                {% if not inquiry.department_responded_at %}
                                <span class="px-1.5 py-0.5 rounded-full text-[9px] font-bold bg-amber-100 text-amber-700 uppercase">{% trans "Awaiting" %}</span>
                                {% else %}
                                <span class="px-1.5 py-0.5 rounded-full text-[9px] font-bold bg-green-100 text-green-700 uppercase">{% trans "Responded" %}</span>
                                {% endif %}
                            </span>
                        </li>
                        {% endif %}
                        {% if inquiry.timeline_sla %}
                        <li class="flex justify-between">
                            <span class="text-slate font-semibold">{% trans "SLA" %}</span>
                            <span class="px-2 py-0.5 rounded-full text-[9px] font-bold uppercase
                                {% if inquiry.timeline_sla == '24_hours' %}bg-green-100 text-green-700
                                {% elif inquiry.timeline_sla == '48_hours' %}bg-yellow-100 text-yellow-700
                                {% elif inquiry.timeline_sla == '72_hours' %}bg-orange-100 text-orange-700
                                {% else %}bg-red-100 text-red-700{% endif %}">
                                {{ inquiry.get_timeline_sla_display }}
                            </span>
                        </li>
                        {% endif %}
                    </ul>
                </section>
            </div>
        </div>

        <div id="panel-timeline" class="tab-panel hidden">
            {% include "complaints/partials/inquiry_timeline_panel.html" %}
        </div>

        <div id="panel-department" class="tab-panel hidden space-y-6">
            {% if inquiry.outgoing_department %}
            <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
                <div class="flex items-center gap-2 mb-4 pb-4 border-b
                    {% if inquiry.department_responded_at %}border-blue-200{% elif inquiry.dept_response_is_overdue %}border-red-200{% else %}border-amber-200{% endif %}">
                    <div class="w-10 h-10 rounded-xl flex items-center justify-center
                        {% if inquiry.department_responded_at %}bg-blue-100{% elif inquiry.dept_response_is_overdue %}bg-red-100{% else %}bg-amber-100{% endif %}">
                        <i data-lucide="building-2" class="w-5 h-5
                            {% if inquiry.department_responded_at %}text-blue-600{% elif inquiry.dept_response_is_overdue %}text-red-600{% else %}text-amber-600{% endif %}"></i>
                    </div>
                    <div>
                        <h3 class="font-bold text-navy">
                            {% blocktrans with dept=inquiry.outgoing_department.get_localized_name %}Response from {{ dept }}{% endblocktrans %}
                        </h3>
                        {% if inquiry.department_responded_at %}
                        <span class="text-xs text-navy"><i data-lucide="check-circle" class="w-3 h-3 inline mr-1"></i>{% trans "Received" %}</span>
                        {% elif inquiry.dept_response_is_overdue %}
                        <span class="text-xs text-red-600"><i data-lucide="alert-triangle" class="w-3 h-3 inline mr-1"></i>{% trans "OVERDUE" %}</span>
                        {% else %}
                        <span class="text-xs text-amber-600"><i data-lucide="clock" class="w-3 h-3 inline mr-1"></i>{% trans "Awaiting Response" %}</span>
                        {% endif %}
                    </div>
                </div>
                <div>
                    {% if inquiry.transferred_at %}
                    <div class="flex items-center gap-3 mb-4 text-sm text-slate-600">
                        <span class="flex items-center gap-1">
                            <i data-lucide="send" class="w-4 h-4"></i>
                            {% trans "Sent:" %} {{ inquiry.transferred_at|date:"Y-m-d H:i" }}
                        </span>
                        {% if inquiry.dept_response_sla_due_at and not inquiry.department_responded_at %}
                        <span>•</span>
                        <span class="flex items-center gap-1 {% if inquiry.dept_response_is_overdue %}text-red-600 font-semibold{% endif %}">
                            <i data-lucide="timer" class="w-4 h-4"></i>
                            {% trans "Deadline:" %} {{ inquiry.dept_response_sla_due_at|date:"Y-m-d H:i" }}
                        </span>
                        {% endif %}
                    </div>
                    {% endif %}

                    {% if inquiry.department_responded_at %}
                    <div class="flex items-center gap-3 mb-4 text-sm text-slate-600">
                        <span class="flex items-center gap-1">
                            <i data-lucide="user" class="w-4 h-4"></i>
                            {{ inquiry.department_responded_by.get_full_name|default:"-" }}
                        </span>
                        <span>•</span>
                        <span class="flex items-center gap-1">
                            <i data-lucide="calendar" class="w-4 h-4"></i>
                            {{ inquiry.department_responded_at|date:"Y-m-d H:i" }}
                        </span>
                    </div>
                    {% if inquiry.department_response_en %}
                    <div class="mb-4">
                        <p class="text-[10px] font-bold text-slate uppercase mb-1">English</p>
                        <div class="prose prose-sm max-w-none bg-slate-50 rounded-xl p-4">
                            <p class="text-slate-700 leading-relaxed">{{ inquiry.department_response_en|linebreaks }}</p>
                        </div>
                    </div>
                    {% endif %}
                    {% if inquiry.department_response_ar %}
                    <div class="mb-4">
                        <p class="text-[10px] font-bold text-slate uppercase mb-1">العربية</p>
                        <div class="prose prose-sm max-w-none bg-slate-50 rounded-xl p-4">
                            <p class="text-slate-700 leading-relaxed" dir="rtl">{{ inquiry.department_response_ar|linebreaks }}</p>
                        </div>
                    </div>
                    {% endif %}
                    {% if inquiry.department_response_summary_en %}
                    <div class="mt-4 bg-light border border-blue-200 rounded-xl p-4">
                        <div class="flex items-center gap-2 mb-2">
                            <i data-lucide="sparkles" class="w-4 h-4 text-navy"></i>
                            <span class="text-sm font-bold text-navy">{% trans "AI Summary" %}</span>
                        </div>
                        <p class="text-sm text-slate-700 leading-relaxed">{{ inquiry.department_response_summary_en }}</p>
                        {% if inquiry.department_response_summary_ar %}
                        <p class="text-sm text-slate-700 leading-relaxed mt-2" dir="rtl">{{ inquiry.department_response_summary_ar }}</p>
                        {% endif %}
                    </div>
                    {% endif %}
                    <div class="mt-4 border rounded-xl p-4
                        {% if inquiry.dept_response_acceptance_status == 'acceptable' %}border-green-200 bg-green-50
                        {% elif inquiry.dept_response_acceptance_status == 'not_acceptable' %}border-red-200 bg-red-50
                        {% else %}border-yellow-200 bg-yellow-50{% endif %}">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-2">
                                {% if inquiry.dept_response_acceptance_status == 'acceptable' %}
                                <i data-lucide="check-circle" class="w-4 h-4 text-green-600"></i>
                                <span class="text-sm font-semibold text-green-700">{% trans "Accepted" %}</span>
                                {% elif inquiry.dept_response_acceptance_status == 'not_acceptable' %}
                                <i data-lucide="x-circle" class="w-4 h-4 text-red-600"></i>
                                <span class="text-sm font-semibold text-red-700">{% trans "Not Acceptable" %}</span>
                                {% else %}
                                <i data-lucide="clock" class="w-4 h-4 text-yellow-600"></i>
                                <span class="text-sm font-semibold text-yellow-700">{% trans "Pending Review" %}</span>
                                {% endif %}
                                {% if inquiry.dept_response_accepted_by %}
                                <span class="text-xs text-slate-500">by {{ inquiry.dept_response_accepted_by.get_full_name }}</span>
                                {% endif %}
                            </div>
                            {% if can_review_dept_response and inquiry.dept_response_acceptance_status == 'pending' %}
                            <div class="flex gap-2">
                                <form method="post" action="{% url 'inquiries:inquiry_review_dept_response' inquiry.pk %}">
                                    {% csrf_token %}
                                    <input type="hidden" name="acceptance_status" value="acceptable">
                                    <button type="submit" class="px-3 py-1.5 text-xs font-semibold text-white bg-green-600 rounded-lg hover:bg-green-700 transition flex items-center gap-1">
                                        <i data-lucide="check" class="w-3 h-3"></i> {% trans "Acceptable" %}
                                    </button>
                                </form>
                                <form method="post" action="{% url 'inquiries:inquiry_review_dept_response' inquiry.pk %}">
                                    {% csrf_token %}
                                    <input type="hidden" name="acceptance_status" value="not_acceptable">
                                    <button type="submit" class="px-3 py-1.5 text-xs font-semibold text-white bg-red-600 rounded-lg hover:bg-red-700 transition flex items-center gap-1">
                                        <i data-lucide="x" class="w-3 h-3"></i> {% trans "Not Acceptable" %}
                                    </button>
                                </form>
                            </div>
                            {% endif %}
                        </div>
                        {% if inquiry.dept_response_acceptance_notes %}
                        <p class="text-xs text-slate-600 mt-2">{{ inquiry.dept_response_acceptance_notes }}</p>
                        {% endif %}
                    </div>
                    {% else %}
                    <div class="text-center py-6">
                        <div class="inline-block w-8 h-8 border-4 border-amber-200 border-t-amber-500 rounded-full animate-spin mb-3"></div>
                        <p class="text-slate text-sm">{% trans "Waiting for department response..." %}</p>
                        {% if inquiry.dept_response_sla_due_at %}
                        <p class="text-xs text-slate-400 mt-1">{% trans "Deadline:" %} {{ inquiry.dept_response_sla_due_at|date:"Y-m-d H:i" }}</p>
                        {% endif %}
                        {% if can_respond %}
                        <button type="button"
                            onclick="openDeptResponseModal('inquiry', '{{ inquiry.pk }}', '{% url 'inquiries:inquiry_department_response' pk=inquiry.pk %}', '{{ inquiry.reference_number }}', '{{ inquiry.subject|escapejs }}', '{{ inquiry.department_response_en|default:'' }}', '{{ inquiry.department_response_ar|default:'' }}')"
                            class="mt-3 inline-flex items-center gap-2 px-4 py-2 bg-navy text-white rounded-xl text-sm font-semibold hover:bg-blue transition">
                            <i data-lucide="message-square" class="w-4 h-4"></i> {% trans "Submit Response" %}
                        </button>
                        {% endif %}
                    </div>
                    {% if can_send_reminder %}
                    <div class="mt-3 flex gap-2">
                        <form method="post" action="{% url 'inquiries:inquiry_send_dept_response_reminder' inquiry.pk %}" class="flex-1">
                            {% csrf_token %}
                            <input type="hidden" name="reminder_type" value="first">
                            <button type="submit" class="w-full bg-amber-500 text-white px-4 py-2 rounded-xl font-semibold hover:bg-amber-600 transition flex items-center justify-center gap-2 text-sm">
                                <i data-lucide="bell" class="w-4 h-4"></i> {% trans "Send Reminder" %}
                            </button>
                        </form>
                        {% if inquiry.dept_response_reminder_sent_at %}
                        <form method="post" action="{% url 'inquiries:inquiry_send_dept_response_reminder' inquiry.pk %}" class="flex-1">
                            {% csrf_token %}
                            <input type="hidden" name="reminder_type" value="second">
                            <button type="submit" class="w-full bg-red-500 text-white px-4 py-2 rounded-xl font-semibold hover:bg-red-600 transition flex items-center justify-center gap-2 text-sm">
                                <i data-lucide="alert-triangle" class="w-4 h-4"></i> {% trans "Urgent Reminder" %}
                            </button>
                        </form>
                        {% endif %}
                    </div>
                    {% endif %}
                    {% endif %}
                </div>
            </section>
            {% endif %}

            {% if inquiry.response %}
            <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
                <h3 class="font-bold text-navy mb-4 flex items-center gap-2">
                    <i data-lucide="circle-check" class="w-5 h-5 text-green-600"></i>
                    {% trans "Response" %}
                    {% if inquiry.response_sent_at %}
                    <span class="text-xs font-normal text-green-600 ml-2">
                        <i data-lucide="send" class="w-3 h-3 inline mr-1"></i>{% trans "Sent to inquirer" %}
                    </span>
                    {% endif %}
                </h3>
                <div class="flex items-center gap-3 mb-4 text-sm text-slate-600">
                    <span class="flex items-center gap-1">
                        <i data-lucide="user" class="w-4 h-4"></i>
                        {% if inquiry.responded_by %}{{ inquiry.responded_by.get_full_name|default:inquiry.responded_by.email }}{% endif %}
                    </span>
                    <span>•</span>
                    <span class="flex items-center gap-1">
                        <i data-lucide="calendar" class="w-4 h-4"></i>
                        {% if inquiry.response_sent_at %}{{ inquiry.response_sent_at|date:"Y-m-d H:i" }}{% else %}{{ inquiry.responded_at|date:"Y-m-d H:i" }}{% endif %}
                    </span>
                </div>
                {% if inquiry.response_en %}
                <div class="mb-4">
                    <p class="text-[10px] font-bold text-slate uppercase mb-1">English</p>
                    <div class="prose prose-sm max-w-none bg-slate-50 rounded-xl p-4">
                        <p class="text-slate-700 leading-relaxed">{{ inquiry.response_en|linebreaks }}</p>
                    </div>
                </div>
                {% endif %}
                {% if inquiry.response_ar %}
                <div class="mb-4">
                    <p class="text-[10px] font-bold text-slate uppercase mb-1">العربية</p>
                    <div class="prose prose-sm max-w-none bg-slate-50 rounded-xl p-4">
                        <p class="text-slate-700 leading-relaxed" dir="rtl">{{ inquiry.response_ar|linebreaks }}</p>
                    </div>
                </div>
                {% endif %}
                {% if not inquiry.response_en and not inquiry.response_ar %}
                <div class="prose prose-sm max-w-none bg-slate-50 rounded-xl p-4">
                    <p class="text-slate-700 leading-relaxed">{{ inquiry.response|linebreaks }}</p>
                </div>
                {% endif %}
            </section>
            {% endif %}
        </div>

        <div id="panel-rca" class="tab-panel hidden">
            <section class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100">
                <h3 class="font-bold text-navy mb-4 flex items-center gap-2">
                    <i data-lucide="search" class="w-5 h-5 text-purple-600"></i>
                    {% trans "Root Cause Analyses" %}
                </h3>
                <div class="space-y-3">
                    {% if linked_rcas %}
                    {% for rca in linked_rcas %}
                    <a href="{% url 'rca:rca_detail' pk=rca.pk %}" class="block p-3 rounded-lg border border-slate-200 hover:border-blue-300 transition group">
                        <p class="text-sm font-bold text-navy group-hover:text-blue truncate">{{ rca.title }}</p>
                        <div class="flex items-center gap-2 mt-1">
                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase
                                {% if rca.status == 'draft' %}bg-slate-100 text-slate-600
                                {% elif rca.status == 'in_progress' %}bg-blue-100 text-blue-700
                                {% elif rca.status == 'review' %}bg-yellow-100 text-yellow-700
                                {% elif rca.status == 'approved' %}bg-green-100 text-green-700
                                {% elif rca.status == 'closed' %}bg-gray-100 text-gray-600{% endif %}">
                                {{ rca.get_status_display }}
                            </span>
                            <span class="text-[10px] text-slate">{{ rca.created_at|date:"M d, Y" }}</span>
                        </div>
                    </a>
                    {% endfor %}
                    {% else %}
                    <div class="text-center py-8">
                        <i data-lucide="search" class="w-12 h-12 mx-auto text-slate-300 mb-3"></i>
                        <p class="text-slate text-sm">{% trans "No Root Cause Analyses linked to this inquiry" %}</p>
                    </div>
                    {% endif %}
                </div>
            </section>
        </div>

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

    <div class="col-span-4 space-y-6">
        <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 inquiry.status == 'open' and not inquiry.activated_at %}
                {% if can_edit %}
                <form method="post" action="{% url 'inquiries:inquiry_activate' inquiry.pk %}" class="contents">
                    {% csrf_token %}
                    <button type="submit"
                        class="col-span-2 p-3 border-blue-200 bg-blue-50 rounded-xl hover:bg-blue-100 flex items-center justify-center gap-2 group transition mb-2"
                        {% if inquiry.assigned_to == request.user %}disabled style="opacity: 0.5; cursor: not-allowed;"{% endif %}>
                        <i data-lucide="{% if inquiry.assigned_to == request.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 inquiry.assigned_to == request.user %}{% trans "Activated" %}{% else %}{% trans "Activate" %}{% endif %}
                        </span>
                    </button>
                </form>
                <form method="post" action="{% url 'inquiries:inquiry_change_status' inquiry.pk %}" class="col-span-2 contents" onsubmit="return confirm('{% trans "Are you sure you want to cancel this inquiry?" %}')">
                    {% csrf_token %}
                    <input type="hidden" name="status" value="closed">
                    <button type="submit" class="col-span-2 p-3 border-red-200 bg-red-50 rounded-xl hover:bg-red-100 flex items-center justify-center gap-2 group transition">
                        <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 Inquiry" %}</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 inquiry to perform actions" %}</p>
                </div>
                {% endif %}
                {% else %}
                {% if can_respond %}
                <button onclick="showRespondModal()" class="col-span-2 p-3 border-navy bg-navy text-white rounded-xl hover:bg-blue transition flex items-center justify-center gap-2 group">
                    <i data-lucide="message-square" class="w-5 h-5"></i>
                    <span class="text-[10px] font-bold uppercase">{% trans "Send Response to Patient" %}</span>
                </button>
                {% endif %}
                {% if inquiry.status == 'resolved' or inquiry.status == 'closed' %}
                {% if can_respond %}
                <form method="post" action="{% url 'inquiries:inquiry_reopen' inquiry.pk %}" class="col-span-2 contents">
                    {% csrf_token %}
                    <input type="hidden" name="note" value="Inquiry reopened">
                    <button type="submit" class="col-span-2 p-3 border-amber-200 bg-amber-50 rounded-xl hover:bg-amber-100 flex items-center justify-center gap-2 group transition">
                        <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>
                {% endif %}
                {% endif %}
                {% if can_respond %}
                <button onclick="showAssignModal()" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="user-plus" class="w-5 h-5 text-slate group-hover:text-blue"></i>
                    <span class="text-[10px] font-bold uppercase">{% if inquiry.assigned_to %}{% trans "Reassign" %}{% else %}{% trans "Assign" %}{% endif %}</span>
                </button>
                {% endif %}
                {% if can_edit and inquiry.status != 'closed' %}
                <button onclick="document.getElementById('statusUpdateForm').classList.toggle('hidden')" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="refresh-cw" class="w-5 h-5 text-slate group-hover:text-orange-500"></i>
                    <span class="text-[10px] font-bold uppercase">{% trans "Status" %}</span>
                </button>
                {% endif %}
                {% if can_edit and inquiry.status != 'closed' %}
                <a href="{% url 'inquiries:inquiry_edit' inquiry.pk %}" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="edit" class="w-5 h-5 text-slate group-hover:text-blue"></i>
                    <span class="text-[10px] font-bold uppercase">{% trans "Edit" %}</span>
                </a>
                {% endif %}
                {% if can_edit %}
                <a href="{% url 'rca:rca_create' %}?related_model=inquiry&related_id={{ inquiry.pk }}" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="search" class="w-5 h-5 text-slate group-hover:text-purple-600"></i>
                    <span class="text-[10px] font-bold uppercase">{% trans "RCA" %}</span>
                </a>
                {% endif %}
                <a href="{% url 'projects:project_create' %}?related_model=inquiry&related_id={{ inquiry.pk }}" class="p-3 border rounded-xl hover:bg-light flex flex-col items-center gap-2 group transition">
                    <i data-lucide="folder-plus" class="w-5 h-5 text-slate group-hover:text-teal-600"></i>
                    <span class="text-[10px] font-bold uppercase">{% trans "QI Project" %}</span>
                </a>
                {% if can_respond %}
                <button onclick="showSendModal('{{ inquiry.id }}', 'inquiry')" class="col-span-2 p-3 border-indigo-200 bg-indigo-50 rounded-xl hover:bg-indigo-100 flex items-center justify-center gap-2 group transition">
                    <i data-lucide="send" class="w-5 h-5 text-indigo-600"></i>
                    <span class="text-[10px] font-bold text-indigo-700 uppercase">{% trans "Send to Department" %}</span>
                </button>
                {% endif %}
                {% if can_edit and inquiry.status != 'closed' and inquiry.status != 'cancelled' %}
                <button onclick="document.getElementById('escalateModal').style.display='flex'" class="p-3 border-red-200 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>
                {% endif %}
                {% endif %}
            </div>
        </section>

        {% if can_edit and inquiry.status != 'closed' %}
        <section id="statusUpdateForm" class="bg-white rounded-2xl p-6 shadow-sm border border-slate-100 hidden">
            <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 'inquiries:inquiry_change_status' inquiry.pk %}">
                {% csrf_token %}
                <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 mb-3">
                    {% for val, label in status_choices %}
                    <option value="{{ val }}" {% if inquiry.status == val %}selected{% endif %}>{{ label }}</option>
                    {% endfor %}
                </select>
                <button type="submit" class="w-full px-4 py-2.5 bg-orange-500 text-white rounded-xl font-bold hover:bg-orange-600 transition text-sm inline-flex items-center justify-center gap-2">
                    <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                    {% trans "Change Status" %}
                </button>
            </form>
        </section>
        {% endif %}
    </div>
</main>

<!-- Respond Modal -->
<div id="respondModal" style="display:none" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-slate-200">
            <div class="flex items-center justify-between">
                <h3 class="text-xl font-bold text-navy flex items-center gap-2">
                    <i data-lucide="message-square" class="w-5 h-5"></i>
                    {% trans "Send Response to Patient" %}
                </h3>
                <button type="button" onclick="closeModal('respondModal')" class="text-slate-400 hover:text-slate-600 transition">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>
        </div>
        <form method="post" action="{% url 'inquiries:inquiry_respond' inquiry.pk %}" id="respondForm">
            {% csrf_token %}
            <div class="p-6">
                {% if inquiry.short_description_en or inquiry.short_description_ar or inquiry.ai_brief_en or inquiry.ai_brief_ar %}
                <div class="bg-light/50 border border-slate-200 rounded-2xl p-4 mb-5">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="sparkles" class="w-4 h-4 text-navy"></i>
                        <span class="text-sm font-bold text-navy">{% trans "AI Summary" %}</span>
                    </div>
                    {% if inquiry.short_description_en or inquiry.ai_brief_en %}
                    <p class="text-sm text-slate-700 leading-relaxed">{% if inquiry.short_description_en %}{{ inquiry.short_description_en }}{% elif inquiry.ai_brief_en %}{{ inquiry.ai_brief_en }}{% endif %}</p>
                    {% endif %}
                    {% if inquiry.short_description_ar or inquiry.ai_brief_ar %}
                    <p class="text-sm text-slate-700 leading-relaxed mt-2" dir="rtl">{% if inquiry.short_description_ar %}{{ inquiry.short_description_ar }}{% elif inquiry.ai_brief_ar %}{{ inquiry.ai_brief_ar }}{% endif %}</p>
                    {% endif %}
                </div>
                {% endif %}

                <div class="mb-5">
                    <button type="button" id="generateAiBtn" onclick="generateAIResponse()" class="w-full inline-flex items-center justify-center gap-2 px-4 py-3 bg-navy text-white rounded-xl font-bold hover:bg-blue transition text-sm shadow-lg">
                        <i data-lucide="sparkles" class="w-4 h-4"></i>
                        {% trans "Generate AI Response" %}
                    </button>
                </div>

                <div id="aiSuggestions" class="hidden mb-5 space-y-3">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="sparkles" class="w-4 h-4 text-navy"></i>
                        <span class="text-sm font-semibold text-navy">{% trans "AI Generated Response (click to use)" %}</span>
                    </div>
                    <div id="aiSuggestionEn" onclick="useAISuggestion('en')" class="ai-suggestion-card">
                        <p class="text-[10px] font-bold text-slate uppercase mb-1">English</p>
                        <p class="text-sm text-slate-700" id="aiSuggestionEnText"></p>
                    </div>
                    <div id="aiSuggestionAr" onclick="useAISuggestion('ar')" class="ai-suggestion-card">
                        <p class="text-[10px] font-bold text-slate uppercase mb-1">العربية</p>
                        <p class="text-sm text-slate-700" dir="rtl" id="aiSuggestionArText"></p>
                    </div>
                    <button type="button" onclick="useBothAISuggestions()" class="w-full bg-navy text-white px-4 py-2 rounded-xl font-semibold hover:bg-blue transition text-sm inline-flex items-center justify-center gap-2">
                        <i data-lucide="check" class="w-4 h-4"></i>
                        {% trans "Use Both Suggestions" %}
                    </button>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-semibold text-navy mb-2">{% trans "Response (English)" %}</label>
                    <textarea name="response_en" id="responseEn" rows="6"
                        class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 resize-none text-sm"
                        placeholder="{% trans 'Enter your response in English...' %}">{{ inquiry.response_en|default:"" }}</textarea>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-semibold text-navy mb-2">{% trans "Response (Arabic)" %}</label>
                    <textarea name="response_ar" id="responseAr" rows="6" dir="rtl"
                        class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 resize-none text-sm"
                        placeholder="{% trans 'أدخل ردك باللغة العربية...' %}">{{ inquiry.response_ar|default:"" }}</textarea>
                </div>

                <p class="text-xs text-slate-400 mt-1">
                    <i data-lucide="info" class="w-3 h-3 inline mr-1"></i>
                    {% trans "At least one language is required. The response will be sent to the inquirer via SMS and Email." %}
                </p>
            </div>
            <div class="p-6 border-t border-slate-200 flex gap-3">
                <button type="submit" class="flex-1 px-4 py-2.5 bg-navy text-white rounded-xl font-semibold hover:bg-navy/90 transition text-sm inline-flex items-center justify-center gap-2">
                    <i data-lucide="send" class="w-4 h-4"></i>
                    {% trans "Send Response to Patient" %}
                </button>
                <button type="button" onclick="closeModal('respondModal')" class="px-4 py-2.5 bg-white border-2 border-slate-200 rounded-xl font-semibold text-slate-600 hover:bg-slate-50 transition text-sm">
                    {% trans "Cancel" %}
                </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 p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md">
        <div class="p-6 border-b border-slate-200">
            <div class="flex items-center justify-between">
                <h3 class="text-xl font-bold text-navy flex items-center gap-2">
                    <i data-lucide="user-plus" class="w-5 h-5"></i>
                    {% if inquiry.assigned_to %}{% trans "Reassign Inquiry" %}{% else %}{% trans "Assign Inquiry" %}{% endif %}
                </h3>
                <button type="button" onclick="closeModal('assignModal')" class="text-slate-400 hover:text-slate-600 transition">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>
        </div>
        <form method="post" action="{% url 'inquiries:inquiry_assign' inquiry.pk %}">
            {% csrf_token %}
            <div class="p-6">
                <label class="block text-sm font-semibold text-navy mb-2">{% trans "Assign To" %} <span class="text-red-500">*</span></label>
                <select name="user_id" class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 text-sm" required>
                    <option value="">{% trans "Select User" %}</option>
                    {% for u in assignable_users %}
                    <option value="{{ u.id }}" {% if inquiry.assigned_to and inquiry.assigned_to.id == u.id %}selected{% endif %}>{{ u.get_full_name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="p-6 border-t border-slate-200 flex gap-3">
                <button type="submit" class="flex-1 px-4 py-2.5 bg-navy text-white rounded-xl font-semibold hover:bg-navy/90 transition text-sm inline-flex items-center justify-center gap-2">
                    <i data-lucide="user-plus" class="w-4 h-4"></i>
                    {% if inquiry.assigned_to %}{% trans "Reassign" %}{% else %}{% trans "Assign" %}{% endif %}
                </button>
                <button type="button" onclick="closeModal('assignModal')" class="px-4 py-2.5 bg-white border-2 border-slate-200 rounded-xl font-semibold text-slate-600 hover:bg-slate-50 transition text-sm">
                    {% trans "Cancel" %}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Transfer to Department Modal -->
<div id="sendToDeptModal" style="display:none" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
        <div class="p-6 border-b border-slate-200">
            <div class="flex items-center justify-between">
                <h3 class="text-xl font-bold text-navy flex items-center gap-2">
                    <i data-lucide="arrow-right-left" class="w-5 h-5"></i>
                    {% trans "Transfer to Department" %}
                </h3>
                <button type="button" onclick="closeModal('sendToDeptModal')" class="text-slate-400 hover:text-slate-600 transition">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>
            <p class="text-sm text-slate mt-2">{% trans "Select a department to transfer this inquiry. Department champions will be notified to respond." %}</p>
        </div>
        <form method="post" action="{% url 'inquiries:inquiry_transfer_to_department' inquiry.pk %}">
            {% csrf_token %}
            <div class="p-6">
                <div class="mb-4">
                    <label class="block text-sm font-semibold text-navy mb-2">{% trans "Send To" %}</label>
                    <div class="flex gap-2">
                        <label class="flex-1 flex items-center gap-2 px-4 py-3 border-2 rounded-xl cursor-pointer transition-all border-navy bg-navy/5 text-navy font-semibold text-sm" id="inquiryRecipientLabelStaff" onclick="switchInquiryRecipientType('staff')">
                            <input type="radio" name="recipient_type" value="staff" checked class="accent-navy">
                            <i data-lucide="users" class="w-4 h-4"></i>
                            {% trans "Staff" %}
                        </label>
                        <label class="flex-1 flex items-center gap-2 px-4 py-3 border-2 rounded-xl cursor-pointer transition-all border-slate-200 text-slate-500 text-sm" id="inquiryRecipientLabelDeptEmail" onclick="switchInquiryRecipientType('department_email')">
                            <input type="radio" name="recipient_type" value="department_email" class="accent-navy">
                            <i data-lucide="building-2" class="w-4 h-4"></i>
                            {% trans "Department Email" %}
                        </label>
                    </div>
                </div>
                <div class="mb-4" id="inquiryDeptEmailHint" style="display:none;">
                    <div class="flex items-center gap-2 px-3 py-2 bg-amber-50 border border-amber-200 rounded-xl text-sm text-amber-700">
                        <i data-lucide="mail" class="w-4 h-4 shrink-0"></i>
                        <span>{% trans "The notification will be sent to the department's email address." %}</span>
                    </div>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-semibold text-navy mb-2">{% trans "Department" %} <span class="text-red-500">*</span></label>
                    <select name="department_id" id="deptSelect" onchange="loadDeptContactsInline(this.value)" class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 text-sm" required>
                        <option value="">{% trans "Select Department" %}</option>
                    </select>
                </div>
                <div class="mb-4" id="inlineContactSection" style="display:none;">
                    <label class="block text-sm font-semibold text-navy mb-2">{% trans "Send To" %} <span class="text-red-500">*</span></label>
                    <select name="contact_person_id" id="inlineContactSelect" class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 text-sm" required>
                        <option value="">{% trans "Select Contact Person" %}</option>
                    </select>
                </div>
                <div class="mb-4">
                    <div class="flex items-center justify-between mb-2">
                        <label class="text-sm font-semibold text-navy">{% trans "Context / Note" %}</label>
                        {% if inquiry.short_description_en or inquiry.ai_brief_en %}
                        <span class="inline-flex items-center gap-1 px-2 py-0.5 bg-light rounded-md text-[10px] font-bold text-navy uppercase">
                            <i data-lucide="sparkles" class="w-3 h-3"></i> {% trans "AI Summary" %}
                        </span>
                        {% endif %}
                    </div>
                    <div class="flex gap-1 mb-2">
                        <button type="button" class="lang-tab active" onclick="switchDeptNoteLang('en')" id="deptNoteTabEn">English</button>
                        <button type="button" class="lang-tab" onclick="switchDeptNoteLang('ar')" id="deptNoteTabAr">العربية</button>
                    </div>
                    <div id="deptNoteEn">
                        <textarea name="note_en" rows="4"
                            class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 resize-none text-sm"
                            placeholder="{% trans 'Add context or instructions for the department...' %}">{% if inquiry.short_description_en %}{{ inquiry.short_description_en }}{% elif inquiry.ai_brief_en %}{{ inquiry.ai_brief_en }}{% endif %}</textarea>
                    </div>
                    <div id="deptNoteAr" class="hidden">
                        <textarea name="note_ar" rows="4" dir="rtl"
                            class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 resize-none text-sm"
                            placeholder="{% trans 'أضف سياقاً أو تعليمات للقسم...' %}">{% if inquiry.short_description_ar %}{{ inquiry.short_description_ar }}{% elif inquiry.ai_brief_ar %}{{ inquiry.ai_brief_ar }}{% endif %}</textarea>
                    </div>
                </div>
            </div>
            <div class="p-6 border-t border-slate-200 flex gap-3">
                <button type="submit" class="flex-1 px-4 py-2.5 bg-navy text-white rounded-xl font-semibold hover:bg-navy/90 transition text-sm inline-flex items-center justify-center gap-2">
                    <i data-lucide="arrow-right-left" class="w-4 h-4"></i>
                    {% trans "Transfer to Department" %}
                </button>
                <button type="button" onclick="closeModal('sendToDeptModal')" class="px-4 py-2.5 bg-white border-2 border-slate-200 rounded-xl font-semibold text-slate-600 hover:bg-slate-50 transition text-sm">
                    {% trans "Cancel" %}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Escalate Inquiry 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 Inquiry" %}</h3>
        </div>
        <form method="post" action="{% url 'inquiries:inquiry_escalate' inquiry.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" 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 }}">
                            {{ target.staff.get_full_name }}{% if target.role_label %} ({{ target.role_label }}){% endif %}
                        </option>
                        {% endfor %}
                    </optgroup>
                    {% endfor %}
                </select>
            </div>
            <div class="mb-4">
                <label class="block text-sm font-semibold text-slate mb-2">{% trans "Reason" %}</label>
                <textarea name="reason" rows="3" class="w-full border border-slate-200 rounded-xl p-3 text-sm focus:ring-2 focus:ring-navy/20 outline-none" placeholder="{% trans 'Reason for escalation...' %}"></textarea>
            </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="8"
                        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="document.getElementById('escalateModal').style.display='none'" 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-red-500 text-white rounded-xl font-semibold hover:bg-red-600 transition flex items-center justify-center gap-2">
                    <i data-lucide="send" class="w-4 h-4"></i> {% trans "Send Escalation Email" %}
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
});

function switchTab(tabName) {
    document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.add('hidden'));
    document.getElementById('panel-' + tabName).classList.remove('hidden');
    document.querySelectorAll('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');
    if (window.lucide) lucide.createIcons();
}

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

function showRespondModal() {
    document.getElementById('respondModal').style.display = 'flex';
}

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

function showSendToDeptModal() {
    document.getElementById('sendToDeptModal').style.display = 'flex';
    loadDepartments();
}

function switchInquiryRecipientType(type) {
    const staffLabel = document.getElementById('inquiryRecipientLabelStaff');
    const deptEmailLabel = document.getElementById('inquiryRecipientLabelDeptEmail');
    const hint = document.getElementById('inquiryDeptEmailHint');
    if (type === 'staff') {
        staffLabel.classList.add('border-navy', 'bg-navy/5', 'text-navy', 'font-semibold');
        staffLabel.classList.remove('border-slate-200', 'text-slate-500');
        deptEmailLabel.classList.remove('border-navy', 'bg-navy/5', 'text-navy', 'font-semibold');
        deptEmailLabel.classList.add('border-slate-200', 'text-slate-500');
        if (hint) hint.style.display = 'none';
    } else {
        deptEmailLabel.classList.add('border-navy', 'bg-navy/5', 'text-navy', 'font-semibold');
        deptEmailLabel.classList.remove('border-slate-200', 'text-slate-500');
        staffLabel.classList.remove('border-navy', 'bg-navy/5', 'text-navy', 'font-semibold');
        staffLabel.classList.add('border-slate-200', 'text-slate-500');
        if (hint) hint.style.display = '';
    }
}

function switchDeptNoteLang(lang) {
    const tabEn = document.getElementById('deptNoteTabEn');
    const tabAr = document.getElementById('deptNoteTabAr');
    const noteEn = document.getElementById('deptNoteEn');
    const noteAr = document.getElementById('deptNoteAr');
    if (lang === 'en') {
        tabEn.classList.add('active'); tabAr.classList.remove('active');
        noteEn.classList.remove('hidden'); noteAr.classList.add('hidden');
    } else {
        tabAr.classList.add('active'); tabEn.classList.remove('active');
        noteAr.classList.remove('hidden'); noteEn.classList.add('hidden');
    }
}

function loadDepartments() {
    const sel = document.getElementById('deptSelect');
    if (sel.options.length > 1) return;
    const defaultDeptId = '{{ inquiry.department.id|default:"" }}';
    fetch('/organizations/ajax/departments/?hospital_id={{ inquiry.hospital.id }}')
        .then(r => r.json())
        .then(data => {
            sel.innerHTML = '<option value="">{% trans "Select Department" %}</option>';
            (data.departments || data).forEach(d => {
                sel.innerHTML += `<option value="${d.id}"${d.id === defaultDeptId ? ' selected' : ''}>${d.name}</option>`;
            });
            if (defaultDeptId) loadDeptContactsInline(defaultDeptId);
        });
}

function loadDeptContactsInline(deptId) {
    var select = document.getElementById('inlineContactSelect');
    var section = document.getElementById('inlineContactSection');
    select.innerHTML = '<option value="">{% trans "Loading..." %}</option>';
    if (!deptId) { section.style.display = 'none'; return; }
    section.style.display = '';
    fetch('/organizations/dropdowns/department-contacts/' + deptId + '/')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            select.innerHTML = '<option value="">{% trans "Select Contact Person" %}</option>';
            data.forEach(function(c) {
                var opt = document.createElement('option');
                opt.value = c.staff_id;
                opt.textContent = c.name + ' (' + c.role_label + ')';
                select.appendChild(opt);
            });
        })
        .catch(function() {
            select.innerHTML = '<option value="">{% trans "Error loading contacts" %}</option>';
        });
}

function getCSRFToken() {
    const metaTag = document.querySelector('[name=csrfmiddlewaretoken]');
    if (metaTag) return metaTag.value;
    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, 9) === ('csrftoken' + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(9));
                break;
            }
        }
    }
    return cookieValue;
}

function generateAIResponse() {
    const btn = document.getElementById('generateAiBtn');
    const suggestionsDiv = document.getElementById('aiSuggestions');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span> {% trans "Generating..." %}';
    suggestionsDiv.classList.add('hidden');
    fetch('/complaints/api/inquiries/{{ inquiry.pk }}/generate_ai_response/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCSRFToken() },
        credentials: 'same-origin'
    })
    .then(response => { if (!response.ok) return response.json().then(data => { throw new Error(data.error || 'Request failed'); }); return response.json(); })
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="sparkles" class="w-4 h-4"></i> {% trans "Generate AI Response" %}';
        lucide.createIcons();
        if (data.success) {
            document.getElementById('aiSuggestionEnText').textContent = data.response_en;
            document.getElementById('aiSuggestionArText').textContent = data.response_ar;
            suggestionsDiv.classList.remove('hidden');
        } else { alert(data.error || '{% trans "Failed to generate response" %}'); }
    })
    .catch(error => {
        console.error('Error:', error);
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="sparkles" class="w-4 h-4"></i> {% trans "Generate AI Response" %}';
        lucide.createIcons();
        alert(error.message || '{% trans "An error occurred while generating response" %}');
    });
}

function useAISuggestion(lang) {
    if (lang === 'en') {
        document.getElementById('responseEn').value = document.getElementById('aiSuggestionEnText').textContent;
        document.getElementById('aiSuggestionEn').classList.add('selected');
        setTimeout(() => document.getElementById('aiSuggestionEn').classList.remove('selected'), 1500);
    } else {
        document.getElementById('responseAr').value = document.getElementById('aiSuggestionArText').textContent;
        document.getElementById('aiSuggestionAr').classList.add('selected');
        setTimeout(() => document.getElementById('aiSuggestionAr').classList.remove('selected'), 1500);
    }
}

function useBothAISuggestions() {
    useAISuggestion('en'); useAISuggestion('ar');
    document.getElementById('aiSuggestionEn').classList.add('selected');
    document.getElementById('aiSuggestionAr').classList.add('selected');
}

function reanalyzeAI() {
    const btn = document.getElementById('reanalyzeBtn');
    const content = document.getElementById('aiAnalysisContent');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner spinner-dark"></span> {% trans "Analyzing..." %}';
    content.innerHTML = '<div class="text-center py-8"><span class="spinner spinner-dark" style="width:2rem;height:2rem;border-width:3px;"></span><p class="text-slate text-sm mt-3">{% trans "Re-analyzing inquiry with AI..." %}</p></div>';
    fetch('/complaints/api/inquiries/{{ inquiry.pk }}/reanalyze_ai/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCSRFToken() },
        credentials: 'same-origin'
    })
    .then(response => { if (!response.ok) return response.json().then(data => { throw new Error(data.error || 'Request failed'); }); return response.json(); })
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="refresh-cw" class="w-3 h-3"></i> {% trans "Re-analyze" %}';
        lucide.createIcons();
        if (data.success) {
            let html = '';
            if (data.emotion && data.emotion !== 'neutral') {
                html += '<div class="bg-light border border-blue-200 rounded-2xl p-5 mb-6"><h4 class="font-bold text-navy mb-3 flex items-center gap-2"><i data-lucide="cpu" class="w-5 h-5"></i> {% trans "Emotion Analysis" %}</h4><div class="flex items-center justify-between mb-3"><span class="px-4 py-2 bg-navy text-white rounded-xl font-bold flex items-center gap-2"><i data-lucide="frown" class="w-5 h-5"></i> ' + escapeHtml(data.emotion_display) + '</span><span class="text-slate">{% trans "Confidence" %}: ' + data.emotion_confidence_percent.toFixed(0) + '%</span></div><div><div class="flex justify-between text-sm mb-1"><span class="text-slate">{% trans "Intensity" %}</span><span class="font-semibold">' + data.emotion_intensity.toFixed(2) + ' / 1.0</span></div><div class="h-2 bg-slate-200 rounded-full overflow-hidden"><div class="h-full bg-navy rounded-full" style="width: ' + data.emotion_intensity_percent + '%"></div></div></div></div>';
            }
            if (data.short_description_en) html += '<div class="bg-light/50 border border-slate-200 rounded-2xl p-5 mb-4"><h4 class="font-bold text-navy mb-2">{% trans "AI Summary (English)" %}</h4><p class="text-slate">' + escapeHtml(data.short_description_en) + '</p></div>';
            if (data.short_description_ar) html += '<div class="bg-light/50 border border-slate-200 rounded-2xl p-5"><h4 class="font-bold text-navy mb-2">{% trans "AI Summary (Arabic)" %}</h4><p class="text-slate" dir="rtl">' + escapeHtml(data.short_description_ar) + '</p></div>';
            if (!html) html = '<div class="text-center py-8"><i data-lucide="check-circle" class="w-10 h-10 mx-auto text-green-500 mb-3"></i><p class="text-slate text-sm">{% trans "AI analysis complete" %}</p></div>';
            content.innerHTML = html;
            lucide.createIcons();
        } else {
            content.innerHTML = '<div class="text-center py-8"><i data-lucide="alert-circle" class="w-10 h-10 mx-auto text-red-500 mb-3"></i><p class="text-slate text-sm">' + escapeHtml(data.error || '{% trans "Analysis failed" %}') + '</p></div>';
            lucide.createIcons();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="refresh-cw" class="w-3 h-3"></i> {% trans "Re-analyze" %}';
        lucide.createIcons();
        content.innerHTML = '<div class="text-center py-8"><i data-lucide="alert-circle" class="w-10 h-10 mx-auto text-red-500 mb-3"></i><p class="text-slate text-sm">' + escapeHtml(error.message || '{% trans "An error occurred" %}') + '</p></div>';
        lucide.createIcons();
    });
}

function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; }

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal('respondModal');
        closeModal('assignModal');
        closeModal('sendToDeptModal');
    }
});
</script>

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

{% endblock %}
