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

{% block title %}{% trans "Acknowledgement Checklist Items" %}{% endblock %}

{% block extra_css %}
<style>
.page-header-gradient {
    background: linear-gradient(135deg, #005696 0%, #0069a8 50%, #007bbd 100%);
    color: white;
    padding: 1.5rem 2rem;
    border-radius: 1rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
}

.section-card {
    background: white;
    border-radius: 1rem;
    border: 2px solid #e2e8f0;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: all 0.3s ease;
}
.section-card:hover {
    border-color: #005696;
    box-shadow: 0 10px 25px -5px rgba(0, 86, 150, 0.15);
}

.section-header {
    padding: 1rem 1.5rem;
    border-bottom: 2px solid #e2e8f0;
    background: linear-gradient(to right, #f8fafc, #f1f5f9);
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.section-icon {
    width: 40px;
    height: 40px;
    border-radius: 0.75rem;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
{% endblock %}

{% block content %}
<div class="p-6 md:p-8 bg-gradient-to-br from-light to-blue-50 min-h-screen">
    <!-- Page Header -->
    <div class="page-header-gradient">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
            <div class="flex items-center gap-3">
                <div class="section-icon bg-white/20">
                    <i data-lucide="list-checks" class="w-6 h-6 text-white"></i>
                </div>
                <div>
                    <h2 class="text-2xl font-bold">
                        {% trans "Checklist Items" %}
                    </h2>
                    <p class="text-white/80">{% trans "Manage acknowledgement checklist items" %}</p>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <button type="button" onclick="openCategoryCreateModal()" 
                        class="bg-white/20 text-white px-5 py-3 rounded-xl font-bold hover:bg-white/30 transition shadow-lg flex items-center gap-2 border border-white/30">
                    <i data-lucide="folder" class="w-5 h-5"></i>
                    {% trans "Manage Categories" %}
                </button>
                <button type="button" onclick="document.getElementById('createChecklistItemModal').style.display='flex'" 
                        class="bg-white text-[#005696] px-6 py-3 rounded-xl font-bold hover:bg-white/90 transition shadow-lg flex items-center gap-2">
                    <i data-lucide="plus" class="w-5 h-5"></i>
                    {% trans "Add Checklist Item" %}
                </button>
            </div>
        </div>
    </div>

    <!-- Checklist Items List -->
    <div class="section-card">
        <div class="section-header flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
            <div class="flex items-center gap-2">
                <div class="section-icon bg-gradient-to-br from-blue to-navy">
                    <i data-lucide="clipboard-list" class="w-5 h-5 text-white"></i>
                </div>
                <h3 class="font-bold text-navy text-lg">{% trans "All Items" %}</h3>
            </div>
            <div class="flex items-center gap-2 w-full md:w-auto">
                <div class="relative flex-1 md:w-64">
                    <input type="text" id="searchInput" placeholder="{% trans 'Search items...' %}"
                           class="w-full pl-10 pr-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                           value="{{ search_query|default:'' }}">
                    <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate"></i>
                </div>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full" id="itemsTable">
                <thead class="bg-blue-50">
                    <tr>
                        <th class="px-6 py-4 text-left text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Item Text" %}</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Role" %}</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Linked Content" %}</th>
                        <th class="px-6 py-4 text-center text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Required" %}</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Order" %}</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Status" %}</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Created" %}</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-blue-800 uppercase tracking-wider">{% trans "Actions" %}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-blue-50">
                    {% for item in checklist_items %}
                    <tr class="hover:bg-blue-50/50 transition">
                        <td class="px-6 py-4">
                            <div class="flex items-start gap-2">
                                <div>
                                    <strong class="text-navy font-bold">{{ item.get_localized_text }}</strong>
                                    {% if item.code %}
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-blue-100 text-blue-700 ml-2">{{ item.code }}</span>
                                    {% endif %}
                                    {% if item.description_en %}
                                        <p class="text-sm text-slate mt-1">{{ item.description_en|truncatewords:15 }}</p>
                                    {% endif %}
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            {% if item.category %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-blue-100 text-blue-700">
                                    {{ item.category.get_localized_name }}
                                </span>
                            {% else %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-slate-100 text-slate-700">{% trans "No Category" %}</span>
                            {% endif %}
                        </td>
                        <td class="px-6 py-4">
                            {% if item.content %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-indigo-100 text-indigo-700">
                                    {{ item.content.get_localized_title|truncatechars:25 }}
                                </span>
                            {% else %}
                                <span class="text-slate">-</span>
                            {% endif %}
                        </td>
                        <td class="px-6 py-4 text-center">
                            {% if item.is_required %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-red-100 text-red-700">
                                    <i data-lucide="alert-circle" class="w-3 h-3 mr-1"></i>
                                    {% trans "Yes" %}
                                </span>
                            {% else %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-slate-100 text-slate-700">{% trans "No" %}</span>
                            {% endif %}
                        </td>
                        <td class="px-6 py-4 text-navy font-semibold">{{ item.order }}</td>
                        <td class="px-6 py-4">
                            {% if item.is_active %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-emerald-100 text-emerald-700">
                                    <i data-lucide="check" class="w-3 h-3 mr-1"></i>
                                    {% trans "Active" %}
                                </span>
                            {% else %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-slate-100 text-slate-700">
                                    <i data-lucide="x" class="w-3 h-3 mr-1"></i>
                                    {% trans "Inactive" %}
                                </span>
                            {% endif %}
                        </td>
                        <td class="px-6 py-4 text-slate text-sm">
                            {{ item.created_at|date:"M d, Y" }}
                        </td>
                        <td class="px-6 py-4">
                            <div class="flex gap-2">
                                <button type="button" onclick="editChecklistItem('{{ item.pk }}')" class="px-3 py-2 text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition font-medium text-sm" title="{% trans 'Edit' %}">
                                    <i data-lucide="pencil" class="w-4 h-4"></i>
                                </button>
                                <button type="button" onclick="deleteChecklistItem('{{ item.pk }}')" class="px-3 py-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition font-medium text-sm" title="{% trans 'Delete' %}">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="8" class="text-center py-12">
                            <div class="flex flex-col items-center">
                                <i data-lucide="clipboard-list" class="w-16 h-16 text-blue-200 mx-auto mb-4"></i>
                                <p class="text-slate font-medium">{% trans "No checklist items found" %}</p>
                                <button type="button" onclick="document.getElementById('createChecklistItemModal').style.display='flex'" 
                                        class="mt-4 text-blue font-semibold hover:underline">
                                    {% trans "Add your first checklist item" %}
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Create Checklist Item Modal -->
<div id="createChecklistItemModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50" style="display:none;">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto m-4">
        <div class="px-6 py-5 border-b border-blue-100 bg-gradient-to-r from-blue-50 to-transparent flex justify-between items-center sticky top-0 rounded-t-2xl">
            <h3 id="checklistModalTitle" class="font-bold text-navy flex items-center gap-2 text-lg">
                <i data-lucide="plus-circle" class="w-5 h-5 text-blue"></i>
                {% trans "Add New Checklist Item" %}
            </h3>
            <button type="button" onclick="closeChecklistItemModal()" class="text-slate hover:text-navy transition">
                <i data-lucide="x" class="w-6 h-6"></i>
            </button>
        </div>
        <div class="p-6">
            <form id="createChecklistItemForm">
                {% csrf_token %}

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Code -->
                    <div>
                        <label for="code" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="tag" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Code" %} <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="code" name="code" required
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                               placeholder="{% trans 'CLINIC_P1' %}">
                    </div>

                    <!-- Role -->
                    <div>
                        <label for="category" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="folder" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Category" %}
                        </label>
                        <select id="category" name="category" class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition">
                            {% for cat in category_list %}
                            <option value="{{ cat.id }}">{{ cat.name_en }}</option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- Linked Content -->
                    <div>
                        <label for="content" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="link" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Linked Content" %}
                        </label>
                        <select id="content" name="content" class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition">
                            <option value="">{% trans "No linked content" %}</option>
                            {% for content_item in content_list %}
                            <option value="{{ content_item.id }}">{{ content_item.title_en }}</option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- Order -->
                    <div>
                        <label for="order" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="arrow-down-1-0" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Display Order" %}
                        </label>
                        <input type="number" id="order" name="order" value="0" min="0"
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition">
                    </div>

                    <!-- Text (English) -->
                    <div class="md:col-span-2">
                        <label for="text_en" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="type" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Text (English)" %} <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="text_en" name="text_en" required
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                               placeholder="{% trans 'Main text for the checklist item' %}">
                    </div>

                    <!-- Text (Arabic) -->
                    <div class="md:col-span-2">
                        <label for="text_ar" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="type" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Text (Arabic)" %}
                        </label>
                        <input type="text" id="text_ar" name="text_ar" dir="rtl"
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                               placeholder="{% trans 'Arabic translation' %}">
                    </div>

                    <!-- Description (English) -->
                    <div class="md:col-span-2">
                        <label for="description_en" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="file-text" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Description (English)" %}
                        </label>
                        <textarea id="description_en" name="description_en" rows="3"
                                  class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                                  placeholder="{% trans 'Additional details' %}"></textarea>
                    </div>

                    <!-- Description (Arabic) -->
                    <div class="md:col-span-2">
                        <label for="description_ar" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="file-text" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Description (Arabic)" %}
                        </label>
                        <textarea id="description_ar" name="description_ar" rows="3" dir="rtl"
                                  class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                                  placeholder="{% trans 'Arabic translation' %}"></textarea>
                    </div>

                    <!-- Configuration -->
                    <div>
                        <label class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="check-circle" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Configuration" %}
                        </label>
                        <div class="space-y-3">
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" id="is_required" name="is_required" checked
                                       class="w-5 h-5 text-blue border-blue-200 rounded focus:ring-2 focus:ring-blue">
                                <span class="text-navy font-medium">{% trans "Item must be acknowledged" %}</span>
                            </label>
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" id="is_active" name="is_active" checked
                                       class="w-5 h-5 text-blue border-blue-200 rounded focus:ring-2 focus:ring-blue">
                                <span class="text-navy font-medium">{% trans "Item is visible" %}</span>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Error Alert -->
                <div class="bg-red-50 border border-red-200 rounded-xl p-4 mt-6 hidden" id="formError">
                    <div class="flex items-center gap-2 text-red-700">
                        <i data-lucide="alert-triangle" class="w-5 h-5"></i>
                        <span id="formErrorMessage"></span>
                    </div>
                </div>
            </form>
        </div>
        <div class="px-6 py-4 border-t border-blue-100 bg-gradient-to-r from-blue-50 to-transparent flex justify-end gap-3 sticky bottom-0 rounded-b-2xl">
            <button type="button" onclick="closeChecklistItemModal()"
                    class="px-6 py-2.5 border-2 border-slate-200 text-slate-700 rounded-xl font-bold hover:bg-slate-50 transition flex items-center gap-2">
                <i data-lucide="x-circle" class="w-4 h-4"></i>
                {% trans "Cancel" %}
            </button>
            <button type="button" onclick="saveChecklistItem()" id="saveChecklistItemBtn"
                    class="bg-gradient-to-r from-blue to-navy text-white px-6 py-2.5 rounded-xl font-bold hover:from-navy hover:to-blue transition flex items-center gap-2 shadow-lg shadow-blue-200">
                <i data-lucide="save" class="w-4 h-4"></i>
                <span id="saveBtnText">{% trans "Save Item" %}</span>
                <span class="animate-spin hidden" id="saveBtnSpinner">
                    <i data-lucide="loader-2" class="w-4 h-4"></i>
                </span>
            </button>
        </div>
    </div>
</div>

<!-- Category Management Modal -->
<div id="categoryModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50" style="display:none;">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto m-4">
        <div class="px-6 py-5 border-b border-blue-100 bg-gradient-to-r from-blue-50 to-transparent flex justify-between items-center sticky top-0 rounded-t-2xl">
            <h3 id="categoryModalTitle" class="font-bold text-navy flex items-center gap-2 text-lg">
                <i data-lucide="plus-circle" class="w-5 h-5 text-blue"></i>
                {% trans "Add New Category" %}
            </h3>
            <button type="button" onclick="closeCategoryModal()" class="text-slate hover:text-navy transition">
                <i data-lucide="x" class="w-6 h-6"></i>
            </button>
        </div>
        <div class="p-6">
            <div id="categoryFormError" class="hidden mb-4 p-4 bg-red-50 border border-red-200 rounded-xl">
                <p id="categoryErrorMessage" class="text-red-700 text-sm font-medium"></p>
            </div>

            <form id="categoryForm">
                {% csrf_token %}

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="cat_name_en" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="type" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Name (English)" %} <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="cat_name_en" name="cat_name_en" required
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                               placeholder="{% trans 'e.g. Clinics' %}">
                    </div>

                    <div>
                        <label for="cat_name_ar" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="type" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Name (Arabic)" %}
                        </label>
                        <input type="text" id="cat_name_ar" name="cat_name_ar" dir="rtl"
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                               placeholder="{% trans 'Arabic name' %}">
                    </div>

                    <div>
                        <label for="cat_code" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="tag" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Code" %} <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="cat_code" name="cat_code" required
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                               placeholder="{% trans 'e.g. CLINICS' %}">
                    </div>

                    <div>
                        <label for="cat_icon" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="image" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Icon" %}
                        </label>
                        <input type="text" id="cat_icon" name="cat_icon"
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                               placeholder="{% trans 'e.g. building, user' %}">
                    </div>

                    <div>
                        <label for="cat_color" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="palette" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Color" %}
                        </label>
                        <div class="flex gap-2">
                            <input type="color" id="catColorPicker" value="#007bbd" class="w-10 h-10 rounded-lg border-2 border-blue-100 cursor-pointer p-0.5"
                                   onchange="document.getElementById('cat_color').value = this.value">
                            <input type="text" id="cat_color" name="cat_color" value="#007bbd"
                                   class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                                   placeholder="#007bbd"
                                   oninput="document.getElementById('catColorPicker').value = this.value">
                        </div>
                    </div>

                    <div>
                        <label for="cat_order" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="arrow-down-1-0" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Display Order" %}
                        </label>
                        <input type="number" id="cat_order" name="cat_order" value="0" min="0"
                               class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition">
                    </div>

                    <div class="md:col-span-2">
                        <label for="cat_description" class="block text-sm font-bold text-navy mb-2">
                            <i data-lucide="align-left" class="w-4 h-4 inline mr-1 text-blue"></i>
                            {% trans "Description" %}
                        </label>
                        <textarea id="cat_description" name="cat_description" rows="3"
                                  class="w-full px-4 py-2.5 border-2 border-blue-100 rounded-xl text-navy focus:ring-2 focus:ring-blue focus:border-transparent transition"
                                  placeholder="{% trans 'Category description' %}"></textarea>
                    </div>

                    <div class="flex items-center gap-3">
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" id="cat_is_active" name="cat_is_active" checked class="sr-only peer">
                            <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue"></div>
                            <span class="ms-3 text-sm font-bold text-navy">{% trans "Active" %}</span>
                        </label>
                    </div>
                </div>
            </form>
        </div>
        <div class="px-6 py-4 border-t border-blue-100 bg-gradient-to-r from-blue-50 to-transparent flex justify-end gap-3 sticky bottom-0 rounded-b-2xl">
            <button type="button" onclick="closeCategoryModal()" class="px-6 py-2.5 border-2 border-slate-200 text-slate-700 rounded-xl font-bold hover:bg-slate-50 transition flex items-center gap-2">
                <i data-lucide="x-circle" class="w-4 h-4"></i>
                {% trans "Cancel" %}
            </button>
            <button type="button" onclick="saveCategory()" id="catSaveBtn" class="bg-gradient-to-r from-blue to-navy text-white px-6 py-2.5 rounded-xl font-bold hover:from-navy hover:to-blue transition flex items-center gap-2 shadow-lg shadow-blue-200">
                <i data-lucide="save" class="w-4 h-4"></i>
                <span id="catSaveBtnText">{% trans "Save Category" %}</span>
                <span class="animate-spin hidden" id="catSaveBtnSpinner">
                    <i data-lucide="loader-2" class="w-4 h-4"></i>
                </span>
            </button>
        </div>
    </div>
</div>

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

    let searchTimeout;
    document.getElementById('searchInput').addEventListener('keyup', function() {
        clearTimeout(searchTimeout);
        const searchValue = this.value.toLowerCase();
        searchTimeout = setTimeout(() => {
            const table = document.getElementById('itemsTable');
            const rows = table.getElementsByTagName('tr');

            for (let i = 1; i < rows.length; i++) {
                const row = rows[i];
                const cells = row.getElementsByTagName('td');
                let found = false;

                for (let j = 0; j < cells.length; j++) {
                    const cellText = cells[j].textContent.toLowerCase();
                    if (cellText.includes(searchValue)) {
                        found = true;
                        break;
                    }
                }

                row.style.display = found ? '' : 'none';
            }
        }, 300);
    });
});

function showAlert(message, type = 'info') {
    const alert = document.createElement('div');
    const bgColor = type === 'success' ? 'bg-gradient-to-r from-emerald-500 to-emerald-600' : 'bg-gradient-to-r from-blue-500 to-blue-600';
    alert.className = `${bgColor} text-white px-6 py-4 rounded-xl shadow-xl z-[60] flex items-center gap-3 fixed top-4 right-4 max-w-lg`;
    alert.innerHTML = `
        <i data-lucide="${type === 'success' ? 'check-circle' : 'info'}" class="w-5 h-5 flex-shrink-0"></i>
        <span class="font-semibold text-sm">${message}</span>
        <button type="button" onclick="this.parentElement.remove()" class="text-white/80 hover:text-white flex-shrink-0">
            <i data-lucide="x" class="w-4 h-4"></i>
        </button>
    `;
    document.body.appendChild(alert);
    lucide.createIcons();
    setTimeout(() => { alert.remove(); }, 5000);
}

// ==================== Checklist Item CRUD ====================

function closeChecklistItemModal() {
    document.getElementById('createChecklistItemModal').style.display = 'none';
    document.getElementById('createChecklistItemForm').reset();
    document.getElementById('formError').classList.add('hidden');
    delete document.getElementById('createChecklistItemForm').dataset.editItemId;
}

document.getElementById('createChecklistItemModal').addEventListener('click', function(e) {
    if (e.target === this) closeChecklistItemModal();
});

async function saveChecklistItem() {
    const form = document.getElementById('createChecklistItemForm');
    const saveBtn = document.getElementById('saveChecklistItemBtn');
    const saveBtnText = document.getElementById('saveBtnText');
    const saveBtnSpinner = document.getElementById('saveBtnSpinner');
    const errorAlert = document.getElementById('formError');
    const errorMessage = document.getElementById('formErrorMessage');

    errorAlert.classList.add('hidden');

    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }

    const editItemId = form.dataset.editItemId;
    const isEditing = !!editItemId;

    const formData = new FormData(form);
    const data = {
        code: formData.get('code'),
        category: formData.get('category'),
        content: formData.get('content') || null,
        text_en: formData.get('text_en'),
        text_ar: formData.get('text_ar'),
        description_en: formData.get('description_en'),
        description_ar: formData.get('description_ar'),
        is_required: formData.get('is_required') === 'on',
        is_active: formData.get('is_active') === 'on',
        order: parseInt(formData.get('order')) || 0
    };

    saveBtn.disabled = true;
    saveBtnText.textContent = '{% trans "Saving..." %}';
    saveBtnSpinner.classList.remove('hidden');

    try {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        
        const url = isEditing 
            ? `/accounts/api/checklist-items/${editItemId}/`
            : '/accounts/api/checklist-items/';
        const method = isEditing ? 'PUT' : 'POST';

        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify(data)
        });

        const responseData = await response.json();

        if (response.ok) {
            closeChecklistItemModal();
            showAlert(isEditing 
                ? '{% trans "Checklist item updated successfully!" %}'
                : '{% trans "Checklist item created successfully!" %}', 'success');
            setTimeout(() => { window.location.reload(); }, 1000);
        } else {
            errorMessage.textContent = responseData.error || responseData.detail || '{% trans "Failed to save checklist item" %}';
            errorAlert.classList.remove('hidden');
        }
    } catch (error) {
        console.error('Error:', error);
        errorMessage.textContent = '{% trans "An error occurred. Please try again." %}';
        errorAlert.classList.remove('hidden');
    } finally {
        saveBtn.disabled = false;
        saveBtnText.textContent = '{% trans "Save Item" %}';
        saveBtnSpinner.classList.add('hidden');
    }
}

async function editChecklistItem(itemId) {
    try {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        
        const response = await fetch(`/accounts/api/checklist-items/${itemId}/`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        });
        
        if (response.ok) {
            const item = await response.json();
            
            document.getElementById('code').value = item.code || '';
            document.getElementById('category').value = item.category || '';
            document.getElementById('content').value = item.content || '';
            document.getElementById('order').value = item.order || 0;
            document.getElementById('text_en').value = item.text_en || '';
            document.getElementById('text_ar').value = item.text_ar || '';
            document.getElementById('description_en').value = item.description_en || '';
            document.getElementById('description_ar').value = item.description_ar || '';
            document.getElementById('is_required').checked = item.is_required !== false;
            document.getElementById('is_active').checked = item.is_active !== false;
            
            document.getElementById('createChecklistItemForm').dataset.editItemId = itemId;
            
            document.getElementById('checklistModalTitle').innerHTML = '<i data-lucide="pencil" class="w-5 h-5 text-blue"></i> {% trans "Edit Checklist Item" %}';
            
            document.getElementById('createChecklistItemModal').style.display = 'flex';
            lucide.createIcons();
        } else {
            showAlert('{% trans "Failed to load checklist item" %}', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showAlert('{% trans "An error occurred loading the item" %}', 'error');
    }
}

async function deleteChecklistItem(itemId) {
    if (!confirm('{% trans "Are you sure you want to delete this checklist item?" %}')) {
        return;
    }
    
    try {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        
        const response = await fetch(`/accounts/api/checklist-items/${itemId}/`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        });
        
        if (response.ok || response.status === 204) {
            showAlert('{% trans "Checklist item deleted successfully!" %}', 'success');
            setTimeout(() => { window.location.reload(); }, 1000);
        } else {
            const responseData = await response.json().catch(() => ({}));
            showAlert(responseData.error || responseData.detail || '{% trans "Failed to delete checklist item" %}', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showAlert('{% trans "An error occurred. Please try again." %}', 'error');
    }
}

// ==================== Category CRUD ====================

const CATEGORY_API = '/accounts/api/category-items/';
let editCategoryId = null;

function openCategoryCreateModal() {
    editCategoryId = null;
    const form = document.getElementById('categoryForm');
    form.reset();
    document.getElementById('cat_is_active').checked = true;
    document.getElementById('cat_color').value = '#007bbd';
    document.getElementById('catColorPicker').value = '#007bbd';
    document.getElementById('categoryModalTitle').innerHTML = '<i data-lucide="plus-circle" class="w-5 h-5 text-blue"></i> {% trans "Add New Category" %}';
    document.getElementById('catSaveBtnText').textContent = '{% trans "Save Category" %}';
    document.getElementById('categoryFormError').classList.add('hidden');
    document.getElementById('categoryModal').style.display = 'flex';
    lucide.createIcons();
}

function closeCategoryModal() {
    document.getElementById('categoryModal').style.display = 'none';
    document.getElementById('categoryForm').reset();
    document.getElementById('categoryFormError').classList.add('hidden');
    editCategoryId = null;
}

document.getElementById('categoryModal').addEventListener('click', function(e) {
    if (e.target === this) closeCategoryModal();
});

async function refreshCategoryDropdown() {
    try {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const response = await fetch(CATEGORY_API, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken }
        });

        if (response.ok) {
            const categories = await response.json();
            const select = document.getElementById('category');
            const currentVal = select.value;
            const results = Array.isArray(categories) ? categories : categories.results || [];

            select.innerHTML = '';
            results
                .filter(cat => cat.is_active)
                .sort((a, b) => (a.order || 0) - (b.order || 0) || a.name_en.localeCompare(b.name_en))
                .forEach(cat => {
                    const opt = document.createElement('option');
                    opt.value = cat.id;
                    opt.textContent = cat.name_en;
                    select.appendChild(opt);
                });

            if (currentVal) select.value = currentVal;
        }
    } catch (error) {
        console.error('Error refreshing categories:', error);
    }
}

async function saveCategory() {
    const form = document.getElementById('categoryForm');
    const saveBtn = document.getElementById('catSaveBtn');
    const saveBtnText = document.getElementById('catSaveBtnText');
    const saveBtnSpinner = document.getElementById('catSaveBtnSpinner');
    const errorAlert = document.getElementById('categoryFormError');
    const errorMessage = document.getElementById('categoryErrorMessage');

    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }

    const formData = new FormData(form);
    const data = {
        name_en: formData.get('cat_name_en'),
        name_ar: formData.get('cat_name_ar'),
        code: formData.get('cat_code'),
        description: formData.get('cat_description') || '',
        icon: formData.get('cat_icon') || '',
        color: formData.get('cat_color') || '#007bbd',
        order: parseInt(formData.get('cat_order')) || 0,
        is_active: formData.get('cat_is_active') === 'on',
    };

    saveBtn.disabled = true;
    saveBtnText.textContent = '{% trans "Saving..." %}';
    saveBtnSpinner.classList.remove('hidden');

    try {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const url = editCategoryId ? `${CATEGORY_API}${editCategoryId}/` : CATEGORY_API;
        const method = editCategoryId ? 'PUT' : 'POST';

        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify(data)
        });

        const responseData = await response.json();

        if (response.ok) {
            closeCategoryModal();
            showAlert(editCategoryId
                ? '{% trans "Category updated successfully!" %}'
                : '{% trans "Category created successfully!" %}', 'success');
            await refreshCategoryDropdown();
            setTimeout(() => { window.location.reload(); }, 1500);
        } else {
            const errors = [];
            for (const [field, msgs] of Object.entries(responseData)) {
                errors.push(`${field}: ${Array.isArray(msgs) ? msgs.join(', ') : msgs}`);
            }
            errorMessage.textContent = errors.join(' | ') || '{% trans "Failed to save category" %}';
            errorAlert.classList.remove('hidden');
        }
    } catch (error) {
        console.error('Error:', error);
        errorMessage.textContent = '{% trans "An error occurred. Please try again." %}';
        errorAlert.classList.remove('hidden');
    } finally {
        saveBtn.disabled = false;
        saveBtnText.textContent = '{% trans "Save Category" %}';
        saveBtnSpinner.classList.add('hidden');
    }
}

