import pygame
import sys
import random
import sqlite3
from datetime import datetime
import os

# 初始化pygame
pygame.init()

# 屏幕设置
WIDTH, HEIGHT = 1200, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("唐诗三百首 - 古典诗词鉴赏系统")

# 尝试加载中文字体
def load_chinese_font():
    """尝试加载中文字体"""
    font_paths = [
        # Windows 字体
        "C:/Windows/Fonts/simhei.ttf",  # 黑体
        "C:/Windows/Fonts/simsun.ttc",  # 宋体
        "C:/Windows/Fonts/msyh.ttc",    # 微软雅黑
        # macOS 字体
        "/System/Library/Fonts/PingFang.ttc",
        "/System/Library/Fonts/STHeiti Medium.ttc",
        # Linux 字体
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
        # 备用字体
        "simhei.ttf",
        "msyh.ttc"
    ]
    
    for font_path in font_paths:
        if os.path.exists(font_path):
            try:
                # 测试字体是否能加载
                pygame.font.Font(font_path, 20)
                return font_path
            except:
                continue
    
    print("警告：未找到中文字体，将使用系统默认字体")
    return None

# 加载字体
chinese_font_path = load_chinese_font()

# 字体设置（使用中文字体）
if chinese_font_path:
    font_small = pygame.font.Font(chinese_font_path, 20)
    font_medium = pygame.font.Font(chinese_font_path, 28)
    font_large = pygame.font.Font(chinese_font_path, 36)
    font_title = pygame.font.Font(chinese_font_path, 48)
    font_poem = pygame.font.Font(chinese_font_path, 32)  # 诗歌专用字体
else:
    # 如果找不到中文字体，使用默认字体
    font_small = pygame.font.Font(None, 24)
    font_medium = pygame.font.Font(None, 32)
    font_large = pygame.font.Font(None, 40)
    font_title = pygame.font.Font(None, 56)
    font_poem = pygame.font.Font(None, 36)
    print("注意：系统可能无法正常显示中文，请安装中文字体")

# 颜色定义（古风配色）
COLORS = {
    'bg': (250, 245, 235),           # 背景色 - 米白
    'primary': (139, 0, 0),          # 主色 - 深红
    'secondary': (165, 42, 42),      # 次要色 - 棕色
    'accent': (188, 143, 143),       # 强调色 - 玫瑰棕
    'text': (60, 40, 30),            # 文字色 - 深棕
    'light': (255, 250, 240),        # 浅色背景 - 象牙白
    'border': (210, 180, 140),       # 边框色 - 浅棕
    'button': (178, 34, 34),         # 按钮色 - 砖红
    'button_hover': (205, 92, 92),   # 按钮悬停色
    'button_text': (255, 255, 255),  # 按钮文字色
    'card_bg': (255, 253, 248),      # 卡片背景 - 淡黄
    'highlight': (218, 165, 32),     # 高亮色 - 金色
    'poem_text': (80, 60, 40),       # 诗歌文字色
    'author': (120, 90, 60),         # 作者文字色
}

