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

{% block title %}{{ t('newsletter.translate_campaign') }}{% endblock %}

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

<!-- Source info -->
<div class="source-info">
    <h4>✉️ {{ t('newsletter.source_campaign') }} ({{ source.get_language_name() }})</h4>
    <p><strong>{{ source.subject }}</strong></p>
    <p>{{ t('newsletter.status_label') }}: {{ t('newsletter.status_' + source.status) }}</p>
    <a href="{{ url_for('admin_newsletter_edit', newsletter_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="subject" class="required">{{ t('newsletter.subject') }}</label>
                <input type="text" id="subject" name="subject" required
                       placeholder="{{ t('newsletter.translated_subject_placeholder') }}">
                <div class="help-text">{{ t('translate.original') }} {{ source.subject }}</div>
            </div>

            <div class="form-group">
                <label for="content">{{ t('newsletter.content') }}</label>
                <textarea id="content" name="content"
                          placeholder="{{ t('translate.translated_content_placeholder') }}">{{ source.content }}</textarea>
            </div>

            <!-- Recipient preview for target language -->
            <div class="form-section mt-5">
                <h3>👥 {{ t('newsletter.recipient_list') }}</h3>
                <div class="help-text mb-3">{{ t('newsletter.translate_recipients_help') }}</div>

                <div class="recipient-counter" id="recipient-counter">
                    <div class="recipient-counter-icon">👥</div>
                    <div class="recipient-counter-number" id="recipient-count">—</div>
                    <div class="recipient-counter-label">{{ t('newsletter.recipients') }}</div>
                </div>

                <!-- Read-only recipient table -->
                <div class="recipient-table-wrap">
                    <table class="recipient-table">
                        <thead>
                            <tr>
                                <th>{{ t('newsletter.sort_email') }}</th>
                                <th>{{ t('newsletter.sort_name') }}</th>
                                <th>{{ t('newsletter.sort_source') }}</th>
                            </tr>
                        </thead>
                        <tbody id="recipient-tbody">
                            <tr><td colspan="3" class="text-center p-4">{{ t('common.loading') }}</td></tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div class="pagination-footer" id="recipient-pagination-footer">
                    <div class="pagination" id="recipient-pagination"></div>
                    <div class="per-page-selector">
                        <span>{{ t('pagination.per_page') }}</span>
                        <select id="recipient-per-page" onchange="changeRecipientsPerPage(this.value)">
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                        <span>{{ t('pagination.per_page_suffix') }}</span>
                    </div>
                </div>

                <div class="recipient-list-footer">
                    <span id="recipient-list-info">—</span>
                </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('newsletter.status_' + tr.status) }}</span>
                        </span>
                        <a href="{{ url_for('admin_newsletter_edit', newsletter_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>
        </div>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script src="{{ url_for('static', filename='js/tinymce/tinymce.min.js') }}"></script>
<script>
tinymce.init({
    base_url: '/static/js/tinymce',
    license_key: 'gpl',
    convert_urls: false,
    relative_urls: false,
    remove_script_host: false,
    selector: '#content',
    height: 450,
    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 underline strikethrough | forecolor backcolor | alignleft aligncenter alignright | bullist numlist | link image table hr | code',
    skin: _tinyTheme.skin,
    content_style: _tinyTheme.content_style,
    // Library-only image insertion (opens the shared admin picker;
    // raw URL entry is blocked to match posts/pages behavior).
    file_picker_callback: function(callback, value, meta) {
        if (meta.filetype === 'image' && typeof window.openImagePicker === 'function') {
            window.openImagePicker(callback);
        }
    },
    setup: function(editor) {
        editor.on('change', function() { editor.save(); });
    }
});

// ── Form submit ──
document.getElementById('translateForm').addEventListener('submit', function(e) {
    if (typeof tinymce !== 'undefined') tinymce.triggerSave();
    if (!document.getElementById('subject').value.trim()) {
        e.preventDefault();
        alert('{{ t("translate.title_required") }}');
        document.getElementById('subject').focus();
        return false;
    }
});

// ============================================================
// RECIPIENT PREVIEW (read-only, for target language)
// ============================================================

var currentPage = 1;
var perPage = 20;

function loadTranslateRecipients() {
    var targetLang = document.getElementById('language').value;
    if (!targetLang) {
        document.getElementById('recipient-count').textContent = '—';
        document.getElementById('recipient-tbody').innerHTML =
            '<tr><td colspan="3" class="text-center p-4">{{ t("translate.select_language_first") }}</td></tr>';
        return;
    }

    var params = new URLSearchParams();
    params.set('langs', targetLang);
    params.set('page', currentPage);
    params.set('per_page', perPage);

    fetch('{{ url_for("admin_newsletter_recipients_api") }}?' + params.toString())
        .then(function(r) { return r.json(); })
        .then(function(data) {
            document.getElementById('recipient-count').textContent = data.count;
            renderTranslateRecipients(data.items || []);
            renderTranslatePagination(data.page, data.total_pages, data.total);
            document.getElementById('recipient-list-info').textContent =
                data.total > 0
                    ? '{{ t("newsletter.showing_recipients") }}'.replace('{shown}', data.items.length).replace('{total}', data.total)
                    : '—';
        })
        .catch(function() {
            document.getElementById('recipient-count').textContent = '?';
        });
}

