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

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

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>📨 {{ t('newsletter.title') }}</h2>
        <p>{{ t('newsletter.subtitle') }}</p>
    </div>
    <a href="{{ url_for('admin_newsletter_new') }}" class="btn btn-primary">✉️ {{ t('newsletter.compose') }}</a>
</div>

<!-- Status filter -->
<div class="filter-bar">
    <a href="{{ url_for('admin_newsletter_list', status='all', lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'all' %}active{% endif %}">{{ t('table.all') }}</a>
    <a href="{{ url_for('admin_newsletter_list', status='draft', lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'draft' %}active{% endif %}">{{ t('newsletter.status_draft') }}</a>
    <a href="{{ url_for('admin_newsletter_list', status='sent', lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'sent' %}active{% endif %}">{{ t('newsletter.status_sent') }}</a>
</div>

<!-- Filters & Search -->
<div class="filter-row">
    <input type="text" id="searchInput" value="{{ search_query or '' }}" placeholder="🔍 {{ t('newsletter.search_placeholder') }}" autocomplete="off">

    <label>{{ t('table.language') }}:</label>
    <select onchange="var u=new window.URL(this.value,location.origin);var pp=new URLSearchParams(location.search).get('per_page');if(pp)u.searchParams.set('per_page',pp);location.href=u">
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang='all', sort=sort_by, q=search_query, per_page=per_page) }}" {% if lang_filter == 'all' %}selected{% endif %}>{{ t('table.all_languages') }}</option>
        {% for lang in available_languages %}
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang=lang.code, sort=sort_by, q=search_query, per_page=per_page) }}" {% if lang_filter == lang.code %}selected{% endif %}>{{ lang.name }}</option>
        {% endfor %}
    </select>

    <label class="ml-3">{{ t('newsletter.subject') }}:</label>
    <select onchange="var u=new window.URL(this.value,location.origin);var pp=new URLSearchParams(location.search).get('per_page');if(pp)u.searchParams.set('per_page',pp);location.href=u">
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang=lang_filter, sort='updated-desc', q=search_query, per_page=per_page) }}" {% if sort_by not in ['subject-asc', 'subject-desc'] %}selected{% endif %}>—</option>
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang=lang_filter, sort='subject-asc', q=search_query, per_page=per_page) }}" {% if sort_by == 'subject-asc' %}selected{% endif %}>A→Z</option>
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang=lang_filter, sort='subject-desc', q=search_query, per_page=per_page) }}" {% if sort_by == 'subject-desc' %}selected{% endif %}>Z→A</option>
    </select>

    <label class="ml-3">{{ t('newsletter.date') }}:</label>
    <select onchange="var u=new window.URL(this.value,location.origin);var pp=new URLSearchParams(location.search).get('per_page');if(pp)u.searchParams.set('per_page',pp);location.href=u">
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang=lang_filter, sort='updated-desc', q=search_query, per_page=per_page) }}" {% if sort_by not in ['sent-desc', 'sent-asc'] %}selected{% endif %}>—</option>
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang=lang_filter, sort='sent-desc', q=search_query, per_page=per_page) }}" {% if sort_by == 'sent-desc' %}selected{% endif %}>{{ t('table.newest_first') }}</option>
        <option value="{{ url_for('admin_newsletter_list', status=status_filter, lang=lang_filter, sort='sent-asc', q=search_query, per_page=per_page) }}" {% if sort_by == 'sent-asc' %}selected{% endif %}>{{ t('table.oldest_first') }}</option>
    </select>
</div>

