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

{% block title %}{{ t('translate.create_translation_post') }}{% endblock %}


{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>🌍 {{ t('translate.creating_translation') }}</h2>
        <p>{{ t('translate.create_translation_post') }}</p>
    </div>
    <div class="btn-group">
        <button type="submit" form="translateForm" name="status" value="draft" class="btn btn-secondary btn-sm">📝 {{ t('translate.save_translation_draft') }}</button>
        <button type="submit" form="translateForm" name="status" value="published" class="btn btn-primary btn-sm">🚀 {{ t('translate.publish_translation') }}</button>
            <a href="{{ request.args.get('return_to') or request.referrer or url_for('admin_posts_list') }}" class="btn btn-secondary btn-sm">{{ t('common.cancel') }}</a>
    </div>
</div>

<!-- Source info -->
<div class="source-info">
    <h4>📄 {{ t('translate.source_page') }} ({{ source.get_language_name() }})</h4>
    <p><strong>{{ source.title }}</strong></p>
    <p>{{ t('table.status') }}: {{ t('common.status_' + source.status) }} · {{ t('editor.slug_label') }}: /{{ source.slug }}</p>
    <a href="{{ url_for('admin_posts_edit', post_id=source.id) }}">← {{ t('translate.back_to_original') }}</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="{{ request.args.get('return_to') or request.referrer or '' }}">
    <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" required placeholder="{{ t('translate.translated_title_placeholder') }}">
                <div class="help-text">{{ t('translate.original') }} {{ source.title }}</div>
            </div>
            <div class="form-group">
                <label for="slug">{{ t('editor.slug_label') }}</label>
                <input type="text" id="slug" name="slug" oninput="cleanSlugInput(this)" placeholder="{{ t('translate.translated_slug_placeholder') }}" onblur="checkSlug('post', null)">
                <div id="slug-feedback" class="help-text">{{ t('editor.slug_help') }}. {{ t('translate.original') }} /{{ source.slug }}</div>
            </div>
            <div class="form-group">
                <label for="excerpt">{{ t('editor.excerpt_label') }}</label>
                <textarea id="excerpt" name="excerpt" rows="3" placeholder="{{ t('translate.translated_excerpt_placeholder') }}">{{ source.excerpt or '' }}</textarea>
            </div>
            <div class="form-group">
                <label for="content">{{ t('editor.content_label') }}</label>
                <textarea id="content" name="content" placeholder="{{ t('translate.translated_content_placeholder') }}">{{ source.content }}</textarea>
            </div>

            <!-- SEO Meta Tags -->
            <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" maxlength="60" value="{{ source.meta_title or '' }}" placeholder="{{ t('seo.meta_title_placeholder') }}">
                    </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" placeholder="{{ t('seo.meta_description_placeholder') }}">{{ source.meta_description or '' }}</textarea>
                    </div>
                    <div class="form-group">
                        <label for="meta_keywords">{{ t('seo.keywords') }}</label>
                        <input type="text" id="meta_keywords" name="meta_keywords" value="{{ source.meta_keywords or '' }}" placeholder="{{ t('seo.keywords_placeholder') }}">
                        <div class="help-text">{{ t('translate.keywords_no_translation') }}</div>
                    </div>
                    <div class="form-group">
                        <label for="canonical_url">{{ t('seo.canonical_url') }}</label>
                        <input type="url" id="canonical_url" name="canonical_url" placeholder="{{ t('seo.canonical_url_placeholder') }}">
                    </div>
                </div>
            </div>

            <!-- Open Graph -->
            <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="{{ source.og_title or '' }}" placeholder="{{ t('seo.og_title_placeholder') }}">
                    </div>
                    <div class="form-group">
                        <label for="og_description">{{ t('seo.og_description') }}</label>
                        <textarea id="og_description" name="og_description" rows="2" placeholder="{{ t('seo.og_description_placeholder') }}">{{ source.og_description or '' }}</textarea>
                    </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="{{ source.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" class="btn-remove-preview" onclick="clearImageField('og_image')" title="{{ t('common.remove') }}">✕</button>
                        </div>
                        <div class="help-text" id="og_image_hint">{{ t('translate.image_copied') }}</div>
                    </div>
                </div>
            </div>

            <!-- Twitter Card -->
            <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="{{ source.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">{{ source.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="{{ source.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" class="btn-remove-preview" onclick="clearImageField('twitter_image')" title="{{ t('common.remove') }}">✕</button>
                        </div>
                        <div class="help-text" id="twitter_image_hint"></div>
                    </div>
                </div>
            </div>

            <!-- Featured Image -->
            <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="{{ source.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" class="btn-remove-preview" onclick="clearImageField('featured_image')" title="{{ t('common.remove') }}">✕</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">{{ t('seo.featured_image_alt') }}</label>
                        <input type="text" id="featured_image_alt" name="featured_image_alt" value="{{ source.featured_image_alt or '' }}">
                    </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">{{ source.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 source.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="{{ source.faq_json or '[]' }}">
                </div>
            </div>

        </div>

        <!-- SIDEBAR (right) -->
        <div class="editor-sidebar">
            <!-- Target Language & AI -->
            <div class="form-section">
                <h3>🌍 {{ t('translate.target_language') }}</h3>
                <div class="form-group">
                    <label for="language" class="required">{{ t('translate.translate_to') }}</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('translate.all_languages_done') }}</div>
                    {% endif %}
                </div>
                
                <button type="button" class="ai-translate-all" onclick="aiTranslateAll()" id="btnTranslateAll" {% if not missing_languages %}disabled{% endif %}>
                    🤖 {{ t('translate.ai_translate_all') }}
                </button>
                <div class="form-group mt-3">
                    <label for="translate_instructions">{{ t('translate.instructions_label') }}</label>
                    <textarea id="translate_instructions" rows="2" class="text-sm" placeholder="{{ t('translate.instructions_placeholder') }}"></textarea>
                </div>
                <div class="help-text">{{ t('translate.ai_translate_all_help') }}</div>
            </div>

            <!-- Existing translations -->
            <div class="form-section">
                <h3>📋 {{ t('translate.existing_translations') }}</h3>
                <div class="mb-2">
                    <span class="text-bold">{{ source.get_language_name() }}</span>
                    <span class="badge-source">{{ t('translate.source_badge') }}</span>
                </div>
                {% 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_posts_edit', post_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 %}
            </div>

            <!-- Categorization (inherited from source) -->
            <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="{{ source.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('translate.copied_from_source') }}</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 source.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 source.show_author %}checked{% endif %}>
                        {{ t('editor.show_author') }}
                    </label>
                </div>
                <div class="help-text">{{ t('editor.display_help') }}</div>
            </div>
        </div>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script src="{{ url_for('static', filename='js/tinymce/tinymce.min.js') }}"></script>
<script>
function toggleSection(header) {
    const content = header.nextElementSibling;
    const arrow = header.querySelector('.arrow');
    content.classList.toggle('active');
    arrow.classList.toggle('active');
}

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,
    plugins: ['advlist','autolink','lists','link','image','charmap','preview','anchor','searchreplace','visualblocks','code','fullscreen','insertdatetime','media','table','help','wordcount'],
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | link image | code',
    skin: _tinyTheme.skin,
    content_style: _tinyTheme.content_style,
    file_picker_callback: function(cb, val, meta) { if (meta.filetype === 'image') openImagePicker(cb); },
    setup: function(editor) { editor.on('change', function() { editor.save(); }); }
});

