# -*- coding: utf-8 -*-
"""
唐诗三百首阅读器 (Tang Poems Reader)
技术栈：Python + Tkinter (零依赖，开箱即用)
运行：python tang_poems.py
"""

import json
import random
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox


# ============================================================
# 唐诗数据（精选71首，涵盖六大类别）
# ============================================================
POEMS_DATA = [
    # ===== 山水田园 =====
    {"title": "春晓", "author": "孟浩然", "category": "山水田园",
     "content": "春眠不觉晓，处处闻啼鸟。\n夜来风雨声，花落知多少。"},
    {"title": "鹿柴", "author": "王维", "category": "山水田园",
     "content": "空山不见人，但闻人语响。\n返景入深林，复照青苔上。"},
    {"title": "山居秋暝", "author": "王维", "category": "山水田园",
     "content": "空山新雨后，天气晚来秋。\n明月松间照，清泉石上流。\n竹喧归浣女，莲动下渔舟。\n随意春芳歇，王孙自可留。"},
    {"title": "过故人庄", "author": "孟浩然", "category": "山水田园",
     "content": "故人具鸡黍，邀我至田家。\n绿树村边合，青山郭外斜。\n开轩面场圃，把酒话桑麻。\n待到重阳日，还来就菊花。"},
    {"title": "渭川田家", "author": "王维", "category": "山水田园",
     "content": "斜阳照墟落，穷巷牛羊归。\n野老念牧童，倚杖候荆扉。\n雉雊麦苗秀，蚕眠桑叶稀。\n田夫荷锄至，相见语依依。\n即此羡闲逸，怅然吟式微。"},
    {"title": "鸟鸣涧", "author": "王维", "category": "山水田园",
     "content": "人闲桂花落，夜静春山空。\n月出惊山鸟，时鸣春涧中。"},
    {"title": "竹里馆", "author": "王维", "category": "山水田园",
     "content": "独坐幽篁里，弹琴复长啸。\n深林人不知，明月来相照。"},
    {"title": "辛夷坞", "author": "王维", "category": "山水田园",
     "content": "木末芙蓉花，山中发红萼。\n涧户寂无人，纷纷开且落。"},
    {"title": "滁州西涧", "author": "韦应物", "category": "山水田园",
     "content": "独怜幽草涧边生，上有黄鹂深树鸣。\n春潮带雨晚来急，野渡无人舟自横。"},

    # ===== 送别怀人 =====
    {"title": "送杜少府之任蜀州", "author": "王勃", "category": "送别怀人",
     "content": "城阙辅三秦，风烟望五津。\n与君离别意，同是宦游人。\n海内存知己，天涯若比邻。\n无为在歧路，儿女共沾巾。"},
    {"title": "黄鹤楼送孟浩然之广陵", "author": "李白", "category": "送别怀人",
     "content": "故人西辞黄鹤楼，烟花三月下扬州。\n孤帆远影碧空尽，唯见长江天际流。"},
    {"title": "送元二使安西", "author": "王维", "category": "送别怀人",
     "content": "渭城朝雨浥轻尘，客舍青青柳色新。\n劝君更尽一杯酒，西出阳关无故人。"},
    {"title": "赠汪伦", "author": "李白", "category": "送别怀人",
     "content": "李白乘舟将欲行，忽闻岸上踏歌声。\n桃花潭水深千尺，不及汪伦送我情。"},
    {"title": "别董大", "author": "高适", "category": "送别怀人",
     "content": "千里黄云白日曛，北风吹雁雪纷纷。\n莫愁前路无知己，天下谁人不识君。"},
    {"title": "芙蓉楼送辛渐", "author": "王昌龄", "category": "送别怀人",
     "content": "寒雨连江夜入吴，平明送客楚山孤。\n洛阳亲友如相问，一片冰心在玉壶。"},
    {"title": "送友人", "author": "李白", "category": "送别怀人",
     "content": "青山横北郭，白水绕东城。\n此地一为别，孤蓬万里征。\n浮云游子意，落日故人情。\n挥手自兹去，萧萧班马鸣。"},
    {"title": "赋得古原草送别", "author": "白居易", "category": "送别怀人",
     "content": "离离原上草，一岁一枯荣。\n野火烧不尽，春风吹又生。\n远芳侵古道，晴翠接荒城。\n又送王孙去，萋萋满别情。"},
    {"title": "金陵酒肆留别", "author": "李白", "category": "送别怀人",
     "content": "风吹柳花满店香，吴姬压酒劝客尝。\n金陵子弟来相送，欲行不行各尽觞。\n请君试问东流水，别意与之谁短长。"},

    # ===== 边塞军旅 =====
    {"title": "出塞", "author": "王昌龄", "category": "边塞军旅",
     "content": "秦时明月汉时关，万里长征人未还。\n但使龙城飞将在，不教胡马度阴山。"},
    {"title": "凉州词", "author": "王翰", "category": "边塞军旅",
     "content": "葡萄美酒夜光杯，欲饮琵琶马上催。\n醉卧沙场君莫笑，古来征战几人回？"},
    {"title": "凉州词", "author": "王之涣", "category": "边塞军旅",
     "content": "黄河远上白云间，一片孤城万仞山。\n羌笛何须怨杨柳，春风不度玉门关。"},
    {"title": "从军行·其四", "author": "王昌龄", "category": "边塞军旅",
     "content": "青海长云暗雪山，孤城遥望玉门关。\n黄沙百战穿金甲，不破楼兰终不还。"},
    {"title": "燕歌行", "author": "高适", "category": "边塞军旅",
     "content": "汉家烟尘在东北，汉将辞家破残贼。\n男儿本自重横行，天子非常赐颜色。\n摐金伐鼓下榆关，旌旆逶迤碣石间。\n校尉羽书飞瀚海，单于猎火照狼山。\n山川萧条极边土，胡骑凭陵杂风雨。\n战士军前半死生，美人帐下犹歌舞。\n大漠穷秋塞草腓，孤城落日斗兵稀。\n身当恩遇恒轻敌，力尽关山未解围。\n铁衣远戍辛勤久，玉箸应啼别离后。\n少妇城南欲断肠，征人蓟北空回首。\n边庭飘飖那可度，绝域苍茫更何有。\n杀气三时作阵云，寒声一夜传刁斗。\n相看白刃血纷纷，死节从来岂顾勋。\n君不见沙场征战苦，至今犹忆李将军。"},
    {"title": "塞下曲·其一", "author": "李白", "category": "边塞军旅",
     "content": "五月天山雪，无花只有寒。\n笛中闻折柳，春色未曾看。\n晓战随金鼓，宵眠抱玉鞍。\n愿将腰下剑，直为斩楼兰。"},
    {"title": "塞下曲·其二", "author": "卢纶", "category": "边塞军旅",
     "content": "林暗草惊风，将军夜引弓。\n平明寻白羽，没在石棱中。"},
    {"title": "塞下曲·其三", "author": "卢纶", "category": "边塞军旅",
     "content": "月黑雁飞高，单于夜遁逃。\n欲将轻骑逐，大雪满弓刀。"},

    # ===== 思乡羁旅 =====
    {"title": "静夜思", "author": "李白", "category": "思乡羁旅",
     "content": "床前明月光，疑是地上霜。\n举头望明月，低头思故乡。"},
    {"title": "九月九日忆山东兄弟", "author": "王维", "category": "思乡羁旅",
     "content": "独在异乡为异客，每逢佳节倍思亲。\n遥知兄弟登高处，遍插茱萸少一人。"},
    {"title": "枫桥夜泊", "author": "张继", "category": "思乡羁旅",
     "content": "月落乌啼霜满天，江枫渔火对愁眠。\n姑苏城外寒山寺，夜半钟声到客船。"},
    {"title": "次北固山下", "author": "王湾", "category": "思乡羁旅",
     "content": "客路青山外，行舟绿水前。\n潮平两岸阔，风正一帆悬。\n海日生残夜，江春入旧年。\n乡书何处达？归雁洛阳边。"},
    {"title": "早发白帝城", "author": "李白", "category": "思乡羁旅",
     "content": "朝辞白帝彩云间，千里江陵一日还。\n两岸猿声啼不住，轻舟已过万重山。"},
    {"title": "夜雨寄北", "author": "李商隐", "category": "思乡羁旅",
     "content": "君问归期未有期，巴山夜雨涨秋池。\n何当共剪西窗烛，却话巴山夜雨时。"},
    {"title": "商山早行", "author": "温庭筠", "category": "思乡羁旅",
     "content": "晨起动征铎，客行悲故乡。\n鸡声茅店月，人迹板桥霜。\n槲叶落山路，枳花明驿墙。\n因思杜陵梦，凫雁满回塘。"},
    {"title": "邯郸冬至夜思家", "author": "白居易", "category": "思乡羁旅",
     "content": "邯郸驿里逢冬至，抱膝灯前影伴身。\n想得家中夜深坐，还应说着远行人。"},

    # ===== 咏史怀古 =====
    {"title": "登鹳雀楼", "author": "王之涣", "category": "咏史怀古",
     "content": "白日依山尽，黄河入海流。\n欲穷千里目，更上一层楼。"},
    {"title": "黄鹤楼", "author": "崔颢", "category": "咏史怀古",
     "content": "昔人已乘黄鹤去，此地空余黄鹤楼。\n黄鹤一去不复返，白云千载空悠悠。\n晴川历历汉阳树，芳草萋萋鹦鹉洲。\n日暮乡关何处是？烟波江上使人愁。"},
    {"title": "登高", "author": "杜甫", "category": "咏史怀古",
     "content": "风急天高猿啸哀，渚清沙白鸟飞回。\n无边落木萧萧下，不尽长江滚滚来。\n万里悲秋常作客，百年多病独登台。\n艰难苦恨繁霜鬓，潦倒新停浊酒杯。"},
    {"title": "蜀相", "author": "杜甫", "category": "咏史怀古",
     "content": "丞相祠堂何处寻？锦官城外柏森森。\n映阶碧草自春色，隔叶黄鹂空好音。\n三顾频烦天下计，两朝开济老臣心。\n出师未捷身先死，长使英雄泪满襟。"},
    {"title": "乌衣巷", "author": "刘禹锡", "category": "咏史怀古",
     "content": "朱雀桥边野草花，乌衣巷口夕阳斜。\n旧时王谢堂前燕，飞入寻常百姓家。"},
    {"title": "石头城", "author": "刘禹锡", "category": "咏史怀古",
     "content": "山围故国周遭在，潮打空城寂寞回。\n淮水东边旧时月，夜深还过女墙来。"},
    {"title": "赤壁", "author": "杜牧", "category": "咏史怀古",
     "content": "折戟沉沙铁未销，自将磨洗认前朝。\n东风不与周郎便，铜雀春深锁二乔。"},
    {"title": "泊秦淮", "author": "杜牧", "category": "咏史怀古",
     "content": "烟笼寒水月笼沙，夜泊秦淮近酒家。\n商女不知亡国恨，隔江犹唱后庭花。"},
    {"title": "西塞山怀古", "author": "刘禹锡", "category": "咏史怀古",
     "content": "王濬楼船下益州，金陵王气黯然收。\n千寻铁锁沉江底，一片降幡出石头。\n人世几回伤往事，山形依旧枕寒流。\n今逢四海为家日，故垒萧萧芦荻秋。"},
    {"title": "登金陵凤凰台", "author": "李白", "category": "咏史怀古",
     "content": "凤凰台上凤凰游，凤去台空江自流。\n吴宫花草埋幽径，晋代衣冠成古丘。\n三山半落青天外，二水中分白鹭洲。\n总为浮云能蔽日，长安不见使人愁。"},

    # ===== 抒情言志 =====
    {"title": "将进酒", "author": "李白", "category": "抒情言志",
     "content": "君不见黄河之水天上来，奔流到海不复回。\n君不见高堂明镜悲白发，朝如青丝暮成雪。\n人生得意须尽欢，莫使金樽空对月。\n天生我材必有用，千金散尽还复来。\n烹羊宰牛且为乐，会须一饮三百杯。\n岑夫子，丹丘生，将进酒，杯莫停。\n与君歌一曲，请君为我倾耳听。\n钟鼓馔玉不足贵，但愿长醉不愿醒。\n古来圣贤皆寂寞，惟有饮者留其名。\n陈王昔时宴平乐，斗酒十千恣欢谑。\n主人何为言少钱，径须沽取对君酌。\n五花马，千金裘，呼儿将出换美酒，与尔同销万古愁。"},
    {"title": "行路难·其一", "author": "李白", "category": "抒情言志",
     "content": "金樽清酒斗十千，玉盘珍羞直万钱。\n停杯投箸不能食，拔剑四顾心茫然。\n欲渡黄河冰塞川，将登太行雪满山。\n闲来垂钓碧溪上，忽复乘舟梦日边。\n行路难，行路难，多歧路，今安在？\n长风破浪会有时，直挂云帆济沧海。"},
    {"title": "望岳", "author": "杜甫", "category": "抒情言志",
     "content": "岱宗夫如何？齐鲁青未了。\n造化钟神秀，阴阳割昏晓。\n荡胸生曾云，决眦入归鸟。\n会当凌绝顶，一览众山小。"},
    {"title": "春望", "author": "杜甫", "category": "抒情言志",
     "content": "国破山河在，城春草木深。\n感时花溅泪，恨别鸟惊心。\n烽火连三月，家书抵万金。\n白头搔更短，浑欲不胜簪。"},
    {"title": "游子吟", "author": "孟郊", "category": "抒情言志",
     "content": "慈母手中线，游子身上衣。\n临行密密缝，意恐迟迟归。\n谁言寸草心，报得三春晖。"},
    {"title": "悯农·其一", "author": "李绅", "category": "抒情言志",
     "content": "春种一粒粟，秋收万颗子。\n四海无闲田，农夫犹饿死。"},
    {"title": "悯农·其二", "author": "李绅", "category": "抒情言志",
     "content": "锄禾日当午，汗滴禾下土。\n谁知盘中餐，粒粒皆辛苦。"},
    {"title": "江雪", "author": "柳宗元", "category": "抒情言志",
     "content": "千山鸟飞绝，万径人踪灭。\n孤舟蓑笠翁，独钓寒江雪。"},
    {"title": "寻隐者不遇", "author": "贾岛", "category": "抒情言志",
     "content": "松下问童子，言师采药去。\n只在此山中，云深不知处。"},
    {"title": "乐游原", "author": "李商隐", "category": "抒情言志",
     "content": "向晚意不适，驱车登古原。\n夕阳无限好，只是近黄昏。"},
    {"title": "无题·相见时难别亦难", "author": "李商隐", "category": "抒情言志",
     "content": "相见时难别亦难，东风无力百花残。\n春蚕到死丝方尽，蜡炬成灰泪始干。\n晓镜但愁云鬓改，夜吟应觉月光寒。\n蓬山此去无多路，青鸟殷勤为探看。"},
    {"title": "锦瑟", "author": "李商隐", "category": "抒情言志",
     "content": "锦瑟无端五十弦，一弦一柱思华年。\n庄生晓梦迷蝴蝶，望帝春心托杜鹃。\n沧海月明珠有泪，蓝田日暖玉生烟。\n此情可待成追忆，只是当时已惘然。"},
    {"title": "登幽州台歌", "author": "陈子昂", "category": "抒情言志",
     "content": "前不见古人，后不见来者。\n念天地之悠悠，独怆然而涕下！"},
    {"title": "回乡偶书", "author": "贺知章", "category": "抒情言志",
     "content": "少小离家老大回，乡音无改鬓毛衰。\n儿童相见不相识，笑问客从何处来。"},
    {"title": "示儿", "author": "陆游", "category": "抒情言志",
     "content": "死去元知万事空，但悲不见九州同。\n王师北定中原日，家祭无忘告乃翁。"},
    {"title": "石灰吟", "author": "于谦", "category": "抒情言志",
     "content": "千锤万凿出深山，烈火焚烧若等闲。\n粉骨碎身浑不怕，要留清白在人间。"},
    {"title": "竹石", "author": "郑燮", "category": "抒情言志",
     "content": "咬定青山不放松，立根原在破岩中。\n千磨万击还坚劲，任尔东西南北风。"},
]

