<?php
/**
 * 芋头CMS - 内容总览
 * 左侧为栏目树，右侧为 AJAX 内容列表
 */
if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    header('Content-Type: application/json; charset=utf-8');

    $channels = $db->fetchAll("SELECT * FROM {$db->table('channel')} ORDER BY list_order ASC, id ASC");
    $typeTables = [1 => 'article', 2 => 'product', 3 => 'page', 4 => 'image', 5 => 'download', 7 => 'video', 8 => 'guestbook', 9 => 'recruit'];
    $countMap = [];

    foreach ($typeTables as $table) {
        try {
            $cols = $db->fetchAll("DESCRIBE {$db->table($table)}");
            $colNames = array_column($cols, 'Field');
            if (!in_array('channel_id', $colNames, true)) {
                continue;
            }

            $rows = $db->fetchAll("SELECT channel_id, COUNT(*) AS cnt FROM {$db->table($table)} GROUP BY channel_id");
            foreach ($rows as $row) {
                $channelId = intval($row['channel_id']);
                if (!isset($countMap[$channelId])) {
                    $countMap[$channelId] = 0;
                }
                $countMap[$channelId] += intval($row['cnt']);
            }
        } catch (Exception $e) {
        }
    }

    echo json_encode(['code' => 200, 'channels' => $channels, 'countMap' => $countMap], JSON_UNESCAPED_UNICODE);
    exit;
}
?>

<div class="content-manage-layout">
    <aside class="channel-sidebar">
        <div class="channel-sidebar-header">
            <div>
                <div class="channel-sidebar-title">栏目导航</div>
                <div class="channel-sidebar-subtitle">按栏目快速筛选内容</div>
            </div>
            <div class="sidebar-actions">
                <button class="btn btn-xs btn-secondary" type="button" onclick="collapseAllChannels()" title="收起全部">收起</button>
                <button class="btn btn-xs btn-primary" type="button" onclick="expandAllChannels()" title="展开全部">展开</button>
            </div>
        </div>
        <div class="channel-tree" id="channelTree">
            <div class="channel-loading"><i class="fa fa-spinner fa-spin"></i> 加载栏目中...</div>
        </div>
    </aside>

    <main class="content-main">
        <div class="content-overview-head">
            <div>
                <h2>内容总览</h2>
                <p>统一查看全部栏目内容，支持树形筛选、标题搜索与快捷发布。</p>
            </div>
            <div class="overview-actions">
                <button class="btn btn-secondary" type="button" onclick="refreshContentView()">
                    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><polyline points="21 3 21 9 15 9"/></svg>
                    刷新
                </button>
            </div>
        </div>

        <div class="content-topbar">
            <div class="topbar-left">
                <div class="channel-breadcrumb" id="channelBreadcrumb">
                    <span style="color:#94a3b8;font-size:13px;">全部内容</span>
                </div>
                <button class="btn btn-primary btn-add-content" id="btnAddContent" onclick="addContent()" style="display:none;">
                    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 5v14M5 12h14"/></svg>
                    <span id="btnAddContentText">发布内容</span>
                </button>
            </div>
            <div class="topbar-right">
                <form class="search-form" onsubmit="return false;">
                    <input type="text" class="search-input" id="searchInput" placeholder="搜索标题...">
                    <button type="button" class="btn btn-secondary" onclick="doSearch()">
                        <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
                        搜索
                    </button>
                    <button type="button" class="btn btn-secondary" id="clearSearchBtn" onclick="clearSearch()" style="display:none;">清除</button>
                </form>
            </div>
        </div>

        <div class="content-list-wrapper" id="contentListWrapper">
            <div class="table-loading"><i class="fa fa-spinner fa-spin"></i> 加载内容中...</div>
        </div>
    </main>
</div>

<style>
.content-manage-layout {
    display: flex;
    min-height: calc(100vh - 140px);
    gap: 16px;
}

