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

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

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>📝 {{ t('posts.title') }}</h2>
        <p>{{ t('posts.subtitle') }}</p>
    </div>
    <a href="{{ url_for('admin_posts_new') }}" class="btn btn-primary">{{ t('posts.new_post') }}</a>
</div>


<!-- Status filter -->
<div class="filter-bar">
    <a href="{{ url_for('admin_posts_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_posts_list', status='published', lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'published' %}active{% endif %}">{{ t('table.published') }}</a>
    <a href="{{ url_for('admin_posts_list', status='draft', lang=lang_filter, sort=sort_by, per_page=per_page) }}" class="filter-link {% if status_filter == 'draft' %}active{% endif %}">{{ t('table.drafts') }}</a>
</div>

<!-- Filters & Search -->
<div class="filter-row">
    <input type="text" id="searchInput" value="{{ search_query or '' }}" placeholder="🔍 {{ t('posts.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_posts_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_posts_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('table.title') }}:</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_posts_list', status=status_filter, lang=lang_filter, sort='updated-desc', q=search_query, per_page=per_page) }}" {% if sort_by not in ['title-asc', 'title-desc'] %}selected{% endif %}>—</option>
        <option value="{{ url_for('admin_posts_list', status=status_filter, lang=lang_filter, sort='title-asc', q=search_query, per_page=per_page) }}" {% if sort_by == 'title-asc' %}selected{% endif %}>A→Z</option>
        <option value="{{ url_for('admin_posts_list', status=status_filter, lang=lang_filter, sort='title-desc', q=search_query, per_page=per_page) }}" {% if sort_by == 'title-desc' %}selected{% endif %}>Z→A</option>
    </select>
    
    <label class="ml-3">{{ t('table.published_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_posts_list', status=status_filter, lang=lang_filter, sort='updated-desc', q=search_query, per_page=per_page) }}" {% if sort_by not in ['published-desc', 'published-asc'] %}selected{% endif %}>—</option>
        <option value="{{ url_for('admin_posts_list', status=status_filter, lang=lang_filter, sort='published-desc', q=search_query, per_page=per_page) }}" {% if sort_by == 'published-desc' %}selected{% endif %}>{{ t('table.newest_first') }}</option>
        <option value="{{ url_for('admin_posts_list', status=status_filter, lang=lang_filter, sort='published-asc', q=search_query, per_page=per_page) }}" {% if sort_by == 'published-asc' %}selected{% endif %}>{{ t('table.oldest_first') }}</option>
    </select>
</div>

<div id="posts-content">
{% if posts.items %}
<div class="table-scroll">
<table class="content-table">
    <thead>
        <tr>
            <th>{{ t('table.title') }}</th>
            <th>{{ t('table.status') }}</th>
            <th>{{ t('table.language') }}</th>
            <th>{{ t('table.author') }}</th>
            <th>{{ t('table.published_date') }}</th>
            <th>{{ t('table.updated_date') }}</th>
            <th>{{ t('table.actions') }}</th>
        </tr>
    </thead>
    <tbody>
        {% for post in posts.items %}
        <tr>
            <td>
                <a href="{{ url_for('admin_posts_edit', post_id=post.id) }}" class="title-link">{{ post.title }}</a>
                <div class="slug-text">/{{ post.slug }}</div>
            </td>
            <td>
                <span class="status-badge status-{{ post.status }}">{{ t('common.status_' + post.status) }}</span>
                {% if post.translation_group in in_menu_groups %}
                <span class="text-xs text-muted d-block mt-1">📌 {{ t('pages.in_menu') }}</span>
                {% endif %}
            </td>
            <td><span class="lang-badge">{{ post.language|upper }}</span></td>
            <td class="author-cell">{{ post.author.username if post.author else '—' }}</td>
            <td class="date-cell">
                {% if post.published_at %}
                    {{ post.published_at|format_date }}<br>
                    <small>{{ post.published_at|format_time }}</small>
                {% else %}
                    —
                {% endif %}
            </td>
            <td class="date-cell">
                {{ post.updated_at|format_date }}<br>
                <small>{{ post.updated_at|format_time }}</small>
            </td>
            <td>
                <div class="actions">
                    <a href="{{ url_for('admin_posts_edit', post_id=post.id) }}" class="action-link action-edit">✏️ {{ t('table.edit') }}</a>
                    <a href="{{ url_for('admin_posts_translate', post_id=post.id) }}" class="action-link action-translate">🌍 {{ t('table.translate') }}</a>
                    <button type="button" class="action-link action-duplicate" onclick="duplicateItem('post', {{ post.id }}, '{{ post.title|e }}')">📋 {{ t('table.duplicate') }}</button>
                    {% if post.status == 'published' %}
                    <a href="/{{ post.slug }}" target="_blank" class="action-link action-view">👁️ {{ t('table.preview') }}</a>
                    {% else %}
                    <a href="{{ url_for('admin_posts_preview', post_id=post.id) }}" target="_blank" class="action-link action-view">👁️ {{ t('table.preview') }}</a>
                    {% endif %}
                    <form method="POST" action="{{ url_for('admin_posts_delete', post_id=post.id) }}" class="d-inline">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button type="button" class="action-link action-delete" onclick="checkUsageThenDelete('post', {{ post.id }}, this.closest('form'), '{{ post.title|replace("'", "\\'")|e }}')">🗑️ {{ t('table.delete') }}</button>
                    </form>
                </div>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
