<?php
ob_start();
requireAdmin();

// ========== 正常页面显示 ==========
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$where = "1=1";
if ($search) {
    $search = $db->escape($search);
    $where .= " AND (version LIKE '%$search%' OR content LIKE '%$search%')";
}

$total_result = $db->query("SELECT COUNT(*) as cnt FROM changelog WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

$logs = $db->fetchAll("
    SELECT * FROM changelog 
    WHERE $where 
    ORDER BY release_date DESC, id DESC 
    LIMIT $offset, $perpage
");

// 统计数据
$stats = [
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM changelog")['cnt'],
    'active' => $db->fetchOne("SELECT COUNT(*) as cnt FROM changelog WHERE status = 1")['cnt'],
    'inactive' => $db->fetchOne("SELECT COUNT(*) as cnt FROM changelog WHERE status = 0")['cnt'],
    'featured' => $db->fetchOne("SELECT COUNT(*) as cnt FROM changelog WHERE is_featured = 1")['cnt'],
];
?>

<div class="changelog-manager">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:note-text.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            更新日志管理
        </h2>
        <button class="btn btn-primary" id="showAddModalBtn">
            <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
            添加更新日志
        </button>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:note-text.svg?color=%23667eea" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-total"><?php echo $stats['total']; ?></span>
                <span class="stat-label">总日志数</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-active"><?php echo $stats['active']; ?></span>
                <span class="stat-label">显示中</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-inactive"><?php echo $stats['inactive']; ?></span>
                <span class="stat-label">已隐藏</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:star.svg?color=%23f59e0b" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-featured"><?php echo $stats['featured']; ?></span>
                <span class="stat-label">重要更新</span>
            </div>
        </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
        <form method="GET">
            <input type="hidden" name="page" value="changelog">
            <div class="search-input-wrapper">
                <img src="https://api.iconify.design/mdi:magnify.svg?color=%239ca3af" width="18" height="18" class="search-icon" alt="">
                <input type="text" name="search" placeholder="搜索版本号或内容..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <button type="submit" class="btn btn-primary">
                <img src="https://api.iconify.design/mdi:magnify.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                搜索
            </button>
            <?php if ($search): ?>
                <a href="?page=changelog" class="btn btn-secondary">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                    清空
                </a>
            <?php endif; ?>
        </form>
    </div>
    
    <!-- 日志列表 -->
    <div class="table-wrapper">
        <table class="data-table" id="changelogTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>版本号</th>
                    <th>发布日期</th>
                    <th>更新内容</th>
                    <th>重要</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($logs)): ?>
                    <tr>
                        <td colspan="7">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:note-off.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无更新日志</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                        <tr id="log-row-<?php echo $log['id']; ?>">
                            <td class="id-cell">#<?php echo $log['id']; ?></td>
                            <td>
                                <div class="version-cell">
                                    <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="14" height="14" alt="">
                                    <strong>v<?php echo htmlspecialchars($log['version']); ?></strong>
                                </div>
                            </td>
                            <td>
                                <div class="date-cell">
                                    <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="14" height="14" alt="">
                                    <?php echo $log['release_date']; ?>
                                </div>
                            </td>
                            <td class="content-cell">
                                <div class="content-preview">
                                    <?php echo nl2br(htmlspecialchars(mb_substr($log['content'], 0, 80))); ?>
                                    <?php if (mb_strlen($log['content']) > 80): ?>...<?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <?php if ($log['is_featured']): ?>
                                    <span class="featured-badge">
                                        <img src="https://api.iconify.design/mdi:star.svg?color=%23f59e0b" width="14" height="14" alt="">
                                        重要
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $log['status'] ? 'active' : 'inactive'; ?>" id="status-badge-<?php echo $log['id']; ?>">
                                    <span class="status-dot"></span>
                                    <?php echo $log['status'] ? '显示' : '隐藏'; ?>
                                </span>
                            </td>
                            <td class="action-buttons">
                                <button class="action-btn edit-btn" data-id="<?php echo $log['id']; ?>" data-version="<?php echo htmlspecialchars($log['version']); ?>" data-date="<?php echo $log['release_date']; ?>" data-content="<?php echo htmlspecialchars($log['content']); ?>" data-featured="<?php echo $log['is_featured']; ?>" data-status="<?php echo $log['status']; ?>" title="编辑">
                                    <img src="https://api.iconify.design/mdi:pencil.svg?color=%23667eea" width="16" height="16" alt="">
                                </button>
                                <button class="action-btn toggle-status-btn" data-id="<?php echo $log['id']; ?>" data-status="<?php echo $log['status']; ?>" title="<?php echo $log['status'] ? '隐藏' : '显示'; ?>">
                                    <?php if ($log['status']): ?>
                                        <img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="16" height="16" alt="">
                                    <?php else: ?>
                                        <img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="16" height="16" alt="">
                                    <?php endif; ?>
                                </button>
                                <button class="action-btn delete-btn" data-id="<?php echo $log['id']; ?>" title="删除">
                                    <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="16" height="16" alt="">
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=changelog&p=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>" class="page-link page-prev">
                    <img src="https://api.iconify.design/mdi:chevron-left.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
            
            <?php
            $total_pages = ceil($total / $perpage);
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1): ?>
                <a href="?page=changelog&p=1&search=<?php echo urlencode($search); ?>" class="page-link">1</a>
                <?php if ($start_page > 2): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                <a href="?page=changelog&p=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
                <a href="?page=changelog&p=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=changelog&p=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>" class="page-link page-next">
                    <img src="https://api.iconify.design/mdi:chevron-right.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 添加/编辑弹窗 -->
