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

{% block title %}{{ t('forms.translate_form') }} — {{ source.title }}{% endblock %}

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>🌍 {{ t('forms.translate_form') }}</h2>
        <p>{{ t('forms.translating_from') }} <strong>{{ source.title }}</strong> ({{ source.get_language_name() }})</p>
    </div>
    <div class="btn-group">
        <button type="submit" form="translateForm" class="btn btn-primary btn-sm">📝 {{ t('forms.translate_form') }}</button>
        <a href="{{ admin_back_url('admin_forms_list') }}" class="btn btn-secondary btn-sm">{{ t('common.cancel') }}</a>
    </div>
</div>

<!-- Source info -->
<div class="source-info">
    <h4>📋 {{ t('forms.source_form') }} ({{ source.get_language_name() }})</h4>
    <p><strong>{{ source.title }}</strong> · {{ source.form_type }} · {{ source.get_fields()|length }} {{ t('forms.fields_count') }}</p>
    <a href="{{ url_for('admin_forms_edit', form_id=source.id) }}">← {{ t('common.back') }}</a>
</div>

<form method="POST" id="translateForm" 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">
            <!-- Form info -->
            <div class="form-group">
                <label for="formTitle" class="required">{{ t('editor.title_label') }}</label>
                <input type="text" id="formTitle" name="title" required placeholder="{{ t('forms.translated_title_placeholder') }}">
                <div class="help-text">{{ t('forms.original') }}: {{ source.title }}</div>
            </div>

            <div class="form-group">
                <label for="formDescription">{{ t('forms.form_description') }}</label>
                <textarea id="formDescription" name="description" rows="2" placeholder="{{ t('forms.translated_desc_placeholder') }}">{{ source.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. Target Language & AI -->
            <div class="form-section">
                <h3>🌍 {{ t('forms.select_target_language') }}</h3>
                <div class="form-group">
                    <label for="language">{{ t('forms.language') }}</label>
                    <select id="language" name="language">
                        {% for lang in missing_languages %}
                        <option value="{{ lang.code }}">{{ lang.name }}</option>
                        {% endfor %}
                    </select>
                    {% if not missing_languages %}
                    <div class="help-text text-error">{{ t('forms.all_translated') }}</div>
                    {% endif %}
                </div>

                <button type="button" class="ai-translate-all" onclick="aiTranslateFormFields()" id="btnTranslateAll" {% if not missing_languages %}disabled{% endif %}>
                    🤖 {{ t('forms.ai_translate_fields') }}
                </button>
                <div class="help-text mt-2">{{ t('forms.ai_translate_all_help') }}</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_translate') }}</div>
            </div>

            <!-- 3. Existing translations -->
            <div class="form-section">
                <h3>📋 {{ t('forms.existing_translations') }}</h3>
                <div class="mb-2">
                    <span class="translation-lang">{{ source.get_language_name() }}</span>
                    <span class="current-lang-badge">{{ t('forms.source_badge') }}</span>
                </div>
                {% 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">{{ t('forms.no_translations') }}</p>
                {% endif %}
            </div>

            <!-- 4. Form Settings -->
            <div class="form-section">
                <h3>⚙️ {{ t('forms.form_settings') }}</h3>
                {% set s = source.get_settings() %}
                <div class="form-group">
                    <label>{{ t('forms.settings_submit_label') }}</label>
                    <input type="text" id="settingSubmitLabel" value="{{ s.submit_label }}">
                    <div class="help-text">{{ t('forms.original') }}: {{ s.submit_label }}</div>
                </div>
                <div class="form-group">
                    <label>{{ t('forms.settings_success_message') }}</label>
                    <textarea id="settingSuccessMessage" rows="2">{{ s.success_message }}</textarea>
                    <div class="help-text">{{ t('forms.original') }}: {{ s.success_message[:80] }}{% if s.success_message|length > 80 %}...{% endif %}</div>
                </div>
                <div class="form-group">
                    <label>{{ t('forms.settings_redirect_url') }}</label>
                    <input type="text" id="settingRedirectUrl" 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" id="settingNotifyEmail" 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" id="settingNotifyOnSubmit" {{ '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" id="settingStoreSubmissions" {{ '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" id="settingConfirmationEmail"
                               {{ '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" id="settingDoubleOptIn"
                               {{ '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 id="settingAntiSpam">
                        <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>
        </div>
    </div>

    <!-- Hidden fields for JSON data (populated by JS before submit) -->
    <input type="hidden" name="fields_json" id="fieldsJson" value="">
    <input type="hidden" name="settings_json" id="settingsJson" value="">
</form>

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

(function() {
    'use strict';
    
    // Initial fields from source form
    var fields = {{ source.fields | safe }};
    var fieldCounter = fields.length;
    
    var $list = document.getElementById('fieldsList');
    var $empty = document.getElementById('fieldsEmpty');
    var $count = document.getElementById('fieldCount');
    var $fieldsJson = document.getElementById('fieldsJson');
    var $settingsJson = document.getElementById('settingsJson');
    
    // 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") }}'
    };
    
    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;
        $fieldsJson.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; $fieldsJson.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(); }); $fieldsJson.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);
    });
    
    // Collect settings into JSON
    function collectSettingsJson() {
        var doi = document.getElementById('settingDoubleOptIn').checked;
        var ce = doi || document.getElementById('settingConfirmationEmail').checked;
        return JSON.stringify({
            submit_label: document.getElementById('settingSubmitLabel').value.trim() || 'Submit',
            success_message: document.getElementById('settingSuccessMessage').value.trim(),
            redirect_url: document.getElementById('settingRedirectUrl').value.trim(),
            notify_email: document.getElementById('settingNotifyEmail').value.trim(),
            notify_on_submit: document.getElementById('settingNotifyOnSubmit').checked,
            store_submissions: document.getElementById('settingStoreSubmissions').checked,
            anti_spam: document.getElementById('settingAntiSpam').value,
            confirmation_email: ce,
            double_opt_in: doi
        });
    }
    
    // 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('translateForm').addEventListener('submit', function() {
        $fieldsJson.value = JSON.stringify(fields);
        $settingsJson.value = collectSettingsJson();
    });
    
})();

// AI: Translate all fields via API (creates form server-side, redirects)
async function aiTranslateFormFields() {
    var langSelect = document.getElementById('language');
    var targetLang = langSelect.value;
    var targetLangName = langSelect.options[langSelect.selectedIndex].text;
    
    if (!targetLang) { AdminDialog.alert('{{ t("forms.select_language_first") }}'); return; }
    var okc = await AdminDialog.confirm('{{ t("forms.confirm_ai_translate_full") | replace("'", "\\'") }}'.replace('{lang}', targetLangName));
    if (!okc) return;
    
    var btn = document.getElementById('btnTranslateAll');
    btn.disabled = true;
    btn.innerHTML = '⏳ {{ t("forms.translating_fields") }}';
    
    try {
        var response = await fetch('/admin/api/translate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                content_type: 'form',
                source_id: {{ source.id }},
                target_lang: targetLang
            })
        });
        var data = await response.json();
        
        if (data.error) {
            if (data.existing_id) {
                AdminDialog.confirm(data.error + '\n\n{{ t("forms.open_existing_translation") }}').then(function(ok) {
                    if (ok) window.location.href = '/admin/forms/' + data.existing_id + '/edit';
                });
            } else {
                AdminDialog.alert('{{ t("common.error") }}: ' + data.error);
            }
        } else if (data.edit_url) {
            // Await the themed alert before navigating (native alert blocked).
            await AdminDialog.alert(data.message + '\n\n{{ t("forms.redirect_to_translation") }}');
            window.location.href = data.edit_url;
            return;
        }
    } catch (err) {
        AdminDialog.alert('{{ t("common.error") }}: ' + err.message);
    }
    
    btn.innerHTML = '🤖 {{ t("forms.ai_translate_fields") }}';
    btn.disabled = false;
}

// AI: Generate form content via AliothAI modal
function openFormAI() {
    var langSelect = document.getElementById('language');
    var langName = langSelect ? langSelect.options[langSelect.selectedIndex].text : '{{ source.get_language_name() }}';
    var titleVal = document.getElementById('formTitle').value || '{{ source.title }}';
    var descVal = document.getElementById('formDescription') ? document.getElementById('formDescription').value : '';

    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)) {
        var $json = document.getElementById('fieldsJson');
        $json.value = JSON.stringify(result.fields);
        window.dispatchEvent(new CustomEvent('ai-fields-update', { detail: result.fields }));
    }
    if (result.settings) {
        var s = result.settings;
        if (s.submit_label) {
            var el = document.getElementById('settingSubmitLabel');
            if (el) el.value = s.submit_label;
        }
        if (s.success_message) {
            var el = document.getElementById('settingSuccessMessage');
            if (el) el.value = s.success_message;
        }
    }
}
</script>
{% endblock %}
