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

# ==================== 词库 ====================
WORDS = [
    {"word": "abandon", "meaning": "放弃"}, {"word": "ability", "meaning": "能力"},
    {"word": "abroad", "meaning": "在国外"}, {"word": "absent", "meaning": "缺席的"},
    {"word": "absorb", "meaning": "吸收"}, {"word": "abstract", "meaning": "抽象的"},
    {"word": "accept", "meaning": "接受"}, {"word": "access", "meaning": "通道；访问"},
    {"word": "accident", "meaning": "事故"}, {"word": "account", "meaning": "账户；说明"},
    {"word": "achieve", "meaning": "实现"}, {"word": "acquire", "meaning": "获得"},
    {"word": "adapt", "meaning": "适应"}, {"word": "adequate", "meaning": "足够的"},
    {"word": "adjust", "meaning": "调整"}, {"word": "admire", "meaning": "钦佩"},
    {"word": "adopt", "meaning": "采纳；收养"}, {"word": "advance", "meaning": "前进"},
    {"word": "advantage", "meaning": "优势"}, {"word": "advertise", "meaning": "做广告"},
    {"word": "affair", "meaning": "事务"}, {"word": "affect", "meaning": "影响"},
    {"word": "afford", "meaning": "负担得起"}, {"word": "agency", "meaning": "代理处"},
    {"word": "agenda", "meaning": "议程"}, {"word": "agent", "meaning": "代理人"},
    {"word": "aggressive", "meaning": "侵略的"}, {"word": "agree", "meaning": "同意"},
    {"word": "agriculture", "meaning": "农业"}, {"word": "allow", "meaning": "允许"},
    {"word": "although", "meaning": "虽然"}, {"word": "amount", "meaning": "数量"},
    {"word": "analyze", "meaning": "分析"}, {"word": "announce", "meaning": "宣布"},
    {"word": "annual", "meaning": "每年的"}, {"word": "anxious", "meaning": "焦虑的"},
    {"word": "appear", "meaning": "出现"}, {"word": "apply", "meaning": "申请；应用"},
    {"word": "appoint", "meaning": "任命"}, {"word": "appreciate", "meaning": "感激"},
    {"word": "approach", "meaning": "接近；方法"}, {"word": "approve", "meaning": "批准"},
    {"word": "argue", "meaning": "争论"}, {"word": "arrange", "meaning": "安排"},
    {"word": "article", "meaning": "文章；物品"}, {"word": "assess", "meaning": "评估"},
    {"word": "assign", "meaning": "分配"}, {"word": "assist", "meaning": "帮助"},
    {"word": "assume", "meaning": "假设"}, {"word": "attach", "meaning": "附上；连接"},
    {"word": "attempt", "meaning": "尝试"}, {"word": "attend", "meaning": "参加"},
    {"word": "attitude", "meaning": "态度"}, {"word": "attract", "meaning": "吸引"},
    {"word": "authority", "meaning": "权威"}, {"word": "available", "meaning": "可用的"},
    {"word": "average", "meaning": "平均的"}, {"word": "avoid", "meaning": "避免"},
    {"word": "aware", "meaning": "意识到的"}, {"word": "balance", "meaning": "平衡"},
    {"word": "barrier", "meaning": "障碍"}, {"word": "behave", "meaning": "表现"},
    {"word": "belief", "meaning": "信念"}, {"word": "benefit", "meaning": "利益；好处"},
    {"word": "blame", "meaning": "责备"}, {"word": "bother", "meaning": "打扰"},
    {"word": "boundary", "meaning": "边界"}, {"word": "brilliant", "meaning": "杰出的"},
    {"word": "budget", "meaning": "预算"}, {"word": "burden", "meaning": "负担"},
    {"word": "calculate", "meaning": "计算"}, {"word": "campaign", "meaning": "运动"},
    {"word": "capable", "meaning": "有能力的"}, {"word": "capacity", "meaning": "容量；能力"},
    {"word": "capture", "meaning": "捕获"}, {"word": "career", "meaning": "职业；生涯"},
    {"word": "category", "meaning": "类别"}, {"word": "celebrate", "meaning": "庆祝"},
    {"word": "challenge", "meaning": "挑战"}, {"word": "character", "meaning": "性格；角色"},
    {"word": "charge", "meaning": "收费；指控"}, {"word": "climate", "meaning": "气候"},
    {"word": "collaborate", "meaning": "合作"}, {"word": "compare", "meaning": "比较"},
    {"word": "compete", "meaning": "竞争"}, {"word": "complain", "meaning": "抱怨"},
    {"word": "complete", "meaning": "完成"}, {"word": "complex", "meaning": "复杂的"},
    {"word": "concentrate", "meaning": "集中；专注"}, {"word": "concept", "meaning": "概念"},
    {"word": "concern", "meaning": "关心；担忧"}, {"word": "conclude", "meaning": "总结"},
    {"word": "confidence", "meaning": "信心"}, {"word": "confirm", "meaning": "确认"},
    {"word": "conflict", "meaning": "冲突"}, {"word": "connect", "meaning": "连接"},
    {"word": "consider", "meaning": "考虑"}, {"word": "constant", "meaning": "不断的"},
    {"word": "consume", "meaning": "消费"}, {"word": "contain", "meaning": "包含"},
    {"word": "contribute", "meaning": "贡献"}, {"word": "convenient", "meaning": "方便的"},
    {"word": "convince", "meaning": "说服"}, {"word": "cooperate", "meaning": "合作"},
    {"word": "create", "meaning": "创造"}, {"word": "critical", "meaning": "批评的；关键的"},
    {"word": "cultivate", "meaning": "培养"}, {"word": "curious", "meaning": "好奇的"},
    {"word": "current", "meaning": "当前的"}, {"word": "debate", "meaning": "辩论"},
    {"word": "decade", "meaning": "十年"}, {"word": "decline", "meaning": "下降；拒绝"},
    {"word": "define", "meaning": "定义"}, {"word": "deliver", "meaning": "递送；发表"},
    {"word": "demand", "meaning": "需求"}, {"word": "depend", "meaning": "依赖"},
    {"word": "describe", "meaning": "描述"}, {"word": "deserve", "meaning": "值得"},
    {"word": "destroy", "meaning": "破坏"}, {"word": "determine", "meaning": "决定"},
    {"word": "develop", "meaning": "发展"}, {"word": "devote", "meaning": "致力于"},
    {"word": "discover", "meaning": "发现"}, {"word": "display", "meaning": "展示"},
    {"word": "distinguish", "meaning": "区分"}, {"word": "distribute", "meaning": "分配"},
    {"word": "dominate", "meaning": "支配"}, {"word": "dramatic", "meaning": "戏剧性的"},
    {"word": "economy", "meaning": "经济"}, {"word": "educate", "meaning": "教育"},
    {"word": "efficient", "meaning": "高效的"}, {"word": "eliminate", "meaning": "消除"},
    {"word": "embrace", "meaning": "拥抱；包含"}, {"word": "emerge", "meaning": "出现"},
    {"word": "emotion", "meaning": "情感"}, {"word": "enable", "meaning": "使能够"},
    {"word": "encourage", "meaning": "鼓励"}, {"word": "engage", "meaning": "从事；吸引"},
    {"word": "enhance", "meaning": "提高"}, {"word": "enormous", "meaning": "巨大的"},
    {"word": "ensure", "meaning": "确保"}, {"word": "environment", "meaning": "环境"},
    {"word": "essential", "meaning": "必要的"}, {"word": "establish", "meaning": "建立"},
    {"word": "evaluate", "meaning": "评估"}, {"word": "evidence", "meaning": "证据"},
    {"word": "evolve", "meaning": "进化"}, {"word": "examine", "meaning": "检查"},
    {"word": "excellent", "meaning": "优秀的"}, {"word": "exchange", "meaning": "交换"},
    {"word": "excite", "meaning": "使兴奋"}, {"word": "expand", "meaning": "扩大"},
    {"word": "expect", "meaning": "期望"}, {"word": "experience", "meaning": "经验；经历"},
    {"word": "expert", "meaning": "专家"}, {"word": "explain", "meaning": "解释"},
    {"word": "explore", "meaning": "探索"}, {"word": "extend", "meaning": "延伸"},
    {"word": "extraordinary", "meaning": "非凡的"}, {"word": "extreme", "meaning": "极端的"},
    {"word": "factor", "meaning": "因素"}, {"word": "familiar", "meaning": "熟悉的"},
    {"word": "feature", "meaning": "特征"}, {"word": "finance", "meaning": "金融"},
    {"word": "flexible", "meaning": "灵活的"}, {"word": "foundation", "meaning": "基础"},
    {"word": "function", "meaning": "功能"}, {"word": "fundamental", "meaning": "基本的"},
    {"word": "generate", "meaning": "产生"}, {"word": "generous", "meaning": "慷慨的"},
    {"word": "global", "meaning": "全球的"}, {"word": "gradual", "meaning": "逐渐的"},
    {"word": "guarantee", "meaning": "保证"}, {"word": "harmony", "meaning": "和谐"},
    {"word": "horizon", "meaning": "地平线；视野"}, {"word": "identify", "meaning": "识别"},
    {"word": "ignore", "meaning": "忽视"}, {"word": "imagine", "meaning": "想象"},
    {"word": "impact", "meaning": "影响"}, {"word": "implement", "meaning": "实施"},
    {"word": "improve", "meaning": "改善"}, {"word": "include", "meaning": "包含"},
    {"word": "indicate", "meaning": "表明"}, {"word": "individual", "meaning": "个人的"},
    {"word": "influence", "meaning": "影响"}, {"word": "inform", "meaning": "通知"},
    {"word": "innovation", "meaning": "创新"}, {"word": "inspire", "meaning": "鼓舞"},
    {"word": "install", "meaning": "安装"}, {"word": "intelligence", "meaning": "智力"},
    {"word": "intense", "meaning": "强烈的"}, {"word": "interact", "meaning": "互动"},
    {"word": "interest", "meaning": "兴趣"}, {"word": "interpret", "meaning": "解释"},
    {"word": "involve", "meaning": "涉及"}, {"word": "issue", "meaning": "问题；发行"},
    {"word": "knowledge", "meaning": "知识"}, {"word": "landscape", "meaning": "风景"},
    {"word": "launch", "meaning": "发射；启动"}, {"word": "legislation", "meaning": "立法"},
    {"word": "maintain", "meaning": "维持"}, {"word": "manage", "meaning": "管理"},
    {"word": "massive", "meaning": "大量的"}, {"word": "mental", "meaning": "精神的"},
    {"word": "method", "meaning": "方法"}, {"word": "minority", "meaning": "少数"},
    {"word": "motivate", "meaning": "激励"}, {"word": "multiple", "meaning": "多个的"},
    {"word": "negotiate", "meaning": "谈判"}, {"word": "normal", "meaning": "正常的"},
    {"word": "obtain", "meaning": "获得"}, {"word": "obvious", "meaning": "明显的"},
    {"word": "occupy", "meaning": "占据"}, {"word": "operate", "meaning": "操作"},
    {"word": "opinion", "meaning": "意见"}, {"word": "opportunity", "meaning": "机会"},
    {"word": "oppose", "meaning": "反对"}, {"word": "optimistic", "meaning": "乐观的"},
    {"word": "organize", "meaning": "组织"}, {"word": "original", "meaning": "原始的"},
    {"word": "outcome", "meaning": "结果"}, {"word": "overcome", "meaning": "克服"},
    {"word": "participate", "meaning": "参与"}, {"word": "particular", "meaning": "特别的"},
    {"word": "passion", "meaning": "热情"}, {"word": "patience", "meaning": "耐心"},
    {"word": "pattern", "meaning": "模式"}, {"word": "perceive", "meaning": "感知"},
    {"word": "perform", "meaning": "表演；执行"}, {"word": "permanent", "meaning": "永久的"},
    {"word": "permit", "meaning": "允许"}, {"word": "persist", "meaning": "坚持"},
    {"word": "personality", "meaning": "个性"}, {"word": "perspective", "meaning": "视角"},
    {"word": "phenomenon", "meaning": "现象"}, {"word": "physical", "meaning": "身体的；物理的"},
    {"word": "platform", "meaning": "平台"}, {"word": "pleasant", "meaning": "令人愉快的"},
    {"word": "popular", "meaning": "流行的"}, {"word": "positive", "meaning": "积极的"},
    {"word": "possess", "meaning": "拥有"}, {"word": "potential", "meaning": "潜力"},
    {"word": "poverty", "meaning": "贫穷"}, {"word": "practical", "meaning": "实际的"},
    {"word": "predict", "meaning": "预测"}, {"word": "prefer", "meaning": "更喜欢"},
    {"word": "prepare", "meaning": "准备"}, {"word": "present", "meaning": "呈现；礼物"},
    {"word": "pressure", "meaning": "压力"}, {"word": "previous", "meaning": "以前的"},
    {"word": "primary", "meaning": "主要的"}, {"word": "principle", "meaning": "原则"},
    {"word": "priority", "meaning": "优先"}, {"word": "proceed", "meaning": "继续进行"},
    {"word": "process", "meaning": "过程"}, {"word": "professional", "meaning": "专业的"},
    {"word": "profit", "meaning": "利润"}, {"word": "progress", "meaning": "进步"},
    {"word": "project", "meaning": "项目"}, {"word": "promote", "meaning": "促进；提升"},
    {"word": "proper", "meaning": "适当的"}, {"word": "property", "meaning": "财产"},
    {"word": "protect", "meaning": "保护"}, {"word": "provide", "meaning": "提供"},
    {"word": "psychology", "meaning": "心理学"}, {"word": "publish", "meaning": "出版"},
    {"word": "purchase", "meaning": "购买"}, {"word": "pursue", "meaning": "追求"},
    {"word": "quality", "meaning": "质量"}, {"word": "quantity", "meaning": "数量"},
    {"word": "random", "meaning": "随机的"}, {"word": "rapid", "meaning": "迅速的"},
    {"word": "rare", "meaning": "稀有的"}, {"word": "rational", "meaning": "理性的"},
    {"word": "react", "meaning": "反应"}, {"word": "realistic", "meaning": "现实的"},
    {"word": "reasonable", "meaning": "合理的"}, {"word": "recognize", "meaning": "认出；承认"},
    {"word": "recommend", "meaning": "推荐"}, {"word": "recover", "meaning": "恢复"},
    {"word": "reduce", "meaning": "减少"}, {"word": "reflect", "meaning": "反映"},
    {"word": "reform", "meaning": "改革"}, {"word": "register", "meaning": "注册"},
    {"word": "regulate", "meaning": "调节"}, {"word": "reject", "meaning": "拒绝"},
    {"word": "relate", "meaning": "联系"}, {"word": "release", "meaning": "释放；发布"},
    {"word": "relevant", "meaning": "相关的"}, {"word": "relief", "meaning": "减轻；救济"},
    {"word": "rely", "meaning": "依赖"}, {"word": "remain", "meaning": "保持；剩余"},
    {"word": "remove", "meaning": "移除"}, {"word": "replace", "meaning": "替换"},
    {"word": "represent", "meaning": "代表"}, {"word": "require", "meaning": "需要"},
    {"word": "research", "meaning": "研究"}, {"word": "resource", "meaning": "资源"},
    {"word": "respond", "meaning": "回应"}, {"word": "responsible", "meaning": "负责的"},
    {"word": "restore", "meaning": "恢复；修复"}, {"word": "restrict", "meaning": "限制"},
    {"word": "reveal", "meaning": "揭示"}, {"word": "revise", "meaning": "修订；复习"},
    {"word": "reward", "meaning": "奖励"}, {"word": "risk", "meaning": "风险"},
    {"word": "sacrifice", "meaning": "牺牲"}, {"word": "satisfy", "meaning": "满足"},
    {"word": "schedule", "meaning": "时间表"}, {"word": "scheme", "meaning": "方案"},
    {"word": "security", "meaning": "安全"}, {"word": "senior", "meaning": "高级的；年长的"},
    {"word": "sensitive", "meaning": "敏感的"}, {"word": "separate", "meaning": "分开的"},
    {"word": "severe", "meaning": "严重的"}, {"word": "shortage", "meaning": "短缺"},
    {"word": "significant", "meaning": "重要的；显著的"}, {"word": "similar", "meaning": "相似的"},
    {"word": "solution", "meaning": "解决方案"}, {"word": "source", "meaning": "来源"},
    {"word": "specific", "meaning": "具体的"}, {"word": "stable", "meaning": "稳定的"},
    {"word": "standard", "meaning": "标准"}, {"word": "status", "meaning": "地位；状态"},
    {"word": "stimulate", "meaning": "刺激"}, {"word": "strategy", "meaning": "策略"},
    {"word": "strength", "meaning": "力量"}, {"word": "structure", "meaning": "结构"},
    {"word": "struggle", "meaning": "奋斗"}, {"word": "style", "meaning": "风格"},
    {"word": "sufficient", "meaning": "足够的"}, {"word": "support", "meaning": "支持"},
    {"word": "suppose", "meaning": "假设"}, {"word": "survive", "meaning": "幸存"},
    {"word": "symbol", "meaning": "象征"}, {"word": "sympathy", "meaning": "同情"},
    {"word": "target", "meaning": "目标"}, {"word": "technique", "meaning": "技术；技巧"},
    {"word": "technology", "meaning": "科技"}, {"word": "temporary", "meaning": "暂时的"},
    {"word": "tendency", "meaning": "趋势"}, {"word": "thorough", "meaning": "彻底的"},
    {"word": "threaten", "meaning": "威胁"}, {"word": "tradition", "meaning": "传统"},
    {"word": "transfer", "meaning": "转移"}, {"word": "transform", "meaning": "转变"},
    {"word": "transport", "meaning": "运输"}, {"word": "tremendous", "meaning": "巨大的"},
    {"word": "trend", "meaning": "趋势"}, {"word": "typical", "meaning": "典型的"},
    {"word": "ultimate", "meaning": "最终的"}, {"word": "undergo", "meaning": "经历"},
    {"word": "unique", "meaning": "独特的"}, {"word": "universal", "meaning": "普遍的"},
    {"word": "update", "meaning": "更新"}, {"word": "urban", "meaning": "城市的"},
    {"word": "urge", "meaning": "催促"}, {"word": "utilize", "meaning": "利用"},
    {"word": "valid", "meaning": "有效的"}, {"word": "value", "meaning": "价值"},
    {"word": "variety", "meaning": "多样性"}, {"word": "version", "meaning": "版本"},
    {"word": "victim", "meaning": "受害者"}, {"word": "visible", "meaning": "可见的"},
    {"word": "vision", "meaning": "视力；愿景"}, {"word": "vital", "meaning": "至关重要的"},
    {"word": "voluntary", "meaning": "自愿的"}, {"word": "welfare", "meaning": "福利"},
    {"word": "widespread", "meaning": "广泛的"}, {"word": "willing", "meaning": "愿意的"},
    {"word": "wisdom", "meaning": "智慧"}, {"word": "worthwhile", "meaning": "值得的"},
]