.channel-sidebar {
    width: 150px;
    flex-shrink: 0;
    background: #fff;
    border-radius: 10px;
    border: 1px solid #e2e8f0;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.channel-sidebar-header {
    padding: 14px 16px;
    border-bottom: 1px solid #e2e8f0;
    background: linear-gradient(180deg, #f8fafc 0%, #ffffff 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.channel-sidebar-title {
    font-size: 13px;
    font-weight: 700;
    color: #334155;
}

.channel-sidebar-subtitle {
    font-size: 12px;
    color: #94a3b8;
    margin-top: 2px;
}

.sidebar-actions {
    display: flex;
    gap: 6px;
}

.channel-tree {
    flex: 1;
    overflow-y: auto;
    padding: 8px 0;
}

.channel-loading {
    text-align: center;
    padding: 32px 20px;
    color: #94a3b8;
    font-size: 13px;
}

.channel-tree-item {
    padding: 8px 12px;
    border-radius: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #475569;
    transition: all 0.15s;
    margin: 1px 6px;
    user-select: none;
}

.channel-tree-item:hover {
    background: #f8fafc;
    color: #2563eb;
}

.channel-tree-item.active {
    background: #eff6ff;
    color: #2563eb;
    font-weight: 600;
}

.channel-tree-item.root-item {
    font-weight: 700;
    color: #1e293b;
    border-bottom: 1px solid #e2e8f0;
    padding-bottom: 10px;
    margin-bottom: 6px;
}

.channel-tree-toggle {
    width: 16px;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    border-radius: 3px;
    cursor: pointer;
    color: #94a3b8;
    transition: transform 0.15s;
}

.channel-tree-toggle:hover {
    background: #e2e8f0;
}

.channel-tree-toggle.collapsed {
    transform: rotate(-90deg);
}

.channel-tree-item .ch-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.channel-count-badge {
    font-size: 10px;
    color: #94a3b8;
    background: #f1f5f9;
    padding: 1px 6px;
    border-radius: 999px;
    min-width: 18px;
    text-align: center;
}

.channel-count-badge.has-content {
    background: #ecfdf5;
    color: #10b981;
}

.channel-quick-add {
    width: 20px;
    height: 20px;
    display: none;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    cursor: pointer;
    color: #94a3b8;
    flex-shrink: 0;
    margin-left: auto;
}

.channel-tree-item:hover .channel-quick-add {
    display: inline-flex;
}

.channel-quick-add:hover {
    background: #2563eb;
    color: #fff;
}

.content-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
}

.content-overview-head {
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    padding: 18px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
}

.content-overview-head h2 {
    margin: 0;
    font-size: 18px;
    line-height: 1.2;
    color: #0f172a;
}

.content-overview-head p {
    margin: 6px 0 0 0;
    color: #64748b;
    font-size: 13px;
}

.overview-actions {
    display: flex;
    gap: 8px;
}

.content-topbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    border-radius: 10px;
    border: 1px solid #e2e8f0;
    padding: 10px 16px;
    min-height: 56px;
    margin-bottom: 12px;
}

.topbar-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.channel-breadcrumb {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #475569;
}

.channel-breadcrumb .crumb-item {
    display: flex;
    align-items: center;
    gap: 4px;
}

.channel-breadcrumb .crumb-item a {
    color: #2563eb;
    text-decoration: none;
    padding: 2px 6px;
    border-radius: 4px;
}

.channel-breadcrumb .crumb-item a:hover {
    background: #eff6ff;
}

.channel-breadcrumb .crumb-sep {
    color: #cbd5e1;
}

.search-form {
    display: flex;
    gap: 8px;
    align-items: center;
}

.search-input {
    width: 240px;
    padding: 8px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 13px;
    outline: none;
}

.search-input:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.08);
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 14px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    transition: all 0.2s;
}

.btn-xs {
    padding: 5px 9px;
    font-size: 11px;
}