# 数据库类
class TangPoetryDB:
    def __init__(self):
        self.conn = sqlite3.connect('tang_poetry.db', check_same_thread=False)
        self.init_database()
    
    def init_database(self):
        """初始化数据库"""
        cursor = self.conn.cursor()
        
        # 创建诗歌表
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS poems (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            author TEXT NOT NULL,
            dynasty TEXT,
            content TEXT NOT NULL,
            translation TEXT,
            annotation TEXT,
            appreciation TEXT,
            tags TEXT,
            category TEXT,
            difficulty INTEGER DEFAULT 2,
            popularity INTEGER DEFAULT 0,
            created_at TIMESTAMP
        )
        ''')
        
        self.conn.commit()
        
        # 插入示例数据
        self.insert_sample_data()
    
    def insert_sample_data(self):
        """插入示例唐诗数据"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM poems")
        if cursor.fetchone()[0] > 0:
            return
        
        sample_poems = self._get_sample_poems()
        current_time = datetime.now().isoformat()
        
        for poem in sample_poems:
            cursor.execute('''
            INSERT INTO poems (title, author, dynasty, content, translation, 
                             annotation, appreciation, tags, category, difficulty, 
                             popularity, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                poem['title'],
                poem['author'],
                poem['dynasty'],
                poem['content'],
                poem.get('translation', ''),
                poem.get('annotation', ''),
                poem.get('appreciation', ''),
                poem.get('tags', ''),
                poem.get('category', ''),
                poem.get('difficulty', 2),
                random.randint(10, 100),
                current_time
            ))
        
        self.conn.commit()
        print(f"已插入 {len(sample_poems)} 首唐诗到数据库")
    
    def _get_sample_poems(self):
        """返回示例唐诗数据"""
        return [
            {
                "title": "静夜思",
                "author": "李白",
                "dynasty": "唐",
                "content": "床前明月光，疑是地上霜。举头望明月，低头思故乡。",
                "translation": "明亮的月光洒在床前，好像地上泛起了一层白霜。我禁不住抬起头来，看着窗外空中的明月，不由得低头沉思，想起远方的家乡。",
                "annotation": "1. 静夜思：宁静的夜晚产生的思绪。\n2. 疑：好像。\n3. 举头：抬头。",
                "appreciation": "这首诗写的是在寂静的月夜思念家乡的感受。诗的前两句是写诗人在作客他乡的特定环境中一刹那间所产生的错觉。后两句通过动作神态的刻画，深化思乡之情。",
                "tags": "思乡,月亮,夜晚,抒情",
                "category": "抒情诗",
                "difficulty": 1
            },
            {
                "title": "春晓",
                "author": "孟浩然",
                "dynasty": "唐",
                "content": "春眠不觉晓，处处闻啼鸟。夜来风雨声，花落知多少。",
                "translation": "春日里贪睡不知不觉天已破晓，搅乱我酣眠的是那啁啾的小鸟。昨天夜里风声雨声一直不断，那娇美的春花不知被吹落了多少？",
                "annotation": "1. 春晓：春天的早晨。\n2. 不觉晓：不知不觉天就亮了。\n3. 啼鸟：鸟的啼叫声。",
                "appreciation": "这首诗是唐代诗人孟浩然隐居鹿门山时所作。诗人抓住春天的早晨刚刚醒来时的一瞬间展开联想，描绘了一幅春天早晨绚丽的图景。",
                "tags": "春天,早晨,自然,抒情",
                "category": "田园诗",
                "difficulty": 1
            },
            {
                "title": "登鹳雀楼",
                "author": "王之涣",
                "dynasty": "唐",
                "content": "白日依山尽，黄河入海流。欲穷千里目，更上一层楼。",
                "translation": "夕阳依傍着西山慢慢地沉没，滔滔黄河朝着东海汹涌奔流。若想把千里的风光景物看够，那就要登上更高的一层城楼。",
                "annotation": "1. 鹳雀楼：旧址在山西永济县，楼高三层，前对中条山，下临黄河。\n2. 依：依傍。\n3. 穷：尽，使达到极点。",
                "appreciation": "这首诗写诗人在登高望远中表现出来的不凡的胸襟抱负，反映了盛唐时期人们积极向上的进取精神。",
                "tags": "登高,哲理,黄河,山水",
                "category": "哲理诗",
                "difficulty": 1
            },
            {
                "title": "望庐山瀑布",
                "author": "李白",
                "dynasty": "唐",
                "content": "日照香炉生紫烟，遥看瀑布挂前川。飞流直下三千尺，疑是银河落九天。",
                "translation": "香炉峰在阳光的照射下生起紫色烟霞，远远望见瀑布似白色绢绸悬挂在山前。高崖上飞腾直落的瀑布好像有几千尺，让人恍惚以为银河从天上泻落到人间。",
                "annotation": "1. 香炉：指香炉峰。\n2. 紫烟：指日光透过云雾，远望如紫色的烟云。\n3. 遥看：从远处看。\n4. 挂：悬挂。",
                "appreciation": "这是诗人李白五十岁左右隐居庐山时写的一首风景诗。这首诗形象地描绘了庐山瀑布雄奇壮丽的景色，反映了诗人对祖国大好河山的无限热爱。",
                "tags": "庐山,瀑布,山水,自然",
                "category": "山水诗",
                "difficulty": 2
            },
            {
                "title": "悯农",
                "author": "李绅",
                "dynasty": "唐",
                "content": "锄禾日当午，汗滴禾下土。谁知盘中餐，粒粒皆辛苦。",
                "translation": "盛夏中午，烈日炎炎，农民还在劳作，汗珠滴入泥土。有谁想到，我们碗中的米饭，粒粒饱含着农民的血汗？",
                "annotation": "1. 悯：怜悯。\n2. 锄禾：用锄头松禾苗周围的土。\n3. 餐：一作'飧'。熟食的通称。",
                "appreciation": "这首诗描绘了在烈日当空的正午农民田里劳作的景象，概括地表现了农民终年辛勤劳动的生活，最后以'谁知盘中餐，粒粒皆辛苦'这样近似蕴意深远的格言，表达了诗人对农民真挚的同情之心。",
                "tags": "农民,劳动,悯农,社会",
                "category": "社会诗",
                "difficulty": 1
            },
            {
                "title": "江雪",
                "author": "柳宗元",
                "dynasty": "唐",
                "content": "千山鸟飞绝，万径人踪灭。孤舟蓑笠翁，独钓寒江雪。",
                "translation": "所有的山上，飞鸟的身影已经绝迹，所有道路都不见人的踪迹。江面孤舟上，一位披戴着蓑笠的老翁，独自在寒冷的江面上钓鱼。",
                "annotation": "1. 绝：无，没有。\n2. 万径：虚指，指千万条路。\n3. 人踪：人的脚印。\n4. 孤：孤零零。",
                "appreciation": "这首诗描绘了一幅渔翁寒江独钓图，表达了诗人在遭受打击之后不屈而又深感孤寂的情绪。全诗构思独特，语言简洁凝练，意蕴丰富。",
                "tags": "冬天,雪景,孤独,隐逸",
                "category": "隐逸诗",
                "difficulty": 2
            },
            {
                "title": "黄鹤楼送孟浩然之广陵",
                "author": "李白",
                "dynasty": "唐",
                "content": "故人西辞黄鹤楼，烟花三月下扬州。孤帆远影碧空尽，唯见长江天际流。",
                "translation": "老朋友向我频频挥手，告别了黄鹤楼，在这柳絮如烟、繁花似锦的阳春三月去扬州远游。友人的孤船帆影渐渐地远去，消失在碧空的尽头，只看见一线长江，向邈远的天际奔流。",
                "annotation": "1. 黄鹤楼：中国著名的名胜古迹。\n2. 之：往、到达。\n3. 广陵：即扬州。\n4. 故人：老朋友，这里指孟浩然。",
                "appreciation": "这首诗是李白出蜀壮游期间的作品，写诗人送别友人时无限依恋的感情，也写出祖国河山的壮丽美好。",
                "tags": "送别,友情,长江,春天",
                "category": "送别诗",
                "difficulty": 2
            },
            {
                "title": "枫桥夜泊",
                "author": "张继",
                "dynasty": "唐",
                "content": "月落乌啼霜满天，江枫渔火对愁眠。姑苏城外寒山寺，夜半钟声到客船。",
                "translation": "月亮已落下乌鸦啼叫寒气满天，对着江边枫树和渔火忧愁而眠。姑苏城外那寂寞清静寒山古寺，半夜里敲钟的声音传到了客船。",
                "annotation": "1. 枫桥：在今苏州市阊门外。\n2. 夜泊：夜间把船停靠在岸边。\n3. 乌啼：一说为乌鸦啼鸣，一说为乌啼镇。\n4. 霜满天：霜，不可能满天，这个'霜'字应当体会作严寒。",
                "appreciation": "这首七绝以一'愁'字统起。前二句意象密集：落月、啼乌、满天霜、江枫、渔火、不眠人，造成一种意韵浓郁的审美情境。后两句意象疏宕：城、寺、船、钟声，是一种空灵旷远的意境。",
                "tags": "夜晚,秋天,思乡,苏州",
                "category": "抒情诗",
                "difficulty": 3
            },
            {
                "title": "早发白帝城",
                "author": "李白",
                "dynasty": "唐",
                "content": "朝辞白帝彩云间，千里江陵一日还。两岸猿声啼不住，轻舟已过万重山。",
                "translation": "清晨告别五彩云霞映照中的白帝城，千里之遥的江陵，一天就可以到达。两岸猿声还在耳边不停地回荡，轻快的小舟已驶过万重青山。",
                "annotation": "1. 发：启程。\n2. 白帝城：故址在今重庆市奉节县白帝山上。\n3. 朝：早晨。\n4. 辞：告别。",
                "appreciation": "这首诗写的是从白帝城到江陵一天之内的行程情况，主要突出轻快，这也反映了李白心情的轻快。诗人把遇赦后愉快的心情和江山的壮丽多姿、顺水行舟的流畅轻快融为一体来表达。",
                "tags": "长江,行舟,山水,抒情",
                "category": "山水诗",
                "difficulty": 2
            },
            {
                "title": "相思",
                "author": "王维",
                "dynasty": "唐",
                "content": "红豆生南国，春来发几枝。愿君多采撷，此物最相思。",
                "translation": "红豆生长在阳光明媚的南方，每逢春天不知长多少新枝。希望思念的人儿多多采摘，因为它最能寄托相思之情。",
                "annotation": "1. 相思：题一作'相思子'。\n2. 红豆：又名相思子，一种生在江南地区的植物，结出的籽像豌豆而稍扁，呈鲜红色。\n3. 采撷（xié）：采摘。",
                "appreciation": "这是借咏物而寄相思的诗，是眷怀友人之作。全诗情调健美高雅，怀思饱满奔放，语言朴素无华，韵律和谐柔美。可谓绝句的上乘佳品！",
                "tags": "相思,爱情,友情,抒情",
                "category": "抒情诗",
                "difficulty": 1
            },
            {
                "title": "夜宿山寺",
                "author": "李白",
                "dynasty": "唐",
                "content": "危楼高百尺，手可摘星辰。不敢高声语，恐惊天上人。",
                "translation": "山上寺院的高楼真高啊，好像有一百尺的样子，人在楼上好像一伸手就可以摘下天上的星星。站在这里，我不敢大声说话，唯恐惊动天上的神仙。",
                "annotation": "1. 宿：住，过夜。\n2. 危楼：高楼，这里指山顶的寺庙。\n3. 百尺：虚指，不是实数，这里形容楼很高。",
                "appreciation": "这首诗语言朴素自然，却形象逼真。全诗无一生僻字，却字字惊人，堪称'平字见奇'的绝世佳作。诗人借助大胆想象，渲染山寺之奇高，把山寺的高耸和夜晚的恐惧写的很逼真。",
                "tags": "山寺,夜晚,想象,夸张",
                "category": "写景诗",
                "difficulty": 1
            }
        ]
    
    def search_poems(self, query="", author="", category="", difficulty=(1, 5), limit=50):
        """搜索诗歌"""
        cursor = self.conn.cursor()
        
        conditions = []
        params = []
        
        if query:
            conditions.append("(title LIKE ? OR content LIKE ? OR tags LIKE ?)")
            like_query = f"%{query}%"
            params.extend([like_query, like_query, like_query])
        
        if author:
            conditions.append("author = ?")
            params.append(author)
        
        if category:
            conditions.append("category = ?")
            params.append(category)
        
        if difficulty:
            min_diff, max_diff = difficulty
            conditions.append("difficulty BETWEEN ? AND ?")
            params.extend([min_diff, max_diff])
        
        where_clause = " AND ".join(conditions) if conditions else "1=1"
        
        sql = f"""
        SELECT * FROM poems 
        WHERE {where_clause}
        ORDER BY popularity DESC, title
        LIMIT ?
        """
        params.append(limit)
        
        cursor.execute(sql, params)
        columns = [col[0] for col in cursor.description]
        return [dict(zip(columns, row)) for row in cursor.fetchall()]
    
    def get_authors(self):
        """获取所有诗人"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT DISTINCT author FROM poems ORDER BY author")
        return [row[0] for row in cursor.fetchall()]
    
    def get_categories(self):
        """获取所有分类"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT DISTINCT category FROM poems WHERE category != '' ORDER BY category")
        return [row[0] for row in cursor.fetchall()]
    
    def get_random_poem(self):
        """获取随机诗歌"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT * FROM poems ORDER BY RANDOM() LIMIT 1")
        columns = [col[0] for col in cursor.description]
        row = cursor.fetchone()
        return dict(zip(columns, row)) if row else None
    
    def get_statistics(self):
        """获取统计信息"""
        cursor = self.conn.cursor()
        
        stats = {}
        cursor.execute("SELECT COUNT(*) FROM poems")
        stats['total_poems'] = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(DISTINCT author) FROM poems")
        stats['total_authors'] = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(DISTINCT category) FROM poems WHERE category != ''")
        stats['total_categories'] = cursor.fetchone()[0]
        
        cursor.execute("SELECT author, COUNT(*) as count FROM poems GROUP BY author ORDER BY count DESC LIMIT 5")
        stats['top_authors'] = cursor.fetchall()
        
        cursor.execute("SELECT category, COUNT(*) as count FROM poems WHERE category != '' GROUP BY category ORDER BY count DESC")
        stats['category_dist'] = cursor.fetchall()
        
        return stats
    
    def get_all_poems(self):
        """获取所有诗歌"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT * FROM poems ORDER BY author, title")
        columns = [col[0] for col in cursor.description]
        return [dict(zip(columns, row)) for row in cursor.fetchall()]

