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

{% 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);
}

.form-section {
    background: #fff;
    border: 2px solid #e2e8f0;
    border-radius: 1rem;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
}
.form-section:hover {
    border-color: #005696;
    box-shadow: 0 4px 12px rgba(0, 86, 150, 0.1);
}

.choices-field textarea[name*="choices_json"] {
    display: none;
}

.form-label {
    display: block;
    font-size: 0.875rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.form-control, .form-select {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 2px solid #e2e8f0;
    border-radius: 0.75rem;
    font-size: 0.875rem;
    transition: all 0.2s ease;
}
.form-control:focus, .form-select:focus {
    outline: none;
    border-color: #005696;
    box-shadow: 0 0 0 3px rgba(0, 86, 150, 0.1);
}

.hh-btn-primary {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background: #005696;
    color: white;
    border-radius: 0.75rem;
    font-weight: 600;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
}
.hh-btn-primary:hover {
    background: #007bbd;
}

.hh-btn-secondary {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background: white;
    color: #64748b;
    border: 2px solid #e2e8f0;
    border-radius: 0.75rem;
    font-weight: 600;
    transition: all 0.2s ease;
}
.hh-btn-secondary:hover {
    background: #f1f5f9;
    border-color: #005696;
}

.question-card {
    background: #fff;
    border: 2px solid #e2e8f0;
    border-radius: 1rem;
    padding: 1rem 1.25rem;
    margin-bottom: 0.75rem;
    position: relative;
    transition: all 0.3s ease;
}
.question-card:hover {
    border-color: #005696;
    box-shadow: 0 4px 12px rgba(0, 86, 150, 0.1);
}

.routing-rule-card {
    background: #f8fafc;
    border: 1.5px solid #e2e8f0;
    border-radius: 0.75rem;
    padding: 1rem 1.25rem;
    margin-bottom: 0.75rem;
    transition: all 0.2s ease;
}
.routing-rule-card:hover {
    border-color: #8b5cf6;
    background: #faf5ff;
}

.routing-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.2rem 0.6rem;
    border-radius: 9999px;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
}

