{% load i18n %}
<div id="deptResponseModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden">
        <div class="bg-gradient-to-r from-navy to-blue p-4 flex justify-between items-center">
            <h3 class="text-white font-bold text-lg flex items-center gap-2">
                <i data-lucide="message-square" class="w-5 h-5"></i>
                {% trans "Submit Department Response" %}
            </h3>
            <button onclick="closeDeptResponseModal()" class="text-white/80 hover:text-white transition">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <div class="p-6 space-y-4">
            <div class="bg-slate-50 rounded-xl p-4 border border-slate-200">
                <p class="text-[10px] text-slate-500 uppercase font-bold mb-1">{% trans "Reference" %}</p>
                <p id="drmRef" class="font-mono text-sm font-bold text-navy"></p>
                <p class="text-[10px] text-slate-500 uppercase font-bold mb-1 mt-2">{% trans "Subject" %}</p>
                <p id="drmSubject" class="text-sm text-slate-700"></p>
            </div>

            <div id="drmSingleField">
                <label class="block text-sm font-semibold text-slate-700 mb-2">
                    {% trans "Your Response" %} <span class="text-red-500">*</span>
                </label>
                <textarea id="drmResponseNotes" rows="5"
                    class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl text-slate-700 focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 resize-none text-sm"
                    placeholder="{% trans "Enter your department's response..." %}"></textarea>
            </div>

            <div id="drmBilingualFields" class="hidden space-y-3">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">
                        {% trans "Response (English)" %}
                    </label>
                    <textarea id="drmResponseEn" rows="4"
                        class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl text-slate-700 focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 resize-none text-sm"
                        placeholder="{% trans 'Enter your response in English...' %}"></textarea>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">
                        {% trans "Response (Arabic)" %}
                    </label>
                    <textarea id="drmResponseAr" rows="4" dir="rtl"
                        class="w-full px-4 py-3 border-2 border-slate-200 rounded-xl text-slate-700 focus:outline-none focus:border-navy focus:ring-2 focus:ring-navy/20 resize-none text-sm"
                        placeholder="{% trans 'أدخل ردك باللغة العربية...' %}"></textarea>
                </div>
                <p class="text-xs text-slate">
                    <i data-lucide="info" class="w-3 h-3 inline mr-1"></i>
                    {% trans "At least one language is required." %}
                </p>
            </div>

            <div id="drmError" class="hidden text-sm text-red-600 bg-red-50 border border-red-200 p-3 rounded-lg"></div>

            <div class="flex gap-3 pt-2">
                <button type="button" id="drmSubmitBtn" onclick="submitDeptResponse()"
                    class="flex-1 px-4 py-2.5 bg-navy text-white font-medium rounded-xl hover:bg-blue transition flex items-center justify-center gap-2">
                    <i data-lucide="send" class="w-4 h-4"></i>
                    {% trans "Submit Response" %}
                </button>
                <button type="button" onclick="closeDeptResponseModal()"
                    class="flex-1 px-4 py-2.5 bg-slate-100 text-slate-700 font-medium rounded-xl hover:bg-slate-200 transition">
                    {% trans "Cancel" %}
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let _drmConfig = {};

function openDeptResponseModal(type, pk, url, reference, subject, existingEn, existingAr) {
    _drmConfig = { type: type, pk: pk, url: url };

    document.getElementById('drmRef').textContent = reference || '';
    document.getElementById('drmSubject').textContent = subject || '';

    const singleField = document.getElementById('drmSingleField');
    const bilingualFields = document.getElementById('drmBilingualFields');
    const errorEl = document.getElementById('drmError');
    errorEl.classList.add('hidden');

    if (type === 'complaint') {
        bilingualFields.classList.remove('hidden');
        singleField.classList.add('hidden');
        document.getElementById('drmResponseEn').value = existingEn || '';
        document.getElementById('drmResponseAr').value = existingAr || '';
    } else {
        singleField.classList.add('hidden');
        bilingualFields.classList.remove('hidden');
        document.getElementById('drmResponseEn').value = existingEn || '';
        document.getElementById('drmResponseAr').value = existingAr || '';
    }

    document.getElementById('deptResponseModal').classList.remove('hidden');
    if (window.lucide) lucide.createIcons();
}

function closeDeptResponseModal() {
    document.getElementById('deptResponseModal').classList.add('hidden');
    document.getElementById('drmError').classList.add('hidden');
}

function submitDeptResponse() {
    const errorEl = document.getElementById('drmError');
    const submitBtn = document.getElementById('drmSubmitBtn');
    errorEl.classList.add('hidden');

    let body = {};
    if (_drmConfig.type === 'complaint') {
        body.response_notes_en = document.getElementById('drmResponseEn').value.trim();
        body.response_notes_ar = document.getElementById('drmResponseAr').value.trim();
        if (!body.response_notes_en && !body.response_notes_ar) {
            errorEl.textContent = '{% trans "Please enter a response in at least one language." %}';
            errorEl.classList.remove('hidden');
            return;
        }
    } else {
        body.response_en = document.getElementById('drmResponseEn').value.trim();
        body.response_ar = document.getElementById('drmResponseAr').value.trim();
        if (!body.response_en && !body.response_ar) {
            errorEl.textContent = '{% trans "Please enter a response in at least one language." %}';
            errorEl.classList.remove('hidden');
            return;
        }
    }

    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i data-lucide="loader" class="w-4 h-4 animate-spin"></i> {% trans "Submitting..." %}';
    if (window.lucide) lucide.createIcons();

    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]')?.value
        || document.cookie.split(';').map(c => c.trim()).find(c => c.startsWith('csrftoken='))?.split('=')[1];

    fetch(_drmConfig.url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': csrftoken,
            'X-Requested-With': 'XMLHttpRequest',
        },
        body: new URLSearchParams(body),
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeDeptResponseModal();
            if (data.redirect_url) {
                window.location.href = data.redirect_url;
            } else {
                window.location.reload();
            }
        } else {
            errorEl.textContent = data.error || '{% trans "An error occurred." %}';
            errorEl.classList.remove('hidden');
        }
    })
    .catch(() => {
        errorEl.textContent = '{% trans "Network error. Please try again." %}';
        errorEl.classList.remove('hidden');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i data-lucide="send" class="w-4 h-4"></i> {% trans "Submit Response" %}';
        if (window.lucide) lucide.createIcons();
    });
}

document.getElementById('deptResponseModal').addEventListener('click', function(e) {
    if (e.target === this) closeDeptResponseModal();
});
</script>