# UI组件类
class UIComponent:
    @staticmethod
    def draw_text(surface, text, pos, font, color=COLORS['text'], centered=False, max_width=None):
        """绘制文字（支持自动换行）"""
        if not text:
            return pygame.Rect(pos[0], pos[1], 0, 0)
        
        # 如果指定最大宽度，进行自动换行
        if max_width:
            words = text.split(' ')
            lines = []
            current_line = []
            
            for word in words:
                # 测试添加这个词后是否超出宽度
                test_line = ' '.join(current_line + [word])
                test_width = font.size(test_line)[0]
                
                if test_width <= max_width:
                    current_line.append(word)
                else:
                    if current_line:
                        lines.append(' '.join(current_line))
                    current_line = [word]
            
            if current_line:
                lines.append(' '.join(current_line))
            
            # 绘制多行文本
            y_offset = 0
            max_rect = None
            for line in lines:
                text_surface = font.render(line, True, color)
                text_rect = text_surface.get_rect()
                if centered:
                    text_rect.centerx = pos[0]
                    text_rect.top = pos[1] + y_offset
                else:
                    text_rect.topleft = (pos[0], pos[1] + y_offset)
                
                surface.blit(text_surface, text_rect)
                y_offset += font.get_linesize()
                
                if max_rect:
                    max_rect.union_ip(text_rect)
                else:
                    max_rect = text_rect
            
            return max_rect if max_rect else pygame.Rect(pos[0], pos[1], 0, 0)
        else:
            # 单行文本
            text_surface = font.render(text, True, color)
            if centered:
                text_rect = text_surface.get_rect(center=(pos[0], pos[1]))
            else:
                text_rect = text_surface.get_rect(topleft=pos)
            
            surface.blit(text_surface, text_rect)
            return text_rect
    
    @staticmethod
    def draw_button(surface, text, rect, font, bg_color=COLORS['button'], 
                    hover_color=COLORS['button_hover'], text_color=COLORS['button_text'],
                    hover=False, border_radius=8):
        """绘制按钮"""
        color = hover_color if hover else bg_color
        pygame.draw.rect(surface, color, rect, border_radius=border_radius)
        pygame.draw.rect(surface, COLORS['border'], rect, 2, border_radius=border_radius)
        
        text_surface = font.render(text, True, text_color)
        text_rect = text_surface.get_rect(center=rect.center)
        surface.blit(text_surface, text_rect)
        return rect
    
    @staticmethod
    def draw_card(surface, rect, color=COLORS['card_bg'], border=True, border_radius=12):
        """绘制卡片"""
        pygame.draw.rect(surface, color, rect, border_radius=border_radius)
        if border:
            pygame.draw.rect(surface, COLORS['border'], rect, 2, border_radius=border_radius)
    
    @staticmethod
    def draw_poem_content(surface, content, pos, font, color=COLORS['poem_text'], centered=True):
        """绘制诗歌内容（每句一行）"""
        lines = content.split('，')
        if not lines:
            lines = content.split(',')
        
        y_offset = 0
        max_width = 0
        
        for i, line in enumerate(lines):
            # 清理标点
            line = line.replace('。', '').replace('！', '').replace('？', '').replace('；', '').strip()
            if line:
                text_surface = font.render(line, True, color)
                text_rect = text_surface.get_rect()
                
                if centered:
                    text_rect.centerx = pos[0]
                    text_rect.top = pos[1] + y_offset
                else:
                    text_rect.topleft = (pos[0], pos[1] + y_offset)
                
                surface.blit(text_surface, text_rect)
                y_offset += font.get_height() + 10
                max_width = max(max_width, text_rect.width)
        
        return pygame.Rect(pos[0] - max_width//2, pos[1], max_width, y_offset)

# 主应用类
class TangPoetryApp:
    def __init__(self):
        self.db = TangPoetryDB()
        self.current_page = "home"
        self.scroll_pos = 0
        self.search_query = ""
        self.selected_poem = None
        self.selected_category = ""
        self.selected_author = ""
        self.difficulty_range = (1, 5)
        self.clock = pygame.time.Clock()
        self.running = True
        self.input_active = False
        self.input_text = ""
        
        # 创建背景
        self.create_background()
        
        # 打印字体信息
        if chinese_font_path:
            print(f"已加载中文字体: {chinese_font_path}")
        else:
            print("警告：使用默认字体，中文可能显示异常")
            print("建议安装中文字体，如：黑体、宋体、微软雅黑等")
    
    def create_background(self):
        """创建背景图案"""
        self.background = pygame.Surface((WIDTH, HEIGHT))
        self.background.fill(COLORS['bg'])
        
        # 添加古典花纹背景
        for i in range(0, WIDTH, 100):
            for j in range(0, HEIGHT, 100):
                # 绘制简单的装饰性图案
                rect = pygame.Rect(i, j, 100, 100)
                pygame.draw.rect(self.background, (245, 240, 230), rect, 1)
        
        # 添加标题装饰
        title_bg = pygame.Surface((WIDTH, 120))
        title_bg.fill(COLORS['primary'])
        
        # 添加渐变效果
        for i in range(120):
            alpha = 255 - i * 2
            if alpha < 0:
                alpha = 0
            color = (139, 0, 0, alpha)
            pygame.draw.line(title_bg, color, (0, i), (WIDTH, i))
        
        self.title_bg = title_bg
    
    def handle_events(self):
        """处理事件"""
        mouse_pos = pygame.mouse.get_pos()
        mouse_pressed = pygame.mouse.get_pressed()
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                elif event.key == pygame.K_h:
                    self.current_page = "home"
                    self.scroll_pos = 0
                elif event.key == pygame.K_s:
                    self.current_page = "search"
                    self.scroll_pos = 0
                elif event.key == pygame.K_r:
                    self.current_page = "random"
                    self.selected_poem = self.db.get_random_poem()
                elif event.key == pygame.K_t:
                    self.current_page = "statistics"
                elif event.key == pygame.K_b:
                    self.current_page = "browse"
                    self.scroll_pos = 0
                
                # 处理文本输入
                elif self.input_active:
                    if event.key == pygame.K_RETURN:
                        self.search_query = self.input_text
                        self.input_text = ""
                        self.input_active = False
                    elif event.key == pygame.K_BACKSPACE:
                        self.input_text = self.input_text[:-1]
                    else:
                        # 过滤控制字符
                        if event.unicode and ord(event.unicode) >= 32:
                            self.input_text += event.unicode
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 4:  # 滚轮向上
                    self.scroll_pos = max(0, self.scroll_pos - 30)
                elif event.button == 5:  # 滚轮向下
                    self.scroll_pos += 30
                elif event.button == 1:  # 左键点击
                    self.handle_mouse_click(mouse_pos)
    
    def handle_mouse_click(self, mouse_pos):
        """处理鼠标点击"""
        x, y = mouse_pos
        
        # 导航按钮
        nav_buttons = [
            (100, 60, 100, 40, "home"),
            (250, 60, 100, 40, "search"),
            (400, 60, 100, 40, "random"),
            (550, 60, 100, 40, "statistics"),
            (700, 60, 100, 40, "browse"),
        ]
        
        for btn_x, btn_y, btn_w, btn_h, page in nav_buttons:
            if btn_x <= x <= btn_x + btn_w and btn_y <= y <= btn_y + btn_h:
                self.current_page = page
                self.scroll_pos = 0
                if page == "random":
                    self.selected_poem = self.db.get_random_poem()
                return
        
        # 搜索页面
        if self.current_page == "search":
            # 搜索框
            if 100 <= x <= 900 and 200 <= y <= 250:
                self.input_active = True
                self.input_text = self.search_query
            # 搜索按钮
            elif 950 <= x <= 1050 and 200 <= y <= 250:
                self.search_query = self.input_text
                self.input_active = False
            # 随机按钮
            elif 1100 <= x <= 1200 and 200 <= y <= 250:
                self.selected_poem = self.db.get_random_poem()
                self.current_page = "random"
        
        # 随机页面
        elif self.current_page == "random":
            # 随机按钮
            if WIDTH//2 - 100 <= x <= WIDTH//2 + 100 and HEIGHT - 100 <= y <= HEIGHT - 50:
                self.selected_poem = self.db.get_random_poem()
    
    def draw_home_page(self):
        """绘制主页"""
        # 绘制欢迎标题
        UIComponent.draw_text(screen, "唐诗三百首", (WIDTH//2, 180), 
                            font_title, COLORS['primary'], centered=True)
        UIComponent.draw_text(screen, "古典诗词鉴赏系统", (WIDTH//2, 240), 
                            font_medium, COLORS['secondary'], centered=True)
        
        # 绘制功能说明卡片
        card_rect = pygame.Rect(100, 300, WIDTH-200, 400)
        UIComponent.draw_card(screen, card_rect)
        
        welcome_text = [
            "欢迎使用《唐诗三百首》鉴赏系统！",
            "",
            "本系统收录了唐代最经典的诗歌作品，",
            "包含详细的注释、翻译和赏析内容。",
            "",
            "📚 系统功能：",
            "• 主页：系统概览和快速导航",
            "• 搜索：按条件查找诗歌作品",
            "• 随机：随机欣赏一首唐诗",
            "• 统计：查看系统数据和分析",
            "• 浏览：查看所有诗歌列表",
            "",
            "⌨️ 快捷键：",
            "H - 主页 | S - 搜索 | R - 随机",
            "T - 统计 | B - 浏览 | ESC - 退出",
            "",
            "🎯 今日推荐："
        ]
        
        y_offset = 320
        for line in welcome_text:
            UIComponent.draw_text(screen, line, (120, y_offset), font_small, COLORS['text'])
            y_offset += 30
        
        # 显示随机推荐
        random_poem = self.db.get_random_poem()
        if random_poem:
            rec_rect = pygame.Rect(120, y_offset, WIDTH-240, 80)
            UIComponent.draw_card(screen, rec_rect, color=(255, 248, 220))
            
            UIComponent.draw_text(screen, f"《{random_poem['title']}》 - {random_poem['author']}", 
                                (WIDTH//2, y_offset + 20), font_medium, COLORS['primary'], centered=True)
            
            # 显示前两句
            content = random_poem['content']
            if '，' in content:
                first_line = content.split('，')[0] + '，'
                UIComponent.draw_text(screen, first_line, (WIDTH//2, y_offset + 50), 
                                    font_small, COLORS['text'], centered=True)
    
    def draw_search_page(self):
        """绘制搜索页面"""
        # 绘制标题
        UIComponent.draw_text(screen, "🔍 搜索唐诗", (WIDTH//2, 150), 
                            font_title, COLORS['primary'], centered=True)
        
        # 绘制搜索框
        search_rect = pygame.Rect(100, 200, 800, 50)
        UIComponent.draw_card(screen, search_rect)
        
        # 输入框
        input_rect = pygame.Rect(110, 210, 780, 30)
        pygame.draw.rect(screen, (255, 255, 255), input_rect, border_radius=4)
        pygame.draw.rect(screen, COLORS['border'], input_rect, 2, border_radius=4)
        
        # 显示输入文本
        display_text = self.input_text if self.input_active else self.search_query
        if not display_text:
            UIComponent.draw_text(screen, "请输入诗歌标题、作者或内容关键词...", 
                                (120, 215), font_small, (180, 180, 180))
        else:
            UIComponent.draw_text(screen, display_text, (120, 215), font_medium)
        
        # 搜索按钮
        search_btn = pygame.Rect(950, 200, 100, 50)
        hover = search_btn.collidepoint(pygame.mouse.get_pos())
        UIComponent.draw_button(screen, "搜索", search_btn, font_medium, hover=hover)
        
        # 随机按钮
        random_btn = pygame.Rect(1100, 200, 100, 50)
        hover = random_btn.collidepoint(pygame.mouse.get_pos())
        UIComponent.draw_button(screen, "随机", random_btn, font_medium, hover=hover)
        
        # 执行搜索并显示结果
        if self.search_query:
            poems = self.db.search_poems(
                query=self.search_query,
                author=self.selected_author,
                category=self.selected_category,
                difficulty=self.difficulty_range
            )
            
            # 显示结果数量
            UIComponent.draw_text(screen, f"找到 {len(poems)} 个结果", 
                                (WIDTH//2, 270), font_medium, COLORS['secondary'], centered=True)
            
            # 显示搜索结果
            results_rect = pygame.Rect(100, 300, WIDTH-200, HEIGHT-350)
            UIComponent.draw_card(screen, results_rect)
            
            y_offset = 320 - self.scroll_pos
            for i, poem in enumerate(poems[:10]):  # 只显示前10个
                if y_offset > 300 and y_offset < HEIGHT - 100:
                    # 绘制诗歌卡片
                    poem_rect = pygame.Rect(120, y_offset, WIDTH-260, 70)
                    UIComponent.draw_card(screen, poem_rect, color=(255, 250, 240), border=False)
                    
                    # 诗歌信息
                    UIComponent.draw_text(screen, f"《{poem['title']}》", 
                                        (140, y_offset + 15), font_medium, COLORS['primary'])
                    UIComponent.draw_text(screen, f"{poem['author']} | {poem['dynasty']}", 
                                        (140, y_offset + 45), font_small, COLORS['author'])
                    
                    # 显示前几个字
                    preview = poem['content'][:20] + "..."
                    UIComponent.draw_text(screen, preview, (400, y_offset + 30), 
                                        font_small, COLORS['text'])
                    
                    # 查看按钮
                    view_btn = pygame.Rect(WIDTH-180, y_offset + 15, 60, 40)
                    hover = view_btn.collidepoint(pygame.mouse.get_pos())
                    UIComponent.draw_button(screen, "查看", view_btn, font_small, hover=hover)
                    
                    # 如果点击了查看按钮
                    if hover and pygame.mouse.get_pressed()[0]:
                        self.selected_poem = poem
                        self.current_page = "random"
                
                y_offset += 80
        else:
            # 显示搜索提示
            tip_rect = pygame.Rect(100, 300, WIDTH-200, 200)
            UIComponent.draw_card(screen, tip_rect)
            
            tips = [
                "💡 搜索提示：",
                "",
                "1. 可以搜索诗歌标题，如：'静夜思'",
                "2. 可以搜索诗人姓名，如：'李白'",
                "3. 可以搜索诗歌内容，如：'明月'",
                "4. 可以搜索诗歌分类，如：'山水诗'",
                "",
                "试试搜索以下关键词：",
                "• 李白 • 春天 • 月亮 • 送别 • 山水"
            ]
            
            y_offset = 320
            for tip in tips:
                UIComponent.draw_text(screen, tip, (120, y_offset), font_small, COLORS['text'])
                y_offset += 25
    
    def draw_random_page(self):
        """绘制随机页面"""
        if not self.selected_poem:
            self.selected_poem = self.db.get_random_poem()
        
        if self.selected_poem:
            # 绘制诗歌卡片
            poem_rect = pygame.Rect(100, 150, WIDTH-200, HEIGHT-250)
            UIComponent.draw_card(screen, poem_rect)
            
            # 诗歌标题
            UIComponent.draw_text(screen, f"《{self.selected_poem['title']}》", 
                                (WIDTH//2, 180), font_large, COLORS['primary'], centered=True)
            
            # 作者信息
            UIComponent.draw_text(screen, f"{self.selected_poem['author']} 〔{self.selected_poem['dynasty']}〕", 
                                (WIDTH//2, 230), font_medium, COLORS['secondary'], centered=True)
            
            # 诗歌内容
            content_rect = UIComponent.draw_poem_content(screen, self.selected_poem['content'], 
                                                        (WIDTH//2, 280), font_poem, centered=True)
            
            y_offset = content_rect.bottom + 40
            
            # 分隔线
            pygame.draw.line(screen, COLORS['border'], (150, y_offset), 
                           (WIDTH-150, y_offset), 2)
            y_offset += 30
            
            # 翻译
            if self.selected_poem.get('translation'):
                UIComponent.draw_text(screen, "【白话翻译】", (150, y_offset), 
                                    font_medium, COLORS['accent'])
                y_offset += 40
                
                # 显示翻译（自动换行）
                translation = self.selected_poem['translation']
                trans_rect = UIComponent.draw_text(screen, translation, (170, y_offset), 
                                                  font_small, COLORS['text'], max_width=WIDTH-340)
                y_offset = trans_rect.bottom + 30
            
            # 赏析
            if self.selected_poem.get('appreciation'):
                UIComponent.draw_text(screen, "【诗歌赏析】", (150, y_offset), 
                                    font_medium, COLORS['accent'])
                y_offset += 40
                
                # 显示赏析（自动换行）
                appreciation = self.selected_poem['appreciation']
                app_rect = UIComponent.draw_text(screen, appreciation, (170, y_offset), 
                                                font_small, COLORS['text'], max_width=WIDTH-340)
                y_offset = app_rect.bottom + 30
            
            # 随机按钮
            random_btn = pygame.Rect(WIDTH//2 - 100, HEIGHT - 100, 200, 50)
            hover = random_btn.collidepoint(pygame.mouse.get_pos())
            UIComponent.draw_button(screen, "🎲 随机下一首", random_btn, 
                                  font_medium, hover=hover)
    
    def draw_statistics_page(self):
        """绘制统计页面"""
        # 绘制标题
        UIComponent.draw_text(screen, "📊 系统统计", (WIDTH//2, 150), 
                            font_title, COLORS['primary'], centered=True)
        
        stats = self.db.get_statistics()
        
        # 统计卡片
        stat_cards = [
            ("诗歌总数", stats['total_poems'], "📚", COLORS['primary']),
            ("诗人数量", stats['total_authors'], "👨‍🎨", COLORS['secondary']),
            ("分类数量", stats['total_categories'], "📁", COLORS['accent']),
        ]
        
        for i, (title, value, icon, color) in enumerate(stat_cards):
            card_rect = pygame.Rect(150 + i * 300, 220, 250, 150)
            UIComponent.draw_card(screen, card_rect)
            
            UIComponent.draw_text(screen, icon, (card_rect.centerx, card_rect.y + 30), 
                                font_large, color, centered=True)
            UIComponent.draw_text(screen, title, (card_rect.centerx, card_rect.y + 80), 
                                font_medium, COLORS['text'], centered=True)
            UIComponent.draw_text(screen, str(value), (card_rect.centerx, card_rect.y + 110), 
                                font_large, color, centered=True)
        
        # 热门诗人
        authors_rect = pygame.Rect(150, 400, WIDTH-300, 200)
        UIComponent.draw_card(screen, authors_rect)
        
        UIComponent.draw_text(screen, "🏆 热门诗人 TOP 5", (WIDTH//2, 420), 
                            font_medium, COLORS['primary'], centered=True)
        
        y_offset = 450
        for i, (author, count) in enumerate(stats['top_authors']):
            UIComponent.draw_text(screen, f"{i+1}. {author}", (200, y_offset), font_medium)
            UIComponent.draw_text(screen, f"作品数：{count}", (WIDTH-300, y_offset), 
                                font_medium, COLORS['secondary'])
            y_offset += 40
        
        # 分类分布
        if stats['category_dist']:
            cat_rect = pygame.Rect(150, 620, WIDTH-300, 120)
            UIComponent.draw_card(screen, cat_rect)
            
            UIComponent.draw_text(screen, "📈 诗歌分类分布", (WIDTH//2, 640), 
                                font_medium, COLORS['primary'], centered=True)
            
            # 显示分类
            categories_text = " | ".join([f"{cat}({count})" for cat, count in stats['category_dist'][:6]])
            UIComponent.draw_text(screen, categories_text, (WIDTH//2, 680), 
                                font_small, COLORS['text'], centered=True)
    
    def draw_browse_page(self):
        """绘制浏览页面"""
        # 绘制标题
        UIComponent.draw_text(screen, "📚 所有诗歌", (WIDTH//2, 150), 
                            font_title, COLORS['primary'], centered=True)
        
        poems = self.db.get_all_poems()
        
        # 显示诗歌列表
        list_rect = pygame.Rect(100, 200, WIDTH-200, HEIGHT-250)
        UIComponent.draw_card(screen, list_rect)
        
        y_offset = 220 - self.scroll_pos
        for i, poem in enumerate(poems):
            if y_offset > 200 and y_offset < HEIGHT - 100:
                # 绘制诗歌项
                item_rect = pygame.Rect(120, y_offset, WIDTH-260, 60)
                color = (255, 250, 240) if i % 2 == 0 else (255, 253, 248)
                UIComponent.draw_card(screen, item_rect, color=color, border=False)
                
                # 编号和标题
                UIComponent.draw_text(screen, f"{i+1:03d}. 《{poem['title']}》", 
                                    (140, y_offset + 20), font_medium, COLORS['primary'])
                
                # 作者信息
                UIComponent.draw_text(screen, f"{poem['author']} | {poem['dynasty']} | {poem.get('category', '未分类')}", 
                                    (140, y_offset + 45), font_small, COLORS['author'])
                
                # 查看按钮
                view_btn = pygame.Rect(WIDTH-180, y_offset + 10, 60, 40)
                hover = view_btn.collidepoint(pygame.mouse.get_pos())
                UIComponent.draw_button(screen, "查看", view_btn, font_small, hover=hover)
                
                # 如果点击了查看按钮
                if hover and pygame.mouse.get_pressed()[0]:
                    self.selected_poem = poem
                    self.current_page = "random"
            
            y_offset += 70
    
    def draw_navigation(self):
        """绘制导航栏"""
        # 绘制标题背景
        screen.blit(self.title_bg, (0, 0))
        
        # 应用标题
        UIComponent.draw_text(screen, "《唐诗三百首》鉴赏系统", (WIDTH//2, 40), 
                            font_title, COLORS['button_text'], centered=True)
        
        # 导航按钮
        nav_items = [
            ("🏠 主页", "home"),
            ("🔍 搜索", "search"),
            ("🎲 随机", "random"),
            ("📊 统计", "statistics"),
            ("📚 浏览", "browse"),
        ]
        
        for i, (text, page) in enumerate(nav_items):
            x = 100 + i * 150
            color = COLORS['highlight'] if self.current_page == page else COLORS['button_text']
            
            # 绘制按钮背景
            btn_rect = pygame.Rect(x, 60, 100, 40)
            if btn_rect.collidepoint(pygame.mouse.get_pos()):
                pygame.draw.rect(screen, (255, 255, 255, 100), btn_rect, border_radius=8)
            
            UIComponent.draw_text(screen, text, (x + 50, 80), font_medium, color, centered=True)
    
    def draw(self):
        """绘制整个界面"""
        # 绘制背景
        screen.blit(self.background, (0, 0))
        
        # 绘制导航栏
        self.draw_navigation()
        
        # 根据当前页面绘制内容
        if self.current_page == "home":
            self.draw_home_page()
        elif self.current_page == "search":
            self.draw_search_page()
        elif self.current_page == "random":
            self.draw_random_page()
        elif self.current_page == "statistics":
            self.draw_statistics_page()
        elif self.current_page == "browse":
            self.draw_browse_page()
        
        # 绘制页脚
        footer_rect = pygame.Rect(0, HEIGHT-30, WIDTH, 30)
        pygame.draw.rect(screen, COLORS['primary'], footer_rect)
        UIComponent.draw_text(screen, "© 2024 唐诗三百首鉴赏系统 | 按ESC键退出程序", 
                            (WIDTH//2, HEIGHT-20), font_small, 
                            COLORS['button_text'], centered=True)
        
        # 如果输入框激活，显示光标
        if self.input_active and pygame.time.get_ticks() % 1000 < 500:
            cursor_x = 120 + font_medium.size(self.input_text)[0]
            pygame.draw.line(screen, COLORS['primary'], (cursor_x, 215), (cursor_x, 240), 2)
    
    def run(self):
        """运行主循环"""
        print("=" * 50)
        print("唐诗三百首鉴赏系统")
        print("=" * 50)
        print("正在启动...")
        print(f"数据库已初始化，包含 {self.db.get_statistics()['total_poems']} 首唐诗")
        print("使用说明：")
        print("• 鼠标点击导航栏切换页面")
        print("• 在搜索页面可以输入关键词查找诗歌")
        print("• 随机页面可以欣赏随机选择的唐诗")
        print("• 使用快捷键快速导航：H/S/R/T/B/ESC")
        print("=" * 50)
        
        while self.running:
            self.handle_events()
            self.draw()
            pygame.display.flip()
            self.clock.tick(60)
        
        pygame.quit()
        sys.exit()

# 运行应用
if __name__ == "__main__":
    app = TangPoetryApp()
    app.run()