import tkinter as tk
from tkinter import messagebox, ttk
import random
import json
import os
from datetime import datetime

# ==================== 词库（100个高级词汇）====================
WORDS = [
    {"word": "aberration", "phonetic": "/ˌæbəˈreɪʃn/", "meaning": "偏离常轨；异常", "example": "这场暴雪在这个季节属于异常现象。"},
    {"word": "abeyance", "phonetic": "/əˈbeɪəns/", "meaning": "暂停；搁置", "example": "该项目被暂时搁置，等待更多资金到位。"},
    {"word": "abscond", "phonetic": "/æbˈskɒnd/", "meaning": "潜逃；秘密逃走", "example": "小偷带着偷来的珠宝潜逃了。"},
    {"word": "abstain", "phonetic": "/æbˈsteɪn/", "meaning": "戒除；弃权", "example": "她决定在该问题上投弃权票。"},
    {"word": "acquisition", "phonetic": "/ˌækwɪˈzɪʃn/", "meaning": "获得；习得", "example": "新技能的习得对职业发展至关重要。"},
    {"word": "adamant", "phonetic": "/ˈædəmənt/", "meaning": "坚定的；固执的", "example": "她坚信自己做出了正确的选择。"},
    {"word": "adverse", "phonetic": "/ˈædvɜːrs/", "meaning": "不利的；有害的", "example": "由于天气恶劣，探险队取消了行程。"},
    {"word": "advocate", "phonetic": "/ˈædvəkeɪt/", "meaning": "提倡；拥护", "example": "她提倡改善公共交通系统。"},
    {"word": "aesthetic", "phonetic": "/iːsˈθetɪk/", "meaning": "美学的；审美的", "example": "这座建筑具有极高的美学价值。"},
    {"word": "alleviate", "phonetic": "/əˈliːvieɪt/", "meaning": "减轻；缓和", "example": "这种药物有助于缓解慢性疼痛。"},
    {"word": "ambiguous", "phonetic": "/æmˈbɪɡjuəs/", "meaning": "模糊的；含混的", "example": "他的回答含糊不清，让人摸不着头脑。"},
    {"word": "ameliorate", "phonetic": "/əˈmiːliəreɪt/", "meaning": "改善；改良", "example": "新政策旨在改善居民的生活条件。"},
    {"word": "analogy", "phonetic": "/əˈnælədʒi/", "meaning": "类比；比喻", "example": "老师用一个类比来解释这个概念。"},
    {"word": "anomaly", "phonetic": "/əˈnɒməli/", "meaning": "异常；反常现象", "example": "科学家在数据中发现了一个异常值。"},
    {"word": "antagonist", "phonetic": "/ænˈtæɡənɪst/", "meaning": "对手；反派", "example": "小说中的反派是一个腐败的政客。"},
    {"word": "apathy", "phonetic": "/ˈæpəθi/", "meaning": "冷漠；无动于衷", "example": "选民的冷漠是民主制度面临的一大问题。"},
    {"word": "arbitrary", "phonetic": "/ˈɑːrbɪtreri/", "meaning": "任意的；武断的", "example": "这个决定看起来完全是武断的。"},
    {"word": "articulate", "phonetic": "/ɑːrˈtɪkjulət/", "meaning": "清晰表达的；口才好的", "example": "她能够非常清晰地表达自己的想法。"},
    {"word": "assiduous", "phonetic": "/əˈsɪdʒuəs/", "meaning": "刻苦的；勤勉的", "example": "他是一个每天刻苦学习的学生。"},
    {"word": "audacious", "phonetic": "/ɔːˈdeɪʃəs/", "meaning": "大胆的；鲁莽的", "example": "这是一个大胆的计划，但最终获得了成功。"},
    {"word": "austere", "phonetic": "/ɔːˈstɪər/", "meaning": "朴素的；严峻的", "example": "僧侣们过着朴素的生活。"},
    {"word": "banal", "phonetic": "/bəˈnɑːl/", "meaning": "平庸的；陈腐的", "example": "这部电影的情节平庸且毫无悬念。"},
    {"word": "benevolent", "phonetic": "/bəˈnevələnt/", "meaning": "仁慈的；善意的", "example": "这位仁慈的捐赠者向慈善机构捐出了数百万。"},
    {"word": "bolster", "phonetic": "/ˈboʊlstər/", "meaning": "支持；加强", "example": "新的证据进一步支持了这项理论。"},
    {"word": "brevity", "phonetic": "/ˈbrevəti/", "meaning": "简洁；简短", "example": "简洁是智慧的灵魂。"},
    {"word": "candid", "phonetic": "/ˈkændɪd/", "meaning": "坦率的；公正的", "example": "她对局势做出了坦率的评估。"},
    {"word": "capricious", "phonetic": "/kəˈprɪʃəs/", "meaning": "反复无常的；任性的", "example": "反复无常的天气破坏了我们的计划。"},
    {"word": "cogent", "phonetic": "/ˈkoʊdʒənt/", "meaning": "有说服力的；令人信服的", "example": "她就政策变更提出了一个令人信服的论点。"},
    {"word": "coherent", "phonetic": "/koʊˈhɪrənt/", "meaning": "连贯的；有条理的", "example": "他的文章缺乏连贯的结构。"},
    {"word": "complacent", "phonetic": "/kəmˈpleɪsnt/", "meaning": "自满的；满不在乎的", "example": "不要对你的成就感到自满。"},
    {"word": "concise", "phonetic": "/kənˈsaɪs/", "meaning": "简明的；简洁的", "example": "请写一份简明扼要的报告摘要。"},
    {"word": "congenial", "phonetic": "/kənˈdʒiːniəl/", "meaning": "意气相投的；宜人的", "example": "他和同事们相处得非常融洽。"},
    {"word": "connoisseur", "phonetic": "/ˌkɒnəˈsɜːr/", "meaning": "鉴赏家；行家", "example": "他是红酒鉴赏方面的行家。"},
    {"word": "conscientious", "phonetic": "/ˌkɒnʃiˈenʃəs/", "meaning": "认真的；尽责的", "example": "她是一个认真负责的员工，从不偷工减料。"},
    {"word": "conspicuous", "phonetic": "/kənˈspɪkjuəs/", "meaning": "显眼的；引人注目的", "example": "那块醒目的招牌从远处就能看到。"},
    {"word": "contentious", "phonetic": "/kənˈtenʃəs/", "meaning": "有争议的；爱争论的", "example": "这是会议上一个有争议的话题。"},
    {"word": "cumulative", "phonetic": "/ˈkjuːmjulətɪv/", "meaning": "累积的；渐增的", "example": "微小变化的累积效应是非常显著的。"},
    {"word": "debilitate", "phonetic": "/dɪˈbɪlɪteɪt/", "meaning": "使衰弱；使虚弱", "example": "这种疾病会随着时间的推移使患者逐渐衰弱。"},
    {"word": "deliberate", "phonetic": "/dɪˈlɪbərət/", "meaning": "故意的；深思熟虑的", "example": "这是一次故意误导公众的企图。"},
    {"word": "diligent", "phonetic": "/ˈdɪlɪdʒənt/", "meaning": "勤勉的；刻苦的", "example": "她是一个勤奋的学生，总是按时完成作业。"},
    {"word": "discrepancy", "phonetic": "/dɪˈskrepənsi/", "meaning": "差异；不一致", "example": "两份报告之间存在明显的差异。"},
    {"word": "disseminate", "phonetic": "/dɪˈsemɪneɪt/", "meaning": "传播；散布", "example": "互联网帮助信息得以快速传播。"},
    {"word": "diversity", "phonetic": "/daɪˈvɜːrsəti/", "meaning": "多样性；多元化", "example": "公司非常重视工作场所的多元化。"},
    {"word": "docile", "phonetic": "/ˈdəʊsaɪl/", "meaning": "温顺的；易管教的", "example": "这匹温顺的小马非常适合初学者骑乘。"},
    {"word": "ebullient", "phonetic": "/ɪˈbʊliənt/", "meaning": "热情洋溢的；沸腾的", "example": "她热情洋溢的性格点亮了整个房间。"},
    {"word": "eccentric", "phonetic": "/ɪkˈsentrɪk/", "meaning": "古怪的；反常的", "example": "那位古怪的发明家有许多不寻常的想法。"},
    {"word": "eloquent", "phonetic": "/ˈeləkwənt/", "meaning": "雄辩的；有口才的", "example": "他那富有感染力的演讲打动了全场观众。"},
    {"word": "empirical", "phonetic": "/ɪmˈpɪrɪkl/", "meaning": "经验主义的；实证的", "example": "这一理论建立在实证证据的基础之上。"},
    {"word": "enigmatic", "phonetic": "/ˌenɪɡˈmætɪk/", "meaning": "神秘的；令人费解的", "example": "蒙娜丽莎脸上挂着神秘的微笑。"},
    {"word": "ephemeral", "phonetic": "/ɪˈfemərəl/", "meaning": "短暂的；朝生暮死的", "example": "在娱乐圈，名声可能是转瞬即逝的。"},
    {"word": "erudite", "phonetic": "/ˈerudaɪt/", "meaning": "博学的；有学问的", "example": "那位博学的教授精通多种语言。"},
    {"word": "esoteric", "phonetic": "/ˌiːsəˈterɪk/", "meaning": "深奥的；秘传的", "example": "这本书包含了关于古老仪式的深奥知识。"},
    {"word": "exacerbate", "phonetic": "/ɪɡˈzæsərbeɪt/", "meaning": "使恶化；加剧", "example": "他的评论加剧了紧张的局势。"},
    {"word": "exorbitant", "phonetic": "/ɪɡˈzɔːrbɪtənt/", "meaning": "过高的；过分的", "example": "节日期间酒店收取了过高的费用。"},
    {"word": "facilitate", "phonetic": "/fəˈsɪlɪteɪt/", "meaning": "促进；使便利", "example": "这款新应用促进了团队之间的沟通。"},
    {"word": "fastidious", "phonetic": "/fæˈstɪdiəs/", "meaning": "挑剔的；过分讲究的", "example": "她对保持房屋清洁非常挑剔。"},
    {"word": "fervent", "phonetic": "/ˈfɜːrvənt/", "meaning": "热烈的；热情的", "example": "她是这支球队的热情支持者。"},
    {"word": "frugal", "phonetic": "/ˈfruːɡl/", "meaning": "节俭的；朴素的", "example": "尽管很富有，他却过着节俭的生活。"},
    {"word": "gregarious", "phonetic": "/ɡrɪˈɡeriəs/", "meaning": "社交的；群居的", "example": "他是一个喜欢社交的人，热爱参加聚会。"},
    {"word": "hinder", "phonetic": "/ˈhɪndər/", "meaning": "阻碍；妨碍", "example": "恶劣的天气阻碍了救援行动的开展。"},
    {"word": "iconoclast", "phonetic": "/aɪˈkɒnəklæst/", "meaning": "打破传统的人；偶像破坏者", "example": "作为一个打破传统的人，她挑战了每一条惯例。"},
    {"word": "impartial", "phonetic": "/ɪmˈpɑːrʃl/", "meaning": "公正的；不偏不倚的", "example": "法官在整个审判过程中必须保持公正。"},
    {"word": "imperative", "phonetic": "/ɪmˈperətɪv/", "meaning": "必要的；紧急的", "example": "我们必须立即采取行动，这至关重要。"},
    {"word": "indigenous", "phonetic": "/ɪnˈdɪdʒənəs/", "meaning": "本土的；土著的", "example": "土著居民在这里已经生活了几个世纪。"},
    {"word": "inevitable", "phonetic": "/ɪnˈevɪtəbl/", "meaning": "不可避免的", "example": "在任何组织中，变革都是不可避免的。"},
    {"word": "innovative", "phonetic": "/ˈɪnəveɪtɪv/", "meaning": "创新的；革新的", "example": "这家公司以创新产品而闻名。"},
    {"word": "integrate", "phonetic": "/ˈɪntɪɡreɪt/", "meaning": "整合；融入", "example": "学校努力让新生尽快融入集体。"},
    {"word": "integrity", "phonetic": "/ɪnˈteɡrəti/", "meaning": "正直；完整性", "example": "她是一个极具正直品格的女性。"},
    {"word": "intuitive", "phonetic": "/ɪnˈtjuːɪtɪv/", "meaning": "直觉的；直观的", "example": "这款应用拥有直观的用户界面。"},
    {"word": "juxtapose", "phonetic": "/ˈdʒʌkstəpoʊz/", "meaning": "并列；并置", "example": "展览将现代艺术与古代艺术并置展示。"},
    {"word": "kinetic", "phonetic": "/kɪˈnetɪk/", "meaning": "运动的；动力学的", "example": "这座雕塑有一个由风力驱动的动态元素。"},
    {"word": "laconic", "phonetic": "/ləˈkɒnɪk/", "meaning": "简洁的；言简意赅的", "example": "他言简意赅的回答让所有人都陷入了猜测。"},
    {"word": "magnanimous", "phonetic": "/mæɡˈnænɪməs/", "meaning": "宽宏大量的；高尚的", "example": "他能原谅那次侮辱，真是宽宏大量。"},
    {"word": "melancholy", "phonetic": "/ˈmelənkɒli/", "meaning": "忧郁的；悲伤的", "example": "背景音乐中播放着一首忧郁的曲子。"},
    {"word": "meticulous", "phonetic": "/məˈtɪkjuləs/", "meaning": "一丝不苟的；细致的", "example": "她对工作一丝不苟。"},
    {"word": "mitigate", "phonetic": "/ˈmɪtɪɡeɪt/", "meaning": "减轻；缓和", "example": "已采取措施以减轻对环境的影响。"},
    {"word": "mundane", "phonetic": "/ˈmʌndeɪn/", "meaning": "平凡的；世俗的", "example": "他已经厌倦了自己平凡的日常琐事。"},
    {"word": "nascent", "phonetic": "/ˈneɪsnt/", "meaning": "新生的；萌芽的", "example": "这个新兴行业展现出了巨大的潜力。"},
    {"word": "nostalgia", "phonetic": "/nɒˈstældʒə/", "meaning": "怀旧；乡愁", "example": "这首歌让她心中充满了怀旧之情。"},
    {"word": "obfuscate", "phonetic": "/ˈɒbfʌskeɪt/", "meaning": "使困惑；混淆", "example": "政客们经常混淆真正的问题所在。"},
    {"word": "obsolete", "phonetic": "/ˈɒbsəliːt/", "meaning": "过时的；淘汰的", "example": "打字机已经变得过时了。"},
    {"word": "opulent", "phonetic": "/ˈɒpjulənt/", "meaning": "富裕的；豪华的", "example": "他们入住了一家豪华酒店。"},
    {"word": "paradigm", "phonetic": "/ˈpærədaɪm/", "meaning": "范例；范式", "example": "这一发现改变了科学界的范式。"},
    {"word": "perpetual", "phonetic": "/pərˈpetʃuəl/", "meaning": "永久的；持续的", "example": "建筑工地持续不断的噪音让人不胜其烦。"},
    {"word": "pragmatic", "phonetic": "/præɡˈmætɪk/", "meaning": "务实的；实用主义的", "example": "我们需要一个务实的方法来解决这个问题。"},
    {"word": "profound", "phonetic": "/prəˈfaʊnd/", "meaning": "深刻的；意义深远的", "example": "这本书对我的思维方式产生了深远的影响。"},
    {"word": "quintessential", "phonetic": "/ˌkwɪntɪˈsenʃl/", "meaning": "典型的；精华的", "example": "她是典型的纽约客。"},
    {"word": "recalcitrant", "phonetic": "/rɪˈkælsɪtrənt/", "meaning": "倔强的；不服管束的", "example": "那个倔强的学生拒绝遵守规则。"},
    {"word": "resilient", "phonetic": "/rɪˈzɪliənt/", "meaning": "有韧性的；适应力强的", "example": "孩子们的适应能力非常强。"},
    {"word": "sagacious", "phonetic": "/səˈɡeɪʃəs/", "meaning": "睿智的；有洞察力的", "example": "睿智的投资者知道何时买入何时卖出。"},
    {"word": "scrutinize", "phonetic": "/ˈskruːtənaɪz/", "meaning": "仔细检查；细察", "example": "会计仔细审查了每一个细节。"},
    {"word": "sophisticated", "phonetic": "/səˈfɪstɪkeɪtɪd/", "meaning": "复杂精密的；老练的", "example": "该软件使用了复杂的算法。"},
    {"word": "taciturn", "phonetic": "/ˈtæsɪtɜːrn/", "meaning": "沉默寡言的", "example": "他是一个沉默寡言的人，只在必要时开口。"},
    {"word": "tranquil", "phonetic": "/ˈtræŋkwɪl/", "meaning": "宁静的；平静的", "example": "宁静的湖面倒映着远处的山峦。"},
    {"word": "ubiquitous", "phonetic": "/juːˈbɪkwɪtəs/", "meaning": "无所不在的；普遍存在的", "example": "智能手机在现代生活中已变得无处不在。"},
    {"word": "viable", "phonetic": "/ˈvaɪəbl/", "meaning": "可行的；能存活的", "example": "这个商业计划在财务上可行吗？"},
    {"word": "whimsical", "phonetic": "/ˈwɪmzɪkl/", "meaning": "异想天开的；古怪的", "example": "花园的设计异想天开，有着蜿蜒曲折的小径。"},
    {"word": "xenophobia", "phonetic": "/ˌzenəˈfoʊbiə/", "meaning": "仇外心理；惧外症", "example": "在一个多元化的社会中，仇外心理没有立足之地。"},
    {"word": "yearn", "phonetic": "/jɜːrn/", "meaning": "渴望；向往", "example": "她向往乡村那种更简单的生活。"},
    {"word": "zealous", "phonetic": "/ˈzeləs/", "meaning": "热心的；狂热的", "example": "他是环境保护的热心支持者。"},
]

