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

{% block title %}{% if is_sent %}{{ t('newsletter.view_campaign') }}{% else %}{{ t('newsletter.edit_campaign') }}{% endif %}{% endblock %}

{% block content %}
{% set is_sent = newsletter.status == 'sent' %}

<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>{% if is_sent %}👁️ {{ t('newsletter.view_campaign') }}{% else %}✏️ {{ t('newsletter.edit_campaign') }}{% endif %}</h2>
        <p>{{ newsletter.subject }}</p>
    </div>
    <div class="btn-group">
        {% if not is_sent %}
        <button type="submit" form="editForm" class="btn btn-primary btn-sm">💾 {{ t('newsletter.save_draft') }}</button>
        {% endif %}
        <a href="{{ admin_back_url('admin_newsletter_list') }}" class="btn btn-secondary btn-sm">{{ t('common.back') }}</a>
        <form method="POST" action="{{ url_for('admin_newsletter_delete', newsletter_id=newsletter.id) }}" class="d-inline" data-confirm="{{ t('newsletter.delete_confirm') }}" data-confirm-danger>
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <input type="hidden" name="return_to" value="{{ admin_back_value() }}">
            <button type="submit" class="btn btn-danger btn-sm">🗑️ {{ t('table.delete') }}</button>
        </form>
    </div>
</div>

