import pygame
import random
import math
import sys
import datetime
import os

pygame.init()

# ========== 安全字体加载 ==========
def _find_system_font():
    local_fonts = ["msyh.ttc", "simhei.ttf", "msyh.ttf", "simsun.ttc"]
    for f in local_fonts:
        if os.path.exists(f):
            return f
    fonts_dir = os.path.join(os.environ.get("WINDIR", "C:\\Windows"), "Fonts")
    sys_fonts = [
        "msyh.ttc", "simhei.ttf", "msyh.ttf", "simsun.ttc",
        "simkai.ttf", "simfang.ttf", "msyhbd.ttc"
    ]
    for f in sys_fonts:
        p = os.path.join(fonts_dir, f)
        if os.path.exists(p):
            return p
    return None

_font_path = _find_system_font()

def load_font(size):
    if _font_path:
        try:
            return pygame.font.Font(_font_path, size)
        except Exception:
            pass
    return pygame.font.Font(None, size)

FONT = load_font(20)
FONT_S = load_font(16)
BIG = load_font(36)
TITLE = load_font(48)

# ========== 常量 ==========
W, H = 1000, 720

ZODIACS = [
    "白羊座", "金牛座", "双子座", "巨蟹座",
    "狮子座", "处女座", "天秤座", "天蝎座",
    "射手座", "摩羯座", "水瓶座", "双鱼座"
]

COLORS = ["红", "橙", "黄", "绿", "蓝", "紫", "粉", "银", "金", "黑"]
LEVELS = ["大凶", "平平", "小吉", "中吉", "大吉", "欧皇降临"]

QUIPS = {
    "白羊座": "今天别用脑袋撞墙，用脑子。",
    "金牛座": "钱没白花，但也没白省。",
    "双子座": "精分现场，建议自带剧本。",
    "巨蟹座": "情绪像汤，咕嘟咕嘟冒泡。",
    "狮子座": "今天适合当主角，别抢别人戏。",
    "处女座": "看谁都不顺眼，先放过自己。",
    "天秤座": "选择困难，建议抛硬币并反着选。",
    "天蝎座": "别盯人了，他们怕你。",
    "射手座": "跑得越快，烦恼追不上。",
    "摩羯座": "卷可以，记得呼吸。",
    "水瓶座": "脑洞已超标，请系好安全带。",
    "双鱼座": "做梦可以，别赖床一整天。"
}

MATCH_STORIES = {
    "甜": [
        "{a}给{b}带了早餐，{b}嘴上说'随便你'，心里已经放烟花了。",
        "{a}今天会突然收到{b}的消息，点开一看是'在吗'，心跳漏了一拍。",
        "{a}和{b}今天会不约而同穿同色系衣服，朋友都说'你们是不是约好了'。",
        "{b}今天会对{a}笑了一下，{a}回去想了三小时那个笑容什么意思。",
        "{a}鼓起勇气约{b}吃饭，{b}秒回'好呀'——今天适合告白。",
    ],
    "虐": [
        "{a}发了一条朋友圈，{b}看了没点赞，{a}删了重发。",
        "{b}今天说了句'随便'，{a}听出了三层意思，但没有一层是好的。",
        "{a}等{b}的回复等到手机没电，充电后第一条消息是{b}发的'嗯'。",
        "{a}和{b}今天会为了'谁先道歉'冷战，最终谁都没道歉。",
        "{b}跟别人笑得很开心，{a}在旁边假装没看见，回去哭了。",
    ],
    "搞笑": [
        "{a}和{b}今天会同时说同一句话，然后同时说'你学我'。",
        "{b}今天穿了新衣服问{a}好不好看，{a}说'还行'，{b}生气了三天。",
        "{a}想逗{b}笑，结果自己先笑了，{b}一脸冷漠。",
        "{a}和{b}打游戏双排，{a}送人头，{b}在语音里骂了十分钟。",
        "{b}今天跟{a}说'我们绝交吧'，{a}说'好'，{b}更生气了。",
    ]
}