</div>

<!-- Pagination -->
<div class="pagination-footer">
{% if posts.pages > 1 %}
<div class="pagination">
    {% if posts.has_prev %}
        <a href="{{ url_for('admin_posts_list', page=posts.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 posts.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
        {% if p %}
            {% if p == posts.page %}
                <span class="current">{{ p }}</span>
            {% else %}
                <a href="{{ url_for('admin_posts_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 posts.has_next %}
        <a href="{{ url_for('admin_posts_list', page=posts.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">
    <h3>📝 {{ t('posts.no_posts') }}</h3>
    {% if search_query or lang_filter != 'all' or status_filter != 'all' %}
    <p>{{ t('posts.try_adjusting') }}</p>
    <a href="{{ url_for('admin_posts_list') }}" class="btn btn-primary">{{ t('posts.clear_filters') }}</a>
    {% else %}
    <p>{{ t('posts.create_first') }}</p>
    <a href="{{ url_for('admin_posts_new') }}" class="btn btn-primary">{{ t('posts.create_first_btn') }}</a>
    {% endif %}
</div>
{% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
var _statusLabels = {
    'published': '{{ t("common.status_published") }}',
    'draft': '{{ t("common.status_draft") }}'
};

async function checkUsageThenDelete(assetType, assetId, formEl, itemTitle) {
    try {
        const res = await fetch('/admin/api/check-usage', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: assetType, id: assetId })
        });
        const data = await res.json();
        
        var msg = '{{ t("posts.delete_confirm", title="__ITEM__") }}'.replace(/&#34;/g, '"').replace('__ITEM__', itemTitle || '');
        
        if (data.count > 0) {
            msg = '{{ t("posts.usage_warning") }}'.replace(/&#34;/g, '"') + '\n\n';
            data.usage.forEach(function(u) {
                var typeLabel = u.type.charAt(0).toUpperCase() + u.type.slice(1);
                msg += '• ' + typeLabel + ': ' + u.title + ' (' + u.fields.join(', ') + ')\n';
            });
            msg += '\n' + '{{ t("posts.usage_confirm_delete") }}'.replace(/&#34;/g, '"');
        }
        
        AdminDialog.confirm(msg, { danger: true }).then(function(ok) {
            if (ok) formEl.submit();
        });
    } catch (err) {
        AdminDialog.confirm('{{ t("posts.delete_confirm", title="__ITEM__") }}'.replace(/&#34;/g, '"').replace('__ITEM__', itemTitle || ''), { danger: true }).then(function(ok) {
            if (ok) formEl.submit();
        });
    }
}

function duplicateItem(contentType, sourceId, title) {
    AdminDialog.confirm('{{ t('posts.duplicate_confirm', title='__TITLE__')|replace("\n", "\\n") }}'.replace(/&#34;/g, '"').replace('__TITLE__', title)).then(function(ok) {
    if (!ok) return;
    fetch('/admin/api/duplicate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content_type: contentType, source_id: sourceId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.error) {
            AdminDialog.alert('{{ t("common.error") }}: ' + data.error);
        } else {
            window.location.href = data.edit_url;
        }
    })
    .catch(err => AdminDialog.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_posts_list") }}';
    var _perPage = {{ per_page }};
    var _debounceTimer;

    var _i18n = {
        edit: '{{ t("table.edit") }}',
        in_menu: '{{ t("pages.in_menu") }}',
        translate: '{{ t("table.translate") }}',
        duplicate: '{{ t("table.duplicate") }}',
        preview: '{{ t("table.preview") }}',
        delete_action: '{{ t("table.delete") }}',
        delete_confirm: '{{ t("posts.delete_confirm", title="__TITLE__") }}'.replace(/&#34;/g, '"'),
        per_page_label: '{{ t("pagination.per_page") }}',
        per_page_suffix: '{{ t("pagination.per_page_suffix") }}',
        prev: '{{ t("pagination.prev") }}',
        next: '{{ t("pagination.next") }}',
        no_posts: '{{ t("posts.no_posts") }}',
        try_adjusting: '{{ t("posts.try_adjusting") }}',
        clear_filters: '{{ t("posts.clear_filters") }}',
        create_first: '{{ t("posts.create_first") }}',
        create_first_btn: '{{ t("posts.create_first_btn") }}',
        new_url: '{{ url_for("admin_posts_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') + '<br><small>' +
               d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) + '</small>';
    }

    function renderContent(data) {
        var container = document.getElementById('posts-content');
        if (!data.items || data.items.length === 0) {
            var hasFilters = input.value.trim() || _statusFilter !== 'all' || _langFilter !== 'all';
            container.innerHTML = '<div class="empty-state">' +
                '<h3>📝 ' + escapeHtml(_i18n.no_posts) + '</h3>' +
                (hasFilters
                    ? '<p>' + escapeHtml(_i18n.try_adjusting) + '</p>' +
                      '<a href="' + _baseUrl + '" class="btn btn-primary">' + escapeHtml(_i18n.clear_filters) + '</a>'
                    : '<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 rows = data.items.map(function(p) {
            var statusLabel = _statusLabels[p.status] || p.status;
            var previewUrl = p.status === 'published'
                ? '/' + p.slug
                : '/admin/posts/' + p.id + '/preview';
            var safeTitle = escapeHtml(p.title).replace(/'/g, "\\'");
            var confirmMsg = _i18n.delete_confirm.replace('__TITLE__', safeTitle);
            var menuBadge = p.is_in_menu
                ? '<span class="text-xs text-muted d-block mt-1">📌 ' + escapeHtml(_i18n.in_menu) + '</span>'
                : '';

            return '<tr>' +
                '<td><a href="/admin/posts/' + p.id + '/edit" class="title-link">' + escapeHtml(p.title) + '</a>' +
                    '<div class="slug-text">/' + escapeHtml(p.slug) + '</div></td>' +
                '<td><span class="status-badge status-' + escapeHtml(p.status) + '">' + escapeHtml(statusLabel) + '</span>' + menuBadge + '</td>' +
                '<td><span class="lang-badge">' + escapeHtml(p.language.toUpperCase()) + '</span></td>' +
                '<td class="author-cell">' + escapeHtml(p.author) + '</td>' +
                '<td class="date-cell">' + formatDate(p.published_at) + '</td>' +
                '<td class="date-cell">' + formatDate(p.updated_at) + '</td>' +
                '<td><div class="actions">' +
                    '<a href="/admin/posts/' + p.id + '/edit" class="action-link action-edit">✏️ ' + _i18n.edit + '</a>' +
                    '<a href="/admin/posts/' + p.id + '/translate" class="action-link action-translate">🌍 ' + _i18n.translate + '</a>' +
                    '<button type="button" class="action-link action-duplicate" onclick="duplicateItem(\'post\',' + p.id + ',\'' + safeTitle + '\')">📋 ' + _i18n.duplicate + '</button>' +
                    '<a href="' + previewUrl + '" target="_blank" class="action-link action-view">👁️ ' + _i18n.preview + '</a>' +
                    '<form method="POST" action="/admin/posts/' + p.id + '/delete" class="d-inline">' +
                        '<input type="hidden" name="csrf_token" value="' + _csrfToken + '">' +
                        '<button type="button" class="action-link action-delete" onclick="checkUsageThenDelete(\'post\',' + p.id + ',this.closest(\'form\'),\'' + safeTitle + '\')">🗑️ ' + _i18n.delete_action + '</button>' +
                    '</form>' +
                '</div></td></tr>';
        }).join('');

        var html = '<div class="table-scroll"><table class="content-table"><thead><tr>' +
            '<th>{{ t("table.title") }}</th><th>{{ t("table.status") }}</th>' +
            '<th>{{ t("table.language") }}</th><th>{{ t("table.author") }}</th>' +
            '<th>{{ t("table.published_date") }}</th><th>{{ t("table.updated_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 pages = [], i;
            for (i = 1; i <= data.pages; i++) {
                if (i === 1 || i === data.pages || (i >= data.page - 2 && i <= data.page + 2)) {
                    pages.push(i);
                } else if (pages[pages.length - 1] !== null) {
                    pages.push(null);
                }
            }
            pages.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 %}
