<?php
/**
 * 800BUS - 资讯页面
 * 支持显示资讯列表和单个资讯详情
 */
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/media_helpers.php';
require_once __DIR__ . '/includes/admin_helpers.php';
session_start();

// Draw 子站域名检测
$is_draw_site = (strtolower($_SERVER['HTTP_HOST'] ?? '') === 'draw.800bus.top') || (isset($_GET['site']) && $_GET['site'] === 'draw') || (($_SERVER['SERVER_PORT'] ?? '') === '8080');

$is_logged_in = isset($_SESSION['user_id']);
$user_data = null;
if ($is_logged_in) {
    $uid = $_SESSION['user_id'];
    $u_res = $conn->query("SELECT username, is_admin FROM users WHERE id = $uid");
    $user_data = $u_res->fetch_assoc();
}

// 获取参数
$id = (int)($_GET['id'] ?? 0);
$category = trim($_GET['category'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 12;

// 判断是显示详情还是列表
$news = null;
$news_list = [];
$total = 0;
$total_pages = 0;

if ($id > 0) {
    // 显示单个资讯详情
    $news = get_news_by_id($conn, $id);
    if ($news) {
        // 增加浏览次数
        increment_news_view_count($conn, $id);
    }
} else {
    // 显示资讯列表
    $valid_categories = ['公交运营', '人物志'];
    $category_filter = in_array($category, $valid_categories) ? $category : null;
    
    $result = get_news_list($conn, $category_filter, null, null, 1, $page, $per_page);
    $news_list = $result['list'];
    $total = $result['total'];
    $total_pages = $result['total_pages'];
}

// 页面标题
$page_title = '资讯';
if ($id > 0 && $news) {
    $page_title = htmlspecialchars($news['title']) . ' - 资讯';
} elseif ($category) {
    $page_title = $category . ' - 资讯';
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <script>/* 暗色主题闪防 */(function(){try{var t=localStorage.getItem('theme');if(t==='dark'){document.documentElement.setAttribute('data-theme','dark')}else if(!t&&window.matchMedia&&window.matchMedia('(prefers-color-scheme:dark)').matches){document.documentElement.setAttribute('data-theme','dark')}}catch(e){}})();</script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?> - 800BUS</title>
    <link rel="icon" href="/favicon.ico">
    <style>
        :root{
            --ink:#111;--ink-soft:#333;--muted:#666;--mute:#999;
            --line:#e0e0e0;--line-strong:#bbb;
            --accent:#2563eb;--accent-hover:#1d4ed8;
            --gold:#8a6d00;--rose:#c02020;
            --surface:#fff;--bg:#f2f2f2;
        }
        *,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
        html{scroll-behavior:smooth}
        body{
            font-family:"Inter","SF Pro Display","PingFang SC","Noto Sans SC",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
            background:var(--bg);
            color:var(--ink);
            line-height:1.5;
            -webkit-font-smoothing:antialiased;
            -moz-osx-font-smoothing:grayscale;
            min-height:100vh;
            overflow-x:hidden;
        }
        a{color:inherit;text-decoration:none}
        .container{max-width:1200px;margin:0 auto;padding:0 32px}
        @media(max-width:768px){.container{padding:0 20px}}

        /* NAV: loaded from system/header.php */

        /* ── PAGE HEADER ── */
        .page-header{margin:32px 0 24px}
        .page-title{
            font-size:clamp(22px,3vw,28px);
            font-weight:700;line-height:1.3;
            color:var(--ink);margin-bottom:6px;
        }
        .page-subtitle{font-size:14px;color:var(--muted);font-weight:400}

        /* ── CATEGORY TABS ── */
        .category-tabs{
            display:flex;flex-wrap:wrap;justify-content:center;gap:6px;
            margin-bottom:24px;
        }
        .category-tabs a{
            padding:7px 16px;border-radius:3px;
            font-size:12px;font-weight:500;
            background:var(--surface);
            color:var(--muted);
            border:1px solid var(--line);
            transition:background .15s,color .15s,border-color .15s;
        }
        .category-tabs a:hover{
            border-color:var(--line-strong);
            color:var(--ink);
        }
        .category-tabs a.active{
            background:var(--ink);
            color:#fff;
            border-color:var(--ink);
        }

        /* ── NEWS GRID ── */
        .news-grid{
            display:grid;
            grid-template-columns:repeat(3,1fr);
            gap:14px;
            margin-bottom:32px;
        }
        @media(max-width:1024px){.news-grid{grid-template-columns:repeat(2,1fr);gap:12px}}
        @media(max-width:600px){.news-grid{grid-template-columns:1fr;gap:10px}}

        .news-card{
            background:var(--surface);
            border:1px solid var(--line);
            border-radius:3px;
            overflow:hidden;
            text-decoration:none;color:inherit;
            transition:border-color .15s;
            display:flex;flex-direction:column;
        }
        .news-card:hover{
            border-color:var(--line-strong);
        }

        .news-card-image{
            height:180px;
            overflow:hidden;
            background:#e8e8e8;
            position:relative;
        }
        .news-card-image img{
            width:100%;height:100%;
            object-fit:cover;
        }

        .news-card-content{
            padding:16px 18px 18px;
            flex:1;
            display:flex;flex-direction:column;
        }

        .news-card-meta{
            display:flex;align-items:center;gap:6px;
            margin-bottom:10px;
        }

        .news-category-badge{
            font-size:11px;padding:3px 8px;
            border-radius:2px;font-weight:600;
        }
        .news-category-badge.公交运营{
            background:rgba(37,99,235,0.08);color:var(--accent);
        }
        .news-category-badge.人物志{
            background:rgba(22,163,74,0.08);color:#16a34a;
        }

        .news-card-title{
            font-size:15px;font-weight:600;
            margin-bottom:8px;line-height:1.4;
            color:var(--ink);
            display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;
        }

        .news-card-excerpt{
            font-size:13px;line-height:1.6;
            color:var(--muted);
            margin-bottom:14px;flex:1;
            display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;
        }

        .news-card-footer{
            display:flex;justify-content:space-between;align-items:center;
            font-size:11px;color:var(--mute);
            padding-top:12px;
            border-top:1px solid var(--line);
        }

        /* ── DETAIL ── */
        .back-btn{
            display:inline-flex;align-items:center;gap:6px;
            padding:8px 16px;
            background:var(--surface);
            border:1px solid var(--line);
            border-radius:3px;
            color:var(--muted);
            text-decoration:none;
            font-size:13px;font-weight:500;
            margin:28px 0 20px;
            transition:background .15s,color .15s,border-color .15s;
        }
        .back-btn:hover{
            border-color:var(--line-strong);
            color:var(--ink);
        }

        .news-detail{
            background:var(--surface);
            border:1px solid var(--line);
            border-radius:3px;
            padding:32px;
            margin-bottom:32px;
        }
        @media(max-width:768px){.news-detail{padding:20px}}

        .news-detail-header{
            margin-bottom:28px;
            padding-bottom:20px;
            border-bottom:1px solid var(--line);
        }

        .news-detail-title{
            font-size:clamp(22px,3vw,28px);
            font-weight:700;line-height:1.3;
            margin-bottom:14px;
            color:var(--ink);
        }

        .news-detail-meta{
            display:flex;flex-wrap:wrap;gap:14px;
            font-size:13px;color:var(--muted);
        }
        .news-detail-meta span{
            display:flex;align-items:center;gap:5px;
        }

        .news-detail-content{
            font-size:15px;line-height:1.8;
            color:var(--ink-soft);
            margin-bottom:32px;
        }
        .news-detail-content p{margin-bottom:20px}
        .news-detail-content img{max-width:100%;border-radius:3px;border:1px solid var(--line)}
        .news-detail-content h1,.news-detail-content h2,.news-detail-content h3{
            margin:24px 0 12px;color:var(--ink);
        }
        .news-detail-content blockquote{
            border-left:3px solid var(--line-strong);
            padding:12px 16px;margin:16px 0;
            color:var(--muted);background:rgba(0,0,0,0.02);
            border-radius:0 3px 3px 0;
        }
        .news-detail-content code{
            background:rgba(0,0,0,0.05);padding:2px 6px;
            border-radius:2px;font-size:13px;
        }
        .news-detail-content pre{
            background:#f5f5f5;border:1px solid var(--line);
            border-radius:3px;padding:16px;overflow-x:auto;
            margin:16px 0;
        }
        .news-detail-content pre code{background:none;padding:0}
        .news-detail-content ul,.news-detail-content ol{margin:12px 0;padding-left:24px}
        .news-detail-content li{margin-bottom:6px}
        .news-detail-content a{color:var(--accent);text-decoration:underline;text-underline-offset:2px}
        .news-detail-content a:hover{color:var(--accent-hover)}

        .news-images{
            display:grid;
            grid-template-columns:repeat(auto-fill,minmax(250px,1fr));
            gap:12px;margin:24px 0;
        }
        .news-image-item{
            border-radius:3px;overflow:hidden;
            border:1px solid var(--line);
            cursor:pointer;
            transition:border-color .15s;
        }
        .news-image-item:hover{border-color:var(--line-strong)}
        .news-image-item img{
            width:100%;height:200px;object-fit:cover;display:block;
            cursor:zoom-in;
        }

        /* ── IMAGE FULLSCREEN VIEWER ── */
        .news-img-fullscreen{
            display:none;position:fixed;inset:0;background:rgba(0,0,0,0.95);
            z-index:10000;align-items:center;justify-content:center;padding:20px;
        }
        .news-img-fullscreen.show{display:flex}
        .news-img-fullscreen .img-container{
            display:flex;align-items:center;justify-content:center;
            width:100%;height:100%;overflow:hidden;
        }
        .news-img-fullscreen img{
            max-width:100%;max-height:100%;object-fit:contain;border-radius:3px;
            transform-origin:center;touch-action:none;
        }
        .news-img-fullscreen .close-btn{
            position:absolute;top:20px;right:20px;width:40px;height:40px;
            background:rgba(255,255,255,0.15);border:1px solid rgba(255,255,255,0.2);
            border-radius:3px;color:#fff;font-size:20px;cursor:pointer;line-height:1;
        }
        .news-img-fullscreen .close-btn:hover{background:rgba(255,255,255,0.25)}

        /* ── ACTION BUTTONS ── */
        .action-row{
            display:flex;gap:10px;margin-top:20px;flex-wrap:wrap;
        }
        .action-btn{
            padding:9px 20px;border-radius:3px;
            border:1px solid var(--line);background:var(--surface);
            cursor:pointer;font-size:13px;font-weight:600;
            transition:background .15s,border-color .15s,color .15s;
            color:var(--ink);
        }
        .action-btn:hover{
            border-color:var(--line-strong);background:rgba(0,0,0,0.03);
        }
        .action-btn.gold{
            border-color:#d4b96a;color:var(--gold);
        }
        .action-btn.gold:hover{
            background:rgba(138,109,0,0.06);
        }

        /* ── COMMENTS ── */
        .comment-section{margin-top:32px}
        .comment-section h3{
            font-size:15px;font-weight:700;
            margin-bottom:16px;color:var(--ink);
        }
        .comment-form{
            display:flex;gap:10px;margin-bottom:20px;align-items:flex-start;
        }
        .comment-form textarea{
            flex:1;padding:12px 14px;border-radius:3px;
            border:1px solid var(--line);background:var(--surface);
            resize:none;font-size:14px;font-family:inherit;
            outline:none;transition:border-color .15s;
            color:var(--ink);
        }
        .comment-form textarea:focus{border-color:var(--accent)}
        .comment-form button{
            padding:12px 20px;border-radius:3px;border:none;
            background:var(--ink);color:#fff;font-size:13px;
            font-weight:600;cursor:pointer;white-space:nowrap;
        }
        .comment-login-hint{
            color:var(--mute);font-size:13px;margin-bottom:16px;
        }
        .comment-login-hint a{color:var(--accent);text-decoration:underline;text-underline-offset:2px}

        /* ── PAGINATION ── */
        .pagination{
            display:flex;justify-content:center;gap:6px;
            margin:32px 0;
        }
        .pagination a,.pagination span{
            padding:8px 14px;border-radius:3px;
            text-decoration:none;font-size:13px;font-weight:500;
        }
        .pagination a{
            background:var(--surface);
            border:1px solid var(--line);
            color:var(--muted);
            transition:background .15s,color .15s,border-color .15s;
        }
        .pagination a:hover{
            border-color:var(--line-strong);
            color:var(--ink);
        }
        .pagination .current{
            background:var(--ink);
            color:#fff;
            border:1px solid var(--ink);
        }
        .pagination .disabled{
            background:rgba(0,0,0,0.03);
            color:var(--mute);
            border:1px solid transparent;
            cursor:not-allowed;
        }

        /* ── EMPTY STATE ── */
        .empty-state{text-align:center;padding:48px 16px;color:var(--mute)}
        .empty-state .icon{font-size:32px;margin-bottom:16px;opacity:0.5}

        /* ── DARK MODE OVERRIDES ── */
        [data-theme="dark"] .news-card-image{background:#1a1a1a}
        [data-theme="dark"] .news-detail-content pre{background:#111}
        [data-theme="dark"] .news-detail-content blockquote{background:rgba(255,144,0,0.05)}
        [data-theme="dark"] .category-tabs a.active{background:var(--accent);color:#000;border-color:var(--accent)}
        [data-theme="dark"] .pagination .current{background:var(--accent);color:#000;border:1px solid var(--accent)}
        [data-theme="dark"] .comment-form button{background:var(--accent);color:#000}
        [data-theme="dark"] .action-btn.gold{background:rgba(255,144,0,0.1);border-color:rgba(255,144,0,0.3)}
        [data-theme="dark"] .comment-login-hint a{color:var(--accent)}
        [data-theme="dark"] .news-detail-content a{color:var(--accent)}
        [data-theme="dark"] div[style*="background:#eff6ff"]{background:rgba(255,144,0,0.08)!important;border-color:rgba(255,144,0,0.3)!important}
        [data-theme="dark"] div[style*="color:#1d4ed8"]{color:var(--accent)!important}
        [data-theme="dark"] div[style*="border-color:#bfdbfe"]{border-color:rgba(255,144,0,0.3)!important}
        [data-theme="dark"] div[style*="background:#dcfce7"]{background:rgba(74,222,128,0.08)!important;border-color:rgba(74,222,128,0.3)!important}
        [data-theme="dark"] div[style*="color:#15803d"]{color:#4ade80!important}
        [data-theme="dark"] div[style*="border-color:#bbf7d0"]{border-color:rgba(74,222,128,0.3)!important}
        [data-theme="dark"] .news-category-badge.人物志{background:rgba(74,222,128,0.1);color:#4ade80}
        [data-theme="dark"] .news-detail-content pre{background:#111;border-color:#2a2a2a}
        [data-theme="dark"] .news-detail-content code{background:rgba(255,144,0,0.08)}
        [data-theme="dark"] .news-image-item{border-color:#2a2a2a}
        [data-theme="dark"] .action-btn{background:#1a1a1a;border-color:#2a2a2a;color:#fff}
        [data-theme="dark"] .action-btn:hover{border-color:var(--accent);background:rgba(255,144,0,0.06)}
        [data-theme="dark"] .comment-form textarea{background:#111;color:#fff}
        [data-theme="dark"] .pagination a{background:#1a1a1a;border-color:#2a2a2a;color:#ccc}
        [data-theme="dark"] .pagination a:hover{border-color:var(--accent);color:var(--accent)}
        [data-theme="dark"] .back-btn{background:#1a1a1a;color:#ccc;border-color:#2a2a2a}
        [data-theme="dark"] .back-btn:hover{border-color:var(--accent);color:var(--accent)}
        [data-theme="dark"] .category-tabs a{background:#1a1a1a;border-color:#2a2a2a;color:#999}
        [data-theme="dark"] .category-tabs a:hover{border-color:var(--accent);color:var(--accent)}

        /* ── TOAST ── */
        #ntoast{
            position:fixed;top:50%;left:50%;
            transform:translate(-50%,-50%) scale(0.85);
            background:var(--ink);color:#fff;
            padding:12px 24px;border-radius:3px;
            font-size:14px;font-weight:600;z-index:9999;
            opacity:0;pointer-events:none;
            transition:all 0.25s cubic-bezier(0.25,0.46,0.45,0.94);
            text-align:center;max-width:80vw;
        }
    </style>
    <link rel="stylesheet" href="system/dark-theme.css">
    <script src="system/theme-toggle.js" defer></script>
<?php require_once __DIR__ . '/system/head.php'; ?>
</head>
<body class="has-fixed-nav">
    <div id="ntoast"></div>

    <?php $header_active = 'news'; require_once __DIR__ . '/system/header.php'; ?>

    <div class="container">
        <?php if ($id > 0 && $news): ?>
            <!-- 详情页 -->
            <a href="javascript:history.back()" class="back-btn">← 返回</a>

            <div class="news-detail">
                <div class="news-detail-header">
                    <div class="news-card-meta" style="margin-bottom:14px;">
                        <span class="news-category-badge <?= $news['category'] ?>"><?= $news['category'] ?></span>
                        <?php if ($news['is_anonymous']): ?>
                        <span style="font-size:11px;color:var(--mute);">匿名投稿</span>
                        <?php endif; ?>
                    </div>

                    <h1 class="news-detail-title"><?= htmlspecialchars($news['title']) ?></h1>

                    <div class="news-detail-meta">
                        <span>👤 <?php if ($news['is_anonymous']): ?>匿名用户<?php elseif (!empty($news['user_id'])): ?><a href="/user/<?= (int)$news['user_id'] ?>" style="color:inherit;text-decoration:none;"><?= htmlspecialchars($news['username'] ?? '未知') ?></a><?php else: ?><?= htmlspecialchars($news['username'] ?? '未知') ?><?php endif; ?></span>
                        <span>📍 <?= htmlspecialchars(($news['province_name'] ?? '') . ' ' . ($news['city_name'] ?? '')) ?></span>
                        <span>📅 <?= date('Y年m月d日 H:i', strtotime($news['created_at'])) ?></span>
                        <span>👁️ <?= number_format($news['view_count']) ?> 次浏览</span>
                    </div>
                </div>

                <div class="news-detail-content">
                    <?= parse_markdown($news['content']) ?>
                </div>

                <?php if (!empty($news['images']) && is_array($news['images'])): ?>
                <div class="news-images">
                    <?php foreach ($news['images'] as $img): ?>
                    <div class="news-image-item" onclick="openNewsFullscreen('<?= htmlspecialchars($img['original'] ?? $img['thumbnail'] ?? '') ?>')">
                        <img src="<?= htmlspecialchars($img['thumbnail'] ?? $img['original'] ?? '') ?>"
                             alt="资讯图片" loading="lazy">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <?php if ($is_logged_in && !empty($news['author_user_id'])): ?>
            <div class="action-row">
                <button onclick="openNewsRate()" class="action-btn">⭐ 评分</button>
                <button onclick="openNewsTip()" class="action-btn gold">🪙 投币</button>
            </div>
            <?php endif; ?>

            <div class="comment-section">
                <h3>💬 评论区</h3>
                <?php if ($is_logged_in): ?>
                <div class="comment-form">
                    <textarea id="newsCommentInput" placeholder="说点什么..." maxlength="500" rows="2"></textarea>
                    <button onclick="submitNewsComment()" id="newsCommentBtn">发布</button>
                </div>
                <?php else: ?>
                <p class="comment-login-hint"><a href="login.php">登录</a>后参与评论</p>
                <?php endif; ?>
                <div id="newsComments"></div>
            </div>

        <?php else: ?>
            <!-- 列表页 -->
            <div class="page-header">
                <h1 class="page-title">📰 资讯</h1>
                <p class="page-subtitle">了解最新公交运营动态和人物故事</p>
            </div>

            <div class="category-tabs">
                <a href="/news" class="<?= empty($category) ? 'active' : '' ?>">全部</a>
                <a href="/news.php?category=公交运营" class="<?= $category === '公交运营' ? 'active' : '' ?>">🚌 公交运营</a>
                <a href="/news.php?category=人物志" class="<?= $category === '人物志' ? 'active' : '' ?>">👤 人物志</a>
            </div>

            <?php if (!empty($news_list)): ?>
            <div class="news-grid">
                <?php foreach ($news_list as $item): ?>
                <a href="/news/<?= $item['id'] ?>" class="news-card">
                    <?php if (!empty($item['images']) && is_array($item['images'])): ?>
                    <div class="news-card-image">
                        <img src="<?= htmlspecialchars($item['images'][0]['thumbnail'] ?? $item['images'][0]['original'] ?? '') ?>"
                             alt="<?= htmlspecialchars($item['title']) ?>" loading="lazy">
                    </div>
                    <?php endif; ?>

                    <div class="news-card-content">
                        <div class="news-card-meta">
                            <span class="news-category-badge <?= $item['category'] ?>"><?= $item['category'] ?></span>
                            <?php if ($item['is_anonymous']): ?>
                            <span style="font-size:10px;color:var(--mute);">匿名</span>
                            <?php endif; ?>
                        </div>

                        <h2 class="news-card-title"><?= htmlspecialchars($item['title']) ?></h2>

                        <p class="news-card-excerpt"><?= htmlspecialchars(mb_substr(strip_tags($item['content']), 0, 150)) ?></p>

                        <div class="news-card-footer">
                            <span>📍 <?= htmlspecialchars(($item['province_name'] ?? '') . ' ' . ($item['city_name'] ?? '')) ?></span>
                            <span><?= date('m-d', strtotime($item['created_at'])) ?></span>
                        </div>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>

            <!-- 分页 -->
            <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                <a href="/news.php?<?= $category ? 'category=' . urlencode($category) . '&' : '' ?>page=<?= $page - 1 ?>">上一页</a>
                <?php else: ?>
                <span class="disabled">上一页</span>
                <?php endif; ?>

                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                    <?php if ($i == $page): ?>
                    <span class="current"><?= $i ?></span>
                    <?php else: ?>
                    <a href="/news.php?<?= $category ? 'category=' . urlencode($category) . '&' : '' ?>page=<?= $i ?>"><?= $i ?></a>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $total_pages): ?>
                <a href="/news.php?<?= $category ? 'category=' . urlencode($category) . '&' : '' ?>page=<?= $page + 1 ?>">下一页</a>
                <?php else: ?>
                <span class="disabled">下一页</span>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <?php else: ?>
            <div class="empty-state">
                <div class="icon">📭</div>
                <div>暂无资讯内容</div>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <?php require_once __DIR__ . '/system/footer.php'; ?>

    <script>
        var newsId = <?= $id ?>;
        var isLoggedIn = <?= $is_logged_in ? 'true' : 'false' ?>;
        var newsUserName = <?= json_encode($user_data['username'] ?? '') ?>;
        var _nt = null;
        function ntoast(m, d) {
            d = d || 2000;
            var e = document.getElementById('ntoast');
            e.textContent = m;
            e.style.opacity = '1';
            e.style.transform = 'translate(-50%,-50%) scale(1)';
            clearTimeout(_nt);
            _nt = setTimeout(function() { e.style.opacity = '0'; e.style.transform = 'translate(-50%,-50%) scale(0.85)'; }, d);
        }

        /* ── NEWS IMAGE FULLSCREEN VIEWER ── */
        function openNewsFullscreen(src) {
            var fs = document.getElementById('newsImgFullscreen');
            var img = document.getElementById('newsFullscreenImg');
            img.src = src;
            img.style.transform = 'scale(1)';
            fs.scale = 1;
            fs.lastX = 0;
            fs.lastY = 0;
            fs.isDragging = false;
            fs.classList.add('show');
            document.body.style.overflow = 'hidden';
        }
        function closeNewsFullscreen() {
            var fs = document.getElementById('newsImgFullscreen');
            fs.classList.remove('show');
            document.body.style.overflow = '';
        }
        function handleNewsFullscreenClick(e) {
            if (e.target === e.currentTarget || e.target.classList.contains('img-container')) {
                closeNewsFullscreen();
            }
        }
        (function() {
            var fs = document.getElementById('newsImgFullscreen');
            var img = document.getElementById('newsFullscreenImg');
            if (!fs || !img) return;
            var scale = 1, lastX = 0, lastY = 0, isDragging = false;
            fs.scale = 1; fs.lastX = 0; fs.lastY = 0; fs.isDragging = false;
            fs.addEventListener('wheel', function(e) {
                e.preventDefault();
                var delta = e.deltaY > 0 ? 0.85 : 1.15;
                scale = Math.max(0.5, Math.min(5, scale * delta));
                fs.scale = scale;
                img.style.transform = 'scale(' + scale + ')';
            }, {passive: false});
            fs.addEventListener('mousedown', function(e) {
                if (scale > 1) { isDragging = true; lastX = e.clientX; lastY = e.clientY; fs.style.cursor = 'grabbing'; }
            });
            fs.addEventListener('mousemove', function(e) {
                if (!isDragging) return;
                var dx = e.clientX - lastX, dy = e.clientY - lastY;
                lastX = e.clientX; lastY = e.clientY;
                fs.lastX += dx; fs.lastY += dy;
                img.style.transform = 'scale(' + scale + ') translate(' + (fs.lastX / scale) + 'px,' + (fs.lastY / scale) + 'px)';
            });
            fs.addEventListener('mouseup', function() { isDragging = false; fs.style.cursor = ''; });
            fs.addEventListener('mouseleave', function() { isDragging = false; fs.style.cursor = ''; });
            var tStartX = 0, tStartY = 0, tDist = 0;
            fs.addEventListener('touchstart', function(e) {
                if (e.touches.length === 1) {
                    if (scale > 1) { isDragging = true; lastX = e.touches[0].clientX; lastY = e.touches[0].clientY; }
                    tStartX = e.touches[0].clientX; tStartY = e.touches[0].clientY;
                } else if (e.touches.length === 2) {
                    isDragging = false;
                    tDist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
                }
            }, {passive: false});
            fs.addEventListener('touchmove', function(e) {
                e.preventDefault();
                if (e.touches.length === 1 && isDragging) {
                    var dx = e.touches[0].clientX - lastX, dy = e.touches[0].clientY - lastY;
                    lastX = e.touches[0].clientX; lastY = e.touches[0].clientY;
                    fs.lastX += dx; fs.lastY += dy;
                    img.style.transform = 'scale(' + scale + ') translate(' + (fs.lastX / scale) + 'px,' + (fs.lastY / scale) + 'px)';
                } else if (e.touches.length === 2 && tDist > 0) {
                    var newDist = Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY);
                    var r = newDist / tDist; tDist = newDist;
                    scale = Math.max(0.5, Math.min(5, scale * r)); fs.scale = scale;
                    img.style.transform = 'scale(' + scale + ') translate(' + (fs.lastX / scale) + 'px,' + (fs.lastY / scale) + 'px)';
                }
            }, {passive: false});
            fs.addEventListener('touchend', function(e) {
                isDragging = false;
                if (e.changedTouches.length === 1 && scale === 1) {
                    var dt = Math.abs(Date.now() - (fs._tapTime || 0));
                    var dx = Math.abs(e.changedTouches[0].clientX - tStartX);
                    var dy = Math.abs(e.changedTouches[0].clientY - tStartY);
                    if (dt < 300 && dx < 10 && dy < 10) closeNewsFullscreen();
                }
                fs._tapTime = Date.now();
            });
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && fs.classList.contains('show')) closeNewsFullscreen();
            });
        })();

        function openNewsRate() {
            if (!isLoggedIn) { window.location.href = 'login.php'; return; }
            var val = prompt("请输入您的评分 (1-5):", "5");
            if (val && val >= 1 && val <= 5) {
                var fd = new FormData();
                fd.append('id', newsId);
                fd.append('rating', val);
                fd.append('source_type', 'news');
                fetch('/api/rate.php', { method: 'POST', body: fd })
                    .then(function(r) { return r.json(); })
                    .then(function(d) { ntoast(d.msg || '评分完成'); })
                    .catch(function() { ntoast('网络错误'); });
            }
        }

        function openNewsTip() {
            if (!isLoggedIn) { window.location.href = 'login.php'; return; }
            document.getElementById('newsTipModal').style.display = 'flex';
        }
        function closeNewsTip() {
            document.getElementById('newsTipModal').style.display = 'none';
        }
        function confirmNewsTip(amt) {
            var fd = new FormData();
            fd.append('news_id', newsId);
            fd.append('amount', amt);
            fetch('/api/handler.php?action=tip_coin_news', { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    ntoast(d.msg || '投币完成');
                    if (d.status === 'success') closeNewsTip();
                })
                .catch(function(e) { ntoast('投币请求失败: ' + e.message); });
        }

        function loadNewsComments() {
            fetch('/api/comments.php?submission_id=' + newsId + '&source_type=news')
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    if (d.status !== 'success') return;
                    var html = '';
                    if (!d.data || d.data.length === 0) {
                        html = '<p style="color:var(--mute);font-size:13px;text-align:center;padding:20px;">暂无评论</p>';
                    } else {
                        d.data.forEach(function(c) {
                            html += '<div style="padding:14px 0;border-bottom:1px solid var(--line);">';
                            html += '<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;">';
                            html += (c.user_id ? '<a href="/user/' + c.user_id + '" style="font-weight:600;font-size:13px;color:var(--ink);text-decoration:none;" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'">' + escapeHtml(c.username || '匿名') + '</a>' : '<span style="font-weight:600;font-size:13px;">' + escapeHtml(c.username || '匿名') + '</span>');
                            html += '<span style="font-size:11px;color:var(--mute);">' + timeAgo(c.created_at) + '</span></div>';
                            html += '<p style="margin:0;font-size:14px;line-height:1.6;color:var(--ink-soft);">' + escapeHtml(c.content) + '</p>';
                            if (c.replies && c.replies.length > 0) {
                                c.replies.forEach(function(r) {
                                    html += '<div style="margin-top:10px;margin-left:20px;padding:10px 14px;background:rgba(0,0,0,0.02);border:1px solid var(--line);border-radius:3px;">';
                                    html += '<div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">';
                                    html += (r.user_id ? '<a href="/user/' + r.user_id + '" style="font-weight:600;font-size:12px;color:var(--ink);text-decoration:none;" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'">' + escapeHtml(r.username || '匿名') + '</a>' : '<span style="font-weight:600;font-size:12px;">' + escapeHtml(r.username || '匿名') + '</span>');
                                    if (r.reply_to) html += '<span style="font-size:11px;color:var(--mute);">回复 ' + escapeHtml(r.reply_to) + '</span>';
                                    html += '<span style="font-size:11px;color:var(--mute);">' + timeAgo(r.created_at) + '</span></div>';
                                    html += '<p style="margin:0;font-size:13px;line-height:1.5;color:var(--ink-soft);">' + escapeHtml(r.content) + '</p></div>';
                                });
                            }
                            html += '</div>';
                        });
                    }
                    document.getElementById('newsComments').innerHTML = html;
                });
        }

        function submitNewsComment() {
            if (!isLoggedIn) { window.location.href = 'login.php'; return; }
            var input = document.getElementById('newsCommentInput');
            var content = input.value.trim();
            if (!content) return;
            var fd = new FormData();
            fd.append('submission_id', newsId);
            fd.append('content', content);
            fd.append('source_type', 'news');
            document.getElementById('newsCommentBtn').disabled = true;
            fetch('/api/comments.php', { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    document.getElementById('newsCommentBtn').disabled = false;
                    if (d.status === 'success') {
                        input.value = '';
                        loadNewsComments();
                        ntoast(d.msg || '评论已提交');
                    } else {
                        ntoast(d.msg || '评论失败');
                    }
                })
                .catch(function() {
                    document.getElementById('newsCommentBtn').disabled = false;
                    ntoast('网络错误');
                });
        }

        function escapeHtml(s) {
            var d = document.createElement('div');
            d.appendChild(document.createTextNode(s || ''));
            return d.innerHTML;
        }
        function timeAgo(dt) {
            var diff = (Date.now() - new Date(dt).getTime()) / 1000;
            if (diff < 60) return '刚刚';
            if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
            if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
            return Math.floor(diff / 86400) + '天前';
        }

        <?php if ($id > 0 && $news): ?>
        loadNewsComments();
        <?php endif; ?>
    </script>

    <?php if ($id > 0 && $news && $is_logged_in && !empty($news['author_user_id'])): ?>
    <div id="newsTipModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9998;align-items:center;justify-content:center;">
        <div style="background:var(--surface);border:1px solid var(--line);border-radius:4px;padding:28px 24px;width:320px;max-width:90vw;text-align:center;">
            <div style="font-size:36px;margin-bottom:8px;">🪙</div>
            <div style="font-size:16px;font-weight:700;margin-bottom:16px;color:var(--ink);">投币支持</div>
            <div style="display:flex;gap:10px;margin-bottom:16px;">
                <button onclick="confirmNewsTip(1)" style="flex:1;padding:12px;border:1px solid var(--line);border-radius:3px;background:var(--surface);color:var(--gold);font-size:18px;font-weight:800;cursor:pointer;">1 🪙</button>
                <button onclick="confirmNewsTip(2)" style="flex:1;padding:12px;border:1px solid var(--line);border-radius:3px;background:var(--surface);color:var(--muted);font-size:18px;font-weight:800;cursor:pointer;">2 🪙</button>
            </div>
            <button onclick="closeNewsTip()" style="width:100%;padding:10px;border:1px solid var(--line);background:var(--surface);border-radius:3px;font-size:13px;font-weight:600;cursor:pointer;color:var(--muted);">取消</button>
        </div>
    </div>
    <?php endif; ?>

    <!-- News Image Fullscreen Viewer -->
    <div id="newsImgFullscreen" class="news-img-fullscreen" onclick="handleNewsFullscreenClick(event)">
        <button class="close-btn" onclick="closeNewsFullscreen()">&times;</button>
        <div class="img-container">
            <img id="newsFullscreenImg" src="" alt="Full Image">
        </div>
    </div>
</body>
</html>
