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

{% block title %}{{ t('forms.edit_form') }} — {{ form.title }}{% endblock %}

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>📋 {{ t('forms.edit_form') }}</h2>
        <p>{{ t('forms.edit_subtitle') }}</p>
    </div>
    <div class="btn-group">
        <button type="submit" form="formEditor" class="btn btn-primary btn-sm">💾 {{ t('editor.save_changes') }}</button>
        <a href="{{ url_for('admin_forms_submissions', form_id=form.id) }}" class="btn btn-secondary btn-sm">📊 {{ t('forms.submissions_count') }} ({{ form.get_submission_count() }})</a>
        <a href="{{ admin_back_url('admin_forms_list') }}" class="btn btn-secondary btn-sm">{{ t('common.cancel') }}</a>
        <form method="POST" action="{{ url_for('admin_forms_delete', form_id=form.id) }}" class="d-inline" id="formDeleteForm">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <input type="hidden" name="return_to" value="{{ admin_back_value() }}">
            <button type="button" class="btn btn-danger btn-sm" onclick="checkUsageThenDelete('form', {{ form.id }}, this.closest('form'))">🗑️ {{ t('common.delete') }}</button>
        </form>
    </div>
</div>

<form method="POST" id="formEditor" class="container-xl" data-inline-save>
    <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">
            <!-- Form info -->
            <div class="form-group">
                <label for="formTitle" class="required">{{ t('editor.title_label') }}</label>
                <input type="text" id="formTitle" name="title" value="{{ form.title }}" required>
            </div>

            <div class="form-group">
                <label for="slug">{{ t('forms.form_slug') }}</label>
                <input type="text" id="slug" name="slug" value="{{ form.slug }}">
            </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') }}">{{ form.description or '' }}</textarea>
            </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>{{ t('editor.status_label') }}</label>
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_active" {{ 'checked' if form.is_active }}>
                        {{ t('forms.status_active') }}
                    </label>
                </div>
                <div class="form-group">
                    <label for="language">{{ t('editor.language_label') }}</label>
                    <select id="language" name="language">
                        {% for lang in active_languages %}
                        <option value="{{ lang.code }}" data-name="{{ lang.name }}" {% if form.language == lang.code %}selected{% endif %}>{{ lang.name }}</option>
                        {% endfor %}
                        {% if form.language and form.language not in active_languages|map(attribute='code')|list %}
                        <option value="{{ form.language }}" data-name="{{ form.get_language_name() }}" selected>{{ form.get_language_name() }} — {{ t('common.language_deactivated') }}</option>
                        {% endif %}
                    </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. Translations -->
            <div class="form-section">
                <h3>🌍 {{ t('forms.translations') }}</h3>
                
                <!-- Current language -->
                <div class="mb-3">
                    <span class="current-lang-badge">{{ form.get_language_name() }}</span>
                    <span class="text-sm text-muted ml-1">— {{ t('forms.this_version') }}</span>
                </div>
                
                <!-- Existing translations -->
                {% if translations %}
                <ul class="translation-list">
                    {% for tr in translations %}
                    <li class="translation-item">
                        <span class="translation-lang">{{ tr.get_language_name() }}</span>
                        <a href="{{ url_for('admin_forms_edit', form_id=tr.id) }}" class="translation-link">{{ t('common.edit') }} →</a>
                    </li>
                    {% endfor %}
                </ul>
                {% else %}
                <p class="text-sm text-muted mb-2">{{ t('forms.no_translations') }}</p>
                {% endif %}
                
                <!-- Add translation -->
                {% if missing_languages %}
                <div class="mt-3">
                    <select id="newTranslationLang" class="add-translation-select">
                        <option value="">{{ t('forms.select_language_placeholder') }}</option>
                        {% for lang in missing_languages %}
                        <option value="{{ lang.code }}">{{ lang.name }}</option>
                        {% endfor %}
                    </select>
                    <a href="{{ url_for('admin_forms_translate', form_id=form.id) }}" 
                       class="sidebar-btn sidebar-btn--highlight mt-2 mb-2">
                        🌍 {{ t('forms.create_translation') }}
                    </a>
                    <button type="button" class="ai-assist-btn sidebar-btn" onclick="aiCreateFormTranslation()" id="btnAiTranslate">
                        🤖 {{ t('forms.ai_translate_create') }}
                    </button>
                    <div class="help-text">{{ t('forms.ai_translate_help') }}</div>
                </div>
                {% endif %}
            </div>

            <!-- 4. Form Settings -->
            <div class="form-section">
                <h3>⚙️ {{ t('forms.form_settings') }}</h3>
                {% set s = form.get_settings() %}
                <div class="form-group">
                    <label>{{ t('forms.settings_submit_label') }}</label>
                    <input type="text" name="submit_label" value="{{ s.submit_label }}">
                </div>
                <div class="form-group">
                    <label>{{ t('forms.settings_success_message') }}</label>
                    <textarea name="success_message" rows="2">{{ s.success_message }}</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="{{ s.redirect_url }}" placeholder="https://...">
                    <div class="help-text">{{ t('forms.settings_redirect_help') }}</div>
                </div>
            </div>

            <!-- 5. 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="{{ s.notify_email }}" 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' if s.notify_on_submit }}>
                        {{ t('forms.settings_notify_on_submit') }}
                    </label>
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="store_submissions" {{ 'checked' if s.store_submissions }}>
                        {{ 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' if s.confirmation_email or s.double_opt_in }}
                               {{ 'disabled' if s.double_opt_in }}
                               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' if s.double_opt_in }}
                               onchange="syncOptInCheckboxes()">
                        {{ t('forms.settings_double_opt_in') }}
                    </label>
                    <div class="help-text">{{ t('forms.settings_double_opt_in_help') }}</div>
                </div>
            </div>

            <!-- 6. 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' if s.anti_spam == 'honeypot' }}>{{ t('forms.settings_anti_spam_honeypot') }}</option>
                        <option value="none" {{ 'selected' if s.anti_spam == 'none' }}>{{ t('forms.settings_anti_spam_none') }}</option>
                    </select>
                </div>
            </div>

            <!-- 7. Info -->
            <div class="form-section">
                <h3>📅 {{ t('editor.info') }}</h3>
                <p class="text-sm text-muted mb-2">
                    <strong>{{ t('editor.created') }}</strong><br>
                    {{ form.created_at|format_datetime }}
                </p>
                <p class="text-sm text-muted">
                    <strong>{{ t('editor.last_updated') }}</strong><br>
                    {{ form.updated_at|format_datetime }}
                </p>
            </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;
    }
}

