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

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

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>✉️ {{ t('newsletter.compose') }}</h2>
        <p>{{ t('newsletter.compose_subtitle') }}</p>
    </div>
    <div class="btn-group">
        <button type="submit" form="createForm" class="btn btn-primary btn-sm">💾 {{ t('newsletter.save_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>

<form method="POST" id="createForm" class="container-xl">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <div id="excluded-inputs"></div>
    <input type="hidden" name="imported_emails" id="imported-emails-json" 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.subject_placeholder') }}">
            </div>

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

            <!-- Audience filters (above recipient list) -->
            <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) -->
                <div class="collapsible">
                    <div class="collapsible-header" onclick="toggleSection(this)">
                        <span>🌐 {{ t('newsletter.target_languages') }}</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">
                                <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) -->
                <div class="collapsible">
                    <div class="collapsible-header" onclick="toggleSection(this)">
                        <span>📋 {{ t('newsletter.target_forms') }}</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">
                                {{ 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>
                        {{ t('newsletter.confirmed_only') }}
                    </label>
                    <div class="help-text">{{ t('newsletter.confirmed_only_help') }}</div>
                </div>
            </div>

            <!-- Recipient list (below editor) -->
            <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>
        </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">
                        {% for lang in active_languages %}
                        <option value="{{ lang.code }}" {% if lang.code == 'en' %}selected{% endif %}>{{ lang.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <!-- 2. Actions -->
            <div class="form-section">
                <h3>🚀 {{ t('newsletter.actions') }}</h3>
                <button type="submit" class="sidebar-btn btn-secondary mb-2">
                    💾 {{ t('newsletter.save_draft') }}
                </button>
                <div class="help-text">{{ t('newsletter.save_first_hint') }}</div>
            </div>

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

        </div>
    </div>
</form>
{% endblock %}

{% block extra_js %}
<script src="{{ url_for('static', filename='js/tinymce/tinymce.min.js') }}"></script>
<script>
// ── TinyMCE ──
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: sync TinyMCE ──
document.getElementById('createForm').addEventListener('submit', function(e) {
    if (typeof tinymce !== 'undefined') tinymce.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].text : 'English';
    var subjectVal = document.getElementById('subject').value;
    var contentVal = '';
    if (typeof tinymce !== 'undefined' && tinymce.get('content')) {
        contentVal = tinymce.get('content').getContent({ format: 'text' });
    } else {
        contentVal = document.getElementById('content').value;
    }

    AliothAI.open({
        mode: mode,
        contentType: '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 tinymce !== 'undefined' && tinymce.get('content')) {
            tinymce.get('content').setContent(result.content);
        } else {
            document.getElementById('content').value = result.content;
        }
    }
}

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

var excludedSet = new Set();
var importedEmails = [];
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();
    updateRecipientList();
}

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

    // Deselect all — need ALL emails from server
    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) {
            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);
        alert('{{ t("newsletter.csv_imported") }}'.replace('{count}', data.count));
        currentPage = 1;
        updateRecipientList();
    })
    .catch(function(e) {
        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();
</script>
{% endblock %}