CATEGORIES = ["全部", "山水田园", "送别怀人", "边塞军旅", "思乡羁旅", "咏史怀古", "抒情言志", "❤ 我的收藏"]
FAVORITES_FILE = Path("favorites.json")


class TangPoemApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("📜 唐诗三百首阅读器")
        self.geometry("1100x720")
        self.minsize(900, 600)

        self.all_poems = POEMS_DATA[:]
        self.current_poems = []
        self.current_index = -1
        self.favorites = self.load_favorites()

        self.setup_ui()
        self.filter_poems()

    # --------------------------------------------------------
    # UI 构建
    # --------------------------------------------------------
    def setup_ui(self):
        # 主布局：左右分割
        main_pane = ttk.PanedWindow(self, orient=tk.HORIZONTAL)
        main_pane.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # --- 左侧面板 ---
        left_frame = ttk.Frame(main_pane, width=280)
        left_frame.pack_propagate(False)
        main_pane.add(left_frame, weight=0)

        # 搜索框
        search_frame = ttk.LabelFrame(left_frame, text="🔍 搜索")
        search_frame.pack(fill=tk.X, padx=5, pady=5)
        self.search_entry = ttk.Entry(search_frame)
        self.search_entry.pack(fill=tk.X, padx=5, pady=5)
        self.search_entry.bind("<KeyRelease>", self.on_search)

        # 分类列表
        cat_frame = ttk.LabelFrame(left_frame, text="📂 分类")
        cat_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        self.cat_listbox = tk.Listbox(cat_frame, font=("Microsoft YaHei", 10), activestyle="none")
        for cat in CATEGORIES:
            self.cat_listbox.insert(tk.END, cat)
        self.cat_listbox.selection_set(0)
        self.cat_listbox.bind("<<ListboxSelect>>", self.on_category_changed)
        self.cat_listbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 作者筛选
        author_frame = ttk.LabelFrame(left_frame, text="👤 作者")
        author_frame.pack(fill=tk.X, padx=5, pady=5)
        authors = sorted(set(p["author"] for p in POEMS_DATA))
        self.author_combo = ttk.Combobox(author_frame, values=["全部"] + authors, state="readonly")
        self.author_combo.set("全部")
        self.author_combo.bind("<<ComboboxSelected>>", lambda e: self.filter_poems())
        self.author_combo.pack(fill=tk.X, padx=5, pady=5)

        # 随机按钮
        random_btn = ttk.Button(left_frame, text="🎲 随机一首", command=self.random_poem)
        random_btn.pack(fill=tk.X, padx=5, pady=10)

        # --- 右侧面板 ---
        right_frame = ttk.Frame(main_pane)
        main_pane.add(right_frame, weight=1)

        # 顶部工具栏
        top_bar = ttk.Frame(right_frame)
        top_bar.pack(fill=tk.X, pady=(0, 5))

        self.count_label = ttk.Label(top_bar, text="📖 诗词列表", font=("", 10, "bold"))
        self.count_label.pack(side=tk.LEFT)

        self.prev_btn = ttk.Button(top_bar, text="⬅ 上一篇", command=self.prev_poem)
        self.prev_btn.pack(side=tk.RIGHT, padx=2)
        self.next_btn = ttk.Button(top_bar, text="下一篇 ➡", command=self.next_poem)
        self.next_btn.pack(side=tk.RIGHT, padx=2)

        # 诗词列表
        list_frame = ttk.Frame(right_frame)
        list_frame.pack(fill=tk.BOTH, expand=True)

        self.poem_listbox = tk.Listbox(list_frame, font=("Microsoft YaHei", 10), activestyle="dotbox")
        scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.poem_listbox.yview)
        self.poem_listbox.config(yscrollcommand=scrollbar.set)

        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.poem_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.poem_listbox.bind("<<ListboxSelect>>", self.on_poem_selected)

        # 诗词正文
        content_frame = ttk.LabelFrame(right_frame, text="📜 诗词正文")
        content_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        self.content_text = tk.Text(content_frame, wrap=tk.WORD, font=("SimSun", 14), relief=tk.FLAT, padx=10, pady=10)
        self.content_text.config(state=tk.DISABLED)
        content_scroll = ttk.Scrollbar(content_frame, command=self.content_text.yview)
        self.content_text.config(yscrollcommand=content_scroll.set)
        content_scroll.pack(side=tk.RIGHT, fill=tk.Y)
        self.content_text.pack(fill=tk.BOTH, expand=True)

        # 底部按钮栏
        bottom_bar = ttk.Frame(right_frame)
        bottom_bar.pack(fill=tk.X, pady=(5, 0))

        self.fav_btn = ttk.Button(bottom_bar, text="❤ 收藏", command=self.toggle_favorite)
        self.fav_btn.pack(side=tk.LEFT, padx=5)

        copy_btn = ttk.Button(bottom_bar, text="📋 复制", command=self.copy_poem)
        copy_btn.pack(side=tk.LEFT)

        self.status_label = ttk.Label(bottom_bar, text="")
        self.status_label.pack(side=tk.RIGHT)

    # --------------------------------------------------------
    # 数据 & 逻辑
    # --------------------------------------------------------
    def load_favorites(self):
        if FAVORITES_FILE.exists():
            try:
                return set(json.loads(FAVORITES_FILE.read_text(encoding="utf-8")))
            except:
                return set()
        return set()

    def save_favorites(self):
        FAVORITES_FILE.write_text(json.dumps(sorted(self.favorites), ensure_ascii=False, indent=2), encoding="utf-8")

    def get_selected_category(self):
        selection = self.cat_listbox.curselection()
        return self.cat_listbox.get(selection[0]) if selection else "全部"

    def filter_poems(self, event=None):
        category = self.get_selected_category()
        author = self.author_combo.get()

        poems = self.all_poems[:]

        if category == "❤ 我的收藏":
            poems = [p for p in poems if p["title"] in self.favorites]
        elif category != "全部":
            poems = [p for p in poems if p["category"] == category]

        if author != "全部":
            poems = [p for p in poems if p["author"] == author]

        self.current_poems = poems
        self.update_list()

    def update_list(self):
        self.poem_listbox.delete(0, tk.END)
        for poem in self.current_poems:
            prefix = "❤ " if poem["title"] in self.favorites else ""
            self.poem_listbox.insert(tk.END, f"{prefix}{poem['title']} —— {poem['author']}")

        self.count_label.config(text=f"📖 诗词列表   共 {len(self.current_poems)} 首")
        self.status_label.config(text=f"共 {len(self.current_poems)} 首 | 收藏 {len(self.favorites)} 首")

        if self.current_poems:
            self.poem_listbox.selection_set(0)
            self.display_poem(0)
        else:
            self.content_text.config(state=tk.NORMAL)
            self.content_text.delete(1.0, tk.END)
            self.content_text.config(state=tk.DISABLED)

    def display_poem(self, index):
        if not self.current_poems or index < 0 or index >= len(self.current_poems):
            return

        self.current_index = index
        poem = self.current_poems[index]

        self.content_text.config(state=tk.NORMAL)
        self.content_text.delete(1.0, tk.END)

        # 插入标题
        self.content_text.insert(tk.END, poem["title"] + "\n", "title")
        # 插入作者和分类
        self.content_text.insert(tk.END, f"〔{poem['author']} · {poem['category']}〕\n\n", "meta")
        # 插入内容
        self.content_text.insert(tk.END, poem["content"], "content")

        # 配置标签样式
        self.content_text.tag_config("title", font=("SimHei", 22, "bold"), justify="center")
        self.content_text.tag_config("meta", font=("SimSun", 12), foreground="#666", justify="center")
        self.content_text.tag_config("content", font=("SimSun", 16), spacing1=10, spacing2=5)
        
        self.content_text.config(state=tk.DISABLED)

        # 更新按钮状态
        is_fav = poem["title"] in self.favorites
        self.fav_btn.config(text="💔 取消收藏" if is_fav else "❤ 收藏")
        self.prev_btn.config(state=tk.NORMAL if index > 0 else tk.DISABLED)
        self.next_btn.config(state=tk.NORMAL if index < len(self.current_poems) - 1 else tk.DISABLED)

    # --------------------------------------------------------
    # 事件绑定
    # --------------------------------------------------------
    def on_category_changed(self, event):
        self.current_index = -1
        self.filter_poems()

    def on_search(self, event):
        keyword = self.search_entry.get().strip().lower()
        if not keyword:
            self.filter_poems()
            return

        results = []
        for poem in self.all_poems:
            if (keyword in poem["title"].lower() or
                keyword in poem["author"].lower() or
                keyword in poem["content"].lower()):
                results.append(poem)

        self.current_poems = results
        self.current_index = -1
        self.update_list()

    def on_poem_selected(self, event):
        selection = self.poem_listbox.curselection()
        if selection:
            self.display_poem(selection[0])

    def prev_poem(self):
        if self.current_index > 0:
            self.poem_listbox.selection_clear(self.current_index)
            self.poem_listbox.selection_set(self.current_index - 1)
            self.display_poem(self.current_index - 1)

    def next_poem(self):
        if self.current_index < len(self.current_poems) - 1:
            self.poem_listbox.selection_clear(self.current_index)
            self.poem_listbox.selection_set(self.current_index + 1)
            self.display_poem(self.current_index + 1)

    def random_poem(self):
        if self.current_poems:
            idx = random.randint(0, len(self.current_poems) - 1)
            self.poem_listbox.selection_clear(0, tk.END)
            self.poem_listbox.selection_set(idx)
            self.display_poem(idx)

    def toggle_favorite(self):
        if self.current_index < 0:
            return
        title = self.current_poems[self.current_index]["title"]
        if title in self.favorites:
            self.favorites.remove(title)
        else:
            self.favorites.add(title)
        self.save_favorites()
        self.filter_poems()
        self.display_poem(self.current_index)

    def copy_poem(self):
        if self.current_index < 0:
            return
        poem = self.current_poems[self.current_index]
        text = f"{poem['title']}\n〔{poem['author']}〕\n\n{poem['content']}"
        self.clipboard_clear()
        self.clipboard_append(text)
        messagebox.showinfo("已复制", "诗词已复制到剪贴板！")


# ------------------------------------------------------------
# 入口
# ------------------------------------------------------------
if __name__ == "__main__":
    app = TangPoemApp()
    app.mainloop()