GACHA_POOL = [
    ("SSR", "桃花暴击", "今天遇到的人都会对你笑", (255, 215, 0)),
    ("SSR", "财运附体", "花钱如流水但进账如海啸", (255, 215, 0)),
    ("SSR", "欧皇光环", "今天买啥中啥，包括彩票", (255, 215, 0)),
    ("SR",  "老板好感+1", "今天提加薪不会被拒", (200, 100, 255)),
    ("SR",  "考试必过", "蒙的全对，会的全对", (200, 100, 255)),
    ("SR",  "熬夜不掉头发", "今日熬夜buff，明日依然精神", (200, 100, 255)),
    ("SR",  "社交牛逼症", "今天跟谁都能聊三句", (200, 100, 255)),
    ("R",   "奶茶半价运", "路过奶茶店必遇半价", (100, 200, 255)),
    ("R",   "走路捡钱", "今天至少捡到一块钱", (100, 200, 255)),
    ("R",   "好运外卖", "今天外卖准时且好吃", (100, 200, 255)),
    ("N",   "空气好运", "今天呼吸的空气都是甜的", (150, 150, 150)),
    ("N",   "普通的一天", "没有坏事就是好事", (150, 150, 150)),
]
GACHA_RATES = ["N"]*45 + ["R"]*30 + ["SR"]*18 + ["SSR"]*7

ACHIEVEMENTS = {
    "欧皇认证": {"need": 3, "icon": "🏆", "desc": "累计抽中3次SSR，运气已溢出"},
    "天选之人": {"need": 5, "icon": "👑", "desc": "累计抽中5次SSR，宇宙偏爱你"},
    "星盘之主": {"need": 10, "icon": "🌟", "desc": "累计抽中10次SSR，你就是玄学本身"},
}

# ========== 全局状态 ==========
current_date = None
date_seed = None
ssr_count = 0
unlocked = set()
newly_unlocked = []
show_achievement_popup = False
popup_timer = 0

state = "menu"
selected = None
match_target = None
result = None
spin_angle = 0
spinning = False
spin_speed = 0

gacha_coins = 3
gacha_results = []
gacha_anim = False
gacha_anim_frame = 0

stars = [{"x": random.randint(0,W), "y": random.randint(0,H), "s": random.uniform(0.3,1.8)} for _ in range(150)]
particles = []

# ========== 日期系统 ==========
def check_date_seed():
    global current_date, date_seed
    today = datetime.date.today().isoformat()
    if today != current_date:
        current_date = today
        date_seed = today + "_FORTUNE_SALT"
        return True
    return False

def apply_date_seed():
    if date_seed:
        random.seed(date_seed)

def restore_seed():
    random.seed()

def check_achievements():
    global newly_unlocked, show_achievement_popup, popup_timer
    for name, info in ACHIEVEMENTS.items():
        if name not in unlocked and ssr_count >= info["need"]:
            unlocked.add(name)
            newly_unlocked.append(name)
            show_achievement_popup = True
            popup_timer = 180

check_date_seed()

# ========== 绘图函数 ==========
def draw_stars():
    screen.fill((8, 6, 25))
    for s in stars:
        s["y"] += s["s"]
        if s["y"] > H:
            s["y"] = 0
        pygame.draw.circle(screen, (200, 200, 255), (int(s["x"]), int(s["y"])), int(s["s"]))

def draw_particles():
    for p in particles[:]:
        p["y"] += p["vy"]
        p["x"] += p["vx"]
        p["life"] -= 1
        surf = pygame.Surface((p["size"]*2, p["size"]*2))
        surf.set_alpha(max(0, p["life"]*3))
        surf.fill((0, 0, 0))
        # 用带 alpha 的 surf 画圆
        pygame.draw.circle(surf, p["color"], (p["size"], p["size"]), p["size"])
        screen.blit(surf, (int(p["x"]-p["size"]), int(p["y"]-p["size"])))
        if p["life"] <= 0:
            particles.remove(p)