(function() {
    'use strict';
    
    // Initial fields from server
    var fields = {{ form.fields | safe }};
    var fieldCounter = fields.length;
    
    var $list = document.getElementById('fieldsList');
    var $empty = document.getElementById('fieldsEmpty');
    var $count = document.getElementById('fieldCount');
    var $json = document.getElementById('fieldsJson');
    
    // I18N from Jinja
    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") }}',
        select_language_first: '{{ t("forms.select_language_first") }}',
        confirm_ai_translate: '{{ t("forms.confirm_ai_translate") }}',
        open_existing: '{{ t("forms.open_existing_translation") }}',
        translating: '{{ t("ai.translating") }}',
        ai_translate_create: '{{ t("forms.ai_translate_create") }}'
    };
    
    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; }
    
    // Defaults for new fields
    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);
        fields.push(def);
        renderFields();
    }
    
    function removeField(id) {
        fields = fields.filter(function(f) { return f.id !== id; });
        renderFields();
    }
    
    function moveField(id, dir) {
        var idx = fields.findIndex(function(f) { return f.id === id; });
        var newIdx = idx + dir;
        if (idx < 0 || newIdx < 0 || newIdx >= fields.length) return;
        var item = fields.splice(idx, 1)[0];
        fields.splice(newIdx, 0, item);
        renderFields();
    }
    
    function duplicateField(id) {
        var idx = fields.findIndex(function(f) { return f.id === id; });
        if (idx < 0) return;
        var copy = JSON.parse(JSON.stringify(fields[idx]));
        copy.id = uid();
        copy.name = copy.name + '_copy';
        fields.splice(idx + 1, 0, copy);
        renderFields();
    }
    
    function renderFields() {
        $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>';
            
            // Edit panel
            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>'; // fe-field-body
            html += '</div>'; // fe-field-item
        });
        
        // Remove old items and insert new
        $list.querySelectorAll('.fe-field-item').forEach(function(el) { el.remove(); });
        $empty.insertAdjacentHTML('beforebegin', html);
    }
    
    // Expose functions to global scope for inline handlers
    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 = fields.find(function(f) { return f.id === id; });
        if (f) { f[key] = value; $json.value = JSON.stringify(fields); }
        // Update title in header if label changed
        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 = 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(fields); }
    };
    
    // Palette click handlers
    document.getElementById('fieldPalette').addEventListener('click', function(e) {
        var btn = e.target.closest('.fe-palette-btn');
        if (btn) addField(btn.dataset.type);
    });
    
    // Initial render
    renderFields();
    
    // Listen for AI-generated fields update
    window.addEventListener('ai-fields-update', function(e) {
        fields = e.detail || [];
        fieldCounter = fields.length;
        renderFields();
    });
    
    // Before form submit — ensure JSON is up to date
    document.getElementById('formEditor').addEventListener('submit', function() {
        $json.value = JSON.stringify(fields);
    });
    
})();