async function editCategoryModal(itemId) {
    try {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const response = await fetch(`${CATEGORY_API}${itemId}/`, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken }
        });

        if (response.ok) {
            const item = await response.json();

            document.getElementById('cat_name_en').value = item.name_en || '';
            document.getElementById('cat_name_ar').value = item.name_ar || '';
            document.getElementById('cat_code').value = item.code || '';
            document.getElementById('cat_description').value = item.description || '';
            document.getElementById('cat_icon').value = item.icon || '';
            document.getElementById('cat_color').value = item.color || '#007bbd';
            document.getElementById('catColorPicker').value = item.color || '#007bbd';
            document.getElementById('cat_order').value = item.order || 0;
            document.getElementById('cat_is_active').checked = item.is_active !== false;

            editCategoryId = itemId;
            document.getElementById('categoryModalTitle').innerHTML = '<i data-lucide="pencil" class="w-5 h-5 text-blue"></i> {% trans "Edit Category" %}';
            document.getElementById('catSaveBtnText').textContent = '{% trans "Update Category" %}';
            document.getElementById('categoryFormError').classList.add('hidden');
            document.getElementById('categoryModal').style.display = 'flex';
            lucide.createIcons();
        } else {
            showAlert('{% trans "Failed to load category" %}', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showAlert('{% trans "An error occurred loading the category" %}', 'error');
    }
}
</script>
{% endblock %}