<div id="newsletter-content">
{% if newsletters.items %}
<div class="table-scroll">
<table class="content-table">
    <thead>
        <tr>
            <th>{{ t('newsletter.subject') }}</th>
            <th>{{ t('newsletter.status_label') }}</th>
            <th>{{ t('table.language') }}</th>
            <th>{{ t('newsletter.recipients') }}</th>
            <th>{{ t('newsletter.date') }}</th>
            <th>{{ t('table.actions') }}</th>
        </tr>
    </thead>
    <tbody>
        {% for nl in newsletters.items %}
        <tr>
            <td>
                <a href="{{ url_for('admin_newsletter_edit', newsletter_id=nl.id) }}" class="text-link">{{ nl.subject }}</a>
            </td>
            <td>
                <span class="newsletter-status newsletter-status--{{ nl.status }}">
                    {{ t('newsletter.status_' + nl.status) }}
                </span>
            </td>
            <td><span class="lang-badge">{{ nl.language|upper }}</span></td>
            <td>
                {% if nl.status == 'sent' %}
                    {{ nl.recipients_count }}
                    {% if nl.failed_count > 0 %}
                        <span class="text-muted">({{ nl.failed_count }} {{ t('newsletter.failed') }})</span>
                    {% endif %}
                {% else %}
                    —
                {% endif %}
            </td>
            <td class="date-cell">
                {% if nl.sent_at %}
                    {{ nl.sent_at|format_datetime }}
                {% else %}
                    {{ nl.updated_at|format_datetime }}
                {% endif %}
            </td>
            <td>
                <div class="actions">
                    {% if nl.status == 'draft' %}
                    <a href="{{ url_for('admin_newsletter_edit', newsletter_id=nl.id) }}" class="action-link action-edit">✏️ {{ t('common.edit') }}</a>
                    {% else %}
                    <a href="{{ url_for('admin_newsletter_edit', newsletter_id=nl.id) }}" class="action-link action-view">👁️ {{ t('table.view') }}</a>
                    {% endif %}
                    <a href="{{ url_for('admin_newsletter_translate', newsletter_id=nl.id) }}" class="action-link action-translate">🌍 {{ t('table.translate') }}</a>
                    <button type="button" class="action-link action-duplicate" onclick="duplicateNewsletter({{ nl.id }}, '{{ nl.subject|e }}')">📋 {{ t('table.duplicate') }}</button>
                    <form method="POST" action="{{ url_for('admin_newsletter_delete', newsletter_id=nl.id) }}" class="d-inline" onsubmit="return confirm('{{ t('newsletter.delete_confirm') }}')">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button type="submit" class="action-link action-delete">🗑️ {{ t('table.delete') }}</button>
                    </form>
                </div>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
</div>