<form method="POST" id="editForm" class="container-xl" data-inline-save>
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="return_to" value="{{ admin_back_value() }}">
    <div id="excluded-inputs"></div>
    <input type="hidden" name="imported_emails" id="imported-emails-json" value="{{ newsletter.imported_emails if newsletter.imported_emails else '[]' }}">

    <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"
                       value="{{ newsletter.subject }}"
                       placeholder="{{ t('newsletter.subject_placeholder') }}"
                       {{ 'disabled' if is_sent }} required>
            </div>

            <div class="form-group">
                <label for="content">{{ t('newsletter.content') }}</label>
                <textarea id="content" name="content"
                          {{ 'disabled' if is_sent }}>{{ newsletter.content }}</textarea>
            </div>

            <!-- Audience filters (above recipient list) — only for drafts -->
            {% if not is_sent %}
            <div class="form-section mt-5">
                <h3>🎯 {{ t('newsletter.audience') }}</h3>

                <!-- Live recipient counter -->
                <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>

                <!-- Language filter (collapsible) -->
                {% set selected_langs = newsletter.get_target_languages() %}
                <div class="collapsible">
                    <div class="collapsible-header" onclick="toggleSection(this)">
                        <span>🌐 {{ t('newsletter.target_languages') }}{% if selected_langs %} <span class="language-badge">{{ selected_langs|length }}</span>{% endif %}</span>
                        <span class="arrow">▶</span>
                    </div>
                    <div class="collapsible-content">
                        <div class="help-text mb-2">{{ t('newsletter.target_languages_help') }}</div>
                        <div class="checkbox-group">
                            {% for lang in active_languages %}
                            <label class="checkbox-label">
                                <input type="checkbox" name="target_languages" value="{{ lang.code }}"
                                       class="lang-checkbox"
                                       {{ 'checked' if lang.code in selected_langs }}
                                       {{ 'disabled' if is_sent }}>
                                <img src="{{ url_for('static', filename='i18n/' + lang.code + '.svg') }}" alt="" class="lang-flag">
                                {{ lang.name }}
                                {% if lang.code in recipient_stats %}
                                    <span class="badge badge-muted">{{ recipient_stats[lang.code] }}</span>
                                {% endif %}
                            </label>
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <!-- Form filter (collapsible) -->
                {% set selected_forms = newsletter.get_target_form_ids() %}
                <div class="collapsible">
                    <div class="collapsible-header" onclick="toggleSection(this)">
                        <span>📋 {{ t('newsletter.target_forms') }}{% if selected_forms %} <span class="language-badge">{{ selected_forms|length }}</span>{% endif %}</span>
                        <span class="arrow">▶</span>
                    </div>
                    <div class="collapsible-content">
                        <div class="help-text mb-2">{{ t('newsletter.target_forms_help') }}</div>
                        <div class="checkbox-group">
                            {% for f in email_forms %}
                            <label class="checkbox-label">
                                <input type="checkbox" name="target_form_ids" value="{{ f.id }}"
                                       class="form-checkbox"
                                       {{ 'checked' if f.id in selected_forms }}
                                       {{ 'disabled' if is_sent }}>
                                {{ f.title }}
                                <span class="language-badge">{{ f.language }}</span>
                                {% if f.id in form_stats %}
                                    <span class="badge badge-muted">{{ form_stats[f.id] }} ✉️</span>
                                {% endif %}
                            </label>
                            {% endfor %}
                            {% if not email_forms %}
                            <p class="text-sm text-muted">{{ t('newsletter.no_forms_with_email') }}</p>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <!-- Confirmed only filter -->
                <hr class="section-divider">
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="confirmed_only" id="confirmedOnly"
                               {{ 'checked' if newsletter.confirmed_only }}
                               {{ 'disabled' if is_sent }}>
                        {{ t('newsletter.confirmed_only') }}
                    </label>
                    <div class="help-text">{{ t('newsletter.confirmed_only_help') }}</div>
                </div>
            </div>
            {% endif %}

            <!-- Recipient list (below editor) — only for drafts -->
            {% if not is_sent %}
            <div class="form-section mt-5">
                <h3>👥 {{ t('newsletter.recipient_list') }}</h3>
                <div class="help-text mb-3">{{ t('newsletter.recipient_list_help') }}</div>

                <!-- CSV Import -->
                <div class="csv-import-zone" onclick="document.getElementById('csv-file-input').click()">
                    <input type="file" id="csv-file-input" accept=".csv,.txt" onchange="handleCSVImport(this)">
                    📎 {{ t('newsletter.import_csv') }}
                    <div class="help-text mt-1">{{ t('newsletter.import_csv_help') }}</div>
                </div>

                <!-- Toolbar: search + sort -->
                <div class="recipient-list-toolbar">
                    <input type="text" class="recipient-search" id="recipient-search"
                           placeholder="{{ t('newsletter.search_recipients') }}"
                           oninput="onRecipientSearch()">
                    <button type="button" class="recipient-sort-btn active" data-sort="email" onclick="sortRecipients('email', this)">{{ t('newsletter.sort_email') }} ↕</button>
                    <button type="button" class="recipient-sort-btn" data-sort="name" onclick="sortRecipients('name', this)">{{ t('newsletter.sort_name') }} ↕</button>
                    <button type="button" class="recipient-sort-btn" data-sort="source" onclick="sortRecipients('source', this)">{{ t('newsletter.sort_source') }} ↕</button>
                </div>

                <!-- Recipients table -->
                <div class="recipient-table-wrap">
                    <table class="recipient-table">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="select-all-cb" checked onchange="toggleAllRecipients(this.checked)" title="{{ t('newsletter.select_all') }}"></th>
                                <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="4" class="text-center p-4">{{ t('common.loading') }}</td></tr>
                        </tbody>
                    </table>
                </div>

                <!-- Footer: count + bulk actions -->
                <div class="recipient-list-footer">
                    <span id="recipient-list-info">—</span>
                    <span class="flex gap-2 items-center flex-wrap">
                        <a href="#" onclick="toggleAllRecipients(true);return false;" class="btn btn-secondary">{{ t('newsletter.select_all') }}</a>
                        <a href="#" onclick="toggleAllRecipients(false);return false;" class="btn btn-secondary">{{ t('newsletter.deselect_all') }}</a>
                    </span>
                </div>
            </div>

            <!-- Pagination (outside card — matches CMS-wide pattern) -->
            <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>
            {% else %}
            <!-- Sent: show recipient stats -->
            <div class="form-section mt-5">
                <h3>👥 {{ t('newsletter.recipient_list') }}</h3>
                <div class="info-box">
                    <p>✅ {{ t('newsletter.sent_info') }}</p>
                    <p><strong>{{ t('newsletter.recipients') }}:</strong> {{ newsletter.recipients_count }}</p>
                    {% if newsletter.failed_count > 0 %}
                    <p><strong>{{ t('newsletter.failed') }}:</strong> {{ newsletter.failed_count }}</p>
                    {% endif %}
                </div>
            </div>
            {% endif %}
        </div>

        <!-- ============================================================ -->
        <!-- SIDEBAR (right) -->
        <!-- ============================================================ -->
        <div class="editor-sidebar">
            <!-- 1. Status & Language -->
            <div class="form-section">
                <h3>📊 {{ t('editor.status_language') }}</h3>
                <div class="form-group">
                    <label for="language">{{ t('newsletter.campaign_language_help') }}</label>
                    <select id="language" name="language" {{ 'disabled' if is_sent }}>
                        {% for lang in active_languages %}
                        <option value="{{ lang.code }}" data-name="{{ lang.name }}" {% if newsletter.language == lang.code %}selected{% endif %}>{{ lang.name }}</option>
                        {% endfor %}
                        {% if newsletter.language and newsletter.language not in active_languages|map(attribute='code')|list %}
                        <option value="{{ newsletter.language }}" data-name="{{ newsletter.get_language_name() }}" selected>{{ newsletter.get_language_name() }} — {{ t('common.language_deactivated') }}</option>
                        {% endif %}
                    </select>
                </div>
            </div>

            <!-- 2. Actions -->
            <div class="form-section">
                <h3>🚀 {{ t('newsletter.actions') }}</h3>

                {% if is_sent %}
                    <div class="info-box">
                        <p>✅ {{ t('newsletter.sent_info') }}</p>
                        <p><strong>{{ t('newsletter.sent_at') }}:</strong> {{ newsletter.sent_at|format_datetime if newsletter.sent_at }}</p>
                    </div>
                {% else %}
                    <button type="submit" class="sidebar-btn btn-secondary mb-2">
                        💾 {{ t('newsletter.save_draft') }}
                    </button>

                    <!-- Test send -->
                    <div class="form-group mt-3">
                        <label>{{ t('newsletter.test_send') }}</label>
                        <div class="flex gap-2">
                            <input type="email" id="test-email" value="{{ current_user.email }}"
                                   class="flex-1" placeholder="email@example.com">
                            <button type="button" class="btn btn-secondary btn-sm" onclick="sendTestEmail()">
                                🧪 {{ t('newsletter.send_test') }}
                            </button>
                        </div>
                    </div>

                    <!-- Send for real -->
                    <div class="mt-3">
                        <button type="button" class="sidebar-btn sidebar-btn--primary" onclick="confirmSend()">
                            🚀 {{ t('newsletter.send_now') }}
                        </button>
                        <div class="help-text mt-1">{{ t('newsletter.send_warning') }}</div>
                    </div>
                {% endif %}
            </div>

            <!-- 3. AI Tools -->
            {% if not is_sent %}
            <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>
                <div class="help-text mt-2">{{ t('newsletter.ai_generate_help') }}</div>
            </div>
            {% endif %}

            <!-- 4. Translations -->
            <div class="form-section">
                <h3>🌍 {{ t('translate.translations_title') }}</h3>

                <!-- Current language -->
                <div class="mb-3">
                    <span class="current-lang-badge">{{ newsletter.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('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 %}

                <!-- 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_newsletter_translate', newsletter_id=newsletter.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" onclick="aiCreateTranslation()" id="btnCreateTranslation">
                        🤖 {{ t('translate.ai_translate_create') }}
                    </button>
                    <div class="help-text">{{ t('newsletter.ai_translate_help') }}</div>
                </div>
                {% endif %}
            </div>

            <!-- 5. Info (timestamps) -->
            <div class="form-section">
                <h3>📅 {{ t('editor.info') }}</h3>
                <p class="sidebar-meta">
                    <strong>{{ t('editor.created') }}</strong><br>
                    {{ newsletter.created_at|format_datetime }}
                </p>
                <p class="sidebar-meta">
                    <strong>{{ t('editor.last_updated') }}</strong><br>
                    {{ newsletter.updated_at|format_datetime }}
                </p>
                {% if newsletter.sent_at %}
                <p class="sidebar-meta">
                    <strong>{{ t('newsletter.sent_at') }}</strong><br>
                    {{ newsletter.sent_at|format_datetime }}
                </p>
                {% endif %}
            </div>

        </div>
    </div>
</form>

<!-- Test email hidden form -->
<form id="test-form" method="POST" action="{{ url_for('admin_newsletter_test', newsletter_id=newsletter.id) }}" class="d-none">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="test_email" id="test-email-hidden">
</form>

<!-- Send hidden form -->
<form id="send-form" method="POST" action="{{ url_for('admin_newsletter_send', newsletter_id=newsletter.id) }}" class="d-none">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="return_to" value="{{ admin_back_value() }}">
</form>
{% endblock %}

{% block extra_js %}
{% include 'admin/editor_assets.html' %}
<script>
{% if not is_sent %}
// ── AliothEditor ──
// 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
});
{% endif %}

// ── Form submit: sync editor ──
document.getElementById('editForm').addEventListener('submit', function(e) {
    if (typeof AliothEditor !== 'undefined') AliothEditor.triggerSave();
    syncExcludedInputs();
});

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

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

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

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

function applyAIResult(result, mode) {
    if (!result) return;
    if (result.title) {
        document.getElementById('subject').value = result.title;
    }
    if (result.content) {
        if (typeof AliothEditor !== 'undefined' && AliothEditor.get('content')) {
            AliothEditor.get('content').setContent(result.content);
        } else {
            document.getElementById('content').value = result.content;
        }
    }
}

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

function aiCreateTranslation() {
    var langSelect = document.getElementById('newTranslationLang');
    var targetLang = langSelect.value;

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

    var targetLangName = langSelect.options[langSelect.selectedIndex].text;

    AdminDialog.confirm('{{ t("newsletter.translate_confirm")|replace("\n", "\\n") }}'.replace('{lang}', targetLangName)).then(function(ok) {
    if (!ok) return;
    var 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: 'newsletter',
            source_id: {{ newsletter.id }},
            target_lang: targetLang
        })
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
        if (data.error) {
            AdminDialog.alert('{{ t("common.error") }}: ' + data.error).then(function() {
                if (data.existing_id) {
                    AdminDialog.confirm('{{ t("translate.open_existing") }}').then(function(ok2) {
                        if (ok2) window.location.href = '/admin/newsletter/' + data.existing_id + '/edit';
                    });
                }
            });
        } else {
            // Await the themed alert before navigating (native alert blocked).
            AdminDialog.alert(data.message).then(function() {
                window.location.href = data.edit_url;
            });
        }
        btn.innerHTML = '🤖 {{ t("translate.ai_translate_create") }}';
        btn.disabled = false;
    })
    .catch(function(err) {
        AdminDialog.alert('{{ t("common.error") }}: ' + err.message);
        btn.innerHTML = '🤖 {{ t("translate.ai_translate_create") }}';
        btn.disabled = false;
    });
    });
}