.btn-primary {
    background: #2563eb;
    color: #fff;
}

.btn-primary:hover {
    background: #1d4ed8;
}

.btn-secondary {
    background: #f8fafc;
    color: #475569;
    border: 1px solid #e2e8f0;
}

.btn-secondary:hover {
    background: #eef2f7;
}

.btn-add-content {
    margin-left: 4px;
}

.content-list-wrapper {
    flex: 1;
    background: #fff;
    border-radius: 10px;
    border: 1px solid #e2e8f0;
    overflow: auto;
    display: flex;
    flex-direction: column;
}

.list-meta-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    padding: 14px 16px;
    border-bottom: 1px solid #e2e8f0;
    background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
}

.list-meta-group {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.list-meta-title {
    font-size: 13px;
    font-weight: 600;
    color: #334155;
}

.list-meta-pill {
    display: inline-flex;
    align-items: center;
    padding: 4px 10px;
    border-radius: 999px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    color: #64748b;
    font-size: 12px;
}

.list-meta-pill.is-active {
    background: #eff6ff;
    border-color: #bfdbfe;
    color: #2563eb;
}

.content-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

.content-table th,
.content-table td {
    padding: 11px 12px;
    text-align: left;
    border-bottom: 1px solid #e2e8f0;
    font-size: 13px;
    vertical-align: middle;
}

.content-table th {
    background: #f8fafc;
    font-weight: 600;
    color: #475569;
    position: sticky;
    top: 0;
    z-index: 1;
}

.content-table tr:hover td {
    background: #fafcff;
}

.table-loading {
    text-align: center;
    padding: 40px;
    color: #94a3b8;
    font-size: 13px;
}

.id-cell {
    text-align: center;
    font-family: "Courier New", monospace;
    color: #94a3b8;
    font-size: 11px;
    width: 30px;
    padding: 8px 4px !important;
}

.checkbox-cell {
    text-align: center;
    width: 30px;
    padding: 8px 4px !important;
}

.checkbox-cell input[type=checkbox] {
    cursor: pointer;
}

.title-cell {
    max-width: none;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.title-link {
    color: #1e293b;
    text-decoration: none;
    font-weight: 500;
}

.title-link:hover {
    color: #2563eb;
}

.row-thumb {
    width: 34px;
    height: 34px;
    object-fit: cover;
    border-radius: 6px;
    margin-right: 8px;
    vertical-align: middle;
    border: 1px solid #e2e8f0;
}

.type-badge,
.status-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 3px 9px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 600;
}

.type-1 { background: #ecfdf5; color: #10b981; }
.type-2 { background: #eff6ff; color: #2563eb; }
.type-3 { background: #fdf4ff; color: #a855f7; }
.type-4 { background: #fff7ed; color: #f97316; }
.type-5 { background: #f0fdf4; color: #22c55e; }
.type-7 { background: #fef9c3; color: #ca8a04; }
.type-8 { background: #f1f5f9; color: #64748b; }
.type-9 { background: #fff1f2; color: #e11d48; }

.status-1 { background: #ecfdf5; color: #10b981; }
.status-0 { background: #fef2f2; color: #ef4444; }

.action-cell {
    display: flex;
    gap: 6px;
    align-items: center;
    justify-content: center;
}

.action-cell button {
    min-width: 46px;
    height: 28px;
    border-radius: 7px;
    font-size: 12px;
    cursor: pointer;
    border: none;
    background: #f1f5f9;
    color: #475569;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: all 0.15s;
    flex-shrink: 0;
}

.action-cell button:hover {
    background: #e2e8f0;
    color: #2563eb;
}

.action-cell .btn-del {
    background: #fef2f2;
    color: #ef4444;
}

.action-cell .btn-del:hover {
    background: #fee2e2;
    color: #dc2626;
}

.content-pagination {
    display: flex;
    justify-content: center;
    gap: 6px;
    padding: 14px 16px;
    border-top: 1px solid #e2e8f0;
    flex-shrink: 0;
    flex-wrap: wrap;
}

.content-pagination a,
.content-pagination span {
    padding: 6px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    color: #475569;
    text-decoration: none;
    font-size: 13px;
    min-width: 36px;
    text-align: center;
}

.content-pagination a:hover {
    background: #f1f5f9;
}

.content-pagination a.active {
    background: #2563eb;
    color: #fff;
    border-color: #2563eb;
}

.content-pagination span {
    border-color: transparent;
    background: transparent;
    padding-left: 4px;
    padding-right: 4px;
}

@media (max-width: 960px) {
    .content-manage-layout {
        flex-direction: column;
        min-height: auto;
    }

    .channel-sidebar {
        width: 100%;
        max-height: 320px;
    }

    .content-overview-head,
    .content-topbar {
        flex-direction: column;
        align-items: stretch;
    }

    .topbar-left,
    .topbar-right,
    .search-form {
        width: 100%;
    }

    .topbar-left {
        flex-wrap: wrap;
        gap: 10px;
    }

    .search-form {
        flex-direction: column;
        align-items: stretch;
    }

    .search-input,
    .search-form .btn,
    .btn-add-content {
        width: 100%;
    }

    .sidebar-actions,
    .overview-actions {
        width: 100%;
    }

    .sidebar-actions .btn,
    .overview-actions .btn {
        flex: 1;
    }

    .content-table {
        min-width: 980px;
    }

    .list-meta-bar {
        align-items: flex-start;
        flex-direction: column;
    }
}
</style>

<script>
var currentChannel = null;
var currentChannelName = '';
var currentChannelType = 0;
var currentPage = 1;
var currentSearch = '';
var allChannels = [];
var countMap = {};
var typeMeta = {
    1: { act: 'article', addText: '发布文章', label: '文章' },
    2: { act: 'product', addText: '新增产品', label: '产品' },
    3: { act: 'page', addText: '新增单页', label: '单页' },
    4: { act: 'image', addText: '新增图集', label: '图集' },
    5: { act: 'download', addText: '新增下载', label: '下载' },
    7: { act: 'video', addText: '新增视频', label: '视频' },
    9: { act: 'recruit', addText: '新增招聘', label: '招聘' }
};

function init() {
    loadChannelTree();
    loadContentList();
    updateSearchControls();
}

function loadChannelTree() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '?act=content&ajax=1', true);
    xhr.onload = function() {
        if (xhr.status !== 200) {
            return;
        }
        try {
            var res = JSON.parse(xhr.responseText);
            if (res.code === 200) {
                allChannels = res.channels || [];
                countMap = res.countMap || {};
                renderChannelTree(allChannels);
            }
        } catch (e) {
        }
    };
    xhr.send();
}

function escapeHtml(s) {
    s = String(s || '');
    return s.replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

function escapeJsString(s) {
    return String(s || '')
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/\r?\n/g, ' ');
}

function getChildrenOf(parentId) {
    return allChannels.filter(function(c) {
        return parseInt(c.parent_id, 10) === parseInt(parentId, 10);
    });
}

function getSubtreeCount(channelId) {
    if (!channelId) {
        return Object.keys(countMap).reduce(function(sum, key) {
            return sum + intval(countMap[key]);
        }, 0);
    }

    var total = 0;
    var stack = [parseInt(channelId, 10)];
    while (stack.length > 0) {
        var currentId = stack.pop();
        total += intval(countMap[currentId] || 0);
        getChildrenOf(currentId).forEach(function(child) {
            stack.push(parseInt(child.id, 10));
        });
    }
    return total;
}

function intval(value) {
    return parseInt(value, 10) || 0;
}

function buildTreeHtml(parentId) {
    var html = '';
    var children = getChildrenOf(parentId);

    children.forEach(function(c) {
        var nodeId = intval(c.id);
        var hasSubs = getChildrenOf(nodeId).length > 0;
        var totalCount = getSubtreeCount(nodeId);
        var isActive = currentChannel === nodeId;
        var toggleHtml = hasSubs
            ? '<span class="channel-tree-toggle" onclick="event.stopPropagation();toggleNode(this,' + nodeId + ')"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 18 6-6-6-6"/></svg></span>'
            : '<span style="width:16px;display:inline-block;"></span>';

        html += '<div class="channel-node" data-id="' + nodeId + '">';
        html += '<div class="channel-tree-item ' + (isActive ? 'active' : '') + '" data-id="' + nodeId + '" onclick="selectChannel(' + nodeId + ', \'' + escapeJsString(c.channel_name) + '\', ' + intval(c.channel_type) + ', this)">';
        html += toggleHtml;
        html += '<span class="ch-name">' + escapeHtml(c.channel_name) + '</span>';
        html += '<span class="channel-count-badge ' + (totalCount > 0 ? 'has-content' : '') + '">' + (totalCount > 0 ? totalCount : '') + '</span>';
        if (typeMeta[intval(c.channel_type)]) {
            html += '<span class="channel-quick-add" onclick="event.stopPropagation();quickAddContent(' + nodeId + ', ' + intval(c.channel_type) + ')" title="添加内容">';
            html += '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 5v14M5 12h14"/></svg>';
            html += '</span>';
        }
        html += '</div>';

        if (hasSubs) {
            html += '<div class="channel-children" style="display:block;">' + buildTreeHtml(nodeId) + '</div>';
        }

        html += '</div>';
    });

    return html;
}

function renderChannelTree() {
    var totalCount = getSubtreeCount(0);
    var html = '';
    html += '<div class="channel-tree-item root-item ' + (!currentChannel ? 'active' : '') + '" onclick="selectChannel(null, \'\', 0, this)">';
    html += '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>';
    html += '<span class="ch-name">全部内容</span>';
    html += '<span class="channel-count-badge ' + (totalCount > 0 ? 'has-content' : '') + '">' + (totalCount > 0 ? totalCount : '') + '</span>';
    html += '</div>';
    html += buildTreeHtml(0);
    document.getElementById('channelTree').innerHTML = html;
}

function toggleNode(el, id) {
    el.classList.toggle('collapsed');
    var node = document.querySelector('.channel-node[data-id="' + id + '"]');
    if (!node) {
        return;
    }
    var children = node.querySelector('.channel-children');
    if (children) {
        children.style.display = el.classList.contains('collapsed') ? 'none' : 'block';
    }
}

function setActiveChannel(el, id) {
    document.querySelectorAll('.channel-tree-item').forEach(function(item) {
        item.classList.remove('active');
    });

    if (el) {
        el.classList.add('active');
        return;
    }

    if (!id) {
        var root = document.querySelector('.channel-tree-item.root-item');
        if (root) {
            root.classList.add('active');
        }
    }
}

function updateSearchControls() {
    var clearBtn = document.getElementById('clearSearchBtn');
    if (clearBtn) {
        clearBtn.style.display = currentSearch ? 'inline-flex' : 'none';
    }
}

function selectChannel(id, name, type, el) {
    currentChannel = id;
    currentChannelName = name || '';
    currentChannelType = type || 0;
    currentPage = 1;

    setActiveChannel(el, id);
    updateBreadcrumb(id, name);
    updateAddButton();
    loadContentList();
}

function updateAddButton() {
    var btn = document.getElementById('btnAddContent');
    var btnText = document.getElementById('btnAddContentText');
    var meta = typeMeta[currentChannelType];
    if (!btn || !btnText) {
        return;
    }
    if (currentChannel && meta) {
        btn.style.display = 'inline-flex';
        btnText.textContent = meta.addText;
    } else {
        btn.style.display = 'none';
    }
}

function addContent() {
    if (!currentChannel || !typeMeta[currentChannelType]) {
        return;
    }
    location.href = '?act=' + typeMeta[currentChannelType].act + '&action=add&channel_id=' + currentChannel;
}

function quickAddContent(channelId, channelType) {
    if (!typeMeta[channelType]) {
        return;
    }
    location.href = '?act=' + typeMeta[channelType].act + '&action=add&channel_id=' + channelId;
}

function deleteItem(id, type) {
    if (!confirm('确定要删除吗？')) {
        return;
    }

    var meta = typeMeta[type];
    var act = meta ? meta.act : 'article';
    if (parseInt(type, 10) === 8) { act = 'guestbook'; }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '?act=' + act + '&action=delete', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try {
            var data = JSON.parse(xhr.responseText);
            if (data.code == 200) {
                loadChannelTree();
                loadContentList();
            } else {
                alert(data.msg || '删除失败');
            }
        } catch (e) {
            loadContentList();
        }
    };
    xhr.send('id=' + encodeURIComponent(id) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
}

function updateBreadcrumb(id, name) {
    var breadcrumb = document.getElementById('channelBreadcrumb');
    if (!breadcrumb) {
        return;
    }
    if (!id) {
        breadcrumb.innerHTML = '<span style="color:#94a3b8;font-size:13px;">全部内容</span>';
        return;
    }
    breadcrumb.innerHTML =
        '<span class="crumb-item"><a href="javascript:selectChannel(null, \'\', 0, null)">全部内容</a></span>' +
        '<span class="crumb-sep">/</span>' +
        '<span class="crumb-item"><span style="color:#475569;font-weight:500;">' + escapeHtml(name || '') + '</span></span>';
}

function loadContentList() {
    var wrapper = document.getElementById('contentListWrapper');
    wrapper.innerHTML = '<div class="table-loading"><i class="fa fa-spinner fa-spin"></i> 加载内容中...</div>';

    var xhr = new XMLHttpRequest();
    var url = '?act=content_list&page=' + currentPage;
    if (currentChannel) {
        url += '&channel_id=' + currentChannel;
    }
    if (currentChannelType && typeMeta[currentChannelType]) {
        url += '&type=' + currentChannelType;
    }
    if (currentSearch) {
        url += '&search=' + encodeURIComponent(currentSearch);
    }

    xhr.open('GET', url, true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            wrapper.innerHTML = xhr.responseText;
            setupCheckAll();
            updateSearchControls();
        }
    };
    xhr.send();
}

function setupCheckAll() {
    var checkAll = document.getElementById('checkAll');
    if (!checkAll) {
        return;
    }
    checkAll.onclick = function() {
        document.querySelectorAll('.row-check').forEach(function(item) {
            item.checked = checkAll.checked;
        });
    };
}

function doSearch() {
    currentSearch = document.getElementById('searchInput').value.trim();
    currentPage = 1;
    updateSearchControls();
    loadContentList();
}

function clearSearch() {
    currentSearch = '';
    currentPage = 1;
    document.getElementById('searchInput').value = '';
    updateSearchControls();
    loadContentList();
}

function goToPage(page) {
    currentPage = page;
    loadContentList();
    document.getElementById('contentListWrapper').scrollTop = 0;
}

function expandAllChannels() {
    document.querySelectorAll('.channel-tree-toggle').forEach(function(item) {
        item.classList.remove('collapsed');
    });
    document.querySelectorAll('.channel-children').forEach(function(item) {
        item.style.display = 'block';
    });
}

function collapseAllChannels() {
    document.querySelectorAll('.channel-tree-toggle').forEach(function(item) {
        item.classList.add('collapsed');
    });
    document.querySelectorAll('.channel-children').forEach(function(item) {
        item.style.display = 'none';
    });
}

function refreshContentView() {
    loadChannelTree();
    loadContentList();
}

document.getElementById('searchInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        doSearch();
    }
});

init();
</script>
