import pygame
import sys

# 初始化
pygame.init()

WIDTH, HEIGHT = 500, 350
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Timer")
clock = pygame.time.Clock()

# 颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (220, 50, 50)
GREEN = (40, 180, 80)
GRAY = (180, 180, 180)
BLUE = (80, 80, 220)

# 关键：全程不用SysFont，杜绝你环境的致命报错
font_big = pygame.font.Font(None, 70)
font_btn = pygame.font.Font(None, 28)
font_tip = pygame.font.Font(None, 22)

# 倒计时核心变量
total_second = 0
remain = 0
running = False
input_mode = True
hour = 0
minute = 0
second = 0

# 按钮矩形
btn_start = pygame.Rect(60, 240, 110, 50)
btn_pause = pygame.Rect(190, 240, 110, 50)
btn_reset = pygame.Rect(320, 240, 110, 50)

def sec2hms(s):
    """总秒数格式化 时:分:秒"""
    s = int(s)
    h = s // 3600
    m = (s % 3600) // 60
    s = s % 60
    return f"{h:02d}:{m:02d}:{s:02d}"

# 主循环
while True:
    screen.fill(WHITE)

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

        # 鼠标点击按钮
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_pos = pygame.mouse.get_pos()
            if btn_start.collidepoint(mouse_pos):
                if input_mode:
                    total_second = hour * 3600 + minute * 60 + second
                    remain = total_second
                    input_mode = False
                running = True
            if btn_pause.collidepoint(mouse_pos):
                running = False
            if btn_reset.collidepoint(mouse_pos):
                running = False
                input_mode = True
                hour = minute = second = 0
                remain = 0

        # 键盘输入数字设置时间
        if event.type == pygame.KEYDOWN and input_mode:
            num = None
            if pygame.K_0 <= event.key <= pygame.K_9:
                num = event.key - pygame.K_0
            elif pygame.K_KP0 <= event.key <= pygame.K_KP9:
                num = event.key - pygame.K_KP0

            if num is not None:
                if hour < 99:
                    hour = hour * 10 + num
                elif minute < 59:
                    minute = minute * 10 + num
                elif second < 59:
                    second = second * 10 + num
            # 退格删除
            if event.key == pygame.K_BACKSPACE:
                if second > 0:
                    second = second // 10
                elif minute > 0:
                    minute = minute // 10
                elif hour > 0:
                    hour = hour // 10

    # 倒计时更新
    if running:
        delta_time = clock.tick(60)
        remain -= delta_time / 1000
        if remain <= 0:
            remain = 0
            running = False

    # 绘制时分秒数字（数字不会乱码）
    if input_mode:
        time_str = f"{hour:02d}:{minute:02d}:{second:02d}"
    else:
        time_str = sec2hms(remain)
    time_surface = font_big.render(time_str, True, BLACK)
    screen.blit(time_surface, time_surface.get_rect(center=(WIDTH // 2, 110)))

    # 顶部提示英文，避免中文方框
    tip_surface = font_tip.render("Input number to set time", True, GRAY)
    screen.blit(tip_surface, (30, 20))

    # 进度条
    bar_x, bar_y = 50, 170
    bar_w, bar_h = 400, 12
    pygame.draw.rect(screen, GRAY, (bar_x, bar_y, bar_w, bar_h))
    if total_second > 0:
        fill_width = bar_w * (remain / total_second)
        fill_color = GREEN if remain > 0 else RED
        pygame.draw.rect(screen, fill_color, (bar_x, bar_y, fill_width, bar_h))

    # 绘制按钮（英文文字，彻底规避中文渲染报错）
    def draw_button(rect, text, color):
        pygame.draw.rect(screen, color, rect, border_radius=6)
        txt_surf = font_btn.render(text, True, (255, 255, 255))
        screen.blit(txt_surf, txt_surf.get_rect(center=rect.center))

    draw_button(btn_start, "Start", GREEN)
    draw_button(btn_pause, "Pause", BLUE)
    draw_button(btn_reset, "Reset", RED)

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