DATA_FILE = "word_memory.json"

# ==================== 数据持久化 ====================
def load_data():
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        except:
            pass
    return {}

def save_data(data):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def get_status(word, data):
    w = word["word"]
    if w in data:
        return data[w]
    return {"stage": 0, "correct": 0, "wrong": 0, "last_review": None, "next_review": None}

def update_status(word, data, correct):
    w = word["word"]
    if w not in data:
        data[w] = {"stage": 0, "correct": 0, "wrong": 0, "last_review": None, "next_review": None}
    s = data[w]
    now = datetime.now().isoformat()
    if correct:
        s["correct"] += 1
        s["stage"] = min(s["stage"] + 1, 3)
    else:
        s["wrong"] += 1
        s["stage"] = max(s["stage"] - 1, 0)
    s["last_review"] = now
    intervals = [1, 2, 5, 15]
    days = intervals[s["stage"]]
    s["next_review"] = (datetime.now() + timedelta(days=days)).isoformat()
    save_data(data)

# ==================== GUI 主程序 ====================
class WordApp:
    def __init__(self, root):
        self.root = root
        self.root.title("英语单词背诵小程序")
        self.root.geometry("700x550")
        self.root.resizable(False, False)
        self.root.configure(bg="#F0F4F8")

        self.data = load_data()
        self.current_word = None
        self.options = []
        self.quiz_type = "en_to_cn"  # en_to_cn / cn_to_en
        self.score = 0
        self.total = 0

        self.style = ttk.Style()
        self.style.theme_use("clam")
        self.style.configure("TButton", font=("Microsoft YaHei", 12), padding=6)
        self.style.configure("Title.TLabel", font=("Microsoft YaHei", 22, "bold"), background="#F0F4F8", foreground="#2C3E50")
        self.style.configure("Sub.TLabel", font=("Microsoft YaHei", 14), background="#F0F4F8", foreground="#34495E")
        self.style.configure("Word.TLabel", font=("Microsoft YaHei", 28, "bold"), background="#F0F4F8", foreground="#1A5276")
        self.style.configure("Info.TLabel", font=("Microsoft YaHei", 11), background="#F0F4F8", foreground="#7F8C8D")
        self.style.configure("Green.TLabel", font=("Microsoft YaHei", 13, "bold"), background="#F0F4F8", foreground="#27AE60")
        self.style.configure("Red.TLabel", font=("Microsoft YaHei", 13, "bold"), background="#F0F4F8", foreground="#E74C3C")

        self.build_main_page()

    # ---------- 主页面 ----------
    def build_main_page(self):
        self.clear()
        container = tk.Frame(self.root, bg="#F0F4F8")
        container.pack(expand=True, fill="both", padx=40, pady=30)

        ttk.Label(container, text="📖 英语单词背诵小程序", style="Title.TLabel").pack(pady=(0, 10))
        ttk.Label(container, text="科学记忆 · 艾宾浩斯复习法", style="Sub.TLabel").pack(pady=(0, 30))

        stats = self.get_stats()
        info_text = f"📊 总词数: {stats['total']}  |  已学: {stats['learned']}  |  掌握: {stats['mastered']}  |  正确率: {stats['accuracy']}"
        ttk.Label(container, text=info_text, style="Info.TLabel").pack(pady=(0, 30))

        buttons = [
            ("📚 开始学习（新词+复习）", self.start_learn),
            ("🔤 测验：看英文选中文", lambda: self.start_quiz("en_to_cn")),
            ("🈶 测验：看中文选英文", lambda: self.start_quiz("cn_to_en")),
            ("📕 错题本", self.show_wrong_book),
            ("📈 学习统计", self.show_statistics),
        ]
        for text, cmd in buttons:
            ttk.Button(container, text=text, command=cmd, width=30).pack(pady=6)

    # ---------- 学习模式 ----------
    def start_learn(self):
        now = datetime.now()
        due, new = [], []
        for w in WORDS:
            s = get_status(w, self.data)
            if s["stage"] == 0 and len(new) < 5:
                new.append(w)
            elif s["next_review"] and datetime.fromisoformat(s["next_review"]) <= now and len(due) < 5:
                due.append(w)
        self.learn_list = (due + new)
        if not self.learn_list:
            messagebox.showinfo("提示", "🎉 今天没有需要学习的单词，去测验一下吧！")
            return
        random.shuffle(self.learn_list)
        self.learn_index = 0
        self.show_learn_card()

    def show_learn_card(self):
        self.clear()
        container = tk.Frame(self.root, bg="#F0F4F8")
        container.pack(expand=True, fill="both", padx=50, pady=40)

        idx = self.learn_index
        total = len(self.learn_list)
        word = self.learn_list[idx]

        ttk.Label(container, text=f"学习进度 ({idx+1}/{total})", style="Info.TLabel").pack(pady=(0, 20))

        # 卡片背景
        card = tk.Frame(container, bg="white", relief="ridge", bd=2)
        card.pack(pady=10, ipadx=40, ipady=30)

        ttk.Label(card, text=word["word"], style="Word.TLabel").pack(pady=(10, 5))
        ttk.Label(card, text="点击按钮查看释义 ↓", style="Info.TLabel").pack(pady=5)

        self.meaning_label = ttk.Label(card, text="", style="Sub.TLabel")
        self.meaning_label.pack(pady=5)

        btn_frame = tk.Frame(container, bg="#F0F4F8")
        btn_frame.pack(pady=20)

        ttk.Button(btn_frame, text="👁 显示释义", command=lambda: self.reveal_meaning(word)).pack(side="left", padx=10)
        ttk.Button(btn_frame, text="✅ 我记住了", command=lambda: self.mark_learn(word, True)).pack(side="left", padx=10)
        ttk.Button(btn_frame, text="❌ 没记住", command=lambda: self.mark_learn(word, False)).pack(side="left", padx=10)

        ttk.Button(container, text="← 返回主菜单", command=self.build_main_page).pack(pady=(20, 0))

    def reveal_meaning(self, word):
        self.meaning_label.config(text=f"🇨🇳 {word['meaning']}")

    def mark_learn(self, word, remembered):
        update_status(word, self.data, remembered)
        self.learn_index += 1
        if self.learn_index >= len(self.learn_list):
            messagebox.showinfo("完成", "🎉 本轮学习完成！")
            self.build_main_page()
        else:
            self.show_learn_card()

    # ---------- 测验模式 ----------
    def start_quiz(self, quiz_type):
        self.quiz_type = quiz_type
        self.score = 0
        self.total = 0
        self.quiz_list = random.sample(WORDS, min(10, len(WORDS)))
        self.quiz_index = 0
        self.show_quiz_question()

    def show_quiz_question(self):
        self.clear()
        container = tk.Frame(self.root, bg="#F0F4F8")
        container.pack(expand=True, fill="both", padx=50, pady=30)

        idx = self.quiz_index
        total = len(self.quiz_list)
        word = self.quiz_list[idx]

        ttk.Label(container, text=f"测验进度 ({idx+1}/{total})", style="Info.TLabel").pack(pady=(0, 10))
        ttk.Label(container, text=f"得分: {self.score}/{self.total}", style="Info.TLabel").pack(pady=(0, 15))

        card = tk.Frame(container, bg="white", relief="ridge", bd=2)
        card.pack(pady=10, ipadx=40, ipady=25)

        if self.quiz_type == "en_to_cn":
            question_text = word["word"]
            ttk.Label(card, text=question_text, style="Word.TLabel").pack(pady=10)
            ttk.Label(card, text="请选择中文释义：", style="Sub.TLabel").pack(pady=5)
            correct_ans = word["meaning"]
        else:
            question_text = word["meaning"]
            ttk.Label(card, text=f"「{question_text}」", style="Word.TLabel").pack(pady=10)
            ttk.Label(card, text="请选择对应的英文单词：", style="Sub.TLabel").pack(pady=5)
            correct_ans = word["word"]

        # 生成选项
        if self.quiz_type == "en_to_cn":
            others = [x["meaning"] for x in WORDS if x["word"] != word["word"]]
        else:
            others = [x["word"] for x in WORDS if x["word"] != word["word"]]
        options = [correct_ans] + random.sample(others, 3)
        random.shuffle(options)
        self.current_correct = correct_ans

        self.feedback_label = ttk.Label(card, text="", style="Info.TLabel")
        self.feedback_label.pack(pady=5)

        btn_frame = tk.Frame(card, bg="white")
        btn_frame.pack(pady=10)
        for i, opt in enumerate(options):
            ttk.Button(btn_frame, text=opt, command=lambda o=opt: self.check_answer(o)).pack(fill="x", pady=3, padx=20)

        ttk.Button(container, text="← 返回主菜单", command=self.build_main_page).pack(pady=(15, 0))

    def check_answer(self, selected):
        self.total += 1
        if selected == self.current_correct:
            self.score += 1
            self.feedback_label.config(text="✅ 正确！", foreground="#27AE60")
            # 找到当前词
            word = self.quiz_list[self.quiz_index]
            update_status(word, self.data, True)
        else:
            self.feedback_label.config(text=f"❌ 错误！正确答案: {self.current_correct}", foreground="#E74C3C")
            word = self.quiz_list[self.quiz_index]
            update_status(word, self.data, False)

        self.quiz_index += 1
        self.root.after(1200, self.next_question)

    def next_question(self):
        if self.quiz_index >= len(self.quiz_list):
            messagebox.showinfo("测验结束", f"🏆 本次得分: {self.score}/{self.total}")
            self.build_main_page()
        else:
            self.show_quiz_question()

    # ---------- 错题本 ----------
    def show_wrong_book(self):
        self.clear()
        container = tk.Frame(self.root, bg="#F0F4F8")
        container.pack(expand=True, fill="both", padx=40, pady=20)

        ttk.Label(container, text="📕 错题本（错误率最高）", style="Title.TLabel").pack(pady=(0, 15))

        stats = []
        for w in WORDS:
            s = get_status(w, self.data)
            total = s["correct"] + s["wrong"]
            if total > 0:
                rate = s["wrong"] / total
                stats.append((rate, w["word"], w["meaning"], s["wrong"], s["correct"]))
        stats.sort(key=lambda x: x[0], reverse=True)
        stats = stats[:15]

        # 表格
        columns = ("单词", "释义", "错误", "正确", "错误率")
        tree = ttk.Treeview(container, columns=columns, show="headings", height=12)
        for col in columns:
            tree.heading(col, text=col)
            tree.column(col, anchor="center", width=100)
        tree.column("单词", width=130)
        tree.column("释义", width=120)

        if not stats:
            ttk.Label(container, text="暂无错题记录，去测验吧！", style="Sub.TLabel").pack(pady=20)
        else:
            for rate, word, meaning, wrong, correct in stats:
                tree.insert("", "end", values=(word, meaning, wrong, correct, f"{rate:.0%}"))
            tree.pack(fill="both", pady=10)

        ttk.Button(container, text="← 返回主菜单", command=self.build_main_page).pack(pady=10)

    # ---------- 统计 ----------
    def show_statistics(self):
        self.clear()
        container = tk.Frame(self.root, bg="#F0F4F8")
        container.pack(expand=True, fill="both", padx=50, pady=40)

        s = self.get_stats()
        ttk.Label(container, text="📈 学习统计", style="Title.TLabel").pack(pady=(0, 25))

        items = [
            ("总词汇量", f"{s['total']}"),
            ("已学习", f"{s['learned']} ({s['learned_pct']})"),
            ("已掌握（3星）", f"{s['mastered']} ({s['mastered_pct']})"),
            ("学习中", f"{s['learning']}"),
            ("累计正确答题", f"{s['total_correct']}"),
            ("累计错误答题", f"{s['total_wrong']}"),
            ("总正确率", f"{s['accuracy']}"),
        ]
        for label, value in items:
            row = tk.Frame(container, bg="#F0F4F8")
            row.pack(fill="x", pady=4)
            ttk.Label(row, text=f"{label}: ", style="Sub.TLabel").pack(side="left")
            ttk.Label(row, text=value, style="Info.TLabel").pack(side="left")

        ttk.Button(container, text="← 返回主菜单", command=self.build_main_page).pack(pady=(25, 0))

    def get_stats(self):
        total = len(WORDS)
        learned = 0
        mastered = 0
        total_correct = 0
        total_wrong = 0
        for w in WORDS:
            s = get_status(w, self.data)
            if s["stage"] > 0:
                learned += 1
            if s["stage"] >= 3:
                mastered += 1
            total_correct += s["correct"]
            total_wrong += s["wrong"]
        all_ans = total_correct + total_wrong
        acc = f"{total_correct / all_ans * 100:.1f}%" if all_ans > 0 else "暂无"
        return {
            "total": total,
            "learned": learned,
            "learned_pct": f"{learned/total*100:.1f}%",
            "mastered": mastered,
            "mastered_pct": f"{mastered/total*100:.1f}%",
            "learning": learned - mastered,
            "total_correct": total_correct,
            "total_wrong": total_wrong,
            "accuracy": acc,
        }

    # ---------- 工具方法 ----------
    def clear(self):
        for widget in self.root.winfo_children():
            widget.destroy()

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