(function() {
    'use strict';
    var currentPage = 1;
    var currentKeyword = '';
    var totalPages = 1;

    var searchInput = document.getElementById('commentSearch');
    var searchBtn = document.getElementById('commentSearchBtn');
    var clearBtn = document.getElementById('commentClearBtn');
    var tbody = document.getElementById('commentTableBody');
    var pagination = document.getElementById('commentPagination');
    var loading = document.getElementById('commentLoading');

    // escapeHtml / formatTime / showToast / showConfirm / getCSRFToken 由 shared/utils.js 提供
    // api (对象式) 由 admin/static/js/common.js 提供

    function loadComments(page) {
        loading.style.display = 'block';
        var url = '/api/admin/comments?page=' + page + '&page_size=20';
        if (currentKeyword) url += '&keyword=' + encodeURIComponent(currentKeyword);

        api.get(url).then(function(d) {
            loading.style.display = 'none';
            if (!d.success) { showToast(d.message || '加载失败', 'error'); return; }
            totalPages = d.data.total_pages || 1;
            tbody.innerHTML = '';
            var items = d.data.items || [];
            if (items.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="admin-table-empty">暂无评论</td></tr>';
                pagination.innerHTML = '';
                return;
            }
            for (var i = 0; i < items.length; i++) {
                var c = items[i];
                var row = document.createElement('tr');
                var body = escapeHtml(c.body).substring(0, 80) + (c.body && c.body.length > 80 ? '...' : '');
                row.innerHTML =
                    '<td>' + c.id + '</td>' +
                    '<td>' + escapeHtml(c.author_name) + '</td>' +
                    '<td class="comment-body-cell">' + body + '</td>' +
                    '<td><a href="/posts/' + c.post_id + '" target="_blank">' + escapeHtml(c.post_title || '文章#' + c.post_id) + '</a></td>' +
                    '<td>' + formatTime(c.created_at) + '</td>' +
                    '<td><button class="btn btn-danger btn-sm comment-delete-btn" data-id="' + c.id + '">删除</button></td>';
                tbody.appendChild(row);
            }
            renderPagination(page);
            bindDeleteBtns();
        }).catch(function() {
            loading.style.display = 'none';
            showToast('加载失败', 'error');
            tbody.innerHTML = '<tr><td colspan="6" class="admin-table-error">加载失败</td></tr>';
        });
    }

    function bindDeleteBtns() {
        var btns = tbody.querySelectorAll('.comment-delete-btn');
        for (var i = 0; i < btns.length; i++) {
            if (btns[i]._bound) continue;
            btns[i]._bound = true;
            btns[i].addEventListener('click', function() {
                var id = this.dataset.id;
                showConfirm('确认', '确认删除此评论？').then(function(ok) {
                    if (!ok) return;
                    api.del('/api/admin/comments/' + id).then(function(d) {
                        if (d.success) {
                            showToast(d.message, 'success');
                            loadComments(currentPage);
                        } else {
                            showToast(d.message || '删除失败', 'error');
                        }
                    }).catch(function() { showToast('请求失败', 'error'); });
                });
            });
        }
    }

    function renderPagination(page) {
        if (totalPages <= 1) { pagination.innerHTML = ''; return; }
        var html = '';
        if (page > 1) html += '<a href="javascript:void(0)" class="admin-page-link" data-page="' + (page-1) + '">上一页</a>';
        html += '<span class="admin-page-info">' + page + ' / ' + totalPages + '</span>';
        if (page < totalPages) html += '<a href="javascript:void(0)" class="admin-page-link" data-page="' + (page+1) + '">下一页</a>';
        pagination.innerHTML = html;

        var links = pagination.querySelectorAll('.admin-page-link');
        for (var j = 0; j < links.length; j++) {
            links[j].addEventListener('click', function() {
                currentPage = parseInt(this.dataset.page);
                loadComments(currentPage);
            });
        }
    }

    searchBtn.addEventListener('click', function() {
        currentKeyword = searchInput.value.trim();
        currentPage = 1;
        if (currentKeyword) { clearBtn.style.display = 'inline-block'; }
        else { clearBtn.style.display = 'none'; }
        loadComments(currentPage);
    });

    clearBtn.addEventListener('click', function() {
        currentKeyword = '';
        currentPage = 1;
        searchInput.value = '';
        clearBtn.style.display = 'none';
        loadComments(currentPage);
    });

    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') searchBtn.click();
    });

    loadComments(currentPage);
})();