// ============================================================
// TEST EMAIL & SEND
// ============================================================

function sendTestEmail() {
    var email = document.getElementById('test-email').value;
    if (!email) return;
    if (typeof AliothEditor !== 'undefined') AliothEditor.triggerSave();
    document.getElementById('test-email-hidden').value = email;
    document.getElementById('test-form').querySelector('[name=test_email]').value = email;
    document.getElementById('test-form').submit();
}

function confirmSend() {
    var count = document.getElementById('recipient-count').textContent;
    if (count === '0' || count === '—' || count === '?') {
        AdminDialog.alert('{{ t("newsletter.no_recipients_alert") }}');
        return;
    }
    AdminDialog.confirm('{{ t("newsletter.send_confirm") }}'.replace('{count}', count)).then(function(ok) {
        if (!ok) return;
        if (typeof AliothEditor !== 'undefined') AliothEditor.triggerSave();
        syncExcludedInputs();
        document.getElementById('send-form').submit();
    });
}

// ============================================================
// RECIPIENT LIST
// ============================================================

{% if not is_sent %}
var excludedSet = new Set({{ newsletter.get_excluded_emails()|tojson }});
var importedEmails = JSON.parse(document.getElementById('imported-emails-json').value || '[]');
var currentSort = 'email';
var sortAsc = true;
var currentPage = 1;
var perPage = 20;
var searchTimer = null;

