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

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

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


<!-- Status filter -->
<div class="filter-bar">
    <a href="{{ url_for('admin_pages_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_pages_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_pages_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('pages.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_pages_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_pages_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_pages_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_pages_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_pages_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_pages_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_pages_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_pages_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="pages-content">
{% if pages.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 page in pages.items %}
        <tr>
            <td>
                <a href="{{ url_for('admin_pages_edit', page_id=page.id) }}" class="page-title-link">{{ page.title }}</a>
                <div class="page-slug">/{{ page.slug }}</div>
            </td>
            <td>
                <span class="status-badge status-{{ page.status }}">{{ t('common.status_' + page.status) }}</span>
                {% if page.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">{{ page.language|upper }}</span></td>
            <td class="author-cell">{{ page.author.username if page.author else '—' }}</td>
            <td class="date-cell">
                {% if page.published_at %}
                    {{ page.published_at|format_date }}<br>
                    <small>{{ page.published_at.strftime('%H:%M') }}</small>
                {% else %}
                    —
                {% endif %}
            </td>
            <td class="date-cell">
                {{ page.updated_at|format_date }}<br>
                <small>{{ page.updated_at.strftime('%H:%M') }}</small>
            </td>
            <td>
                <div class="actions">
                    <a href="{{ url_for('admin_pages_edit', page_id=page.id) }}" class="action-link action-edit">✏️ {{ t('table.edit') }}</a>
                    <a href="{{ url_for('admin_pages_translate', page_id=page.id) }}" class="action-link action-translate">🌍 {{ t('table.translate') }}</a>
                    <button type="button" class="action-link action-duplicate" onclick="duplicateItem('page', {{ page.id }}, '{{ page.title|e }}')">📋 {{ t('table.duplicate') }}</button>
                    {% if page.status == 'published' %}
                    <a href="/{{ page.slug }}" target="_blank" class="action-link action-view">👁️ {{ t('table.preview') }}</a>
                    {% else %}
                    <a href="{{ url_for('admin_pages_preview', page_id=page.id) }}" target="_blank" class="action-link action-view">👁️ {{ t('table.preview') }}</a>
                    {% endif %}
                    <form method="POST" action="{{ url_for('admin_pages_delete', page_id=page.id) }}" class="d-inline">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button type="button" class="action-link action-delete" onclick="checkUsageThenDelete('page', {{ page.id }}, this.closest('form'), '{{ page.title|replace("'", "\\'")|e }}')">🗑️ {{ t('table.delete') }}</button>
                    </form>
                </div>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
</div>

<!-- Pagination -->
<div class="pagination-footer">
{% if pages.pages > 1 %}
<div class="pagination">
    {% if pages.has_prev %}
        <a href="{{ url_for('admin_pages_list', page=pages.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 pages.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
        {% if p %}
            {% if p == pages.page %}
                <span class="current">{{ p }}</span>
            {% else %}
                <a href="{{ url_for('admin_pages_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 pages.has_next %}
        <a href="{{ url_for('admin_pages_list', page=pages.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('pages.no_pages') }}</h3>
    {% if search_query or lang_filter != 'all' or status_filter != 'all' %}
    <p>{{ t('pages.try_adjusting') }}</p>
    <a href="{{ url_for('admin_pages_list') }}" class="btn btn-primary">{{ t('pages.clear_filters') }}</a>
    {% else %}
    <p>{{ t('pages.create_first') }}</p>
    <a href="{{ url_for('admin_pages_new') }}" class="btn btn-primary">{{ t('pages.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("pages.delete_confirm", title="__ITEM__") }}'.replace(/&#34;/g, '"').replace('__ITEM__', itemTitle || '');
        
        if (data.count > 0) {
            msg = '{{ t("pages.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("pages.usage_confirm_delete") }}'.replace(/&#34;/g, '"');
        }
        
        if (confirm(msg)) {
            formEl.submit();
        }
    } catch (err) {
        if (confirm('{{ t("pages.delete_confirm", title="__ITEM__") }}'.replace(/&#34;/g, '"').replace('__ITEM__', itemTitle || ''))) {
            formEl.submit();
        }
    }
}

function duplicateItem(contentType, sourceId, title) {
    if (!confirm('{{ t('pages.duplicate_confirm', title='__TITLE__')|replace("\n", "\\n") }}'.replace(/&#34;/g, '"').replace('__TITLE__', title))) {
        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) {
            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_pages_list") }}';
    var _perPage = {{ per_page }};
    var _debounceTimer;

    var _i18n = {
        edit: '{{ t("table.edit") }}',
        translate: '{{ t("table.translate") }}',
        duplicate: '{{ t("table.duplicate") }}',
        preview: '{{ t("table.preview") }}',
        delete_action: '{{ t("table.delete") }}',
        delete_confirm: '{{ t("pages.delete_confirm", title="__TITLE__") }}'.replace(/&#34;/g, '"'),
        in_menu: '{{ t("pages.in_menu") }}',
        per_page_label: '{{ t("pagination.per_page") }}',
        per_page_suffix: '{{ t("pagination.per_page_suffix") }}',
        prev: '{{ t("pagination.prev") }}',
        next: '{{ t("pagination.next") }}',
        no_pages: '{{ t("pages.no_pages") }}',
        try_adjusting: '{{ t("pages.try_adjusting") }}',
        clear_filters: '{{ t("pages.clear_filters") }}',
        create_first: '{{ t("pages.create_first") }}',
        create_first_btn: '{{ t("pages.create_first_btn") }}',
        new_url: '{{ url_for("admin_pages_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('pages-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_pages) + '</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/pages/' + 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/pages/' + p.id + '/edit" class="page-title-link">' + escapeHtml(p.title) + '</a>' +
                    '<div class="page-slug">/' + 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/pages/' + p.id + '/edit" class="action-link action-edit">✏️ ' + _i18n.edit + '</a>' +
                    '<a href="/admin/pages/' + p.id + '/translate" class="action-link action-translate">🌍 ' + _i18n.translate + '</a>' +
                    '<button type="button" class="action-link action-duplicate" onclick="duplicateItem(\'page\',' + p.id + ',\'' + safeTitle + '\')">📋 ' + _i18n.duplicate + '</button>' +
                    '<a href="' + previewUrl + '" target="_blank" class="action-link action-view">👁️ ' + _i18n.preview + '</a>' +
                    '<form method="POST" action="/admin/pages/' + p.id + '/delete" class="d-inline">' +
                        '<input type="hidden" name="csrf_token" value="' + _csrfToken + '">' +
                        '<button type="button" class="action-link action-delete" onclick="checkUsageThenDelete(\'page\',' + 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 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 %}