.question-row {
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 0.5rem;
    margin-bottom: 0.5rem;
    transition: all 0.2s ease;
}
.question-row:hover {
    border-color: #005696;
    box-shadow: 0 2px 8px rgba(0, 86, 150, 0.08);
}
.question-row.expanded {
    border-color: #005696;
    box-shadow: 0 2px 8px rgba(0, 86, 150, 0.1);
}
.question-row-header {
    display: flex;
    align-items: center;
    padding: 0.75rem 1rem;
    cursor: pointer;
    gap: 0.75rem;
}
.question-row-header:hover {
    background: #f8fafc;
}
.drag-handle {
    cursor: grab;
    color: #94a3b8;
    padding: 0.25rem;
}
.drag-handle:hover {
    color: #005696;
}
.question-row-number {
    min-width: 1.5rem;
    height: 1.5rem;
    background: #f1f5f9;
    border-radius: 0.375rem;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.75rem;
    font-weight: 600;
    color: #64748b;
}
.question-row-preview {
    flex: 1;
    min-width: 0;
}
.question-row-preview-text {
    font-weight: 500;
    color: #1e293b;
    font-size: 0.875rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.question-row-preview-text-ar {
    font-size: 0.75rem;
    color: #64748b;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.question-type-badge {
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    background: #e0e7ff;
    color: #4338ca;
}
.question-type-badge.rating { background: #dbeafe; color: #1d4ed8; }
.question-type-badge.nps { background: #dcfce7; color: #15803d; }
.question-type-badge.yes-no { background: #f3e8ff; color: #7c3aed; }
.question-type-badge.multiple-choice { background: #fef3c7; color: #b45309; }
.question-type-badge.single-choice { background: #fed7aa; color: #c2410c; }
.question-type-badge.text { background: #f1f5f9; color: #475569; }
.question-type-badge.textarea { background: #e2e8f0; color: #334155; }
.question-type-badge.likert { background: #fce7f3; color: #be185c; }
.question-row-actions {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}
.question-row-body {
    display: none;
    padding: 0 1rem 1rem 1rem;
    border-top: 1px solid #e2e8f0;
    background: #fafafa;
    border-radius: 0 0 0.5rem 0.5rem;
}
.question-row.expanded .question-row-body {
    display: block;
}
.expand-icon {
    transition: transform 0.2s ease;
}
.question-row.expanded .expand-icon {
    transform: rotate(180deg);
}
{% endblock %}

{% block title %}{% if template %}{% trans "Edit Survey Template" %}{% else %}{% trans "Create Survey Template" %}{% endif %} - PX360{% endblock %}

{% block content %}
<div class="p-6">
    <!-- Page Header -->
    <div class="page-header-gradient">
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold flex items-center gap-3">
                    <i data-lucide="file-text" class="w-6 h-6"></i>
                    {% if template %}{% trans "Edit Survey Template" %}{% else %}{% trans "Create Survey Template" %}{% endif %}
                </h1>
                <p class="text-blue-100 text-sm mt-1">
                    {% if template %}{% trans "Modify this survey template and its questions" %}{% else %}{% trans "Create a new survey template with questions" %}{% endif %}
                </p>
            </div>
            <a href="{% url 'surveys:template_list' %}" class="hh-btn hh-btn-secondary bg-white/10 border-white/30 text-white hover:bg-white hover:text-navy">
                <i data-lucide="arrow-left" class="w-4 h-4"></i>
                {% trans "Back to Templates" %}
            </a>
        </div>
    </div>

    <!-- Form -->
    <div class="form-section p-0 overflow-hidden">
        <div class="p-6">
            <form method="post" id="template-form">
                {% csrf_token %}
                {{ formset.management_form }}
                {{ routing_formset.management_form }}

                <!-- General Settings -->
                <div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-200">
                    <div class="w-10 h-10 bg-blue/10 rounded-xl flex items-center justify-center">
                        <i data-lucide="settings" class="w-5 h-5 text-blue"></i>
                    </div>
                    <h2 class="text-lg font-bold text-navy">{% trans "General Settings" %}</h2>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div>
                        <label for="{{ form.name.id_for_label }}" class="form-label">
                            {% trans "Template Name (English)" %} <span class="text-red-600">*</span>
                        </label>
                        {{ form.name }}
                        {% if form.name.errors %}
                            <div class="mt-1 text-sm text-red-600">{{ form.name.errors }}</div>
                        {% endif %}
                    </div>
                    <div>
                        <label for="{{ form.name_ar.id_for_label }}" class="form-label">
                            {% trans "Template Name (Arabic)" %}
                        </label>
                        {{ form.name_ar }}
                        {% if form.name_ar.errors %}
                            <div class="mt-1 text-sm text-red-600">{{ form.name_ar.errors }}</div>
                        {% endif %}
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                    {{ form.hospital }}
                    <div>
                        <label for="{{ form.survey_type.id_for_label }}" class="form-label">
                            {% trans "Survey Type" %} <span class="text-red-600">*</span>
                        </label>
                        {{ form.survey_type }}
                        {% if form.survey_type.errors %}
                            <div class="mt-1 text-sm text-red-600">{{ form.survey_type.errors }}</div>
                        {% endif %}
                    </div>
                    <div>
                        <label for="{{ form.scoring_method.id_for_label }}" class="form-label">
                            {% trans "Scoring Method" %} <span class="text-red-600">*</span>
                        </label>
                        {{ form.scoring_method }}
                        {% if form.scoring_method.errors %}
                            <div class="mt-1 text-sm text-red-600">{{ form.scoring_method.errors }}</div>
                        {% endif %}
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                    <div>
                        <label for="{{ form.negative_threshold.id_for_label }}" class="form-label">
                            {% trans "Negative Threshold" %}
                        </label>
                        {{ form.negative_threshold }}
                        {% if form.negative_threshold.errors %}
                            <div class="mt-1 text-sm text-red-600">{{ form.negative_threshold.errors }}</div>
                        {% endif %}
                        <p class="mt-1 text-xs text-slate">{% trans "Score below this is flagged as negative" %}</p>
                    </div>
                    <div class="mt-6">
                        <label class="flex items-center gap-2 cursor-pointer">
                            {{ form.is_active }}
                            <span class="text-sm text-slate">{% trans "Active template" %}</span>
                        </label>
                        {% if form.is_active.errors %}
                            <div class="mt-1 text-sm text-red-600">{{ form.is_active.errors }}</div>
                        {% endif %}
                    </div>
                </div>

                <hr class="my-6 border-slate-200">

                <!-- Questions Section -->
                <div class="flex items-center justify-between mb-4 pb-3 border-b border-slate-200">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center">
                            <i data-lucide="list-ordered" class="w-5 h-5 text-purple-600"></i>
                        </div>
                        <h2 class="text-lg font-bold text-navy">{% trans "Questions" %}</h2>
                    </div>
                    <span class="text-sm text-slate">{% trans "Drag to reorder" %}</span>
                </div>

                <div id="questions-container" class="sortable-list">
                    {% for form in formset %}
                    <div class="question-row" data-question-form data-question-id="{{ form.id.value }}">
                        <div class="question-row-header">
                            <span class="drag-handle cursor-grab" title="{% trans "Drag to reorder" %}">
                                <i data-lucide="grip-vertical" class="w-4 h-4"></i>
                            </span>
                            <span class="question-row-number">{{ forloop.counter }}</span>
                            <span class="question-row-preview">
                                <div class="question-row-preview-text">{{ form.text.value|default:"—"|truncatechars:60 }}</div>
                                <div class="question-row-preview-text-ar">{{ form.text_ar.value|default:"" }}</div>
                            </span>
                            <span class="question-type-badge {{ form.question_type.value|default:"text" }}">{{ form.question_type.value|upper|default:"TEXT" }}</span>
                            {% if form.is_required.value %}<span class="text-xs text-red-600 font-semibold">*</span>{% endif %}
                            <span class="question-row-actions ml-auto flex items-center gap-2">
                                <button type="button" class="expand-btn p-1.5 text-slate-400 hover:text-navy hover:bg-slate-100 rounded-lg transition" title="{% trans "Edit question" %}">
                                    <i data-lucide="chevron-down" class="w-4 h-4 expand-icon"></i>
                                </button>
                                <button type="button" class="remove-question-btn p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition" title="{% trans "Remove question" %}">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </span>
                        </div>
                        <div class="question-row-body">
                            {{ form.id }}
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 pt-3">
                                <div>
                                    <label for="{{ form.text.id_for_label }}_{{ forloop.counter0 }}" class="form-label">
                                        {% trans "Question (English)" %} <span class="text-red-600">*</span>
                                    </label>
                                    {{ form.text }}
                                </div>
                                <div>
                                    <label for="{{ form.text_ar.id_for_label }}_{{ forloop.counter0 }}" class="form-label">
                                        {% trans "Question (Arabic)" %}
                                    </label>
                                    {{ form.text_ar }}
                                </div>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                                <div>
                                    <label class="form-label">
                                        {% trans "Question Type" %} <span class="text-red-600">*</span>
                                    </label>
                                    {{ form.question_type }}
                                </div>
                                <div>
                                    <label class="form-label">
                                        {% trans "Order" %}
                                    </label>
                                    {{ form.order }}
                                </div>
                                <div class="mt-6">
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        {{ form.is_required }}
                                        <span class="text-sm text-slate">{% trans "Required" %}</span>
                                    </label>
                                </div>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                <div class="mt-2">
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        {{ form.is_base }}
                                        <span class="text-sm text-slate">{% trans "Base Question" %}</span>
                                    </label>
                                    <p class="mt-1 text-xs text-slate">{% trans "Always shown regardless of events" %}</p>
                                </div>
                                <div>
                                    <label class="form-label">
                                        {% trans "Event Type" %}
                                    </label>
                                    {{ form.event_type }}
                                    <button type="button" class="timeline-toggle mt-2 text-xs font-medium text-purple-600 hover:text-purple-700 flex items-center gap-1">
                                        <i data-lucide="list" class="w-3 h-3"></i>
                                        {% trans "Show Events" %}
                                    </button>
                                    <div class="timeline-helper hidden mt-3 p-3 bg-slate-50 rounded-lg border border-slate-200">
                                        {% if visit_timeline_events.IP %}
                                        <div class="mb-3">
                                            <span class="text-[10px] font-bold uppercase tracking-wide text-slate-500">{% trans "IP" %}</span>
                                            <div class="flex flex-wrap gap-1.5 mt-1">
                                                {% for ev in visit_timeline_events.IP %}
                                                <button type="button" class="timeline-chip px-2 py-1 text-xs bg-white border border-slate-200 rounded-md text-slate-700 hover:border-purple-400 transition" data-value="{{ ev.event_type }}">
                                                    {{ ev.event_type }}
                                                </button>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        {% endif %}
                                        {% if visit_timeline_events.OP %}
                                        <div class="mb-3">
                                            <span class="text-[10px] font-bold uppercase tracking-wide text-slate-500">{% trans "OP" %}</span>
                                            <div class="flex flex-wrap gap-1.5 mt-1">
                                                {% for ev in visit_timeline_events.OP %}
                                                <button type="button" class="timeline-chip px-2 py-1 text-xs bg-white border border-slate-200 rounded-md text-slate-700 hover:border-purple-400 transition" data-value="{{ ev.event_type }}">
                                                    {{ ev.event_type }}
                                                </button>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        {% endif %}
                                        {% if visit_timeline_events.ED %}
                                        <div>
                                            <span class="text-[10px] font-bold uppercase tracking-wide text-slate-500">{% trans "ED" %}</span>
                                            <div class="flex flex-wrap gap-1.5 mt-1">
                                                {% for ev in visit_timeline_events.ED %}
                                                <button type="button" class="timeline-chip px-2 py-1 text-xs bg-white border border-slate-200 rounded-md text-slate-700 hover:border-purple-400 transition" data-value="{{ ev.event_type }}">
                                                    {{ ev.event_type }}
                                                </button>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            <div class="choices-field {% if form.question_type.value not in 'multiple_choice,single_choice' %}hidden{% endif %}">
                                <label class="form-label">
                                    {% trans "Choices" %}
                                </label>
                                <div class="choices-tag-input border-2 border-slate-200 rounded-lg p-3 bg-white" data-choices-input>
                                    <div class="choices-tags flex flex-wrap gap-2 mb-3"></div>
                                    <div class="choices-add-row flex gap-2">
                                        <input type="text" class="choice-label-en form-control flex-1 text-sm" placeholder="{% trans 'English label' %}">
                                        <input type="text" class="choice-label-ar form-control flex-1 text-sm" placeholder="{% trans 'Arabic label' %}">
                                        <button type="button" class="add-choice-btn px-3 py-2 bg-navy text-white rounded-lg text-sm font-semibold hover:bg-blue transition">
                                            {% trans "Add" %}
                                        </button>
                                    </div>
                                </div>
                                {{ form.choices_json }}
                            </div>
                            <div class="mt-4 pt-3 border-t border-gray-100">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    {{ form.is_conditional }}
                                    <span class="text-sm text-slate">{% trans "Conditional" %}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>

                <div class="mb-6">
                    <button type="button" id="add-question-btn" class="hh-btn hh-btn-primary bg-purple-600 hover:bg-purple-700 w-full justify-center">
                        <i data-lucide="plus" class="w-4 h-4"></i>
                        {% trans "Add Question" %}
                    </button>
                </div>

                <!-- Empty form template (hidden) -->
                <div id="empty-form" class="hidden">
                    <div class="question-row" data-question-form>
                        <div class="question-row-header">
                            <span class="drag-handle cursor-grab" title="{% trans "Drag to reorder" %}">
                                <i data-lucide="grip-vertical" class="w-4 h-4"></i>
                            </span>
                            <span class="question-row-number"></span>
                            <span class="question-row-preview">
                                <div class="question-row-preview-text">{% trans "New question" %}</div>
                                <div class="question-row-preview-text-ar"></div>
                            </span>
                            <span class="question-type-badge text">TEXT</span>
                            <span class="question-row-actions ml-auto flex items-center gap-2">
                                <button type="button" class="expand-btn p-1.5 text-slate-400 hover:text-navy hover:bg-slate-100 rounded-lg transition" title="{% trans "Edit question" %}">
                                    <i data-lucide="chevron-down" class="w-4 h-4 expand-icon"></i>
                                </button>
                                <button type="button" class="remove-question-btn p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition" title="{% trans "Remove question" %}">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </span>
                        </div>
                        <div class="question-row-body">
                            {{ formset.empty_form.id }}
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 pt-3">
                                <div>
                                    <label class="form-label">
                                        {% trans "Question (English)" %} <span class="text-red-600">*</span>
                                    </label>
                                    {{ formset.empty_form.text }}
                                </div>
                                <div>
                                    <label class="form-label">
                                        {% trans "Question (Arabic)" %}
                                    </label>
                                    {{ formset.empty_form.text_ar }}
                                </div>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                                <div>
                                    <label class="form-label">
                                        {% trans "Question Type" %} <span class="text-red-600">*</span>
                                    </label>
                                    {{ formset.empty_form.question_type }}
                                </div>
                                <div>
                                    <label class="form-label">
                                        {% trans "Order" %}
                                    </label>
                                    {{ formset.empty_form.order }}
                                </div>
                                <div class="mt-6">
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        {{ formset.empty_form.is_required }}
                                        <span class="text-sm text-slate">{% trans "Required" %}</span>
                                    </label>
                                </div>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                <div class="mt-2">
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        {{ formset.empty_form.is_base }}
                                        <span class="text-sm text-slate">{% trans "Base Question" %}</span>
                                    </label>
                                </div>
                                <div>
                                    <label class="form-label">
                                        {% trans "Event Type" %}
                                    </label>
                                    {{ formset.empty_form.event_type }}
                                    <button type="button" class="timeline-toggle mt-2 text-xs font-medium text-purple-600 hover:text-purple-700 flex items-center gap-1">
                                        <i data-lucide="list" class="w-3 h-3"></i>
                                        {% trans "Show Events" %}
                                    </button>
                                    <div class="timeline-helper hidden mt-3 p-3 bg-slate-50 rounded-lg border border-slate-200">
                                        {% if visit_timeline_events.IP %}
                                        <div class="mb-3">
                                            <span class="text-[10px] font-bold uppercase tracking-wide text-slate-500">{% trans "IP" %}</span>
                                            <div class="flex flex-wrap gap-1.5 mt-1">
                                                {% for ev in visit_timeline_events.IP %}
                                                <button type="button" class="timeline-chip px-2 py-1 text-xs bg-white border border-slate-200 rounded-md text-slate-700 hover:border-purple-400 transition" data-value="{{ ev.event_type }}">
                                                    {{ ev.event_type }}
                                                </button>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        {% endif %}
                                        {% if visit_timeline_events.OP %}
                                        <div class="mb-3">
                                            <span class="text-[10px] font-bold uppercase tracking-wide text-slate-500">{% trans "OP" %}</span>
                                            <div class="flex flex-wrap gap-1.5 mt-1">
                                                {% for ev in visit_timeline_events.OP %}
                                                <button type="button" class="timeline-chip px-2 py-1 text-xs bg-white border border-slate-200 rounded-md text-slate-700 hover:border-purple-400 transition" data-value="{{ ev.event_type }}">
                                                    {{ ev.event_type }}
                                                </button>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        {% endif %}
                                        {% if visit_timeline_events.ED %}
                                        <div>
                                            <span class="text-[10px] font-bold uppercase tracking-wide text-slate-500">{% trans "ED" %}</span>
                                            <div class="flex flex-wrap gap-1.5 mt-1">
                                                {% for ev in visit_timeline_events.ED %}
                                                <button type="button" class="timeline-chip px-2 py-1 text-xs bg-white border border-slate-200 rounded-md text-slate-700 hover:border-purple-400 transition" data-value="{{ ev.event_type }}">
                                                    {{ ev.event_type }}
                                                </button>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            <div class="choices-field hidden">
                                <label class="form-label">
                                    {% trans "Choices" %}
                                </label>
                                <div class="choices-tag-input border-2 border-slate-200 rounded-lg p-3 bg-white" data-choices-input>
                                    <div class="choices-tags flex flex-wrap gap-2 mb-3"></div>
                                    <div class="choices-add-row flex gap-2">
                                        <input type="text" class="choice-label-en form-control flex-1 text-sm" placeholder="{% trans 'English label' %}">
                                        <input type="text" class="choice-label-ar form-control flex-1 text-sm" placeholder="{% trans 'Arabic label' %}">
                                        <button type="button" class="add-choice-btn px-3 py-2 bg-navy text-white rounded-lg text-sm font-semibold hover:bg-blue transition">
                                            {% trans "Add" %}
                                        </button>
                                    </div>
                                </div>
                                {{ formset.empty_form.choices_json }}
                            </div>
                            <div class="mt-4 pt-3 border-t border-gray-100">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    {{ formset.empty_form.is_conditional }}
                                    <span class="text-sm text-slate">{% trans "Conditional" %}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <hr class="my-6 border-slate-200">

                <!-- Routing Rules Section -->
                <div class="flex items-center justify-between mb-6 pb-4 border-b border-slate-200">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center">
                            <i data-lucide="git-branch" class="w-5 h-5 text-amber-600"></i>
                        </div>
                        <div>
                            <h2 class="text-lg font-bold text-navy">{% trans "Routing Rules" %}</h2>
                            <p class="text-xs text-slate mt-0.5">{% trans "Define conditional logic to skip questions or end the survey based on answers" %}</p>
                        </div>
                    </div>
                    <button type="button" id="add-routing-rule-btn" class="hh-btn hh-btn-primary bg-amber-600 hover:bg-amber-700">
                        <i data-lucide="plus" class="w-4 h-4"></i>
                        {% trans "Add Rule" %}
                    </button>
                </div>

                <div id="routing-rules-container">
                    {% for rform in routing_formset %}
                    <div class="routing-rule-card" data-routing-rule>
                        <div class="flex justify-between items-center mb-3">
                            <span class="routing-badge bg-amber-100 text-amber-700">
                                <i data-lucide="git-branch" class="w-3 h-3"></i>
                                {% trans "Rule" %} {{ forloop.counter }}
                            </span>
                            <button type="button" class="remove-rule-btn p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded transition" title="{% trans "Remove rule" %}">
                                <i data-lucide="x" class="w-4 h-4"></i>
                            </button>
                        </div>
                        {{ rform.id }}
                        <div class="flex flex-wrap items-end gap-3">
                            <div class="flex-1 min-w-[140px]">
                                <label class="form-label text-xs">{% trans "When question" %}</label>
                                {{ rform.source_question }}
                            </div>
                            <div class="w-[120px]">
                                <label class="form-label text-xs">{% trans "Condition" %}</label>
                                {{ rform.operator }}
                            </div>
                            <div class="w-[120px]">
                                <label class="form-label text-xs">{% trans "Value" %}</label>
                                {{ rform.value }}
                            </div>
                            <div class="w-[120px]">
                                <label class="form-label text-xs">{% trans "Action" %}</label>
                                {{ rform.action }}
                            </div>
                            <div class="flex-1 min-w-[140px] routing-target-field">
                                <label class="form-label text-xs">{% trans "Go to question" %}</label>
                                {{ rform.target_question }}
                            </div>
                            <div class="w-[60px]">
                                <label class="form-label text-xs">{% trans "Order" %}</label>
                                {{ rform.order }}
                            </div>
                        </div>
                        {% if rform.non_field_errors %}
                            <div class="mt-2 text-sm text-red-600">{{ rform.non_field_errors }}</div>
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>

                <!-- Empty routing rule template -->
                <div id="empty-routing-rule" class="hidden">
                    <div class="routing-rule-card" data-routing-rule>
                        <div class="flex justify-between items-center mb-3">
                            <span class="routing-badge bg-amber-100 text-amber-700">
                                <i data-lucide="git-branch" class="w-3 h-3"></i>
                                {% trans "Rule" %} <span class="rule-number"></span>
                            </span>
                            <button type="button" class="remove-rule-btn p-1 text-red-400 hover:text-red-600 hover:bg-red-50 rounded transition" title="{% trans "Remove rule" %}">
                                <i data-lucide="x" class="w-4 h-4"></i>
                            </button>
                        </div>
                        {{ routing_formset.empty_form.id }}
                        <div class="flex flex-wrap items-end gap-3">
                            <div class="flex-1 min-w-[140px]">
                                <label class="form-label text-xs">{% trans "When question" %}</label>
                                {{ routing_formset.empty_form.source_question }}
                            </div>
                            <div class="w-[120px]">
                                <label class="form-label text-xs">{% trans "Condition" %}</label>
                                {{ routing_formset.empty_form.operator }}
                            </div>
                            <div class="w-[120px]">
                                <label class="form-label text-xs">{% trans "Value" %}</label>
                                {{ routing_formset.empty_form.value }}
                            </div>
                            <div class="w-[120px]">
                                <label class="form-label text-xs">{% trans "Action" %}</label>
                                {{ routing_formset.empty_form.action }}
                            </div>
                            <div class="flex-1 min-w-[140px] routing-target-field">
                                <label class="form-label text-xs">{% trans "Go to question" %}</label>
                                {{ routing_formset.empty_form.target_question }}
                            </div>
                            <div class="w-[60px]">
                                <label class="form-label text-xs">{% trans "Order" %}</label>
                                {{ routing_formset.empty_form.order }}
                            </div>
                        </div>
                    </div>
                </div>

                {% if routing_formset.errors %}
                <div class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
                    {% for error in routing_formset.non_form_errors %}
                    <p>{{ error }}</p>
                    {% endfor %}
                </div>
                {% endif %}

                <div class="flex justify-between items-center mt-6 pt-6 border-t border-slate-200">
                    <a href="{% url 'surveys:template_list' %}" class="hh-btn hh-btn-secondary">
                        <i data-lucide="x" class="w-4 h-4"></i>
                        {% trans "Cancel" %}
                    </a>
                    <div class="flex items-center gap-3">
                        <button type="submit" name="_save_continue" value="1" class="hh-btn hh-btn-secondary border-navy text-navy hover:bg-navy hover:text-white">
                            <i data-lucide="save" class="w-4 h-4"></i>
                            {% trans "Save & Continue Editing" %}
                        </button>
                        <button type="submit" class="hh-btn hh-btn-primary">
                            <i data-lucide="check" class="w-4 h-4"></i>
                            {% if template %}{% trans "Update Template" %}{% else %}{% trans "Create Template" %}{% endif %}
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();

    var totalForms = document.getElementById('id_{{ formset.prefix }}-TOTAL_FORMS');
    var container = document.getElementById('questions-container');
    var emptyFormDiv = document.getElementById('empty-form');
    var addBtn = document.getElementById('add-question-btn');

    var routingTotalForms = document.getElementById('id_{{ routing_formset.prefix }}-TOTAL_FORMS');
    var routingContainer = document.getElementById('routing-rules-container');
    var emptyRoutingDiv = document.getElementById('empty-routing-rule');
    var addRoutingBtn = document.getElementById('add-routing-rule-btn');

    function updateQuestionNumbers() {
        var cards = container.querySelectorAll('[data-question-form]');
        cards.forEach(function(card, index) {
            var numSpan = card.querySelector('.question-row-number');
            if (numSpan) numSpan.textContent = index + 1;
        });
    }

    function updateRuleNumbers() {
        var rules = routingContainer.querySelectorAll('[data-routing-rule]');
        rules.forEach(function(rule, index) {
            var numSpan = rule.querySelector('.rule-number');
            if (numSpan) numSpan.textContent = index + 1;
        });
    }

    function toggleChoicesField(card) {
        var select = card.querySelector('select[name*="-question_type"]');
        var choicesDiv = card.querySelector('.choices-field');
        if (select && choicesDiv) {
            select.addEventListener('change', function() {
                if (this.value === 'multiple_choice' || this.value === 'single_choice') {
                    choicesDiv.classList.remove('hidden');
                } else {
                    choicesDiv.classList.add('hidden');
                }
            });
        }
    }

    function toggleTargetField(ruleCard) {
        var actionSelect = ruleCard.querySelector('select[name*="-action"]');
        var targetField = ruleCard.querySelector('.routing-target-field');
        if (actionSelect && targetField) {
            var update = function() {
                if (actionSelect.value === 'end_survey') {
                    targetField.style.display = 'none';
                } else {
                    targetField.style.display = '';
                }
            };
            actionSelect.addEventListener('change', update);
            update();
        }
    }

    function toggleValueField(ruleCard) {
        var operatorSelect = ruleCard.querySelector('select[name*="-operator"]');
        var valueInput = ruleCard.querySelector('input[name*="-value"]');
        if (operatorSelect && valueInput) {
            var update = function() {
                if (operatorSelect.value === 'answered' || operatorSelect.value === 'not_answered') {
                    valueInput.style.display = 'none';
                } else {
                    valueInput.style.display = '';
                }
            };
            operatorSelect.addEventListener('change', update);
            update();
        }
    }

    function attachStyling(card) {
        var inputs = card.querySelectorAll('input[type="text"], input[type="number"], textarea, select');
        inputs.forEach(function(input) {
            if (!input.classList.contains('form-control') && !input.classList.contains('form-select')) {
                if (input.tagName === 'SELECT') {
                    input.classList.add('form-select');
                } else {
                    input.classList.add('form-control');
                }
            }
        });
    }

    function initTimelineHelper(card) {
        var toggleBtn = card.querySelector('.timeline-toggle');
        var helper = card.querySelector('.timeline-helper');
        if (!toggleBtn || !helper) return;

        toggleBtn.addEventListener('click', function() {
            var isHidden = helper.classList.contains('hidden');
            if (isHidden) {
                helper.classList.remove('hidden');
                toggleBtn.innerHTML = '<i data-lucide="list" class="w-3 h-3"></i>{% trans "Hide Visit Timeline Events" %}';
            } else {
                helper.classList.add('hidden');
                toggleBtn.innerHTML = '<i data-lucide="list" class="w-3 h-3"></i>{% trans "Show Visit Timeline Events" %}';
            }
            lucide.createIcons();
        });

        helper.querySelectorAll('.timeline-chip').forEach(function(chip) {
            chip.addEventListener('click', function() {
                var eventType = this.getAttribute('data-value');
                var eventInput = card.querySelector('input[name*="-event_type"]');
                if (eventInput) {
                    eventInput.value = eventType;
                }
            });
        });
    }

    // Question form management
    if (container) {
        container.querySelectorAll('[data-question-form]').forEach(function(card) {
            toggleChoicesField(card);
            attachStyling(card);
            initTimelineHelper(card);
        });
    }

    if (addBtn && emptyFormDiv) {
        addBtn.addEventListener('click', function() {
            var count = parseInt(totalForms.value);
            var formHtml = emptyFormDiv.innerHTML;
            formHtml = formHtml.replace(/__prefix__/g, count);
            var tempDiv = document.createElement('div');
            tempDiv.innerHTML = formHtml;
            var newCard = tempDiv.firstElementChild;
            newCard.querySelectorAll('.question-row-number').forEach(function(span) {
                span.textContent = count + 1;
            });
            container.appendChild(newCard);
            totalForms.value = count + 1;
            toggleChoicesField(newCard);
            attachStyling(newCard);
            initTimelineHelper(newCard);
            initExpandRow(newCard);
            lucide.createIcons();
            refreshRoutingDropdowns();
        });
    }

    // Expand/collapse question rows
    function initExpandRow(row) {
        row.querySelectorAll('.expand-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                row.classList.toggle('expanded');
            });
        });
        var header = row.querySelector('.question-row-header');
        if (header) {
            header.addEventListener('click', function(e) {
                if (!e.target.closest('.remove-question-btn') && !e.target.closest('.drag-handle')) {
                    row.classList.toggle('expanded');
                }
            });
        }
    }

    // Initialize expand for existing rows
    if (container) {
        container.querySelectorAll('[data-question-form]').forEach(function(row) {
            initExpandRow(row);
        });
    }

    // Drag and drop reordering
    var CSRF = "{{ csrf_token }}";
    var templateId = "{{ template.pk|default:'' }}";
    var reorderUrlFull = "{% url 'surveys:template_question_reorder' '00000000-0000-0000-0000-000000000000' %}".replace('00000000-0000-0000-0000-000000000000', templateId);

    if (container && templateId) {
        new Sortable(container, {
            animation: 200,
            handle: '.drag-handle',
            ghostClass: 'opacity-50',
            onEnd: function(evt) {
                var items = container.querySelectorAll('[data-question-form]');
                var order = [];
                items.forEach(function(el, i) {
                    el.querySelector('.question-row-number').textContent = i + 1;
                    order.push({ id: el.dataset.questionId, order: i + 1 });
                });
                if (templateId && order.length > 0) {
                    fetch(reorderUrlFull, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRFToken': CSRF },
                        body: JSON.stringify(order),
                    });
                }
            },
        });
    }

    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-question-btn')) {
            var card = e.target.closest('[data-question-form]');
            if (card) {
                var cards = container.querySelectorAll('[data-question-form]');
                if (cards.length > 1) {
                    card.remove();
                    totalForms.value = container.querySelectorAll('[data-question-form]').length;
                    updateQuestionNumbers();
                    refreshRoutingDropdowns();
                }
            }
        }
    });

    // Routing rule management
    if (routingContainer) {
        routingContainer.querySelectorAll('[data-routing-rule]').forEach(function(rule) {
            toggleTargetField(rule);
            toggleValueField(rule);
            attachStyling(rule);
        });
    }

    function refreshRoutingDropdowns() {
        var questions = [];
        container.querySelectorAll('[data-question-form]').forEach(function(card, idx) {
            var idInput = card.querySelector('input[name*="-id"]');
            var textInput = card.querySelector('textarea[name*="-text"]');
            var qid = idInput ? idInput.value : '';
            var qtext = textInput ? textInput.value : ('Question ' + (idx + 1));
            questions.push({id: qid, text: qtext, index: idx + 1});
        });

        routingContainer.querySelectorAll('select[name*="-source_question"], select[name*="-target_question"]').forEach(function(sel) {
            var currentVal = sel.value;
            sel.innerHTML = '';

            questions.forEach(function(q) {
                var opt = document.createElement('option');
                opt.value = q.id;
                opt.textContent = q.id ? (q.index + '. ' + (q.text || 'Question ' + q.index).substring(0, 50)) : ('Q' + q.index + ' (unsaved)');
                sel.appendChild(opt);
            });
            sel.value = currentVal;
        });
    }

    if (addRoutingBtn && emptyRoutingDiv) {
        addRoutingBtn.addEventListener('click', function() {
            var count = parseInt(routingTotalForms.value);
            var formHtml = emptyRoutingDiv.innerHTML;
            formHtml = formHtml.replace(/__prefix__/g, count);
            var tempDiv = document.createElement('div');
            tempDiv.innerHTML = formHtml;
            var newRule = tempDiv.firstElementChild;
            newRule.querySelectorAll('.rule-number').forEach(function(span) {
                span.textContent = count + 1;
            });
            routingContainer.appendChild(newRule);
            routingTotalForms.value = count + 1;
            toggleTargetField(newRule);
            toggleValueField(newRule);
            attachStyling(newRule);
            lucide.createIcons();
            refreshRoutingDropdowns();
        });
    }

    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-rule-btn')) {
            var rule = e.target.closest('[data-routing-rule]');
            if (rule) {
                rule.remove();
                routingTotalForms.value = routingContainer.querySelectorAll('[data-routing-rule]').length;
                updateRuleNumbers();
            }
        }
    });

    // Apply styling to all existing inputs
    var allInputs = document.querySelectorAll('#template-form input[type="text"], #template-form input[type="number"], #template-form textarea, #template-form select');
    allInputs.forEach(function(input) {
        if (!input.classList.contains('form-control') && !input.classList.contains('form-select')) {
            if (input.tagName === 'SELECT') {
                input.classList.add('form-select');
            } else {
                input.classList.add('form-control');
            }
        }
    });

    // ===== Choices Tag Input =====
    function initChoicesInput(wrapper) {
        var tagsContainer = wrapper.querySelector('.choices-tags');
        var enInput = wrapper.querySelector('.choice-label-en');
        var arInput = wrapper.querySelector('.choice-label-ar');
        var addBtn = wrapper.querySelector('.add-choice-btn');
        var jsonTextarea = wrapper.parentElement.querySelector('textarea[name*="choices_json"]');

        function getChoices() {
            try {
                return JSON.parse(jsonTextarea.value || '[]');
            } catch (e) {
                return [];
            }
        }

        function setChoices(choices) {
            jsonTextarea.value = JSON.stringify(choices);
            renderTags();
        }

        function renderTags() {
            var choices = getChoices();
            tagsContainer.innerHTML = '';
            choices.forEach(function(choice, idx) {
                var tag = document.createElement('div');
                tag.className = 'inline-flex items-center gap-2 px-3 py-1.5 bg-blue-50 border border-blue-200 rounded-lg text-sm';
                tag.innerHTML = '<span class="font-medium text-navy">' + escapeHtml(choice.label || '') + '</span>' +
                    '<span class="text-slate-400">|</span>' +
                    '<span class="font-medium text-navy" dir="rtl">' + escapeHtml(choice.label_ar || '') + '</span>' +
                    '<button type="button" class="remove-choice-btn ml-1 text-red-400 hover:text-red-600" data-index="' + idx + '">' +
                    '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>' +
                    '</button>';
                tagsContainer.appendChild(tag);
            });
        }

        function addChoice() {
            var en = enInput.value.trim();
            var ar = arInput.value.trim();
            if (!en && !ar) return;
            var choices = getChoices();
            var maxVal = choices.reduce(function(max, c) {
                var v = parseInt(c.value, 10);
                return isNaN(v) ? max : Math.max(max, v);
            }, 0);
            choices.push({
                value: String(maxVal + 1),
                label: en || ar,
                label_ar: ar || en
            });
            setChoices(choices);
            enInput.value = '';
            arInput.value = '';
            enInput.focus();
        }

        if (addBtn) {
            addBtn.addEventListener('click', addChoice);
        }
        if (enInput) {
            enInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') { e.preventDefault(); arInput.focus(); }
            });
        }
        if (arInput) {
            arInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') { e.preventDefault(); addChoice(); }
            });
        }

        tagsContainer.addEventListener('click', function(e) {
            var btn = e.target.closest('.remove-choice-btn');
            if (btn) {
                var idx = parseInt(btn.dataset.index, 10);
                var choices = getChoices();
                choices.splice(idx, 1);
                // Re-number values
                choices.forEach(function(c, i) { c.value = String(i + 1); });
                setChoices(choices);
            }
        });

        renderTags();
    }

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

    // Initialize all existing choices inputs
    document.querySelectorAll('[data-choices-input]').forEach(function(wrapper) {
        initChoicesInput(wrapper);
    });

    // Initialize choices input for dynamically added questions
    if (addBtn) {
        addBtn.addEventListener('click', function() {
            // Wait for DOM update
            setTimeout(function() {
                container.querySelectorAll('[data-choices-input]').forEach(function(wrapper) {
                    if (!wrapper.dataset.initialized) {
                        initChoicesInput(wrapper);
                        wrapper.dataset.initialized = 'true';
                    }
                });
            }, 0);
        });
    }

    // Initial refresh of routing dropdowns
    refreshRoutingDropdowns();
});
</script>
{% endblock %}