function syncExcludedInputs() {
    var container = document.getElementById('excluded-inputs');
    container.innerHTML = '';
    excludedSet.forEach(function(email) {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'excluded_emails';
        input.value = email;
        container.appendChild(input);
    });
}

// ── Build URL params shared by all recipient requests ──
function buildRecipientParams() {
    var params = new URLSearchParams();
    document.querySelectorAll('.lang-checkbox:checked').forEach(function(cb) { params.append('langs', cb.value); });
    document.querySelectorAll('.form-checkbox:checked').forEach(function(cb) { params.append('form_ids', cb.value); });
    excludedSet.forEach(function(e) { params.append('excluded', e); });
    params.append('imported', JSON.stringify(importedEmails));
    return params;
}

function updateRecipientList() {
    var params = buildRecipientParams();
    params.set('page', currentPage);
    params.set('per_page', perPage);
    params.set('sort', currentSort);
    params.set('sort_dir', sortAsc ? 'asc' : 'desc');

    var search = (document.getElementById('recipient-search').value || '').trim();
    if (search) params.set('search', search);

    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;
            renderRecipientTable(data.items || []);
            renderRecipientPagination(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 renderRecipientTable(items) {
    var tbody = document.getElementById('recipient-tbody');

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

    tbody.innerHTML = items.map(function(r) {
        var isExcluded = excludedSet.has(r.email);
        var checked = !isExcluded ? 'checked' : '';
        var rowClass = isExcluded ? 'excluded' : '';
        var badges = '';
        if (r.source === 'import') badges += ' <span class="badge-imported">{{ t("newsletter.imported_badge") }}</span>';
        if (r.email_confirmed === true) badges += ' <span class="badge-confirmed">{{ t("newsletter.confirmed_badge") }}</span>';
        if (r.email_confirmed === false && r.source !== 'import') badges += ' <span class="badge-pending">{{ t("newsletter.pending_badge") }}</span>';

        return '<tr class="' + rowClass + '">' +
            '<td><input type="checkbox" ' + checked + ' onchange="toggleRecipient(\'' + r.email.replace(/'/g, "\\'") + '\', this.checked)"></td>' +
            '<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 renderRecipientPagination(page, totalPages, total) {
    var footer = document.getElementById('recipient-pagination-footer');
    var container = document.getElementById('recipient-pagination');

    // Always show footer (per-page selector), hide only page numbers when single page
    footer.style.display = '';

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

    var html = '';
    if (page > 1) {
        html += '<a href="#" onclick="loadRecipientPage(' + (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="loadRecipientPage(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="loadRecipientPage(' + i + ');return false;">' + i + '</a>';
        }
    }

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

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

    container.innerHTML = html;
}

function loadRecipientPage(page) {
    currentPage = page;
    updateRecipientList();
}

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

// ── Search with debounce ──
function onRecipientSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(function() {
        currentPage = 1;
        updateRecipientList();
    }, 300);
}

function sortRecipients(field, btn) {
    if (currentSort === field) {
        sortAsc = !sortAsc;
    } else {
        currentSort = field;
        sortAsc = true;
    }
    document.querySelectorAll('.recipient-sort-btn').forEach(function(b) { b.classList.remove('active'); });
    btn.classList.add('active');
    currentPage = 1;
    updateRecipientList();
}

function toggleRecipient(email, included) {
    if (included) {
        excludedSet.delete(email);
    } else {
        excludedSet.add(email);
    }
    syncExcludedInputs();
    // Re-fetch current page to get correct count from server
    updateRecipientList();
}

function toggleAllRecipients(include) {
    if (include) {
        // Select all — clear excludedSet, reload page
        excludedSet.clear();
        syncExcludedInputs();
        updateRecipientList();
        document.getElementById('select-all-cb').checked = true;
        return;
    }

    // Deselect all — need ALL emails from server (across all pages)
    var params = buildRecipientParams();
    params.set('emails_only', 'true');

    fetch('{{ url_for("admin_newsletter_recipients_api") }}?' + params.toString())
        .then(function(r) { return r.json(); })
        .then(function(data) {
            (data.emails || []).forEach(function(email) {
                excludedSet.add(email);
            });
            document.getElementById('select-all-cb').checked = false;
            document.getElementById('recipient-count').textContent = '0';
            syncExcludedInputs();
            updateRecipientList();
        });
}

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

// ── CSV Import ──
function handleCSVImport(input) {
    if (!input.files || !input.files[0]) return;
    var formData = new FormData();
    formData.append('csv_file', input.files[0]);

    fetch('{{ url_for("admin_newsletter_import_csv") }}', {
        method: 'POST',
        body: formData
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.error) {
            AdminDialog.alert('{{ t("common.error") }}: ' + data.error);
            return;
        }
        var existing = new Set(importedEmails.map(function(e) { return e.email; }));
        data.imported.forEach(function(imp) {
            if (!existing.has(imp.email)) {
                importedEmails.push(imp);
                existing.add(imp.email);
            }
        });
        document.getElementById('imported-emails-json').value = JSON.stringify(importedEmails);
        AdminDialog.alert('{{ t("newsletter.csv_imported") }}'.replace('{count}', data.count));
        currentPage = 1;
        updateRecipientList();
    })
    .catch(function(e) {
        AdminDialog.alert('{{ t("common.error") }}: ' + e.message);
    });
    input.value = '';
}

// ── Listeners ──
document.querySelectorAll('.lang-checkbox, .form-checkbox').forEach(function(cb) {
    cb.addEventListener('change', function() {
        currentPage = 1;
        updateRecipientList();
    });
});
document.getElementById('confirmedOnly').addEventListener('change', function() {
    currentPage = 1;
    updateRecipientList();
});

// ── Initial load ──
updateRecipientList();

{% else %}
// Sent campaign — no recipient JS needed, just sync stub
function syncExcludedInputs() {}
{% endif %}
</script>
{% endblock %}
