import pygame
import sys
import math

# ---------------- 初始化 ----------------
pygame.init()

WIDTH, HEIGHT = 1000, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("NPC好感度调查 - 热座投票大屏")

FONT_L = pygame.font.SysFont("simhei", 36)
FONT_M = pygame.font.SysFont("simhei", 28)
FONT_S = pygame.font.SysFont("simhei", 20)
FONT_XS = pygame.font.SysFont("simhei", 16)

WHITE = (255, 255, 255)
BLACK = (20, 20, 30)
GRAY = (180, 180, 190)
DARK_GRAY = (60, 60, 70)
BLUE = (80, 140, 240)
GREEN = (80, 220, 140)
RED = (240, 90, 100)
GOLD = (255, 200, 50)
PURPLE = (180, 100, 240)
CYAN = (80, 220, 220)
ORANGE = (255, 150, 50)

# ---------------- 数据定义 ----------------

NPCS = [
    {"name": "艾莉丝", "color": (255, 130, 180), "avatar": "♀", "favor": 50, "desc": "傲娇魔法师"},
    {"name": "雷恩",   "color": (130, 180, 255), "avatar": "♂", "favor": 50, "desc": "热血骑士"},
    {"name": "米拉",   "color": (180, 255, 130), "avatar": "♀", "favor": 50, "desc": "天然呆牧师"},
    {"name": "凯尔",   "color": (255, 180, 100), "avatar": "♂", "favor": 50, "desc": "腹黑商人"},
]

PLAYERS = [
    {"name": "玩家A", "voted": False, "color": BLUE},
    {"name": "玩家B", "voted": False, "color": GREEN},
    {"name": "玩家C", "voted": False, "color": PURPLE},
    {"name": "玩家D", "voted": False, "color": ORANGE},
]

QUESTIONS = [
    {
        "title": "你更倾向于哪种冒险风格？",
        "options": [
            {"text": "潜行暗杀", "effect": [5, -5, 0, 10]},
            {"text": "正面硬刚", "effect": [-5, 10, -3, 0]},
            {"text": "智取谈判", "effect": [0, -3, 5, 8]},
            {"text": "和平外交", "effect": [3, -5, 10, -5]},
        ]
    },
    {
        "title": "面对敌人求饶，你会？",
        "options": [
            {"text": "放他一马", "effect": [5, 0, 8, -5]},
            {"text": "收保护费", "effect": [-3, 0, -5, 15]},
            {"text": "一刀斩了", "effect": [-5, 10, -10, 5]},
            {"text": "交给队友", "effect": [3, 5, 3, 0]},
        ]
    },
    {
        "title": "队伍里谁最让你不爽？",
        "options": [
            {"text": "艾莉丝", "effect": [-15, 5, 0, 0]},
            {"text": "雷恩",   "effect": [5, -10, 0, 0]},
            {"text": "米拉",   "effect": [0, 0, -15, 0]},
            {"text": "凯尔",   "effect": [0, 0, 0, -15]},
        ]
    },
]

# ---------------- 状态变量 ----------------
current_question = 0
current_player_idx = 0
selected_option = -1
phase = "voting"  # voting / result / all_done
anim_current = 50.0

OPTION_RECTS = []
for i in range(4):
    OPTION_RECTS.append(pygame.Rect(80, 200 + i * 85, 840, 72))

NEXT_BTN = pygame.Rect(420, 600, 160, 50)
RESET_BTN = pygame.Rect(600, 600, 160, 50)
CONFIRM_BTN = pygame.Rect(250, 600, 160, 50)

favor_popups = []

# ---------------- 工具函数 ----------------
def lerp(a, b, t):
    return a + (b - a) * t

def draw_text(text, font, color, x, y, center=False):
    surf = font.render(text, True, color)
    rect = surf.get_rect()
    if center:
        rect.center = (x, y)
    else:
        rect.topleft = (x, y)
    screen.blit(surf, rect)