function renderTranslateRecipients(items) {
    var tbody = document.getElementById('recipient-tbody');

    if (items.length === 0) {
        tbody.innerHTML = '<tr><td colspan="3" class="text-center p-4">' +
            '{{ t("newsletter.no_recipients_yet") }}</td></tr>';
        return;
    }

    tbody.innerHTML = items.map(function(r) {
        var badges = '';
        if (r.email_confirmed === true) badges += ' <span class="badge-confirmed">{{ t("newsletter.confirmed_badge") }}</span>';
        if (r.email_confirmed === false) badges += ' <span class="badge-pending">{{ t("newsletter.pending_badge") }}</span>';

        return '<tr>' +
            '<td class="td-truncate">' + escapeHtml(r.email) + '</td>' +
            '<td class="td-truncate">' + escapeHtml(r.name || '—') + badges + '</td>' +
            '<td class="td-truncate">' + escapeHtml(r.source || '—') + '</td>' +
            '</tr>';
    }).join('');
}

function renderTranslatePagination(page, totalPages, total) {
    var footer = document.getElementById('recipient-pagination-footer');
    var container = document.getElementById('recipient-pagination');

    footer.style.display = '';

    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }

    var html = '';
    if (page > 1) {
        html += '<a href="#" onclick="loadTranslatePage(' + (page - 1) + ');return false;">«</a>';
    }

    var startPage = Math.max(1, page - 2);
    var endPage = Math.min(totalPages, page + 2);

    if (startPage > 1) {
        html += '<a href="#" onclick="loadTranslatePage(1);return false;">1</a>';
        if (startPage > 2) html += '<span class="pagination-ellipsis">…</span>';
    }

    for (var i = startPage; i <= endPage; i++) {
        if (i === page) {
            html += '<span class="current">' + i + '</span>';
        } else {
            html += '<a href="#" onclick="loadTranslatePage(' + i + ');return false;">' + i + '</a>';
        }
    }

    if (endPage < totalPages) {
        if (endPage < totalPages - 1) html += '<span class="pagination-ellipsis">…</span>';
        html += '<a href="#" onclick="loadTranslatePage(' + totalPages + ');return false;">' + totalPages + '</a>';
    }

    if (page < totalPages) {
        html += '<a href="#" onclick="loadTranslatePage(' + (page + 1) + ');return false;">»</a>';
    }

    container.innerHTML = html;
}

function loadTranslatePage(page) {
    currentPage = page;
    loadTranslateRecipients();
}

function changeRecipientsPerPage(val) {
    perPage = parseInt(val, 10) || 20;
    currentPage = 1;
    loadTranslateRecipients();
}

function escapeHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

// ── Update recipients when target language changes ──
document.getElementById('language').addEventListener('change', function() {
    currentPage = 1;
    loadTranslateRecipients();
});

// ── Initial load ──
loadTranslateRecipients();

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

async function aiTranslateAll() {
    var langSelect = document.getElementById('language');
    var targetLang = langSelect.value;
    var targetLangName = langSelect.options[langSelect.selectedIndex].text;
    var instructions = (document.getElementById('translate_instructions') || {}).value || '';

    if (!targetLang) {
        alert('{{ t("translate.select_language_first") }}');
        return;
    }

    var btn = document.getElementById('btnTranslateAll');
    btn.disabled = true;
    btn.innerHTML = '⏳ {{ t("translate.translating_to") }}'.replace('{lang}', targetLangName);

    try {
        var response = await fetch('/admin/api/translate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                content_type: 'newsletter',
                source_id: {{ source.id }},
                target_lang: targetLang,
                instructions: instructions,
                return_fields: true
            })
        });
        var data = await response.json();

        if (data.error) {
            if (data.existing_id) {
                if (confirm(data.error + '\n\n{{ t("translate.open_existing") }}')) {
                    window.location.href = '/admin/newsletter/' + data.existing_id + '/edit';
                }
            } else {
                alert('{{ t("common.error") }}: ' + data.error);
            }
            btn.innerHTML = '🤖 {{ t("translate.ai_translate_all") }}';
            btn.disabled = false;
            return;
        }

        // Fill fields with AI translation
        if (data.translated) {
            if (data.translated.subject) {
                document.getElementById('subject').value = data.translated.subject;
            }
            if (data.translated.content) {
                if (typeof tinymce !== 'undefined' && tinymce.get('content')) {
                    tinymce.get('content').setContent(data.translated.content);
                } else {
                    document.getElementById('content').value = data.translated.content;
                }
            }
        }

        // Fallback: if API created a draft instead of returning fields, redirect
        if (data.edit_url) {
            alert(data.message);
            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;
}

// ============================================================
</script>
{% endblock %}