SAVE_FILE = "学习进度.json"

# ==================== 进度存取 ====================
def load_progress():
    if os.path.exists(SAVE_FILE):
        try:
            with open(SAVE_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            pass
    return {}

def save_progress(data):
    with open(SAVE_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

progress = load_progress()
for w in WORDS:
    if w["word"] not in progress:
        progress[w["word"]] = {"status": "未学习", "last": None}
save_progress(progress)

# ==================== 主应用类 ====================
class WordApp:
    def __init__(self, root):
        self.root = root
        self.root.title("百词斩 - 英语单词背诵")
        self.root.geometry("900x650")
        self.root.configure(bg="#f0f2f5")
        self.root.resizable(False, False)

        self.filter = "全部"
        self.idx = 0
        self.show_answer = False

        self.setup_styles()
        self.create_widgets()
        self.show_word()

    def setup_styles(self):
        style = ttk.Style()
        style.theme_use('clam')
        style.configure('Blue.TButton', background='#4285f4', foreground='white', font=('Microsoft YaHei', 12))
        style.map('Blue.TButton', background=[('active', '#5a9bf5')])
        style.configure('Green.TButton', background='#34a853', foreground='white', font=('Microsoft YaHei', 12))
        style.map('Green.TButton', background=[('active', '#45c065')])
        style.configure('Orange.TButton', background='#fbbc04', foreground='white', font=('Microsoft YaHei', 12))
        style.map('Orange.TButton', background=[('active', '#f5c842')])
        style.configure('Gray.TButton', background='#808080', foreground='white', font=('Microsoft YaHei', 12))
        style.map('Gray.TButton', background=[('active', '#999999')])
        style.configure('Purple.TButton', background='#8e44ad', foreground='white', font=('Microsoft YaHei', 12))
        style.map('Purple.TButton', background=[('active', '#a855d6')])

    def create_widgets(self):
        # ===== 顶部标题栏 =====
        top_bar = tk.Frame(self.root, bg='#4285f4', height=65)
        top_bar.pack(fill='x')
        top_bar.pack_propagate(False)

        title_label = tk.Label(top_bar, text="📖 百词斩 - 英语单词背诵", font=('Microsoft YaHei', 22, 'bold'),
                               bg='#4285f4', fg='white')
        title_label.pack(side='left', padx=20, pady=12)

        # 统计标签
        self.stats_label = tk.Label(top_bar, font=('Microsoft YaHei', 11), bg='#4285f4', fg='#e0e0e0')
        self.stats_label.pack(side='right', padx=20, pady=18)
        self.update_stats()

        # ===== 筛选栏 =====
        filter_bar = tk.Frame(self.root, bg='#e8eaed', height=45)
        filter_bar.pack(fill='x')
        filter_bar.pack_propagate(False)

        tk.Label(filter_bar, text="筛选：", font=('Microsoft YaHei', 11), bg='#e8eaed', fg='#333').pack(side='left', padx=(15, 5), pady=10)

        self.filter_var = tk.StringVar(value="全部")
        for text in ["全部", "未学习", "学习中", "已掌握"]:
            rb = tk.Radiobutton(filter_bar, text=text, variable=self.filter_var, value=text,
                                font=('Microsoft YaHei', 11), bg='#e8eaed', selectcolor='#d0d0d0',
                                activebackground='#e8eaed', command=self.on_filter_change)
            rb.pack(side='left', padx=8, pady=10)

        # ===== 卡片区域 =====
        card_outer = tk.Frame(self.root, bg='#f0f2f5')
        card_outer.pack(fill='both', expand=True, padx=40, pady=15)

        self.card = tk.Frame(card_outer, bg='white', highlightbackground='#d0d0d0', highlightthickness=2)
        self.card.pack(fill='both', expand=True, padx=10, pady=10)

        # 进度标签
        self.progress_label = tk.Label(self.card, font=('Microsoft YaHei', 11), bg='white', fg='#888')
        self.progress_label.pack(anchor='ne', padx=20, pady=(10, 0))

        # 单词
        self.word_label = tk.Label(self.card, font=('Microsoft YaHei', 36, 'bold'), bg='white', fg='#4285f4')
        self.word_label.pack(pady=(20, 5))

        # 音标
        self.phonetic_label = tk.Label(self.card, font=('Microsoft YaHei', 16), bg='white', fg='#666')
        self.phonetic_label.pack(pady=(0, 15))

        # 状态标签
        self.status_label = tk.Label(self.card, font=('Microsoft YaHei', 11), bg='white')
        self.status_label.pack()

        # 释义区域
        self.meaning_frame = tk.Frame(self.card, bg='white')
        self.meaning_frame.pack(fill='x', padx=40, pady=(20, 10))

        self.meaning_title = tk.Label(self.meaning_frame, font=('Microsoft YaHei', 14, 'bold'), bg='white', fg='#00897b', anchor='w')
        self.meaning_title.pack(fill='x')

        self.meaning_label = tk.Label(self.meaning_frame, font=('Microsoft YaHei', 18), bg='white', fg='#222', anchor='w')
        self.meaning_label.pack(fill='x', pady=(5, 15))

        self.example_title = tk.Label(self.meaning_frame, font=('Microsoft YaHei', 14, 'bold'), bg='white', fg='#00897b', anchor='w')
        self.example_title.pack(fill='x')

        self.example_label = tk.Label(self.meaning_frame, font=('Microsoft YaHei', 14), bg='white', fg='#555', anchor='w', wraplength=700, justify='left')
        self.example_label.pack(fill='x', pady=(5, 10))

        # 提示/消息
        self.hint_label = tk.Label(self.card, font=('Microsoft YaHei', 13), bg='white', fg='#999')
        self.hint_label.pack(pady=(10, 5))

        self.msg_label = tk.Label(self.card, font=('Microsoft YaHei', 12), bg='white')
        self.msg_label.pack(pady=(0, 10))

        # ===== 底部按钮栏 =====
        bottom_bar = tk.Frame(self.root, bg='#f0f2f5', height=70)
        bottom_bar.pack(fill='x', side='bottom', pady=10)

        # 左组：翻页
        left_frame = tk.Frame(bottom_bar, bg='#f0f2f5')
        left_frame.pack(side='left', padx=30)

        ttk.Button(left_frame, text="◀ 上一个", command=self.prev_word, style='Gray.TButton', width=12).pack(side='left', padx=5, pady=15)
        ttk.Button(left_frame, text="下一个 ▶", command=self.next_word, style='Gray.TButton', width=12).pack(side='left', padx=5, pady=15)

        # 中组：显示/测试
        mid_frame = tk.Frame(bottom_bar, bg='#f0f2f5')
        mid_frame.pack(side='left', padx=20)

        ttk.Button(mid_frame, text="👁 显示/隐藏释义", command=self.toggle_answer, style='Blue.TButton', width=18).pack(side='left', padx=5, pady=15)
        ttk.Button(mid_frame, text="📝 开始测试", command=self.start_test, style='Purple.TButton', width=14).pack(side='left', padx=5, pady=15)

        # 右组：标记
        right_frame = tk.Frame(bottom_bar, bg='#f0f2f5')
        right_frame.pack(side='right', padx=30)

        ttk.Button(right_frame, text="📖 标记学习中", command=lambda: self.mark("学习中"), style='Orange.TButton', width=16).pack(side='left', padx=5, pady=15)
        ttk.Button(right_frame, text="✅ 标记已掌握", command=lambda: self.mark("已掌握"), style='Green.TButton', width=16).pack(side='left', padx=5, pady=15)

        # 绑定键盘
        self.root.bind('<Left>', lambda e: self.prev_word())
        self.root.bind('<Right>', lambda e: self.next_word())
        self.root.bind('<space>', lambda e: self.toggle_answer())

    def filtered_words(self):
        if self.filter == "全部":
            return WORDS
        return [w for w in WORDS if progress[w["word"]]["status"] == self.filter]

    def current_word(self):
        fl = self.filtered_words()
        if not fl:
            return None
        return fl[self.idx % len(fl)]

    def show_word(self):
        c = self.current_word()
        fl = self.filtered_words()

        if not c:
            self.word_label.config(text="暂无单词")
            self.phonetic_label.config(text="")
            self.meaning_frame.pack_forget()
            self.hint_label.config(text="请切换筛选条件")
            self.msg_label.config(text="")
            self.progress_label.config(text="0/0")
            return

        self.word_label.config(text=c["word"])
        self.phonetic_label.config(text=c["phonetic"])

        # 进度
        self.progress_label.config(text=f"{self.idx + 1} / {len(fl)}")

        # 状态颜色
        st = progress[c["word"]]["status"]
        colors = {"未学习": "#808080", "学习中": "#fbbc04", "已掌握": "#34a853"}
        self.status_label.config(text=f"  状态：{st}  ", bg=colors.get(st, "#808080"), fg='white')

        if self.show_answer:
            self.meaning_title.config(text="📝 释义：")
            self.meaning_label.config(text=c["meaning"])
            self.example_title.config(text="📖 例句：")
            self.example_label.config(text=c["example"])
            self.meaning_frame.pack(fill='x', padx=40, pady=(20, 10))
            self.hint_label.config(text="")
        else:
            self.meaning_frame.pack_forget()
            self.hint_label.config(text="按 [空格键] 或点击按钮查看释义")

        self.msg_label.config(text="")

    def next_word(self):
        fl = self.filtered_words()
        if fl:
            self.idx = (self.idx + 1) % len(fl)
            self.show_answer = False
            self.show_word()

    def prev_word(self):
        fl = self.filtered_words()
        if fl:
            self.idx = (self.idx - 1) % len(fl)
            self.show_answer = False
            self.show_word()

    def toggle_answer(self):
        self.show_answer = not self.show_answer
        self.show_word()

    def mark(self, status):
        c = self.current_word()
        if not c:
            return
        progress[c["word"]]["status"] = status
        progress[c["word"]]["last"] = datetime.now().strftime("%Y-%m-%d %H:%M")
        save_progress(progress)
        self.msg_label.config(text=f"已标记为「{status}」", fg='#34a853')
        self.show_answer = True
        self.update_stats()
        self.show_word()

    def on_filter_change(self):
        self.filter = self.filter_var.get()
        self.idx = 0
        self.show_answer = False
        self.show_word()

    def update_stats(self):
        total = len(WORDS)
        m = sum(1 for w in WORDS if progress[w["word"]]["status"] == "已掌握")
        l = sum(1 for w in WORDS if progress[w["word"]]["status"] == "学习中")
        n = sum(1 for w in WORDS if progress[w["word"]]["status"] == "未学习")
        self.stats_label.config(text=f"总计:{total}  已掌握:{m}  学习中:{l}  未学习:{n}")

    def start_test(self):
        TestWindow(self.root, WORDS, progress, self.update_stats)

# ==================== 测试窗口 ====================
class TestWindow:
    def __init__(self, parent, words, progress, callback):
        self.words = words
        self.progress = progress
        self.callback = callback
        self.score = 0
        self.q_cur = 0
        self.q_total = 10
        self.answered = False

        self.win = tk.Toplevel(parent)
        self.win.title("百词斩 - 单词测试")
        self.win.geometry("700x550")
        self.win.configure(bg='#f0f2f5')
        self.win.resizable(False, False)
        self.win.grab_set()

        self.win.protocol("WM_DELETE_WINDOW", self.on_close)

        # 标题
        top = tk.Frame(self.win, bg='#8e44ad', height=55)
        top.pack(fill='x')
        top.pack_propagate(False)
        tk.Label(top, text="📝 单词测试", font=('Microsoft YaHei', 20, 'bold'), bg='#8e44ad', fg='white').pack(pady=12)

        # 进度条
        self.progress_bar = ttk.Progressbar(self.win, length=620, mode='determinate', maximum=self.q_total)
        self.progress_bar.pack(pady=(15, 5))

        self.info_label = tk.Label(self.win, font=('Microsoft YaHei', 12), bg='#f0f2f5', fg='#555')
        self.info_label.pack(pady=(0, 10))

        # 问题卡片
        self.q_card = tk.Frame(self.win, bg='white', highlightbackground='#d0d0d0', highlightthickness=2)
        self.q_card.pack(fill='x', padx=40, pady=10)

        self.q_label = tk.Label(self.q_card, font=('Microsoft YaHei', 16), bg='white', fg='#222', wraplength=580, justify='center')
        self.q_label.pack(pady=(25, 20))

        # 选项按钮
        self.opt_buttons = []
        self.opt_texts = []
        for i in range(4):
            btn = tk.Button(self.q_card, font=('Microsoft YaHei', 14), bg='#f5f5f5', fg='#333',
                            activebackground='#4285f4', activeforeground='white',
                            relief='flat', cursor='hand2', anchor='w', padx=20, pady=10,
                            command=lambda idx=i: self.check_answer(idx))
            btn.pack(fill='x', padx=30, pady=5)
            self.opt_buttons.append(btn)

        # 反馈
        self.fb_label = tk.Label(self.q_card, font=('Microsoft YaHei', 14, 'bold'), bg='white')
        self.fb_label.pack(pady=(10, 5))

        # 按钮区域
        btn_frame = tk.Frame(self.win, bg='#f0f2f5')
        btn_frame.pack(pady=10)

        self.next_btn = tk.Button(btn_frame, text="下一题 ▶", font=('Microsoft YaHei', 12), bg='#4285f4', fg='white',
                                  activebackground='#5a9bf5', relief='flat', padx=25, pady=8, cursor='hand2',
                                  command=self.next_question)
        self.next_btn.pack(side='left', padx=10)

        tk.Button(btn_frame, text="返回主页", font=('Microsoft YaHei', 12), bg='#808080', fg='white',
                  activebackground='#999', relief='flat', padx=25, pady=8, cursor='hand2',
                  command=self.on_close).pack(side='left', padx=10)

        self.next_question()

    def next_question(self):
        if self.q_cur >= self.q_total:
            self.show_result()
            return

        self.answered = False
        self.fb_label.config(text="")
        self.next_btn.config(text="下一题 ▶")

        target = random.choice(self.words)
        self.correct_idx = random.randint(0, 3)
        self.options = []
        used = {target["word"]}
        pool = list(self.words)
        random.shuffle(pool)

        for i in range(4):
            if i == self.correct_idx:
                self.options.append(target)
            else:
                w = pool.pop()
                while w["word"] in used:
                    w = pool.pop()
                used.add(w["word"])
                self.options.append(w)

        self.qtype = random.randint(0, 1)

        if self.qtype == 0:
            qtext = f"「{target['word']}」的意思是？"
        else:
            qtext = f"以下哪个单词的意思是「{target['meaning']}」？"

        self.q_label.config(text=qtext)

        for i, opt in enumerate(self.options):
            txt = opt["meaning"] if self.qtype == 0 else opt["word"]
            self.opt_buttons[i].config(text=f"{i+1}. {txt}", bg='#f5f5f5', fg='#333')

        self.q_cur += 1
        self.progress_bar.config(value=self.q_cur)
        self.info_label.config(text=f"第 {self.q_cur}/{self.q_total} 题    得分：{self.score}")

    def check_answer(self, idx):
        if self.answered:
            return
        self.answered = True

        if idx == self.correct_idx:
            self.score += 1
            self.fb_label.config(text="✅ 回答正确！", fg='#34a853')
        else:
            ans = self.options[self.correct_idx]["word"] if self.qtype == 0 else self.options[self.correct_idx]["meaning"]
            self.fb_label.config(text=f"❌ 回答错误！正确答案是：{ans}", fg='#ea4335')

        self.info_label.config(text=f"第 {self.q_cur}/{self.q_total} 题    得分：{self.score}")

        for i, btn in enumerate(self.opt_buttons):
            if i == self.correct_idx:
                btn.config(bg='#c8e6c9', fg='#1b5e20')
            elif i == idx and i != self.correct_idx:
                btn.config(bg='#ffcdd2', fg='#b71c1c')

        if self.q_cur >= self.q_total:
            self.next_btn.config(text="查看结果")

    def show_result(self):
        self.q_label.config(text=f"🎉 测试完成！\n\n您的得分：{self.score}/{self.q_total}\n正确率：{self.score*100//self.q_total}%")
        for btn in self.opt_buttons:
            btn.pack_forget()
        self.fb_label.config(text="")
        self.next_btn.pack_forget()
        self.callback()

    def on_close(self):
        self.callback()
        self.win.destroy()


# ==================== 启动 ====================
if __name__ == "__main__":
    root = tk.Tk()
    app = WordApp(root)
    root.mainloop()