def draw_gradient_bar(x, y, w, h, color, bg_color, progress, label="", value=""):
    pygame.draw.rect(screen, bg_color, (x, y, w, h), border_radius=6)
    fill_w = int(w * max(0, min(1, progress)))
    if fill_w > 0:
        pygame.draw.rect(screen, color, (x, y, fill_w, h), border_radius=6)
    pygame.draw.rect(screen, WHITE, (x, y, w, h), 2, border_radius=6)
    if label:
        draw_text(label, FONT_S, WHITE, x + 8, y + h // 2)
    if value:
        draw_text(value, FONT_S, WHITE, x + w - 8, y + h // 2)

def draw_radar_chart(cx, cy, radius, values, max_val, colors, labels):
    n = len(values)
    points = []
    for i in range(n):
        angle = -math.pi / 2 + 2 * math.pi * i / n
        val = max(0, min(1, values[i] / max_val))
        px = cx + radius * val * math.cos(angle)
        py = cy + radius * val * math.sin(angle)
        points.append((px, py))

    for r in [0.25, 0.5, 0.75, 1.0]:
        grid_pts = []
        for i in range(n):
            angle = -math.pi / 2 + 2 * math.pi * i / n
            gx = cx + radius * r * math.cos(angle)
            gy = cy + radius * r * math.sin(angle)
            grid_pts.append((gx, gy))
        pygame.draw.polygon(screen, (60, 60, 80), grid_pts, 1)

    for i in range(n):
        angle = -math.pi / 2 + 2 * math.pi * i / n
        gx = cx + radius * math.cos(angle)
        gy = cy + radius * math.sin(angle)
        pygame.draw.line(screen, (60, 60, 80), (cx, cy), (gx, gy), 1)

    if len(points) >= 3:
        pygame.draw.polygon(screen, (*colors[0][:3], 80), points)
    for i in range(n):
        pygame.draw.circle(screen, colors[i], points[i], 6)

    for i in range(n):
        angle = -math.pi / 2 + 2 * math.pi * i / n
        lx = cx + (radius + 30) * math.cos(angle)
        ly = cy + (radius + 30) * math.sin(angle)
        draw_text(labels[i], FONT_S, colors[i], lx, ly, center=True)

def draw_npc_card(npc, x, y, w, h, anim_favor=50):
    pygame.draw.rect(screen, (40, 40, 55), (x, y, w, h), border_radius=12)
    pygame.draw.rect(screen, npc["color"], (x, y, w, h), 2, border_radius=12)

    pygame.draw.circle(screen, npc["color"], (x + 35, y + 35), 22)
    draw_text(npc["avatar"], FONT_L, WHITE, x + 35, y + 35, center=True)

    draw_text(npc["name"], FONT_M, WHITE, x + 65, y + 15)
    draw_text(npc["desc"], FONT_XS, GRAY, x + 65, y + 45)

    bar_y = y + 65
    favor_pct = anim_favor / 100.0
    bar_color = GREEN if favor_pct > 0.6 else (GOLD if favor_pct > 0.3 else RED)
    draw_gradient_bar(x + 10, bar_y, w - 20, 16, bar_color, (50, 50, 60), favor_pct,
                      "好感度", f"{int(anim_favor)}/100")

    if anim_favor >= 80:
        face = "♥ 挚友"
    elif anim_favor >= 60:
        face = "✓ 友好"
    elif anim_favor >= 40:
        face = "· 中立"
    elif anim_favor >= 20:
        face = "△ 冷淡"
    else:
        face = "✗ 敌对"
    draw_text(face, FONT_S, bar_color, x + w // 2, bar_y + 28, center=True)

# ---------------- 粒子系统 ----------------
particles = []

def spawn_particles(x, y, color, count=10):
    for _ in range(count):
        angle = math.radians(pygame.time.get_ticks() % 360 + _ * 36)
        speed = 2 + (_ % 5)
        particles.append({
            "x": x, "y": y,
            "vx": math.cos(angle) * speed,
            "vy": math.sin(angle) * speed - 2,
            "life": 40 + (_ % 20),
            "color": color,
            "size": 3 + (_ % 4)
        })

def update_particles():
    for p in particles[:]:
        p["x"] += p["vx"]
        p["y"] += p["vy"]
        p["vy"] += 0.1
        p["life"] -= 1
        if p["life"] <= 0:
            particles.remove(p)
        else:
            alpha = int(255 * p["life"] / 60)
            c = (*p["color"][:3], max(0, min(255, alpha)))
            surf = pygame.Surface((p["size"]*2, p["size"]*2), pygame.SRCALPHA)
            pygame.draw.circle(surf, c, (p["size"], p["size"]), p["size"])
            screen.blit(surf, (p["x"] - p["size"], p["y"] - p["size"]))

# ---------------- 主循环 ----------------
clock = pygame.time.Clock()
running = True

while running:
    dt = clock.tick(60)
    mouse_pos = pygame.mouse.get_pos()

    screen.fill(BLACK)

    # 网格背景
    for x in range(0, WIDTH, 50):
        pygame.draw.line(screen, (30, 30, 45), (x, 0), (x, HEIGHT), 1)
    for y in range(0, HEIGHT, 50):
        pygame.draw.line(screen, (30, 30, 45), (0, y), (WIDTH, y), 1)

    # ---------------- 顶部信息栏 ----------------
    if phase == "voting":
        player = PLAYERS[current_player_idx]
        pygame.draw.rect(screen, (30, 30, 50), (0, 0, WIDTH, 60))
        draw_text(f"🎮 {player['name']} 的回合", FONT_M, player["color"], 20, 30)

        progress = current_player_idx / len(PLAYERS)
        draw_gradient_bar(250, 22, 400, 16, BLUE, (40, 40, 60), progress)
        draw_text(f"投票进度: {current_player_idx}/{len(PLAYERS)}", FONT_S, GRAY, 670, 30)

        remaining = [p["name"] for p in PLAYERS[current_player_idx+1:] if not p["voted"]]
        if remaining:
            draw_text(f"等待: {', '.join(remaining)}", FONT_S, GRAY, 850, 30)

    elif phase == "result":
        pygame.draw.rect(screen, (30, 50, 30), (0, 0, WIDTH, 60))
        draw_text("📊 投票结果 & NPC好感度变化", FONT_M, GREEN, WIDTH // 2, 30, center=True)

    elif phase == "all_done":
        pygame.draw.rect(screen, (50, 30, 50), (0, 0, WIDTH, 60))
        draw_text("🏆 最终好感度面板", FONT_M, GOLD, WIDTH // 2, 30, center=True)

    # ---------------- 主体内容 ----------------
    if phase == "voting":
        q = QUESTIONS[current_question]
        draw_text(f"Q{current_question + 1}. {q['title']}", FONT_L, WHITE, WIDTH // 2, 100, center=True)
        draw_text(f"(第 {current_question + 1}/{len(QUESTIONS)} 题)", FONT_S, GRAY, WIDTH // 2, 140, center=True)

        for i, opt in enumerate(q["options"]):
            rect = OPTION_RECTS[i]
            hover = rect.collidepoint(mouse_pos)
            is_selected = (i == selected_option)

            if is_selected:
                pygame.draw.rect(screen, (*BLUE[:3], 200), rect, border_radius=10)
                pygame.draw.rect(screen, CYAN, rect, 3, border_radius=10)
            elif hover:
                pygame.draw.rect(screen, (50, 50, 70), rect, border_radius=10)
                pygame.draw.rect(screen, GRAY, rect, 2, border_radius=10)
            else:
                pygame.draw.rect(screen, (35, 35, 50), rect, border_radius=10)
                pygame.draw.rect(screen, DARK_GRAY, rect, 2, border_radius=10)

            mark = "▶ " if is_selected else f"{i+1}. "
            draw_text(mark + opt["text"], FONT_M, WHITE if is_selected else GRAY, rect.x + 20, rect.centery)

            effect_text = ""
            for j, eff in enumerate(opt["effect"]):
                if eff != 0:
                    sign = "+" if eff > 0 else ""
                    effect_text += f"{NPCS[j]['name']}{sign}{eff}  "
            if effect_text:
                draw_text(effect_text, FONT_XS, GRAY, rect.x + 20, rect.y + 55)

        btn_hover = CONFIRM_BTN.collidepoint(mouse_pos)
        btn_color = GREEN if selected_option >= 0 else DARK_GRAY
        pygame.draw.rect(screen, btn_color, CONFIRM_BTN, border_radius=8)
        draw_text("确 认", FONT_M, WHITE if selected_option >= 0 else GRAY,
                   CONFIRM_BTN.centerx, CONFIRM_BTN.centery, center=True)

    elif phase in ("result", "all_done"):
        for i, npc in enumerate(NPCS):
            col = i % 2
            row = i // 2
            card_x = 30 + col * 480
            card_y = 80 + row * 160
            draw_npc_card(npc, card_x, card_y, 460, 140, anim_current)

        if phase == "result":
            radar_cx = 750
            radar_cy = 350
            values = [npc["favor"] for npc in NPCS]
            labels = [npc["name"] for npc in NPCS]
            colors = [npc["color"] for npc in NPCS]
            draw_radar_chart(radar_cx, radar_cy, 120, values, 100, colors, labels)
            draw_text("好感度雷达", FONT_S, GRAY, radar_cx, radar_cy + 160, center=True)

        for popup in favor_popups[:]:
            color = GREEN if popup["change"] > 0 else RED
            text = f"{'+' if popup['change'] > 0 else ''}{popup['change']}"
            surf = FONT_M.render(text, True, color)
            screen.blit(surf, (popup["x"], popup["y"] - (30 - popup["timer"]) * 2))
            popup["timer"] -= 1
            if popup["timer"] <= 0:
                favor_popups.remove(popup)

        if phase == "result":
            btn_hover = NEXT_BTN.collidepoint(mouse_pos)
            pygame.draw.rect(screen, BLUE if btn_hover else (50, 50, 80), NEXT_BTN, border_radius=8)
            next_text = "下一题" if current_question < len(QUESTIONS) - 1 else "查看最终结果"
            draw_text(next_text, FONT_M, WHITE, NEXT_BTN.centerx, NEXT_BTN.centery, center=True)

    # 重置按钮
    reset_hover = RESET_BTN.collidepoint(mouse_pos)
    pygame.draw.rect(screen, RED if reset_hover else (80, 40, 40), RESET_BTN, border_radius=8)
    draw_text("重 置", FONT_M, WHITE, RESET_BTN.centerx, RESET_BTN.centery, center=True)

    update_particles()

    # ---------------- 事件 ----------------
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if phase == "voting":
                for i, rect in enumerate(OPTION_RECTS):
                    if rect.collidepoint(event.pos):
                        selected_option = i
                        spawn_particles(event.pos[0], event.pos[1], CYAN, 8)

                if CONFIRM_BTN.collidepoint(event.pos) and selected_option >= 0:
                    q = QUESTIONS[current_question]
                    opt = q["options"][selected_option]

                    for i, eff in enumerate(opt["effect"]):
                        if eff != 0:
                            NPCS[i]["favor"] = max(0, min(100, NPCS[i]["favor"] + eff))
                            favor_popups.append({
                                "npc": i,
                                "change": eff,
                                "x": 100 + i * 240,
                                "y": 200,
                                "timer": 30
                            })

                    PLAYERS[current_player_idx]["voted"] = True
                    spawn_particles(WIDTH // 2, HEIGHT // 2, GREEN, 20)

                    all_voted = all(p["voted"] for p in PLAYERS)
                    if all_voted:
                        phase = "result"
                        anim_current = NPCS[0]["favor"]
                    else:
                        current_player_idx += 1
                        while current_player_idx < len(PLAYERS) and PLAYERS[current_player_idx]["voted"]:
                            current_player_idx += 1

                    selected_option = -1

            elif phase == "result":
                if NEXT_BTN.collidepoint(event.pos):
                    spawn_particles(event.pos[0], event.pos[1], BLUE, 15)
                    if current_question < len(QUESTIONS) - 1:
                        current_question += 1
                        for p in PLAYERS:
                            p["voted"] = False
                        current_player_idx = 0
                        phase = "voting"
                    else:
                        phase = "all_done"
                        anim_current = NPCS[0]["favor"]

            if RESET_BTN.collidepoint(event.pos):
                for p in PLAYERS:
                    p["voted"] = False
                for npc in NPCS:
                    npc["favor"] = 50
                current_question = 0
                current_player_idx = 0
                selected_option = -1
                phase = "voting"
                anim_current = 50
                favor_popups.clear()
                spawn_particles(WIDTH // 2, HEIGHT // 2, RED, 30)

    # 键盘快捷键（1~4）—— 修复后的版本
    keys = pygame.key.get_pressed()
    if phase == "voting":
        key_map = {pygame.K_1: 0, pygame.K_2: 1, pygame.K_3: 2, pygame.K_4: 3}
        for key, idx in key_map.items():
            if keys[key] and idx < len(QUESTIONS[current_question]["options"]):
                selected_option = idx

    pygame.display.flip()

pygame.quit()
sys.exit()