{% 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="{{ admin_back_url('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="{{ admin_back_value() }}">
    <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 %}
{% include 'admin/editor_assets.html' %}
<script>
// Initialize AliothEditor (self-hosted, three tabs: Visual / Markdown / HTML)
AliothEditor.init({
    selector: '#content',
    height: 450,
    colors: true,  // color palette is content in emails, not site styling
    imagePicker: window.openImagePicker
});

// ── Form submit ──
document.getElementById('translateForm').addEventListener('submit', function(e) {
    if (typeof AliothEditor !== 'undefined') AliothEditor.triggerSave();
    if (!document.getElementById('subject').value.trim()) {
        e.preventDefault();
        AdminDialog.alert('{{ t("translate.title_required") }}').then(function() {
            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) {
        AdminDialog.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) {
                AdminDialog.confirm(data.error + '\n\n{{ t("translate.open_existing") }}').then(function(ok) {
                    if (ok) window.location.href = '/admin/newsletter/' + data.existing_id + '/edit';
                });
            } else {
                AdminDialog.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 AliothEditor !== 'undefined' && AliothEditor.get('content')) {
                    AliothEditor.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) {
            // Await the themed alert before navigating (native alert blocked).
            await AdminDialog.alert(data.message);
            window.location.href = data.edit_url;
            return;
        }
    } catch (err) {
        AdminDialog.alert('{{ t("common.error") }}: ' + err.message);
    }

    btn.innerHTML = '🤖 {{ t("translate.ai_translate_all") }}';
    btn.disabled = false;
}

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