{% extends 'admin/base.html' %}

{% block title %}{{ t('forms.new_form') }}{% endblock %}

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>📋 {{ t('forms.new_form') }}</h2>
        <p>{{ t('forms.create_subtitle') }}</p>
    </div>
    <div class="btn-group">
        <button type="submit" form="formEditor" class="btn btn-primary btn-sm">💾 {{ t('forms.new_form') }}</button>
        <a href="{{ admin_back_url('admin_forms_list') }}" class="btn btn-secondary btn-sm">{{ t('common.cancel') }}</a>
    </div>
</div>

<form method="POST" id="formEditor" class="container-xl">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="return_to" value="{{ admin_back_value() }}">
    <div class="editor-layout">
        <!-- ============================================================ -->
        <!-- MAIN CONTENT (left) -->
        <!-- ============================================================ -->
        <div class="editor-main">
            <div class="form-group">
                <label for="formTitle" class="required">{{ t('editor.title_label') }}</label>
                <input type="text" id="formTitle" name="title" placeholder="{{ t('forms.new_form_placeholder') }}" required autofocus>
            </div>

            <div class="form-group">
                <label for="formDescription">{{ t('forms.form_description') }}</label>
                <textarea id="formDescription" name="description" rows="2" placeholder="{{ t('forms.form_description_help') }}"></textarea>
            </div>

            <!-- Form type (template selector) -->
            <div class="form-section">
                <h3>{{ t('forms.form_type') }}</h3>
                <div class="template-grid">
                    <div class="template-card is-selected" data-type="contact" onclick="selectTemplate(this)">
                        <div class="template-card__icon">✉️</div>
                        <div class="template-card__title">{{ t('forms.type_contact') }}</div>
                        <div class="template-card__desc">{{ t('forms.type_contact_desc') }}</div>
                    </div>
                    <div class="template-card" data-type="survey" onclick="selectTemplate(this)">
                        <div class="template-card__icon">📊</div>
                        <div class="template-card__title">{{ t('forms.type_survey') }}</div>
                        <div class="template-card__desc">{{ t('forms.type_survey_desc') }}</div>
                    </div>
                    <div class="template-card" data-type="subscription" onclick="selectTemplate(this)">
                        <div class="template-card__icon">📬</div>
                        <div class="template-card__title">{{ t('forms.type_subscription') }}</div>
                        <div class="template-card__desc">{{ t('forms.type_subscription_desc') }}</div>
                    </div>
                    <div class="template-card" data-type="custom" onclick="selectTemplate(this)">
                        <div class="template-card__icon">🔧</div>
                        <div class="template-card__title">{{ t('forms.type_custom') }}</div>
                        <div class="template-card__desc">{{ t('forms.type_custom_desc') }}</div>
                    </div>
                </div>
                <input type="hidden" name="form_type" id="formType" value="contact">
            </div>

            <!-- Field types palette -->
            <div class="form-section">
                <h3>{{ t('forms.add_field') }}</h3>
                <div class="fe-palette" id="fieldPalette">
                    <button type="button" class="fe-palette-btn" data-type="text"><span>Aa</span>{{ t('forms.type_text') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="email"><span>@</span>{{ t('forms.type_email') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="phone"><span>📞</span>{{ t('forms.type_phone') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="number"><span>#</span>{{ t('forms.type_number') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="textarea"><span>¶</span>{{ t('forms.type_textarea') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="select"><span>▾</span>{{ t('forms.type_select') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="radio"><span>◉</span>{{ t('forms.type_radio') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="checkbox"><span>☑</span>{{ t('forms.type_checkbox') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="date"><span>📅</span>{{ t('forms.type_date') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="url"><span>🔗</span>{{ t('forms.type_url') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="rating"><span>⭐</span>{{ t('forms.type_rating') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="consent"><span>✅</span>{{ t('forms.type_consent') }}</button>
                    <button type="button" class="fe-palette-btn" data-type="hidden"><span>👁</span>{{ t('forms.type_hidden') }}</button>
                </div>
            </div>

            <!-- Fields list -->
            <div class="form-section">
                <h3>{{ t('forms.fields') }} (<span id="fieldCount">0</span>)</h3>
                <div class="fe-fields-list" id="fieldsList">
                    <div class="fe-empty" id="fieldsEmpty">{{ t('forms.add_field') }}</div>
                </div>
            </div>
        </div>

        <!-- ============================================================ -->
        <!-- SIDEBAR (right) -->
        <!-- ============================================================ -->
        <div class="editor-sidebar">
            <!-- 1. Status & Language -->
            <div class="form-section">
                <h3>📊 {{ t('editor.status_language') }}</h3>
                <div class="form-group">
                    <label for="language">{{ t('editor.language_label') }}</label>
                    <select id="language" name="language">
                        {% for lang in active_languages %}
                        {# Preselect the site's default language (was hardcoded 'en'). #}
                        <option value="{{ lang.code }}" {% if (target_lang or default_language) == lang.code %}selected{% endif %}>{{ lang.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <!-- 2. AI Tools -->
            <div class="form-section">
                <h3>🤖 {{ t('ai.tools_title') }}</h3>
                <button type="button" class="ai-assist-btn sidebar-btn" onclick="openFormAI()">
                    🤖 {{ t('ai.ai_generate_content') }}
                </button>
                <div class="help-text mt-2">{{ t('forms.ai_hint_create_first') }}</div>
            </div>

            <!-- 3. Form Settings -->
            <div class="form-section">
                <h3>⚙️ {{ t('forms.form_settings') }}</h3>
                <div class="form-group">
                    <label>{{ t('forms.settings_submit_label') }}</label>
                    <input type="text" name="submit_label" id="settingSubmitLabel" value="{{ t('forms.tpl_contact_submit') }}">
                </div>
                <div class="form-group">
                    <label>{{ t('forms.settings_success_message') }}</label>
                    <textarea name="success_message" id="settingSuccessMessage" rows="2">{{ t('forms.tpl_contact_success') }}</textarea>
                    <div class="help-text">{{ t('forms.settings_success_help') }}</div>
                </div>
                <div class="form-group">
                    <label>{{ t('forms.settings_redirect_url') }}</label>
                    <input type="text" name="redirect_url" value="" placeholder="https://...">
                    <div class="help-text">{{ t('forms.settings_redirect_help') }}</div>
                </div>
            </div>

            <!-- 4. Email Configuration -->
            <div class="form-section">
                <h3>📧 {{ t('forms.settings_notify_email') }}</h3>
                <div class="form-group">
                    <label>{{ t('forms.settings_notify_email') }}</label>
                    <input type="email" name="notify_email" value="" placeholder="admin@example.com">
                    <div class="help-text">{{ t('forms.settings_notify_help') }}</div>
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="notify_on_submit" checked>
                        {{ t('forms.settings_notify_on_submit') }}
                    </label>
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="store_submissions" checked>
                        {{ t('forms.settings_store_submissions') }}
                    </label>
                </div>
                <hr class="section-divider">
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="confirmation_email" id="confirmationEmail"
                               checked disabled
                               onchange="syncOptInCheckboxes()">
                        {{ t('forms.settings_confirmation_email') }}
                    </label>
                    <div class="help-text">{{ t('forms.settings_confirmation_email_help') }}</div>
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="double_opt_in" id="doubleOptIn"
                               checked
                               onchange="syncOptInCheckboxes()">
                        {{ t('forms.settings_double_opt_in') }}
                    </label>
                    <div class="help-text">{{ t('forms.settings_double_opt_in_help') }}</div>
                </div>
            </div>

            <!-- 5. Anti-Spam -->
            <div class="form-section">
                <h3>🛡️ {{ t('forms.settings_anti_spam') }}</h3>
                <div class="form-group">
                    <select name="anti_spam">
                        <option value="honeypot" selected>{{ t('forms.settings_anti_spam_honeypot') }}</option>
                        <option value="none">{{ t('forms.settings_anti_spam_none') }}</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Hidden field for JSON fields data -->
    <input type="hidden" name="fields_json" id="fieldsJson" value="[]">
</form>

<script>
// Double opt-in ↔ confirmation email checkbox logic
function syncOptInCheckboxes() {
    var doi = document.getElementById('doubleOptIn');
    var ce = document.getElementById('confirmationEmail');
    if (doi.checked) {
        ce.checked = true;
        ce.disabled = true;
    } else {
        ce.disabled = false;
    }
}

var TEMPLATES = {
    contact: {
        fields: [
            {id:'f1', type:'text', name:'name', label:'{{ t("forms.tpl_contact_name") }}', placeholder:'{{ t("forms.tpl_contact_name_placeholder") }}', required:true, width:'half'},
            {id:'f2', type:'email', name:'email', label:'{{ t("forms.tpl_contact_email") }}', placeholder:'{{ t("forms.tpl_contact_email_placeholder") }}', required:true, width:'half'},
            {id:'f3', type:'text', name:'subject', label:'{{ t("forms.tpl_contact_subject") }}', placeholder:'{{ t("forms.tpl_contact_subject_placeholder") }}', required:false, width:'full'},
            {id:'f4', type:'textarea', name:'message', label:'{{ t("forms.tpl_contact_message") }}', placeholder:'{{ t("forms.tpl_contact_message_placeholder") }}', required:true, width:'full'},
            {id:'f5', type:'consent', name:'privacy', label:'{{ t("forms.tpl_contact_privacy") }}', consent_text:'{{ t("forms.tpl_contact_consent") }}', required:true, width:'full'}
        ],
        settings: { submit_label: '{{ t("forms.tpl_contact_submit") }}', success_message: '{{ t("forms.tpl_contact_success") }}' }
    },
    survey: {
        fields: [
            {id:'f1', type:'text', name:'name', label:'{{ t("forms.tpl_survey_name") }}', placeholder:'', required:false, width:'full'},
            {id:'f2', type:'radio', name:'satisfaction', label:'{{ t("forms.tpl_survey_satisfaction") }}', options:['{{ t("forms.tpl_survey_opt_very_satisfied") }}','{{ t("forms.tpl_survey_opt_satisfied") }}','{{ t("forms.tpl_survey_opt_neutral") }}','{{ t("forms.tpl_survey_opt_dissatisfied") }}','{{ t("forms.tpl_survey_opt_very_dissatisfied") }}'], required:true, width:'full'},
            {id:'f3', type:'rating', name:'rating', label:'{{ t("forms.tpl_survey_rating") }}', max_rating:5, required:true, width:'full'},
            {id:'f4', type:'checkbox', name:'improvements', label:'{{ t("forms.tpl_survey_improvements") }}', options:['{{ t("forms.tpl_survey_opt_speed") }}','{{ t("forms.tpl_survey_opt_quality") }}','{{ t("forms.tpl_survey_opt_communication") }}','{{ t("forms.tpl_survey_opt_price") }}','{{ t("forms.tpl_survey_opt_support") }}'], required:false, width:'full'},
            {id:'f5', type:'textarea', name:'comments', label:'{{ t("forms.tpl_survey_comments") }}', placeholder:'{{ t("forms.tpl_survey_comments_placeholder") }}', required:false, width:'full'}
        ],
        settings: { submit_label: '{{ t("forms.tpl_survey_submit") }}', success_message: '{{ t("forms.tpl_survey_success") }}' }
    },
    subscription: {
        fields: [
            {id:'f1', type:'email', name:'email', label:'{{ t("forms.tpl_sub_email") }}', placeholder:'{{ t("forms.tpl_sub_email_placeholder") }}', required:true, width:'full'},
            {id:'f2', type:'text', name:'name', label:'{{ t("forms.tpl_sub_name") }}', placeholder:'{{ t("forms.tpl_sub_name_placeholder") }}', required:false, width:'full'},
            {id:'f3', type:'consent', name:'consent', label:'{{ t("forms.tpl_sub_consent_label") }}', consent_text:'{{ t("forms.tpl_sub_consent_text") }}', required:true, width:'full'}
        ],
        settings: { submit_label: '{{ t("forms.tpl_sub_submit") }}', success_message: '{{ t("forms.tpl_sub_success") }}', double_opt_in: true, confirmation_email: true }
    },
    custom: {
        fields: [
            {id:'f1', type:'text', name:'field_1', label:'{{ t("forms.tpl_custom_field") }}', placeholder:'', required:false, width:'full'}
        ],
        settings: { submit_label: '{{ t("forms.tpl_custom_submit") }}', success_message: '{{ t("forms.tpl_custom_success") }}' }
    }
};

function selectTemplate(el) {
    document.querySelectorAll('.template-card').forEach(function(c) { c.classList.remove('is-selected'); });
    el.classList.add('is-selected');
    var type = el.dataset.type;
    document.getElementById('formType').value = type;
    var tpl = TEMPLATES[type] || TEMPLATES.custom;
    window.fields = JSON.parse(JSON.stringify(tpl.fields));
    renderFields();
    if (tpl.settings.submit_label) document.getElementById('settingSubmitLabel').value = tpl.settings.submit_label;
    if (tpl.settings.success_message) document.getElementById('settingSuccessMessage').value = tpl.settings.success_message;
    // Sync confirmation checkboxes from template
    document.getElementById('doubleOptIn').checked = !!tpl.settings.double_opt_in;
    document.getElementById('confirmationEmail').checked = !!tpl.settings.confirmation_email || !!tpl.settings.double_opt_in;
    syncOptInCheckboxes();
}

(function() {
    'use strict';
    var initialTpl = TEMPLATES.contact;
    window.fields = JSON.parse(JSON.stringify(initialTpl.fields));
    var fieldCounter = window.fields.length;
    var $list = document.getElementById('fieldsList');
    var $empty = document.getElementById('fieldsEmpty');
    var $count = document.getElementById('fieldCount');
    var $json = document.getElementById('fieldsJson');

    var I = {
        label: '{{ t("forms.field_label") }}', name: '{{ t("forms.field_name") }}',
        placeholder: '{{ t("forms.field_placeholder") }}', required: '{{ t("forms.field_required") }}',
        width: '{{ t("forms.field_width") }}', full: '{{ t("forms.field_width_full") }}',
        half: '{{ t("forms.field_width_half") }}', help: '{{ t("forms.field_help_text") }}',
        options: '{{ t("forms.field_options") }}', max_rating: '{{ t("forms.field_max_rating") }}',
        consent_text: '{{ t("forms.field_consent_text") }}', drag: '{{ t("forms.drag") }}',
        copy: '{{ t("forms.copy") }}', remove: '{{ t("common.delete") }}',
        move_up: '{{ t("forms.move_up") }}', move_down: '{{ t("forms.move_down") }}',
        default_text_field: '{{ t("forms.default_text_field") }}', default_email: '{{ t("forms.default_email") }}',
        default_phone: '{{ t("forms.default_phone") }}', default_number: '{{ t("forms.default_number") }}',
        default_message: '{{ t("forms.default_message") }}', default_select: '{{ t("forms.default_select") }}',
        default_choice: '{{ t("forms.default_choice") }}', default_select_all: '{{ t("forms.default_select_all") }}',
        default_date: '{{ t("forms.default_date") }}', default_website: '{{ t("forms.default_website") }}',
        default_rating: '{{ t("forms.default_rating") }}', default_privacy: '{{ t("forms.default_privacy") }}',
        default_hidden: '{{ t("forms.default_hidden") }}', default_consent_text: '{{ t("forms.default_consent_text") }}',
        default_option: '{{ t("forms.default_option") }}', default_your_message: '{{ t("forms.default_your_message") }}'
    };

    function uid() { return 'f' + Math.random().toString(36).substr(2, 7); }
    function esc(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }

    var FIELD_DEFAULTS = {
        text:     { label: I.default_text_field, name: '', placeholder: '', required: false, width: 'full' },
        email:    { label: I.default_email, name: 'email', placeholder: 'your@email.com', required: true, width: 'half' },
        phone:    { label: I.default_phone, name: 'phone', placeholder: '+1...', required: false, width: 'half' },
        number:   { label: I.default_number, name: '', placeholder: '', required: false, width: 'half' },
        textarea: { label: I.default_message, name: 'message', placeholder: I.default_your_message, required: false, width: 'full' },
        select:   { label: I.default_select, name: '', placeholder: '', required: false, width: 'full', options: [I.default_option + ' 1', I.default_option + ' 2', I.default_option + ' 3'] },
        radio:    { label: I.default_choice, name: '', required: false, width: 'full', options: [I.default_option + ' 1', I.default_option + ' 2', I.default_option + ' 3'] },
        checkbox: { label: I.default_select_all, name: '', required: false, width: 'full', options: [I.default_option + ' 1', I.default_option + ' 2'] },
        date:     { label: I.default_date, name: 'date', placeholder: '', required: false, width: 'half' },
        url:      { label: I.default_website, name: 'website', placeholder: 'https://...', required: false, width: 'full' },
        rating:   { label: I.default_rating, name: 'rating', required: false, width: 'full', max_rating: 5 },
        consent:  { label: I.default_privacy, name: 'consent', required: true, width: 'full', consent_text: I.default_consent_text },
        hidden:   { label: I.default_hidden, name: 'hidden_field', required: false, width: 'full' }
    };

    function addField(type) {
        var def = JSON.parse(JSON.stringify(FIELD_DEFAULTS[type] || FIELD_DEFAULTS.text));
        def.id = uid(); def.type = type;
        if (!def.name) def.name = type + '_' + (++fieldCounter);
        window.fields.push(def); renderFields();
    }
    function removeField(id) { window.fields = window.fields.filter(function(f) { return f.id !== id; }); renderFields(); }
    function moveField(id, dir) {
        var idx = window.fields.findIndex(function(f) { return f.id === id; });
        var newIdx = idx + dir;
        if (idx < 0 || newIdx < 0 || newIdx >= window.fields.length) return;
        var item = window.fields.splice(idx, 1)[0];
        window.fields.splice(newIdx, 0, item); renderFields();
    }
    function duplicateField(id) {
        var idx = window.fields.findIndex(function(f) { return f.id === id; });
        if (idx < 0) return;
        var copy = JSON.parse(JSON.stringify(window.fields[idx]));
        copy.id = uid(); copy.name = copy.name + '_copy';
        window.fields.splice(idx + 1, 0, copy); renderFields();
    }

    window.renderFields = function() {
        var fields = window.fields;
        $count.textContent = fields.length;
        $json.value = JSON.stringify(fields);
        if (fields.length === 0) { $empty.style.display = 'block'; $list.querySelectorAll('.fe-field-item').forEach(function(el) { el.remove(); }); return; }
        $empty.style.display = 'none';
        var html = '';
        fields.forEach(function(f, i) {
            var hasOptions = ['select', 'radio', 'checkbox'].indexOf(f.type) >= 0;
            var isRating = f.type === 'rating';
            var isConsent = f.type === 'consent';
            html += '<div class="fe-field-item" data-id="' + f.id + '">';
            html += '<div class="fe-field-header" onclick="toggleFieldPanel(\'' + f.id + '\')">';
            html += '<span class="fe-field-drag" title="' + I.drag + '">⠿</span>';
            html += '<span class="fe-field-type-badge">' + esc(f.type) + '</span>';
            html += '<span class="fe-field-title">' + esc(f.label) + '</span>';
            if (f.required) html += '<span class="fe-field-required-dot" title="' + I.required + '"></span>';
            html += '<div class="fe-field-actions">';
            html += '<button type="button" onclick="event.stopPropagation();moveField(\'' + f.id + '\',-1)" title="' + I.move_up + '">↑</button>';
            html += '<button type="button" onclick="event.stopPropagation();moveField(\'' + f.id + '\',1)" title="' + I.move_down + '">↓</button>';
            html += '<button type="button" onclick="event.stopPropagation();duplicateField(\'' + f.id + '\')" title="' + I.copy + '">⧉</button>';
            html += '<button type="button" class="btn-del" onclick="event.stopPropagation();removeField(\'' + f.id + '\')" title="' + I.remove + '">×</button>';
            html += '</div></div>';
            html += '<div class="fe-field-body">';
            html += '<div class="fe-field-row">';
            html += '<div class="fe-field"><label>' + I.label + '</label><input type="text" value="' + esc(f.label) + '" onchange="updateField(\'' + f.id + '\',\'label\',this.value)"></div>';
            html += '<div class="fe-field"><label>' + I.name + '</label><input type="text" value="' + esc(f.name) + '" onchange="updateField(\'' + f.id + '\',\'name\',this.value)"></div>';
            html += '</div>';
            if (!isConsent && !isRating && f.type !== 'hidden') {
                html += '<div class="fe-field-row">';
                html += '<div class="fe-field"><label>' + I.placeholder + '</label><input type="text" value="' + esc(f.placeholder || '') + '" onchange="updateField(\'' + f.id + '\',\'placeholder\',this.value)"></div>';
                html += '<div class="fe-field"><label>' + I.help + '</label><input type="text" value="' + esc(f.help_text || '') + '" onchange="updateField(\'' + f.id + '\',\'help_text\',this.value)"></div>';
                html += '</div>';
            }
            if (hasOptions) { html += '<div class="fe-field"><label>' + I.options + '</label><textarea rows="3" onchange="updateFieldOptions(\'' + f.id + '\',this.value)">' + esc((f.options || []).join('\n')) + '</textarea></div>'; }
            if (isRating) { html += '<div class="fe-field"><label>' + I.max_rating + '</label><input type="number" value="' + (f.max_rating || 5) + '" min="3" max="10" onchange="updateField(\'' + f.id + '\',\'max_rating\',parseInt(this.value))"></div>'; }
            if (isConsent) { html += '<div class="fe-field"><label>' + I.consent_text + '</label><textarea rows="2" onchange="updateField(\'' + f.id + '\',\'consent_text\',this.value)">' + esc(f.consent_text || '') + '</textarea></div>'; }
            html += '<div class="fe-field-row">';
            html += '<div class="fe-field"><label>' + I.width + '</label><select onchange="updateField(\'' + f.id + '\',\'width\',this.value)">';
            html += '<option value="full"' + (f.width === 'full' ? ' selected' : '') + '>' + I.full + '</option>';
            html += '<option value="half"' + (f.width === 'half' ? ' selected' : '') + '>' + I.half + '</option>';
            html += '</select></div>';
            html += '<div class="fe-field"><label>&nbsp;</label><label class="fe-toggle fe-toggle--aligned"><input type="checkbox"' + (f.required ? ' checked' : '') + ' onchange="updateField(\'' + f.id + '\',\'required\',this.checked)"> ' + I.required + '</label></div>';
            html += '</div>';
            html += '</div></div>';
        });
        $list.querySelectorAll('.fe-field-item').forEach(function(el) { el.remove(); });
        $empty.insertAdjacentHTML('beforebegin', html);
    };

    window.removeField = removeField;
    window.moveField = moveField;
    window.duplicateField = duplicateField;
    window.toggleFieldPanel = function(id) { var el = $list.querySelector('[data-id="' + id + '"]'); if (el) el.classList.toggle('is-open'); };
    window.updateField = function(id, key, value) {
        var f = window.fields.find(function(f) { return f.id === id; });
        if (f) { f[key] = value; $json.value = JSON.stringify(window.fields); }
        if (key === 'label') { var el = $list.querySelector('[data-id="' + id + '"] .fe-field-title'); if (el) el.textContent = value; }
        if (key === 'required') {
            var dot = $list.querySelector('[data-id="' + id + '"] .fe-field-required-dot');
            if (value && !dot) { var header = $list.querySelector('[data-id="' + id + '"] .fe-field-title'); header.insertAdjacentHTML('afterend', '<span class="fe-field-required-dot" title="' + I.required + '"></span>'); }
            else if (!value && dot) { dot.remove(); }
        }
    };
    window.updateFieldOptions = function(id, text) {
        var f = window.fields.find(function(f) { return f.id === id; });
        if (f) { f.options = text.split('\n').filter(function(l) { return l.trim(); }); $json.value = JSON.stringify(window.fields); }
    };

    document.getElementById('fieldPalette').addEventListener('click', function(e) { var btn = e.target.closest('.fe-palette-btn'); if (btn) addField(btn.dataset.type); });
    renderFields();
    window.addEventListener('ai-fields-update', function(e) { window.fields = e.detail || []; fieldCounter = window.fields.length; renderFields(); });
    document.getElementById('formEditor').addEventListener('submit', function() { $json.value = JSON.stringify(window.fields); });
})();

function openFormAI() {
    var titleVal = document.getElementById('formTitle').value || '';
    var descVal = document.getElementById('formDescription') ? document.getElementById('formDescription').value : '';
    var langSelect = document.querySelector('select[name="language"]');
    var langName = langSelect ? langSelect.options[langSelect.selectedIndex].text : '{{ active_languages[0].name if active_languages else "English" }}';
    AliothAI.open({
        mode: 'generate_form', contentType: 'form', language: langName,
        existingTitle: titleVal, existingContent: descVal,
        onApply: function(result) {
            if (!result) return;
            if (result.title) document.getElementById('formTitle').value = result.title;
            if (result.description) { var d = document.getElementById('formDescription'); if (d) d.value = result.description; }
            if (result.fields && Array.isArray(result.fields)) {
                document.getElementById('fieldsJson').value = JSON.stringify(result.fields);
                window.dispatchEvent(new CustomEvent('ai-fields-update', { detail: result.fields }));
            }
            if (result.settings) {
                if (result.settings.submit_label) { var el = document.getElementById('settingSubmitLabel'); if (el) el.value = result.settings.submit_label; }
                if (result.settings.success_message) { var el = document.getElementById('settingSuccessMessage'); if (el) el.value = result.settings.success_message; }
            }
        }
    });
}
</script>
{% endblock %}