// AI: Generate form content
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].dataset.name || langSelect.options[langSelect.selectedIndex].text) : '{{ form.get_language_name() }}';

    AliothAI.open({
        mode: 'generate_form',
        contentType: 'form',
        language: langName,
        existingTitle: titleVal,
        existingContent: descVal,
        onApply: function(result) {
            applyFormAIResult(result);
        }
    });
}

function applyFormAIResult(result) {
    if (!result) return;
    if (result.title) {
        document.getElementById('formTitle').value = result.title;
    }
    if (result.description) {
        var descEl = document.getElementById('formDescription');
        if (descEl) descEl.value = result.description;
    }
    if (result.fields && Array.isArray(result.fields)) {
        // Replace current fields with AI-generated ones
        var $json = document.getElementById('fieldsJson');
        $json.value = JSON.stringify(result.fields);
        // Trigger re-render by dispatching a custom event
        window.dispatchEvent(new CustomEvent('ai-fields-update', { detail: result.fields }));
    }
    if (result.settings) {
        var s = result.settings;
        if (s.submit_label) {
            var el = document.querySelector('input[name="submit_label"]');
            if (el) el.value = s.submit_label;
        }
        if (s.success_message) {
            var el = document.querySelector('textarea[name="success_message"]');
            if (el) el.value = s.success_message;
        }
    }
}

// AI: Create translated form
function aiCreateFormTranslation() {
    var langSelect = document.getElementById('newTranslationLang');
    var targetLang = langSelect.value;
    if (!targetLang) { AdminDialog.alert(I.select_language_first); return; }
    var targetLangName = langSelect.options[langSelect.selectedIndex].text;
    AdminDialog.confirm(I.confirm_ai_translate.replace('{lang}', targetLangName)).then(function(okc) {
    if (!okc) return;
    var btn = document.getElementById('btnAiTranslate');
    btn.disabled = true;
    btn.innerHTML = '⏳ ' + I.translating;
    
    fetch('/admin/api/translate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            content_type: 'form',
            source_id: {{ form.id }},
            target_lang: targetLang
        })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.error) {
            AdminDialog.alert('{{ t("common.error") }}: ' + data.error).then(function() {
                if (data.existing_id) {
                    AdminDialog.confirm(I.open_existing).then(function(ok2) {
                        if (ok2) window.location.href = '/admin/forms/' + data.existing_id + '/edit';
                    });
                }
            });
        } else if (data.edit_url) {
            // Await the themed alert before navigating (native alert blocked).
            AdminDialog.alert(data.message).then(function() {
                window.location.href = data.edit_url;
            });
            return;
        }
        btn.innerHTML = '🤖 ' + I.ai_translate_create;
        btn.disabled = false;
    })
    .catch(function(err) {
        AdminDialog.alert('{{ t("common.error") }}: ' + err.message);
        btn.innerHTML = '🤖 ' + I.ai_translate_create;
        btn.disabled = false;
    });
    });
}

async function checkUsageThenDelete(assetType, assetId, formEl) {
    try {
        const res = await fetch('/admin/api/check-usage', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: assetType, id: assetId })
        });
        const data = await res.json();
        
        var msg = '{{ t("forms.delete_confirm_generic") }}';
        
        if (data.count > 0) {
            msg = '{{ t("forms.usage_warning") }}\n\n';
            data.usage.forEach(function(u) {
                var typeLabel = u.type.charAt(0).toUpperCase() + u.type.slice(1);
                msg += '• ' + typeLabel + ': ' + u.title + ' (' + u.fields.join(', ') + ')\n';
            });
            msg += '\n{{ t("forms.usage_confirm_delete") }}';
        }
        
        AdminDialog.confirm(msg, { danger: true }).then(function(ok) {
            if (ok) formEl.submit();
        });
    } catch (err) {
        AdminDialog.confirm('{{ t("forms.delete_confirm_generic") }}', { danger: true }).then(function(ok) {
            if (ok) formEl.submit();
        });
    }
}
</script>
{% endblock %}