def spawn_particles(x, y, color, count=15):
    for _ in range(count):
        particles.append({
            "x": x, "y": y,
            "vx": random.uniform(-3, 3),
            "vy": random.uniform(-5, -1),
            "size": random.uniform(2, 5),
            "life": random.randint(30, 60),
            "color": color
        })

def button(txt, x, y, w=160, h=44, hover=False, col=None):
    c = col if col else ((80,60,140) if hover else (50,40,90))
    pygame.draw.rect(screen, c, (x,y,w,h), border_radius=10)
    pygame.draw.rect(screen, (120,100,180), (x,y,w,h), 2, border_radius=10)
    t = FONT.render(txt, True, (255,255,255))
    screen.blit(t, (x + w//2 - t.get_width()//2, y + h//2 - t.get_height()//2))
    return pygame.Rect(x,y,w,h)

def draw_wheel(cx, cy, r):
    global spin_angle
    segs = len(ZODIACS)
    for i, z in enumerate(ZODIACS):
        a1 = math.radians(spin_angle + i*360/segs)
        a2 = math.radians(spin_angle + (i+1)*360/segs)
        col = (30+random.randint(0,30), 20+random.randint(0,20), 60+random.randint(0,50))
        pygame.draw.arc(screen, col, (cx-r, cy-r, r*2, r*2), a1, a2, width=r)
        mx = cx + math.cos((a1+a2)/2)*(r*0.6)
        my = cy + math.sin((a1+a2)/2)*(r*0.6)
        t = FONT.render(z[:2], True, (255,255,255))
        screen.blit(t, (int(mx-t.get_width()//2), int(my-t.get_height()//2)))
    pygame.draw.polygon(screen, (255,220,120), [(cx, cy-r-12), (cx-12, cy-r+8), (cx+12, cy-r+8)])

def draw_achievement_popup():
    if not show_achievement_popup or not newly_unlocked:
        return
    overlay = pygame.Surface((W, H))
    overlay.set_alpha(150)
    overlay.fill((0, 0, 0))
    screen.blit(overlay, (0, 0))

    bx, by, bw_pop, bh_pop = W//2-250, H//2-120, 500, 240
    pygame.draw.rect(screen, (40, 30, 70), (bx, by, bw_pop, bh_pop), border_radius=20)
    pygame.draw.rect(screen, (255, 215, 0), (bx, by, bw_pop, bh_pop), 3, border_radius=20)

    title = BIG.render("🎉 成就解锁！", True, (255, 215, 0))
    screen.blit(title, (W//2-title.get_width()//2, by+20))

    for i, name in enumerate(newly_unlocked[-3:]):
        info = ACHIEVEMENTS[name]
        icon_t = BIG.render(f"{info['icon']} {name}", True, (255, 255, 255))
        screen.blit(icon_t, (W//2-icon_t.get_width()//2, by+70+i*60))
        desc_t = FONT.render(info['desc'], True, (200, 200, 200))
        screen.blit(desc_t, (W//2-desc_t.get_width()//2, by+100+i*60))

    hint = FONT_S.render("点击任意位置继续", True, (150, 150, 150))
    screen.blit(hint, (W//2-hint.get_width()//2, by+bh_pop-30))

def draw_achievement_bar():
    if not unlocked and ssr_count == 0:
        return
    y_off = 60
    bar_w = 180
    pygame.draw.rect(screen, (30, 20, 50), (10, y_off, bar_w, 30 + len(ACHIEVEMENTS)*22), border_radius=10)
    t = FONT_S.render(f"🏆 SSR: {ssr_count}/10", True, (255, 215, 0))
    screen.blit(t, (20, y_off+8))
    for name, info in ACHIEVEMENTS.items():
        prog = min(1.0, ssr_count / info["need"])
        py = y_off + 30 + list(ACHIEVEMENTS.keys()).index(name)*22
        pygame.draw.rect(screen, (50, 40, 70), (20, py, bar_w-20, 14), border_radius=7)
        if prog > 0:
            fill_col = (255, 215, 0) if name in unlocked else (100, 80, 150)
            pygame.draw.rect(screen, fill_col, (20, py, int((bar_w-20)*prog), 14), border_radius=7)
        status = "✅" if name in unlocked else f"{min(ssr_count, info['need'])}/{info['need']}"
        lt = FONT_S.render(f"{info['icon']} {name} {status}", True, (200, 200, 200))
        screen.blit(lt, (25, py))

# ========== 核心逻辑 ==========
def roll_fortune_dated(z):
    apply_date_seed()
    r = {
        "星座": z,
        "综合": random.choice(LEVELS),
        "爱情": random.choice(LEVELS),
        "财运": random.choice(LEVELS),
        "健康": random.choice(LEVELS),
        "幸运数字": random.randint(0, 9),
        "幸运色": random.choice(COLORS),
        "宜": random.choice(["摸鱼", "告白", "买彩票", "发呆", "熬夜", "吃甜品", "删人", "算命"]),
        "忌": random.choice(["较真", "回消息太快", "算账", "立flag", "相信老板画饼", "相信星座"]),
        "吐槽": QUIPS[z],
        "日期": current_date
    }
    restore_seed()
    return r

def gacha_pull():
    apply_date_seed()
    rate = random.choice(GACHA_RATES)
    pool = [g for g in GACHA_POOL if g[0] == rate]
    item = random.choice(pool)
    if rate == "SSR":
        global ssr_count
        ssr_count += 1
        check_achievements()
    restore_seed()
    return item

def match_story_dated(a, b):
    apply_date_seed()
    style = random.choice(["甜", "虐", "搞笑"])
    story = random.choice(MATCH_STORIES[style])
    story = story.format(a=a, b=b)
    score = random.randint(20, 99)
    restore_seed()
    return {"a": a, "b": b, "score": score, "style": style, "story": story}

# ========== UI 布局 ==========
zodiac_btns = []
cols, rows = 4, 3
bw, bh, gap = 170, 50, 18
sx = (W - (cols*bw + (cols-1)*gap))//2
sy = 180
for i, z in enumerate(ZODIACS):
    r, c = divmod(i, cols)
    x = sx + c*(bw+gap)
    y = sy + r*(bh+gap)
    zodiac_btns.append((z, pygame.Rect(x, y, bw, bh)))

btn_back = pygame.Rect(20, 20, 100, 38)
btn_again = pygame.Rect(W//2-260, 620, 160, 46)
btn_match = pygame.Rect(W//2-80, 620, 160, 46)
btn_gacha = pygame.Rect(W//2+100, 620, 160, 46)
btn_gacha_spin = pygame.Rect(W//2-90, 420, 180, 55)

# ========== 主循环 ==========
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("🔮 星座运势屋 · 玄学版")
clock = pygame.time.Clock()

while True:
    mouse = pygame.mouse.get_pos()
    check_date_seed()
    draw_stars()
    draw_particles()

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if e.type == pygame.MOUSEBUTTONDOWN:
            if show_achievement_popup:
                show_achievement_popup = False
                newly_unlocked.clear()
                popup_timer = 0
                continue

            if state == "menu":
                if pygame.Rect(W//2-350, 200, 220, 80).collidepoint(mouse):
                    state = "select"
                if pygame.Rect(W//2-110, 200, 220, 80).collidepoint(mouse):
                    state = "match_select"
                if pygame.Rect(W//2+130, 200, 220, 80).collidepoint(mouse):
                    state = "gacha"

            elif state == "select":
                for z, rect in zodiac_btns:
                    if rect.collidepoint(mouse):
                        selected = z
                        state = "spin"
                        spinning = True
                        spin_speed = random.uniform(18, 26)
                        result = None

            elif state == "spin" and not spinning:
                if btn_back.collidepoint(mouse):
                    state = "menu"

            elif state == "result":
                if btn_back.collidepoint(mouse):
                    state = "menu"
                if btn_again.collidepoint(mouse):
                    state = "spin"; spinning = True; spin_speed = random.uniform(18,26)
                if btn_match.collidepoint(mouse):
                    state = "match_select"
                if btn_gacha.collidepoint(mouse):
                    state = "gacha"

            elif state == "match_select":
                if btn_back.collidepoint(mouse):
                    state = "menu"
                for z, rect in zodiac_btns:
                    if rect.collidepoint(mouse):
                        match_target = z
                        match_result_data = match_story_dated(selected or "你", z)
                        state = "match_result"

            elif state == "match_result":
                if btn_back.collidepoint(mouse):
                    state = "menu"

            elif state == "gacha":
                if btn_back.collidepoint(mouse):
                    state = "menu"
                if btn_gacha_spin.collidepoint(mouse) and gacha_coins > 0 and not gacha_anim:
                    gacha_coins -= 1
                    gacha_anim = True
                    gacha_anim_frame = 0

    if state == "spin" and spinning:
        spin_angle += spin_speed
        spin_speed *= 0.97
        if spin_speed < 0.2:
            spinning = False
            result = roll_fortune_dated(selected)
            state = "result"
            spawn_particles(W//2, 300, (255,220,120), 25)

    if state == "gacha" and gacha_anim:
        gacha_anim_frame += 1
        if gacha_anim_frame > 40:
            gacha_anim = False
            item = gacha_pull()
            gacha_results.insert(0, item)
            gacha_results = gacha_results[:8]
            spawn_particles(W//2, 350, item[3], 30)
            if item[0] == "SSR":
                spawn_particles(W//2, 350, (255, 215, 0), 50)

    if show_achievement_popup:
        popup_timer -= 1
        if popup_timer <= 0:
            show_achievement_popup = False
            newly_unlocked.clear()

    # ========== 渲染 ==========
    title = TITLE.render("🔮 星座运势屋 · 玄学版", True, (255,230,180))
    screen.blit(title, (W//2-title.get_width()//2, 15))

    date_t = FONT_S.render(f"📅 {current_date}", True, (150, 150, 200))
    screen.blit(date_t, (W-120, 15))

    draw_achievement_bar()

    if state == "menu":
        sub = FONT.render("选一个模式开始你的今日运势之旅", True, (180,180,220))
        screen.blit(sub, (W//2-sub.get_width()//2, 75))

        btn_s = pygame.Rect(W//2-350, 200, 220, 80)
        btn_m = pygame.Rect(W//2-110, 200, 220, 80)
        btn_g = pygame.Rect(W//2+130, 200, 220, 80)

        button("🎡 星座抽签", btn_s.x, btn_s.y, btn_s.w, btn_s.h, hover=btn_s.collidepoint(mouse), col=(80,50,120))
        button("💘 配对小剧场", btn_m.x, btn_m.y, btn_m.w, btn_m.h, hover=btn_m.collidepoint(mouse), col=(120,50,80))
        button("🎰 幸运扭蛋机", btn_g.x, btn_g.y, btn_g.w, btn_g.h, hover=btn_g.collidepoint(mouse), col=(50,100,80))

        tips = [
            "🎡 星座抽签：今日星象已锁定，同一天结果一致",
            "💘 配对小剧场：选两个星座看今日剧情",
            "🎰 幸运扭蛋机：消耗扭蛋币抽今日buff（初始3币）",
            f"🏆 成就系统：累计SSR {ssr_count}/10，已解锁 {len(unlocked)} 个",
        ]
        for i, t in enumerate(tips):
            tt = FONT_S.render(t, True, (160,160,200))
            screen.blit(tt, (W//2-200, 320+i*30))

    elif state == "select":
        hint = FONT.render("选择你的星座：", True, (200,200,255))
        screen.blit(hint, (W//2-hint.get_width()//2, 130))
        for z, rect in zodiac_btns:
            hover = rect.collidepoint(mouse)
            button(z, rect.x, rect.y, rect.w, rect.h, hover=hover)

    elif state == "spin":
        draw_wheel(W//2, 330, 160)
        if spinning:
            tip = FONT.render("星盘转动中…", True, (255,255,200))
            screen.blit(tip, (W//2-tip.get_width()//2, 520))
        else:
            button("← 返回", btn_back.x, btn_back.y, btn_back.w, btn_back.h, hover=btn_back.collidepoint(mouse))

    elif state == "result" and result:
        x = 280
        y = 90
        lines = [
            f"【{result['星座']}】今日运势",
            f"综合：{result['综合']}    爱情：{result['爱情']}    财运：{result['财运']}    健康：{result['健康']}",
            f"幸运数字：{result['幸运数字']}    幸运色：{result['幸运色']}",
            f"✅ 宜：{result['宜']}",
            f"❌ 忌：{result['忌']}",
            "",
            f"✨ {result['吐槽']}",
            "",
            f"🔒 今日星象已锁定 ({result['日期']})",
        ]
        for i, ln in enumerate(lines):
            col = (180, 180, 180) if "🔒" in ln else (255, 255, 255)
            t = FONT.render(ln, True, col)
            screen.blit(t, (x, y + i*30))

        button("← 返回", btn_back.x, btn_back.y, btn_back.w, btn_back.h, hover=btn_back.collidepoint(mouse))
        button("再抽一次", btn_again.x, btn_again.y, 160, 46, hover=btn_again.collidepoint(mouse))
        button("配对小剧场", btn_match.x, btn_match.y, 160, 46, hover=btn_match.collidepoint(mouse))
        button("扭蛋机", btn_gacha.x, btn_gacha.y, 160, 46, hover=btn_gacha.collidepoint(mouse))

    elif state == "match_select":
        hint = FONT.render(f"为 {selected or '?'} 选择配对星座：", True, (200,200,255))
        screen.blit(hint, (W//2-hint.get_width()//2, 130))
        for z, rect in zodiac_btns:
            hover = rect.collidepoint(mouse)
            button(z, rect.x, rect.y, rect.w, rect.h, hover=hover)
        button("← 返回", btn_back.x, btn_back.y, btn_back.w, btn_back.h, hover=btn_back.collidepoint(mouse))

    elif state == "match_result":
        d = match_result_data
        t1 = BIG.render(f"💘 {d['a']} × {d['b']}", True, (255,180,200))
        screen.blit(t1, (W//2-t1.get_width()//2, 130))

        bar_w = 400
        pygame.draw.rect(screen, (60,40,60), (W//2-bar_w//2, 190, bar_w, 30), border_radius=15)
        fill_w = int(bar_w * d['score'] / 100)
        bar_col = (255,80,120) if d['score'] < 40 else (255,200,50) if d['score'] < 70 else (100,255,150)
        pygame.draw.rect(screen, bar_col, (W//2-bar_w//2, 190, fill_w, 30), border_radius=15)
        pct = BIG.render(f"{d['score']}%", True, (255,255,255))
        screen.blit(pct, (W//2-pct.get_width()//2, 192))

        style_col = {"甜":(255,150,200), "虐":(150,100,255), "搞笑":(255,200,80)}[d['style']]
        st = FONT.render(f"【{d['style']}】· 🔒今日已锁定", True, style_col)
        screen.blit(st, (W//2-st.get_width()//2, 240))

        story = d['story']
        words = list(story)
        s_lines = []
        line = ""
        for w in words:
            test = line + w
            if FONT.size(test)[0] > 600:
                s_lines.append(line)
                line = w
            else:
                line = test
        if line: s_lines.append(line)

        for i, ln in enumerate(s_lines):
            t = FONT.render(ln, True, (255,255,255))
            screen.blit(t, (W//2-t.get_width()//2, 280 + i*30))

        button("← 返回菜单", btn_back.x, btn_back.y, btn_back.w, btn_back.h, hover=btn_back.collidepoint(mouse))

    elif state == "gacha":
        pygame.draw.rect(screen, (60,40,80), (W//2-150, 120, 300, 380), border_radius=20)
        pygame.draw.rect(screen, (100,70,140), (W//2-150, 120, 300, 380), 3, border_radius=20)

        pygame.draw.circle(screen, (80,60,120), (W//2, 200), 60)
        pygame.draw.circle(screen, (150,120,200), (W//2, 200), 60, 2)

        for i in range(8):
            angle = pygame.time.get_ticks()*0.001 + i*0.8
            bx = W//2 + int(math.cos(angle)*35)
            by = 200 + int(math.sin(angle*1.3)*20)
            col = random.choice([(255,100,100),(100,255,100),(100,100,255),(255,255,100),(255,100,255)])
            pygame.draw.circle(screen, col, (bx, by), 10)

        pygame.draw.rect(screen, (40,20,60), (W//2-30, 350, 60, 40), border_radius=5)

        if gacha_results:
            item = gacha_results[0]
            pygame.draw.circle(screen, item[3], (W//2, 370), 14)
            pygame.draw.circle(screen, (255,255,255), (W//2, 370), 14, 2)
            rl = FONT_S.render(item[0], True, item[3])
            screen.blit(rl, (W//2-rl.get_width()//2, 362))

        can_spin = gacha_coins > 0 and not gacha_anim
        col = (80,60,140) if can_spin else (50,50,50)
        pygame.draw.rect(screen, col, btn_gacha_spin, border_radius=12)
        pygame.draw.rect(screen, (120,100,180), btn_gacha_spin, 2, border_radius=12)
        spin_txt = "🎰 扭!" if can_spin else "等待中..."
        st = FONT.render(spin_txt, True, (255,255,255) if can_spin else (100,100,100))
        screen.blit(st, (btn_gacha_spin.x+btn_gacha_spin.w//2-st.get_width()//2,
                         btn_gacha_spin.y+btn_gacha_spin.h//2-st.get_height()//2))

        coin_t = FONT.render(f"🪙 扭蛋币: {gacha_coins}", True, (255,220,100))
        screen.blit(coin_t, (W//2-coin_t.get_width()//2, 490))

        reset_btn = pygame.Rect(W//2-60, 520, 120, 30)
        pygame.draw.rect(screen, (40,40,80), reset_btn, border_radius=8)
        rt = FONT_S.render("免费补满", True, (150,150,200))
        screen.blit(rt, (reset_btn.x+reset_btn.w//2-rt.get_width()//2, reset_btn.y+rt.get_height()//2))
        if reset_btn.collidepoint(mouse) and pygame.mouse.get_pressed()[0]:
            gacha_coins = 3

        hist_t = FONT_S.render("最近抽到的buff：", True, (180,180,220))
        screen.blit(hist_t, (W//2+180, 130))
        for i, item in enumerate(gacha_results[:8]):
            r, name, desc, rcol = item
            tag = FONT_S.render(f"[{r}] {name}", True, rcol)
            screen.blit(tag, (W//2+180, 155+i*45))
            dsc = FONT_S.render(desc, True, (150,150,150))
            screen.blit(dsc, (W//2+180, 155+i*45+18))

        ssr_t = FONT_S.render(f"累计SSR: {ssr_count}", True, (255, 215, 0))
        screen.blit(ssr_t, (W//2+180, 520))

        button("← 返回", btn_back.x, btn_back.y, btn_back.w, btn_back.h, hover=btn_back.collidepoint(mouse))

        if gacha_anim:
            overlay = pygame.Surface((W,H))
            overlay.set_alpha(min(80, gacha_anim_frame*3))
            overlay.fill((0, 0, 0))
            screen.blit(overlay, (0,0))
            if gacha_anim_frame % 4 < 2:
                flash = pygame.Surface((W,H))
                flash.set_alpha(min(100, 30-gacha_anim_frame))
                flash.fill((255, 255, 255))
                screen.blit(flash, (0,0))

    draw_achievement_popup()

    pygame.display.flip()
    clock.tick(60)