let slugIsValid = true;
document.getElementById('translateForm').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; }
    if (!document.getElementById('title').value.trim()) { e.preventDefault(); alert('{{ t("editor.content_required") }}'); return false; }
});

// ============================================================
// AI: TRANSLATE ALL FIELDS AT ONCE
// ============================================================

async function aiTranslateAll() {
    const langSelect = document.getElementById('language');
    const targetLang = langSelect.value;
    const targetLangName = langSelect.options[langSelect.selectedIndex].text;
    const instructions = (document.getElementById('translate_instructions') || {}).value || '';
    
    if (!targetLang) { alert('{{ t("translate.select_language_first") }}'); return; }
    
    const btn = document.getElementById('btnTranslateAll');
    btn.disabled = true;
    btn.innerHTML = '⏳ {{ t("translate.translating_to") }}'.replace('{lang}', targetLangName);
    
    try {
        const response = await fetch('/admin/api/translate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                content_type: 'post',
                source_id: {{ source.id }},
                target_lang: targetLang,
                prefill_only: true,
                instructions: instructions
            })
        });
        const data = await response.json();
        
        if (data.error) {
            // If translation already exists as a saved post, offer to go there
            if (data.existing_id) {
                if (confirm(data.error + '\n\n{{ t("translate.open_existing") }}')) {
                    window.location.href = '/admin/posts/' + data.existing_id + '/edit';
                }
            } else {
                alert('{{ t("common.error") }}: ' + data.error);
            }
            btn.innerHTML = '🤖 {{ t('translate.ai_translate_all') }}';
            btn.disabled = false;
            return;
        }
        
        // AI API created a draft post — redirect to edit it
        if (data.edit_url) {
            alert(data.message + '\n\n{{ t("translate.redirecting_to_edit") }}');
            window.location.href = data.edit_url;
            return;
        }
    } catch (err) {
        alert('{{ t("common.error") }}: ' + err.message);
    }
    
    btn.innerHTML = '🤖 {{ t('translate.ai_translate_all') }}';
    btn.disabled = false;
}

// ============================================================


function setSlugState(feedback, slugInput, state) {
    feedback.classList.remove('slug-valid', 'slug-error', 'text-muted');
    slugInput.classList.remove('slug-input-valid', 'slug-input-error');
    if (state === 'valid') { feedback.classList.add('slug-valid'); slugInput.classList.add('slug-input-valid'); }
    else if (state === 'error') { feedback.classList.add('slug-error'); slugInput.classList.add('slug-input-error'); }
    else { feedback.classList.add('text-muted'); }
}
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") }}'; setSlugState(feedback, slugInput, 'default'); 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; setSlugState(feedback, slugInput, 'valid'); slugIsValid = true; }
        else { feedback.textContent = '❌ ' + data.message; setSlugState(feedback, slugInput, 'error'); slugIsValid = false; }
    } catch (err) { feedback.textContent = '{{ t("editor.slug_check_error") }}'; setSlugState(feedback, slugInput, 'default'); 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 setHintState(el, text, state) {
    el.textContent = text;
    el.classList.remove('hint-success', 'hint-muted');
    if (state) el.classList.add(state);
}
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) { setHintState(ogHint, '', ''); }
        else if (fi) { setHintState(ogHint, '\u2705 {{ t("seo.og_hint_uses_featured") }}', 'hint-success'); }
        else { setHintState(ogHint, '{{ t("seo.og_hint_no_image") }}', 'hint-muted'); }
    }
    if (twHint) {
        var tw = document.getElementById("twitter_image").value;
        if (tw) { setHintState(twHint, '', ''); }
        else if (og || fi) { setHintState(twHint, og ? '\u2705 {{ t("seo.twitter_hint_uses_og") }}' : '\u2705 {{ t("seo.twitter_hint_uses_featured") }}', 'hint-success'); }
        else { setHintState(twHint, '{{ t("seo.og_hint_no_image") }}', 'hint-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 %}