<!-- Pagination -->
<div class="pagination-footer">
{% if newsletters.pages > 1 %}
<div class="pagination">
    {% if newsletters.has_prev %}
        <a href="{{ url_for('admin_newsletter_list', page=newsletters.prev_num, status=status_filter, lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}">{{ t('pagination.prev') }}</a>
    {% endif %}

    {% for p in newsletters.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
        {% if p %}
            {% if p == newsletters.page %}
                <span class="current">{{ p }}</span>
            {% else %}
                <a href="{{ url_for('admin_newsletter_list', page=p, status=status_filter, lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}">{{ p }}</a>
            {% endif %}
        {% else %}
            <span>…</span>
        {% endif %}
    {% endfor %}

    {% if newsletters.has_next %}
        <a href="{{ url_for('admin_newsletter_list', page=newsletters.next_num, status=status_filter, lang=lang_filter, sort=sort_by, q=search_query, per_page=per_page) }}">{{ t('pagination.next') }}</a>
    {% endif %}
</div>
{% endif %}
    <div class="per-page-selector">
        <span>{{ t('pagination.per_page') }}</span>
        <select onchange="var u=new URLSearchParams(location.search);u.set('per_page',this.value);u.delete('page');location.search=u">
            {% for pp in [20, 50, 100] %}
            <option value="{{ pp }}" {% if per_page == pp %}selected{% endif %}>{{ pp }}</option>
            {% endfor %}
        </select>
        <span>{{ t('pagination.per_page_suffix') }}</span>
    </div>
</div>

{% else %}
<div class="empty-state">
    <div class="empty-state-icon">📨</div>
    {% if search_query or lang_filter != 'all' or status_filter != 'all' %}
    <h3>{{ t('newsletter.no_campaigns') }}</h3>
    <p>{{ t('newsletter.try_adjusting') }}</p>
    <a href="{{ url_for('admin_newsletter_list') }}" class="btn btn-primary">{{ t('newsletter.clear_filters') }}</a>
    {% else %}
    <h3>{{ t('newsletter.no_newsletters') }}</h3>
    <p>{{ t('newsletter.create_first') }}</p>
    <a href="{{ url_for('admin_newsletter_new') }}" class="btn btn-primary">{{ t('newsletter.create_first_btn') }}</a>
    {% endif %}
</div>
{% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
function duplicateNewsletter(sourceId, title) {
    if (!confirm('{{ t('newsletter.duplicate_confirm', title='__TITLE__') }}'.replace(/&#34;/g, '"').replace('__TITLE__', title))) {
        return;
    }

    fetch('/admin/api/duplicate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content_type: 'newsletter', source_id: sourceId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.error) {
            alert('{{ t("common.error") }}: ' + data.error);
        } else {
            window.location.href = data.edit_url;
        }
    })
    .catch(err => alert('{{ t("common.error") }}: ' + err.message));
}

// Live search — updates table without page reload
(function() {
    var input = document.getElementById('searchInput');
    if (!input) return;

    var _csrfToken = '{{ csrf_token() }}';
    var _statusFilter = '{{ status_filter }}';
    var _langFilter = '{{ lang_filter }}';
    var _sortBy = '{{ sort_by }}';
    var _baseUrl = '{{ url_for("admin_newsletter_list") }}';
    var _perPage = {{ per_page }};
    var _debounceTimer;

    var _i18n = {
        status_draft: '{{ t("newsletter.status_draft") }}',
        status_sent: '{{ t("newsletter.status_sent") }}',
        edit: '{{ t("common.edit") }}',
        view: '{{ t("table.view") }}',
        translate: '{{ t("table.translate") }}',
        duplicate: '{{ t("table.duplicate") }}',
        delete_action: '{{ t("table.delete") }}',
        delete_confirm: '{{ t("newsletter.delete_confirm") }}',
        failed: '{{ t("newsletter.failed") }}',
        per_page_label: '{{ t("pagination.per_page") }}',
        per_page_suffix: '{{ t("pagination.per_page_suffix") }}',
        prev: '{{ t("pagination.prev") }}',
        next: '{{ t("pagination.next") }}',
        no_campaigns: '{{ t("newsletter.no_campaigns") }}',
        try_adjusting: '{{ t("newsletter.try_adjusting") }}',
        clear_filters: '{{ t("newsletter.clear_filters") }}',
        no_newsletters: '{{ t("newsletter.no_newsletters") }}',
        create_first: '{{ t("newsletter.create_first") }}',
        create_first_btn: '{{ t("newsletter.create_first_btn") }}',
        new_url: '{{ url_for("admin_newsletter_new") }}'
    };

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

    function formatDate(iso) {
        if (!iso) return '—';
        var d = new Date(iso);
        return d.toLocaleDateString('en-CA') + ' ' +
               d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
    }

    function renderContent(data) {
        var container = document.getElementById('newsletter-content');
        if (!data.items || data.items.length === 0) {
            var hasFilters = input.value.trim() || _statusFilter !== 'all' || _langFilter !== 'all';
            container.innerHTML = '<div class="empty-state">' +
                '<div class="empty-state-icon">📨</div>' +
                (hasFilters
                    ? '<h3>' + escapeHtml(_i18n.no_campaigns) + '</h3>' +
                      '<p>' + escapeHtml(_i18n.try_adjusting) + '</p>' +
                      '<a href="' + _baseUrl + '" class="btn btn-primary">' + escapeHtml(_i18n.clear_filters) + '</a>'
                    : '<h3>' + escapeHtml(_i18n.no_newsletters) + '</h3>' +
                      '<p>' + escapeHtml(_i18n.create_first) + '</p>' +
                      '<a href="' + escapeHtml(_i18n.new_url) + '" class="btn btn-primary">' + escapeHtml(_i18n.create_first_btn) + '</a>'
                ) + '</div>';
            return;
        }

        var statusLabels = { draft: _i18n.status_draft, sent: _i18n.status_sent };

        var rows = data.items.map(function(nl) {
            var statusLabel = statusLabels[nl.status] || nl.status;
            var safeSubject = escapeHtml(nl.subject).replace(/'/g, "\\'");
            var dateStr = formatDate(nl.sent_at || nl.updated_at);
            var recipientsCell = '—';
            if (nl.status === 'sent') {
                recipientsCell = '' + (nl.recipients_count || 0);
                if (nl.failed_count > 0) {
                    recipientsCell += ' <span class="text-muted">(' + nl.failed_count + ' ' + _i18n.failed + ')</span>';
                }
            }
            var editAction = nl.status === 'draft'
                ? '<a href="/admin/newsletter/' + nl.id + '/edit" class="action-link action-edit">✏️ ' + _i18n.edit + '</a>'
                : '<a href="/admin/newsletter/' + nl.id + '/edit" class="action-link action-view">👁️ ' + _i18n.view + '</a>';

            return '<tr>' +
                '<td><a href="/admin/newsletter/' + nl.id + '/edit" class="text-link">' + escapeHtml(nl.subject) + '</a></td>' +
                '<td><span class="newsletter-status newsletter-status--' + escapeHtml(nl.status) + '">' + escapeHtml(statusLabel) + '</span></td>' +
                '<td><span class="lang-badge">' + escapeHtml(nl.language.toUpperCase()) + '</span></td>' +
                '<td>' + recipientsCell + '</td>' +
                '<td class="date-cell">' + dateStr + '</td>' +
                '<td><div class="actions">' +
                    editAction +
                    '<a href="/admin/newsletter/' + nl.id + '/translate" class="action-link action-translate">🌍 ' + _i18n.translate + '</a>' +
                    '<button type="button" class="action-link action-duplicate" onclick="duplicateNewsletter(' + nl.id + ',\'' + safeSubject + '\')">📋 ' + _i18n.duplicate + '</button>' +
                    '<form method="POST" action="/admin/newsletter/' + nl.id + '/delete" class="d-inline" onsubmit="return confirm(\'' + escapeHtml(_i18n.delete_confirm) + '\')">' +
                        '<input type="hidden" name="csrf_token" value="' + _csrfToken + '">' +
                        '<button type="submit" class="action-link action-delete">🗑️ ' + _i18n.delete_action + '</button>' +
                    '</form>' +
                '</div></td></tr>';
        }).join('');

        var html = '<div class="table-scroll"><table class="content-table"><thead><tr>' +
            '<th>{{ t("newsletter.subject") }}</th><th>{{ t("newsletter.status_label") }}</th>' +
            '<th>{{ t("table.language") }}</th><th>{{ t("newsletter.recipients") }}</th>' +
            '<th>{{ t("newsletter.date") }}</th><th>{{ t("table.actions") }}</th>' +
            '</tr></thead><tbody>' + rows + '</tbody></table></div>';

        html += '<div class="pagination-footer">';
        if (data.pages > 1) {
            html += '<div class="pagination">';
            if (data.has_prev) {
                html += '<a href="#" onclick="window._liveSearch(' + data.prev_num + ');return false">' + _i18n.prev + '</a>';
            }
            var pageNums = [], i;
            for (i = 1; i <= data.pages; i++) {
                if (i === 1 || i === data.pages || (i >= data.page - 2 && i <= data.page + 2)) {
                    pageNums.push(i);
                } else if (pageNums[pageNums.length - 1] !== null) {
                    pageNums.push(null);
                }
            }
            pageNums.forEach(function(p) {
                if (p === null) { html += '<span>…</span>'; }
                else if (p === data.page) { html += '<span class="current">' + p + '</span>'; }
                else { html += '<a href="#" onclick="window._liveSearch(' + p + ');return false">' + p + '</a>'; }
            });
            if (data.has_next) {
                html += '<a href="#" onclick="window._liveSearch(' + data.next_num + ');return false">' + _i18n.next + '</a>';
            }
            html += '</div>';
        }
        html += '<div class="per-page-selector">' +
            '<span>' + _i18n.per_page_label + '</span>' +
            '<select onchange="var u=new URLSearchParams(location.search);u.set(\'per_page\',this.value);u.delete(\'page\');location.search=u">' +
            [20,50,100].map(function(pp) { return '<option value="' + pp + '"' + (pp === _perPage ? ' selected' : '') + '>' + pp + '</option>'; }).join('') +
            '</select>' +
            '<span>' + _i18n.per_page_suffix + '</span></div>';
        html += '</div>';  /* close pagination-footer */

        container.innerHTML = html;
    }

    window._liveSearch = function(page) {
        var q = input.value.trim();
        var params = new URLSearchParams();
        params.set('status', _statusFilter);
        params.set('lang', _langFilter);
        params.set('sort', _sortBy);
        params.set('format', 'json');
        if (_perPage && _perPage !== 20) params.set('per_page', _perPage);
        if (q) params.set('q', q);
        if (page && page > 1) params.set('page', page);

        fetch(_baseUrl + '?' + params.toString())
            .then(function(r) { return r.json(); })
            .then(function(data) {
                renderContent(data);
                var urlParams = new URLSearchParams(window.location.search);
                if (q) { urlParams.set('q', q); } else { urlParams.delete('q'); }
                if (page && page > 1) { urlParams.set('page', page); } else { urlParams.delete('page'); }
                urlParams.delete('format');
                history.replaceState(null, '', window.location.pathname +
                    (urlParams.toString() ? '?' + urlParams.toString() : ''));
            })
            .catch(function(err) { console.error('Search error:', err); });
    };

    input.addEventListener('input', function() {
        clearTimeout(_debounceTimer);
        _debounceTimer = setTimeout(function() { window._liveSearch(1); }, 300);
    });
})();
</script>
{% endblock %}
