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

{% block title %}{{ t('pages.edit_page') }}{% endblock %}


{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>✏️ {{ t('pages.edit_page') }}</h2>
        <p>{{ t('pages.edit_subtitle') }}</p>
    </div>
    <div class="btn-group">
        <button type="submit" form="editForm" class="btn btn-primary btn-sm">💾 {{ t('editor.save_changes') }}</button>
        <a href="{{ request.args.get('return_to') or request.referrer or url_for('admin_pages_list') }}" class="btn btn-secondary btn-sm">{{ t('common.cancel') }}</a>
        <form method="POST" action="{{ url_for('admin_pages_delete', page_id=page.id) }}" class="d-inline">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="button" class="btn btn-danger" onclick="checkUsageThenDelete('page', {{ page.id }}, this.closest('form'))">🗑️ {{ t('editor.delete_page') }}</button>
        </form>
    </div>
</div>

<form method="POST" id="editForm" class="container-xl">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="return_to" value="{{ request.args.get('return_to') or request.referrer or '' }}">
    {% if page.use_builder %}
    <input type="hidden" name="use_builder" value="on">
    {% endif %}
    <div class="editor-layout">
        <!-- ============================================================ -->
        <!-- MAIN CONTENT (left) -->
        <!-- ============================================================ -->
        <div class="editor-main">
            <div class="form-group">
                <label for="title" class="required">{{ t('editor.title_label') }}</label>
                <input type="text" id="title" name="title" value="{{ page.title }}" required>
                <div class="help-text">{{ t('editor.title_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="slug">{{ t('editor.slug_label') }}</label>
                <input type="text" id="slug" name="slug" oninput="cleanSlugInput(this)" value="{{ page.slug }}" onblur="checkSlug('page', {{ page.id }})">
                <div id="slug-feedback" class="help-text">{{ t('editor.slug_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="excerpt">{{ t('editor.excerpt_label') }}</label>
                <textarea id="excerpt" name="excerpt" rows="3">{{ page.excerpt or '' }}</textarea>
                <div class="help-text">{{ t('editor.excerpt_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="content">{{ t('editor.content_label') }}</label>
                {% if page.use_builder %}
                <div class="builder-readonly-banner">
                    <span>🧩 {{ t('builder.editor_readonly_hint') }}</span>
                    <a href="{{ url_for('admin_page_builder', page_id=page.id) }}" class="btn btn-sm btn-primary">{{ t('builder.open_builder') }}</a>
                </div>
                {% endif %}
                <textarea id="content" name="content">{{ page.content }}</textarea>
            </div>
            
            <!-- SEO Meta Section -->
            <div class="collapsible">
                <div class="collapsible-header" onclick="toggleSection(this)">
                    <span>🔍 {{ t('seo.meta_tags') }}</span>
                    <span class="arrow">▶</span>
                </div>
                <div class="collapsible-content">
                    <div class="form-group">
                        <label for="meta_title">{{ t('seo.meta_title') }}</label>
                        <input type="text" id="meta_title" name="meta_title" value="{{ page.meta_title or '' }}" maxlength="60">
                        <div class="help-text">{{ t('seo.meta_title_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="meta_description">{{ t('seo.meta_description') }}</label>
                        <textarea id="meta_description" name="meta_description" rows="3" maxlength="160">{{ page.meta_description or '' }}</textarea>
                        <div class="help-text">{{ t('seo.meta_description_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="meta_keywords">{{ t('seo.keywords') }}</label>
                        <input type="text" id="meta_keywords" name="meta_keywords" value="{{ page.meta_keywords or '' }}">
                        <div class="help-text">{{ t('seo.keywords_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="canonical_url">{{ t('seo.canonical_url') }}</label>
                        <input type="url" id="canonical_url" name="canonical_url" value="{{ page.canonical_url or '' }}">
                        <div class="help-text">{{ t('seo.canonical_url_help') }}</div>
                    </div>
                    
                </div>
            </div>
            
            <!-- Open Graph Section -->
            <div class="collapsible">
                <div class="collapsible-header" onclick="toggleSection(this)">
                    <span>📱 {{ t('seo.og_section') }}</span>
                    <span class="arrow">▶</span>
                </div>
                <div class="collapsible-content">
                    <div class="form-group">
                        <label for="og_title">{{ t('seo.og_title') }}</label>
                        <input type="text" id="og_title" name="og_title" value="{{ page.og_title or '' }}">
                        <div class="help-text">{{ t('seo.og_title_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="og_description">{{ t('seo.og_description') }}</label>
                        <textarea id="og_description" name="og_description" rows="2">{{ page.og_description or '' }}</textarea>
                        <div class="help-text">{{ t('seo.og_description_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="og_image">{{ t('seo.og_image') }}</label>
                        <div class="image-field-row">
                            <input type="text" id="og_image" name="og_image" value="{{ page.og_image or '' }}" class="input-readonly" readonly>
                            <button type="button" class="btn-pick-image" onclick="pickImageFor('og_image')">📷 {{ t('common.choose') }}</button>
                        </div>
                        <div id="og_image_preview_wrap" class="image-preview-wrap">
                        <img id="og_image_preview" class="image-preview-thumb" alt="{{ t('common.preview') }}">
                        <button type="button" onclick="clearImageField('og_image')" title="{{ t('common.remove') }}" class="btn-remove-preview">✕</button>
                        </div>
                        <div class="help-text" id="og_image_hint">{{ t('seo.og_image_help') }}</div>
                    </div>
                </div>
            </div>
            
            <!-- Twitter Card Section -->
            <div class="collapsible">
                <div class="collapsible-header" onclick="toggleSection(this)">
                    <span>🐦 {{ t('seo.twitter_section') }}</span>
                    <span class="arrow">▶</span>
                </div>
                <div class="collapsible-content">
                    <div class="form-group">
                        <label for="twitter_title">{{ t('seo.twitter_title') }}</label>
                        <input type="text" id="twitter_title" name="twitter_title" value="{{ page.twitter_title or '' }}">
                    </div>
                    
                    <div class="form-group">
                        <label for="twitter_description">{{ t('seo.twitter_description') }}</label>
                        <textarea id="twitter_description" name="twitter_description" rows="2">{{ page.twitter_description or '' }}</textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="twitter_image">{{ t('seo.twitter_image') }}</label>
                        <div class="image-field-row">
                            <input type="text" id="twitter_image" name="twitter_image" value="{{ page.twitter_image or '' }}" class="input-readonly" readonly>
                            <button type="button" class="btn-pick-image" onclick="pickImageFor('twitter_image')">📷 {{ t('common.choose') }}</button>
                        </div>
                        <div id="twitter_image_preview_wrap" class="image-preview-wrap">
                        <img id="twitter_image_preview" class="image-preview-thumb" alt="{{ t('common.preview') }}">
                        <button type="button" onclick="clearImageField('twitter_image')" title="{{ t('common.remove') }}" class="btn-remove-preview">✕</button>
                        </div>
                        <div class="help-text" id="twitter_image_hint">{{ t('seo.twitter_image_help') }}</div>
                    </div>
                </div>
            </div>
            
            <!-- Schema.org Section -->
            <div class="collapsible">
                <div class="collapsible-header" onclick="toggleSection(this)">
                    <span>🏗️ {{ t('seo.schema_section') }}</span>
                    <span class="arrow">▶</span>
                </div>
                <div class="collapsible-content">
                    <div class="form-group">
                        <label for="schema_type">{{ t('seo.schema_type') }}</label>
                        <select id="schema_type" name="schema_type">
                            <option value="WebPage" {% if page.schema_type == 'WebPage' %}selected{% endif %}>WebPage</option>
                            <option value="AboutPage" {% if page.schema_type == 'AboutPage' %}selected{% endif %}>AboutPage</option>
                            <option value="ContactPage" {% if page.schema_type == 'ContactPage' %}selected{% endif %}>ContactPage</option>
                            <option value="FAQPage" {% if page.schema_type == 'FAQPage' %}selected{% endif %}>FAQPage</option>
                            <option value="CollectionPage" {% if page.schema_type == 'CollectionPage' %}selected{% endif %}>CollectionPage</option>
                        </select>
                        <div class="help-text">{{ t('seo.schema_type_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="schema_author">{{ t('seo.schema_author') }}</label>
                        <input type="text" id="schema_author" name="schema_author" value="{{ page.schema_author or '' }}">
                        <div class="help-text">{{ t('seo.schema_author_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="schema_publisher">{{ t('seo.schema_publisher') }}</label>
                        <input type="text" id="schema_publisher" name="schema_publisher" value="{{ page.schema_publisher or '' }}">
                        <div class="help-text">{{ t('seo.schema_publisher_help') }}</div>
                    </div>
                </div>
            </div>
            
            <!-- Featured Image Section -->
            <div class="collapsible">
                <div class="collapsible-header" onclick="toggleSection(this)">
                    <span>🖼️ {{ t('seo.featured_image') }}</span>
                    <span class="arrow">▶</span>
                </div>
                <div class="collapsible-content">
                    <div class="form-group">
                        <label for="featured_image">{{ t('seo.featured_image_url') }}</label>
                        <div class="image-field-row">
                            <input type="text" id="featured_image" name="featured_image" value="{{ page.featured_image or '' }}" class="input-readonly" readonly>
                            <button type="button" class="btn-pick-image" onclick="pickImageFor('featured_image','featured_image_alt')">📷 {{ t('common.choose') }}</button>
                        </div>
                        <div id="featured_image_preview_wrap" class="image-preview-wrap">
                        <img id="featured_image_preview" class="image-preview-thumb" alt="{{ t('common.preview') }}">
                        <button type="button" onclick="clearImageField('featured_image')" title="{{ t('common.remove') }}" class="btn-remove-preview">✕</button>
                        </div>
                        <div class="help-text">{{ t('seo.featured_image_help') }} {{ t('seo.featured_image_social_hint') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="featured_image_alt" class="required">{{ t('seo.featured_image_alt') }}</label>
                        <input type="text" id="featured_image_alt" name="featured_image_alt" value="{{ page.featured_image_alt or '' }}">
                        <div class="help-text">{{ t('seo.featured_image_alt_help') }}</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="featured_image_caption">{{ t('seo.featured_image_caption') }}</label>
                        <textarea id="featured_image_caption" name="featured_image_caption" rows="2">{{ page.featured_image_caption or '' }}</textarea>
                    </div>
                </div>
            </div>
            
            <!-- FAQ Section (AEO) -->
            <div class="collapsible">
                <div class="collapsible-header" onclick="toggleSection(this)">
                    <span>❓ {{ t('editor.faq_section') }}</span>
                    <span class="arrow">▶</span>
                </div>
                <div class="collapsible-content">
                    <div class="help-text mb-3">{{ t('editor.faq_help') }}</div>
                    <div id="faqContainer">
                        {% for faq in page.get_faq_list() %}
                        <div class="faq-editor-item">
                            <div class="form-group">
                                <label>{{ t('editor.faq_question') }}</label>
                                <input type="text" class="faq-question" value="{{ faq.question }}">
                            </div>
                            <div class="form-group">
                                <label>{{ t('editor.faq_answer') }}</label>
                                <textarea class="faq-answer" rows="2">{{ faq.answer }}</textarea>
                            </div>
                            <button type="button" class="btn btn-danger btn-sm" onclick="this.closest('.faq-editor-item').remove(); updateFaqJson();">🗑️ {{ t('editor.faq_remove') }}</button>
                        </div>
                        {% endfor %}
                    </div>
                    <button type="button" class="btn btn-secondary btn-sm mt-2" onclick="addFaqItem()">➕ {{ t('editor.faq_add') }}</button>
                    <input type="hidden" id="faq_json" name="faq_json" value="{{ page.faq_json or '[]' }}">
                </div>
            </div>
            
        </div>
        
        <!-- ============================================================ -->
        <!-- SIDEBAR (right) -->
        <!-- ============================================================ -->
        <div class="editor-sidebar">
            <!-- Status & Language -->
            <div class="form-section">
                <h3>📊 {{ t('editor.status_section') }}</h3>
                <div class="form-group">
                    <label for="status">{{ t('editor.status_label') }}</label>
                    <select id="status" name="status">
                        <option value="draft" {% if page.status == 'draft' %}selected{% endif %}>{{ t('editor.status_draft') }}</option>
                        <option value="published" {% if page.status == 'published' %}selected{% endif %}>{{ t('editor.status_published') }}</option>
                    </select>
                </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 }}" {% if page.language == lang.code %}selected{% endif %}>{{ lang.name }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div class="form-group">
                    <label for="template">{{ t('editor.template_label') }}</label>
                    <select id="template" name="template">
                        <option value="default" {% if page.template == 'default' %}selected{% endif %}>{{ t('editor.template_default') }}</option>
                        <option value="full-width" {% if page.template == 'full-width' %}selected{% endif %}>{{ t('editor.template_full_width') }}</option>
                        <option value="landing" {% if page.template == 'landing' %}selected{% endif %}>{{ t('editor.template_landing') }}</option>
                        <option value="landing-narrow" {% if page.template == 'landing-narrow' %}selected{% endif %}>{{ t('editor.template_landing_narrow') }}</option>
                    </select>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="form-section">
                <h3>🚀 {{ t('editor.quick_actions') }}</h3>
                <a href="{{ url_for('admin_page_builder', page_id=page.id) }}" 
                   class="sidebar-btn btn-ai mb-3">
                    🧩 {{ t('builder.open_builder') }}
                </a>
                <a href="{{ url_for('admin_pages_preview', page_id=page.id) }}" 
                   class="sidebar-btn sidebar-btn--highlight"
                   target="_blank">
                    👁️ {{ t('table.preview') }}
                </a>
            </div>

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

            <!-- ======== TRANSLATIONS BLOCK ======== -->
            <div class="form-section">
                <h3>🌍 {{ t('translate.translations_title') }}</h3>
                
                <!-- Current language -->
                <div class="mb-3">
                    <span class="current-lang-badge">{{ page.get_language_name() }}</span>
                    <span class="text-sm text-muted ml-1">— {{ t('translate.this_version') }}</span>
                </div>
                
                <!-- Existing translations -->
                {% if translations %}
                <ul class="translation-list">
                    {% for tr in translations %}
                    <li class="translation-item">
                        <span>
                            <span class="translation-lang">{{ tr.get_language_name() }}</span>
                            <span class="translation-status {{ tr.status }}">{{ t('common.status_' + tr.status) }}</span>
                        </span>
                        <a href="{{ url_for('admin_pages_edit', page_id=tr.id) }}" class="translation-link">{{ t('table.edit') }} →</a>
                    </li>
                    {% endfor %}
                </ul>
                {% else %}
                <p class="sidebar-meta">{{ t('translate.no_translations_yet') }}</p>
                {% endif %}
                
                <!-- Add translation -->
                {% if missing_languages %}
                <div class="mt-3">
                    <select id="newTranslationLang" class="add-translation-select">
                        <option value="">{{ t('translate.select_language_option') }}</option>
                        {% for lang in missing_languages %}
                        <option value="{{ lang.code }}">{{ lang.name }}</option>
                        {% endfor %}
                    </select>
                    <a href="{{ url_for('admin_pages_translate', page_id=page.id) }}" 
                       class="sidebar-btn btn-translate-create mt-2 mb-2">
                        🌍 {{ t('translate.create_translation') }}
                    </a>
                    <button type="button" class="ai-assist-btn sidebar-btn mt-0" onclick="aiCreateTranslation()" id="btnCreateTranslation">
                        🤖 {{ t('translate.ai_translate_create') }}
                    </button>
                    <div class="help-text">{{ t('translate.ai_translate_help') }}</div>
                </div>
                {% endif %}
            </div>
            
            <!-- Categories & Tags -->
            <div class="form-section">
                <h3>🏷️ {{ t('editor.categorization') }}</h3>
                <div class="form-group">
                    <label for="category">{{ t('editor.category_label') }}</label>
                    <input type="text" id="category" name="category" value="{{ page.category or '' }}">
                </div>
                
                <div class="form-group">
                    <label for="tags">{{ t('editor.tags_label') }}</label>
                    <input type="text" id="tags" name="tags" value="{{ tags_str }}">
                    <div class="help-text">{{ t('editor.tags_help') }}</div>
                </div>
            </div>

            <div class="form-section">
                <h3>👁️ {{ t('editor.display_options') }}</h3>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="show_date" {% if page.show_date is not defined or page.show_date %}checked{% endif %}>
                        {{ t('editor.show_date') }}
                    </label>
                </div>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="show_author" {% if page.show_author is not defined or page.show_author %}checked{% endif %}>
                        {{ t('editor.show_author') }}
                    </label>
                </div>
                <div class="help-text">{{ t('editor.display_help') }}</div>
            </div>
            
            <!-- Timestamps -->
            <div class="form-section">
                <h3>📅 {{ t('editor.info') }}</h3>
                <p class="sidebar-meta">
                    <strong>{{ t('editor.created') }}</strong><br>
                    {{ page.created_at|format_datetime }}
                </p>
                <p class="sidebar-meta">
                    <strong>{{ t('editor.last_updated') }}</strong><br>
                    {{ page.updated_at|format_datetime }}
                </p>
                {% if page.published_at %}
                <p class="sidebar-meta">
                    <strong>{{ t('editor.published') }}</strong><br>
                    {{ page.published_at|format_datetime }}
                </p>
                {% endif %}
            </div>
        </div>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<!-- TinyMCE CDN (Cloudflare - no API key needed) -->
<script src="{{ url_for('static', filename='js/tinymce/tinymce.min.js') }}"></script>

<script>
// Check usage before deleting
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("pages.delete_confirm", title=page.title) }}'.replace(/&#34;/g, '"');
        
        if (data.count > 0) {
            msg = '{{ t("pages.usage_warning") }}'.replace(/&#34;/g, '"') + '\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("pages.usage_confirm_delete") }}'.replace(/&#34;/g, '"');
        }
        
        if (confirm(msg)) {
            formEl.submit();
        }
    } catch (err) {
        if (confirm('{{ t("pages.delete_confirm", title=page.title) }}'.replace(/&#34;/g, '"'))) {
            formEl.submit();
        }
    }
}

// Toggle collapsible sections
function toggleSection(header) {
    const content = header.nextElementSibling;
    const arrow = header.querySelector('.arrow');
    content.classList.toggle('active');
    arrow.classList.toggle('active');
}

// Initialize TinyMCE
tinymce.init({
    base_url: '/static/js/tinymce',
    license_key: 'gpl',
    convert_urls: false,
    relative_urls: false,
    remove_script_host: false,
    selector: '#content',
    height: 500,
    menubar: false,
    {% if page.use_builder %}
    readonly: true,
    toolbar: false,
    statusbar: false,
    {% endif %}
    plugins: [
        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
        'insertdatetime', 'media', 'table', 'help', 'wordcount'
    ],
    {% if not page.use_builder %}
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | link image | code',
    {% endif %}
    skin: _tinyTheme.skin,
    content_style: _tinyTheme.content_style,
    
    file_picker_callback: function(callback, value, meta) {
        if (meta.filetype === 'image') {
            openImagePicker(callback);
        }
    },
    
    setup: function(editor) {
        editor.on('change', function() {
            editor.save();
        });
    }
});

let slugIsValid = true;

// Fix: TinyMCE must sync content back to textarea before form submit
document.getElementById('editForm').addEventListener('submit', function(e) {
    if (typeof tinymce !== 'undefined') {
        tinymce.triggerSave();
    }
    
    if (!slugIsValid) {
        e.preventDefault();
        alert('{{ t("editor.slug_taken") }}');
        document.getElementById('slug').focus();
        return false;
    }
});

// ============================================================
// AI ASSISTANT — uses global AliothAI component from base.html
// ============================================================

function openAIAssistant(mode) {
    var lang = document.getElementById('language');
    var langName = lang ? lang.options[lang.selectedIndex].text : 'English';
    var titleVal = document.getElementById('title').value;
    var contentVal = '';
    if (typeof tinymce !== 'undefined' && tinymce.get('content')) {
        contentVal = tinymce.get('content').getContent({ format: 'text' });
    } else {
        contentVal = document.getElementById('content').value;
    }

    AliothAI.open({
        mode: mode,
        contentType: 'page',
        language: langName,
        existingTitle: titleVal,
        existingContent: contentVal,
        onApply: function(result) {
            applyAIResult(result, mode);
        }
    });
}

function applyAIResult(result, mode) {
    if (!result) return;
    if (result.title) document.getElementById('title').value = result.title;
    if (result.content) {
        if (typeof tinymce !== 'undefined' && tinymce.get('content')) {
            tinymce.get('content').setContent(result.content);
        } else {
            document.getElementById('content').value = result.content;
        }
    }
    if (result.excerpt) { var el = document.getElementById('excerpt'); if (el) el.value = result.excerpt; }
    if (result.meta_title) { var el = document.getElementById('meta_title'); if (el) el.value = result.meta_title; }
    if (result.meta_description) { var el = document.getElementById('meta_description'); if (el) el.value = result.meta_description; }
    if (result.meta_keywords) { var el = document.getElementById('meta_keywords'); if (el) el.value = result.meta_keywords; }
    if (result.og_title) { var el = document.getElementById('og_title'); if (el) el.value = result.og_title; }
    if (result.og_description) { var el = document.getElementById('og_description'); if (el) el.value = result.og_description; }
    var twTitle = document.getElementById('twitter_title');
    if (twTitle && (result.og_title || result.twitter_title)) twTitle.value = result.twitter_title || result.og_title;
    var twDesc = document.getElementById('twitter_description');
    if (twDesc && (result.og_description || result.twitter_description)) twDesc.value = result.twitter_description || result.og_description;
    if (result.faq && Array.isArray(result.faq)) {
        var container = document.getElementById('faqContainer');
        if (container) {
            container.innerHTML = '';
            result.faq.forEach(function(item) {
                addFaqItem();
                var items = container.querySelectorAll('.faq-editor-item');
                var last = items[items.length - 1];
                if (last) {
                    last.querySelector('.faq-question').value = item.question || '';
                    last.querySelector('.faq-answer').value = item.answer || '';
                }
            });
            updateFaqJson();
        }
    }
}

// ============================================================
// AI TRANSLATION — Creates a NEW linked post via API
// ============================================================

function aiCreateTranslation() {
    const langSelect = document.getElementById('newTranslationLang');
    const targetLang = langSelect.value;
    
    if (!targetLang) {
        alert('{{ t("translate.select_language_first") }}');
        return;
    }
    
    const targetLangName = langSelect.options[langSelect.selectedIndex].text;
    
    if (!confirm('{{ t("translate.ai_confirm")|replace("\n", "\\n") }}'.replace('{lang}', targetLangName))) {
        return;
    }
    
    const btn = document.getElementById('btnCreateTranslation');
    btn.disabled = true;
    btn.innerHTML = '⏳ {{ t("translate.translating_to") }}'.replace('{lang}', targetLangName);
    
    fetch('/admin/api/translate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            content_type: 'page',
            source_id: {{ page.id }},
            target_lang: targetLang
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.error) {
            alert('{{ t("common.error") }}: ' + data.error);
            if (data.existing_id) {
                if (confirm('{{ t("translate.open_existing") }}')) {
                    window.location.href = '/admin/pages/' + data.existing_id + '/edit';
                }
            }
        } else {
            alert(data.message);
            window.location.href = data.edit_url;
        }
        btn.innerHTML = '🤖 {{ t("translate.ai_translate_create") }}';
        btn.disabled = false;
    })
    .catch(err => {
        alert('{{ t("common.error") }}: ' + err.message);
        btn.innerHTML = '🤖 {{ t("translate.ai_translate_create") }}';
        btn.disabled = false;
    });
}


async function checkSlug(contentType, excludeId) {
    const slugInput = document.getElementById('slug');
    const feedback = document.getElementById('slug-feedback');
    const slug = slugInput.value.trim();
    if (!slug) { feedback.textContent = '{{ t("editor.slug_help") }}'; feedback.style.color = 'var(--adm-text-muted)'; slugInput.style.borderColor = 'var(--adm-border-light)'; slugIsValid = true; return; }
    try {
        const response = await fetch('/admin/api/check-slug', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ slug, content_type: contentType, exclude_id: excludeId }) });
        const data = await response.json();
        if (data.available) { feedback.textContent = '✅ ' + data.message; feedback.style.color = 'var(--adm-success)'; slugInput.style.borderColor = 'var(--adm-success)'; slugIsValid = true; }
        else { feedback.textContent = '❌ ' + data.message; feedback.style.color = 'var(--adm-error)'; slugInput.style.borderColor = 'var(--adm-error)'; slugIsValid = false; }
    } catch (err) { feedback.textContent = '{{ t("editor.slug_check_error") }}'; feedback.style.color = 'var(--adm-text-muted)'; slugIsValid = true; }
}
function clearImageField(inputId) {
    document.getElementById(inputId).value = '';
    var wrap = document.getElementById(inputId + "_preview_wrap");
    if (wrap) wrap.style.display = "none";
    if (typeof updateImageHints === 'function') updateImageHints();
}
function updateImageHints() {
    var fi = document.getElementById("featured_image").value;
    var og = document.getElementById("og_image").value;
    var ogHint = document.getElementById("og_image_hint");
    var twHint = document.getElementById("twitter_image_hint");
    if (ogHint) {
        if (og) { ogHint.textContent = ''; }
        else if (fi) { ogHint.textContent = '\u2705 {{ t("seo.og_hint_uses_featured") }}'; ogHint.style.color = 'var(--adm-success)'; }
        else { ogHint.textContent = '{{ t("seo.og_hint_no_image") }}'; ogHint.style.color = 'var(--adm-text-muted)'; }
    }
    if (twHint) {
        var tw = document.getElementById("twitter_image").value;
        if (tw) { twHint.textContent = ''; }
        else if (og) { twHint.textContent = '\u2705 {{ t("seo.twitter_hint_uses_og") }}'; twHint.style.color = 'var(--adm-success)'; }
        else if (fi) { twHint.textContent = '\u2705 {{ t("seo.twitter_hint_uses_featured") }}'; twHint.style.color = 'var(--adm-success)'; }
        else { twHint.textContent = '{{ t("seo.twitter_hint_no_image") }}'; twHint.style.color = 'var(--adm-text-muted)'; }
    }
}
document.addEventListener("DOMContentLoaded", function() {
    ["featured_image", "og_image", "twitter_image"].forEach(function(id) {
        var input = document.getElementById(id);
        var preview = document.getElementById(id + "_preview");
        var wrap = document.getElementById(id + "_preview_wrap");
        if (input && preview && input.value) { preview.src = input.value; if (wrap) wrap.style.display = "block"; }
    });
    ["featured_image", "og_image", "twitter_image"].forEach(function(id) {
        var el = document.getElementById(id);
        if (el) { el.addEventListener("input", updateImageHints); }
    });
    updateImageHints();
});
function addFaqItem() {
    var container = document.getElementById('faqContainer');
    var item = document.createElement('div');
    item.className = 'faq-editor-item';
    item.innerHTML = '<div class="form-group"><label>{{ t("editor.faq_question") }}</label><input type="text" class="faq-question" placeholder="{{ t("editor.faq_question_placeholder") }}"></div><div class="form-group"><label>{{ t("editor.faq_answer") }}</label><textarea class="faq-answer" rows="2" placeholder="{{ t("editor.faq_answer_placeholder") }}"></textarea></div><button type="button" class="btn btn-danger btn-sm" onclick="this.closest(\'.faq-editor-item\').remove(); updateFaqJson();">🗑️ {{ t("editor.faq_remove") }}</button>';
    container.appendChild(item);
    item.querySelector('.faq-question').addEventListener('input', updateFaqJson);
    item.querySelector('.faq-answer').addEventListener('input', updateFaqJson);
}
function updateFaqJson() {
    var items = document.querySelectorAll('.faq-editor-item');
    var faq = [];
    items.forEach(function(item) {
        var q = item.querySelector('.faq-question').value.trim();
        var a = item.querySelector('.faq-answer').value.trim();
        if (q || a) faq.push({question: q, answer: a});
    });
    document.getElementById('faq_json').value = JSON.stringify(faq);
}
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.faq-question, .faq-answer').forEach(function(el) {
        el.addEventListener('input', updateFaqJson);
    });
});
function cleanSlugInput(input) {
    var v = input.value.toLowerCase();
    v = v.replace(/\s+/g, "-");
    v = v.replace(/[^a-z0-9\-]/g, "");
    v = v.replace(/-+/g, "-");
    v = v.replace(/^-|-$/g, "");
    input.value = v;
}
</script>
{% endblock %}
