import pygame
import sys

# === 1. 初始化与配置 ===
pygame.init()
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("数学公式查询器")
clock = pygame.time.Clock()

# 颜色定义
COLOR_BG = (240, 242, 245)
COLOR_SIDEBAR = (255, 255, 255)
COLOR_TEXT = (45, 45, 45)
COLOR_PRIMARY = (52, 152, 219)
COLOR_HIGHLIGHT = (235, 245, 255)
COLOR_GRAY = (150, 150, 150)

# 字体加载 (尝试加载系统支持中文的字体)
def get_font(size, bold=False):
    # 按照优先级尝试常用中文字体
    fonts = ["microsoftyahei", "simhei", "arial", "pingfangsc"]
    return pygame.font.SysFont(fonts, size, bold=bold)

FONT_MAIN = get_font(18)
FONT_BOLD = get_font(20, True)
FONT_LATEX = get_font(22, True)

# === 2. 示例数据 (你可以替换为从 JSON 加载) ===
FORMULAS = [
    {
        "title": "勾股定理 (Pythagorean Theorem)",
        "latex": "a² + b² = c²",
        "description": "在平面上的一个直角三角形中，两个直角边边长的平方加起来等于斜边长的平方。",
        "topics": ["几何", "基础数学"],
        "variables": {"a": "直角边", "b": "直角边", "c": "斜边"}
    },
    {
        "title": "欧拉公式 (Euler's Formula)",
        "latex": "e^{iπ} + 1 = 0",
        "description": "被誉为上帝公式，将指数函数、三角函数与虚数单位完美结合。",
        "topics": ["复变函数", "分析学"],
        "variables": {"e": "自然常数", "i": "虚数单位", "π": "圆周率"}
    },
    {
        "title": "二次方程求根公式",
        "latex": "x = [-b ± sqrt(b² - 4ac)] / 2a",
        "description": "用于求解一元二次方程 ax² + bx + c = 0 的根。",
        "topics": ["代数"],
        "variables": {"a,b,c": "系数", "x": "未知数"}
    }
]

# === 3. 功能函数 ===
def draw_text_wrapped(surface, text, x, y, max_width, font, color):
    """简单的自动换行文本绘制"""
    words = [text[i:i+25] for i in range(0, len(text), 25)] # 粗略按字符切分
    for line in words:
        img = font.render(line, True, color)
        surface.blit(img, (x, y))
        y += font.get_linesize()

def get_filtered_results(query):
    if not query: return FORMULAS
    q = query.lower()
    return [f for f in FORMULAS if q in f['title'].lower() or q in "".join(f['topics']).lower()]

# === 4. 主循环变量 ===
search_query = ""
selected_idx = 0
scroll_offset = 0
running = True

while running:
    # 获取过滤后的结果
    results = get_filtered_results(search_query)
    if selected_idx >= len(results): selected_idx = max(0, len(results)-1)

    # --- 事件处理 ---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                search_query = search_query[:-1]
            elif event.key == pygame.K_DOWN:
                selected_idx = min(len(results)-1, selected_idx + 1)
            elif event.key == pygame.K_UP:
                selected_idx = max(0, selected_idx - 1)
            else:
                if event.unicode.isprintable():
                    search_query += event.unicode

        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4: scroll_offset = max(0, scroll_offset - 20)
            if event.button == 5: scroll_offset += 20

    # --- 渲染界面 ---
    screen.fill(COLOR_BG)

    # 1. 左侧列表栏 (Sidebar)
    pygame.draw.rect(screen, COLOR_SIDEBAR, (0, 0, 350, HEIGHT))
    pygame.draw.line(screen, COLOR_GRAY, (350, 0), (350, HEIGHT), 1)

    # 搜索框绘制
    search_bar_rect = pygame.Rect(20, 20, 310, 40)
    pygame.draw.rect(screen, COLOR_BG, search_bar_rect, border_radius=5)
    search_hint = f"搜索: {search_query}" if search_query else "输入关键词搜索..."
    screen.blit(FONT_MAIN.render(search_hint, True, COLOR_TEXT), (30, 30))

    # 列表项绘制
    list_y = 80
    for i, item in enumerate(results):
        item_rect = pygame.Rect(10, list_y + (i * 60), 330, 55)
        if i == selected_idx:
            pygame.draw.rect(screen, COLOR_HIGHLIGHT, item_rect, border_radius=5)
            pygame.draw.rect(screen, COLOR_PRIMARY, item_rect, 2, border_radius=5)
        
        title_surf = FONT_MAIN.render(item['title'][:18], True, COLOR_TEXT)
        screen.blit(title_surf, (20, list_y + (i * 60) + 10))
        
        topic_str = " | ".join(item.get('topics', []))
        topic_surf = FONT_MAIN.render(topic_str, True, COLOR_GRAY)
        screen.blit(topic_surf, (20, list_y + (i * 60) + 32))

    # 2. 右侧详情区 (Detail View)
    if results:
        sel = results[selected_idx]
        detail_x = 380
        
        # 标题
        screen.blit(FONT_BOLD.render(sel['title'], True, COLOR_PRIMARY), (detail_x, 40))
        
        # 公式 (核心展示)
        pygame.draw.rect(screen, (255,255,255), (detail_x-10, 80, 480, 80), border_radius=10)
        latex_surf = FONT_LATEX.render(sel['latex'], True, (0, 0, 0))
        screen.blit(latex_surf, (detail_x + 20, 105))

        # 描述
        y_cursor = 180
        screen.blit(FONT_BOLD.render("描述:", True, COLOR_TEXT), (detail_x, y_cursor))
        draw_text_wrapped(screen, sel['description'], detail_x, y_cursor + 30, 480, FONT_MAIN, COLOR_TEXT)

        # 变量说明
        y_cursor = 320
        screen.blit(FONT_BOLD.render("变量定义:", True, COLOR_TEXT), (detail_x, y_cursor))
        for i, (k, v) in enumerate(sel.get('variables', {}).items()):
            var_txt = f"• {k} : {v}"
            screen.blit(FONT_MAIN.render(var_txt, True, COLOR_TEXT), (detail_x + 10, y_cursor + 35 + i*25))

        # 主题标签
        y_cursor = 480
        for i, t in enumerate(sel.get('topics', [])):
            tag_rect = pygame.Rect(detail_x + (i*100), y_cursor, 90, 30)
            pygame.draw.rect(screen, COLOR_PRIMARY, tag_rect, border_radius=15)
            tag_surf = FONT_MAIN.render(t, True, (255,255,255))
            screen.blit(tag_surf, (tag_rect.centerx - tag_surf.get_width()//2, tag_rect.centery - tag_surf.get_height()//2))

    else:
        screen.blit(FONT_MAIN.render("未找到相关公式", True, COLOR_GRAY), (500, 250))

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

pygame.quit()
sys.exit()