<div id="logModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">
                <img src="https://api.iconify.design/mdi:note-plus.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                添加更新日志
            </h3>
            <button type="button" class="modal-close" onclick="closeModal()">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <form id="logForm">
            <input type="hidden" name="id" id="log_id" value="">
            <div class="modal-body">
                <div class="form-row">
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            版本号 <span class="required">*</span>
                        </label>
                        <input type="text" name="version" id="log_version" required placeholder="例如：1.0.1">
                    </div>
                    <div class="form-group" style="flex:1">
                        <label>
                            <img src="https://api.iconify.design/mdi:calendar.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                            发布日期 <span class="required">*</span>
                        </label>
                        <input type="date" name="release_date" id="log_date" required value="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        更新内容 <span class="required">*</span>
                    </label>
                    <textarea name="content" id="log_content" rows="8" required placeholder="每条更新一行，例如：&#10;✨ 新增资源下载功能&#10;🐛 修复授权验证问题&#10;🎨 优化界面样式"></textarea>
                    <small>支持 Markdown 格式，每条更新一行</small>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="is_featured" id="log_featured" value="1">
                        <img src="https://api.iconify.design/mdi:star.svg?color=%23f59e0b" width="16" height="16" style="margin: 0 4px;" alt="">
                        标记为重要更新
                    </label>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:toggle-switch.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        状态
                    </label>
                    <select name="status" id="log_status">
                        <option value="1">显示</option>
                        <option value="0">隐藏</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn" onclick="closeModal()">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                    保存
                </button>
            </div>
        </form>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.changelog-manager {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
    text-decoration: none;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.stat-icon {
    width: 52px;
    height: 52px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
}
.stat-content {
    display: flex;
    flex-direction: column;
}
.stat-value {
    font-size: 26px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 4px;
}

/* 搜索栏 */
.search-bar {
    margin-bottom: 24px;
}
.search-bar form {
    display: flex;
    gap: 12px;
    align-items: center;
}
.search-input-wrapper {
    position: relative;
    flex: 1;
    max-width: 360px;
}
.search-input-wrapper .search-icon {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    pointer-events: none;
}
.search-input-wrapper input {
    width: 100%;
    padding: 11px 16px 11px 44px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    background: var(--bg-primary);
    font-size: 14px;
    transition: all 0.2s;
}
.search-input-wrapper input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 900px;
}
.data-table th {
    padding: 16px 14px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    white-space: nowrap;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px 14px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr {
    transition: background 0.2s;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 单元格样式 */
.id-cell {
    font-family: 'Monaco', 'Menlo', monospace;
    font-size: 12px;
    color: var(--text-muted);
    font-weight: 500;
}
.version-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}
.date-cell {
    display: flex;
    align-items: center;
    gap: 6px;
    color: var(--text-secondary);
}
.content-preview {
    max-width: 300px;
    font-size: 13px;
    line-height: 1.5;
    color: var(--text-secondary);
}
.featured-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    background: #fef3c7;
    color: #92400e;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.text-muted {
    color: var(--text-muted);
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-active .status-dot {
    background: #10b981;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.status-inactive .status-dot {
    background: #ef4444;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 6px;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: all 0.2s;
}
.action-btn:hover {
    background: var(--bg-primary);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.delete-btn:hover {
    border-color: var(--danger-color);
    background: #fef2f2;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 15px;
    margin: 0;
}

/* 分页 */
.pagination {
    display: flex;
    gap: 6px;
    justify-content: center;
    margin-top: 28px;
}
.page-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    padding: 0 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 500;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.page-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    color: var(--text-muted);
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 600px;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: var(--shadow-lg);
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background 0.2s;
    display: flex;
}
.modal-close:hover {
    background: var(--bg-secondary);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    border-top: 1px solid var(--border-color);
}
.form-row {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}
.form-group {
    margin-bottom: 16px;
    flex: 1;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
}
.required {
    color: var(--danger-color);
    margin-left: 2px;
}
.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 10px 14px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.form-group textarea {
    resize: vertical;
    font-family: inherit;
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}
.form-group input[type="checkbox"] {
    width: auto;
    margin-right: 8px;
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(102, 126, 234, 0.3);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 1024px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    .form-row {
        flex-direction: column;
        gap: 0;
    }
    .search-bar form {
        flex-wrap: wrap;
    }
    .search-input-wrapper {
        max-width: 100%;
    }
}
</style>

<script>
// 更新统计卡片
function updateStatsDisplay(oldStatus, newStatus, isDelete = false, wasFeatured = false) {
    const statTotal = document.getElementById('stat-total');
    const statActive = document.getElementById('stat-active');
    const statInactive = document.getElementById('stat-inactive');
    
    if (isDelete) {
        if (statTotal) {
            let count = parseInt(statTotal.innerText) || 0;
            statTotal.innerText = Math.max(0, count - 1);
        }
        if (oldStatus === 1 && statActive) {
            let count = parseInt(statActive.innerText) || 0;
            statActive.innerText = Math.max(0, count - 1);
        } else if (oldStatus === 0 && statInactive) {
            let count = parseInt(statInactive.innerText) || 0;
            statInactive.innerText = Math.max(0, count - 1);
        }
    } else {
        if (oldStatus === 1 && statActive) {
            let count = parseInt(statActive.innerText) || 0;
            statActive.innerText = Math.max(0, count - 1);
        } else if (oldStatus === 0 && statInactive) {
            let count = parseInt(statInactive.innerText) || 0;
            statInactive.innerText = Math.max(0, count - 1);
        }
        if (newStatus === 1 && statActive) {
            let count = parseInt(statActive.innerText) || 0;
            statActive.innerText = count + 1;
        } else if (newStatus === 0 && statInactive) {
            let count = parseInt(statInactive.innerText) || 0;
            statInactive.innerText = count + 1;
        }
    }
}

(function() {
    const modal = document.getElementById('logModal');
    const form = document.getElementById('logForm');
    
    function openModal(editData) {
        const titleEl = document.getElementById('modalTitle');
        const idEl = document.getElementById('log_id');
        const versionEl = document.getElementById('log_version');
        const dateEl = document.getElementById('log_date');
        const contentEl = document.getElementById('log_content');
        const featuredEl = document.getElementById('log_featured');
        const statusEl = document.getElementById('log_status');
        
        if (!titleEl) return;
        
        if (editData) {
            titleEl.innerHTML = '<img src="https://api.iconify.design/mdi:pencil.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">编辑更新日志';
            if (idEl) idEl.value = editData.id || '';
            if (versionEl) versionEl.value = editData.version || '';
            if (dateEl) dateEl.value = editData.release_date || '';
            if (contentEl) contentEl.value = editData.content || '';
            if (featuredEl) featuredEl.checked = editData.is_featured == 1;
            if (statusEl) statusEl.value = editData.status || 1;
        } else {
            titleEl.innerHTML = '<img src="https://api.iconify.design/mdi:note-plus.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">添加更新日志';
            if (idEl) idEl.value = '';
            if (versionEl) versionEl.value = '';
            if (dateEl) dateEl.value = '<?php echo date('Y-m-d'); ?>';
            if (contentEl) contentEl.value = '';
            if (featuredEl) featuredEl.checked = false;
            if (statusEl) statusEl.value = '1';
        }
        if (modal) modal.style.display = 'flex';
    }
    
    function closeModal() {
        if (modal) modal.style.display = 'none';
    }
    
    // 显示添加弹窗
    const addBtn = document.getElementById('showAddModalBtn');
    if (addBtn) {
        addBtn.addEventListener('click', function() { openModal(null); });
    }
    
    // 编辑按钮
    document.querySelectorAll('.edit-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            openModal({
                id: this.dataset.id,
                version: this.dataset.version,
                release_date: this.dataset.date,
                content: this.dataset.content,
                is_featured: parseInt(this.dataset.featured),
                status: parseInt(this.dataset.status)
            });
        });
    });
    
    // 关闭弹窗
    document.querySelectorAll('.modal-close, .cancel-btn').forEach(function(btn) {
        btn.addEventListener('click', closeModal);
    });
    
    // 点击背景关闭
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) closeModal();
        });
    }
    
    // ESC 关闭
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
    });
    
    // 保存表单
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalHtml = submitBtn ? submitBtn.innerHTML : '保存';
            
            if (submitBtn) {
                submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
                submitBtn.disabled = true;
            }
            
            fetch('/api/changelog_save.php', {
                method: 'POST',
                body: formData
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.success) {
                    window.showToast && window.showToast(data.message, 'success');
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    window.showToast && window.showToast(data.message || '操作失败', 'error');
                    if (submitBtn) {
                        submitBtn.innerHTML = originalHtml;
                        submitBtn.disabled = false;
                    }
                }
                closeModal();
            })
            .catch(function(err) {
                console.error('错误:', err);
                window.showToast && window.showToast('网络错误', 'error');
                if (submitBtn) {
                    submitBtn.innerHTML = originalHtml;
                    submitBtn.disabled = false;
                }
                closeModal();
            });
        });
    }
    
    // 状态切换
    document.querySelectorAll('.toggle-status-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const id = this.dataset.id;
            const currentStatus = parseInt(this.dataset.status);
            const newStatus = currentStatus === 1 ? 0 : 1;
            const btnElement = this;
            const originalHtml = btnElement.innerHTML;
            
            btnElement.innerHTML = '<span class="loading-spinner"></span>';
            btnElement.disabled = true;
            
            fetch('/api/changelog_toggle_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'id=' + id + '&status=' + newStatus
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.success) {
                    updateStatsDisplay(currentStatus, newStatus);
                    
                    var statusSpan = document.getElementById('status-badge-' + id);
                    if (statusSpan) {
                        if (newStatus === 1) {
                            statusSpan.className = 'status-badge status-active';
                            statusSpan.innerHTML = '<span class="status-dot"></span>显示';
                            btnElement.innerHTML = '<img src="https://api.iconify.design/mdi:eye-off.svg?color=%23ef4444" width="16" height="16" alt="">';
                            btnElement.dataset.status = '1';
                            btnElement.setAttribute('title', '隐藏');
                        } else {
                            statusSpan.className = 'status-badge status-inactive';
                            statusSpan.innerHTML = '<span class="status-dot"></span>隐藏';
                            btnElement.innerHTML = '<img src="https://api.iconify.design/mdi:eye.svg?color=%2310b981" width="16" height="16" alt="">';
                            btnElement.dataset.status = '0';
                            btnElement.setAttribute('title', '显示');
                        }
                    }
                    btnElement.disabled = false;
                    window.showToast && window.showToast('状态已更新', 'success');
                } else {
                    window.showToast && window.showToast(data.message || '操作失败', 'error');
                    btnElement.innerHTML = originalHtml;
                    btnElement.disabled = false;
                }
            })
            .catch(function(err) {
                console.error('错误:', err);
                window.showToast && window.showToast('网络错误', 'error');
                btnElement.innerHTML = originalHtml;
                btnElement.disabled = false;
            });
        });
    });
    
    // 删除
    document.querySelectorAll('.delete-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            if (!confirm('确定删除此更新日志吗？此操作不可恢复。')) return;
            
            var id = this.dataset.id;
            var row = document.getElementById('log-row-' + id);
            var statusBadge = document.getElementById('status-badge-' + id);
            var currentStatus = statusBadge?.classList.contains('status-active') ? 1 : 0;
            var btnElement = this;
            var originalHtml = btnElement.innerHTML;
            
            btnElement.innerHTML = '<span class="loading-spinner"></span>';
            btnElement.disabled = true;
            
            fetch('/api/changelog_delete.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'id=' + id
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.success) {
                    updateStatsDisplay(currentStatus, null, true);
                    
                    if (row) {
                        row.style.transition = 'opacity 0.3s';
                        row.style.opacity = '0';
                        setTimeout(function() {
                            row.remove();
                            window.showToast && window.showToast('删除成功', 'success');
                            if (document.querySelectorAll('#changelogTable tbody tr').length === 1) {
                                location.reload();
                            }
                        }, 300);
                    }
                } else {
                    window.showToast && window.showToast(data.message || '删除失败', 'error');
                    btnElement.innerHTML = originalHtml;
                    btnElement.disabled = false;
                }
            })
            .catch(function(err) {
                console.error('错误:', err);
                window.showToast && window.showToast('网络错误', 'error');
                btnElement.innerHTML = originalHtml;
                btnElement.disabled = false;
            });
        });
    });
})();
</script>