(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');

    function api(url, opts) {
        opts = opts || {};
        return fetch(url, opts).then(function(r) { return r.json(); });
    }

    function escapeHtml(text) {
        if (!text) return '';
        var d = document.createElement('div');
        d.textContent = text;
        return d.innerHTML;
    }

    function formatTime(iso) {
        var d = new Date(iso);
        var pad = function(n) { return n < 10 ? '0' + n : n; };
        return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes());
    }

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

        api(url).then(function(d) {
            loading.style.display = 'none';
            if (!d.success) return;
            totalPages = d.data.total_pages || 1;
            tbody.innerHTML = '';
            var items = d.data.items || [];
            if (items.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:40px;color:#9ca3af">暂无评论</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';
            tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:40px;color:#dc2626">加载失败</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;
                if (!confirm('确认删除此评论？')) return;
                fetch('/api/admin/comments/' + id, {
                    method: 'DELETE',
                    headers: { 'X-CSRF-Token': csrfToken }
                }).then(function(r) { return r.json(); })
                .then(function(d) {
                    if (d.success) {
                        loadComments(currentPage);
                    } else {
                        alert(d.message || '删除失败');
                    }
                }).catch(function() { alert('请求失败'); });
            });
        }
    }

    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);
})();
