# ui.py
import pygame
import sys
import time
from config import COLORS, CELL_SIZE, GUESSES, FONT_SIZE # Import necessary configs
from drawing_utils import draw_gradient_background, draw_text_centered

def calculate_window_size(word_length, guesses_count, cell_sz_from_config):
    field_width = word_length * cell_sz_from_config
    field_height = guesses_count * (cell_sz_from_config + 10)
    width_candidate = field_width + 80
    width = max(480, width_candidate) # Min width from original code
    height_candidate = field_height + 220
    height = max(700, height_candidate) # Min height from original code
    return width, height

def show_message_box(gs, text, delay=500, redraw_background_func=None, redraw_args=()):
    """Displays a message box on the screen."""
    # gs: GameState instance
    if redraw_background_func:
        redraw_background_func(*redraw_args)

    main_font = gs.get_font('main', FONT_SIZE) # Use main game font size
    small_font = gs.get_font('small')

    text_surface = main_font.render(text, True, COLORS['BLACK'])
    text_w, text_h = text_surface.get_size()

    padding_x, padding_y = 20, 15
    box_inner_w = text_w + 2 * padding_x
    max_box_w = gs.WIDTH - 2 * 20 # screen_margin

    if box_inner_w > max_box_w: # If text too wide, try smaller font
        text_surface = small_font.render(text, True, COLORS['BLACK'])
        text_w, text_h = text_surface.get_size()
        box_inner_w = text_w + 2 * padding_x
    
    final_box_w = min(box_inner_w, max_box_w)
    final_box_h = text_h + 2 * padding_y
    
    # Position box near bottom, centered
    box_rect = pygame.Rect(0, 0, final_box_w, final_box_h)
    box_rect.center = (gs.WIDTH // 2, gs.HEIGHT - 70) # Original positioning
    box_rect.clamp_ip(gs.screen.get_rect()) # Ensure it's on screen

    pygame.draw.rect(gs.screen, COLORS['MESSAGE_BOX_BG'], box_rect, border_radius=10)
    pygame.draw.rect(gs.screen, COLORS['BLACK'], box_rect, 2, border_radius=10)
    
    text_blit_rect = text_surface.get_rect(center=box_rect.center)
    gs.screen.blit(text_surface, text_blit_rect)

    pygame.display.flip()
    pygame.time.delay(delay)

def draw_stats_display(gs):
    stat_text = f"Побед: {gs.stats['win']} Поражений: {gs.stats['lose']}"
    text_surface = gs.get_font('stat').render(stat_text, True, COLORS['BLACK'])
    gs.screen.blit(text_surface, (10, 10))

def draw_timer_display(gs):
    current_display_time = gs.elapsed_game_time
    if gs.game_start_time > 0: # Timer is active
        current_display_time = (time.time() - gs.game_start_time) + gs.elapsed_game_time
    
    minutes = int(current_display_time // 60)
    seconds = int(current_display_time % 60)
    time_str = f"Время: {minutes:02d}:{seconds:02d}"
    text_surface = gs.get_font('timer').render(time_str, True, COLORS['BLACK'])
    timer_x_pos = gs.WIDTH - text_surface.get_width() - 10
    gs.screen.blit(text_surface, (timer_x_pos, 10))

def draw_game_board(gs, config_module, menu_btn_enabled=True):
    draw_gradient_background(gs.screen, gs.WIDTH, gs.HEIGHT, config_module.COLORS['BG_COLOR1'], config_module.COLORS['BG_COLOR2'])
    draw_stats_display(gs)
    draw_timer_display(gs)

    guesses_to_draw = gs.custom_guesses_count if gs.custom_mode_active else config_module.GUESSES
    grid_width = gs.difficulty * config_module.CELL_SIZE
    start_x = max(10, (gs.WIDTH - grid_width) // 2)
    start_y = 80 # Top margin for grid

    # Draw cells
    for r in range(guesses_to_draw):
        for c in range(gs.difficulty):
            x = start_x + c * config_module.CELL_SIZE
            y = start_y + r * (config_module.CELL_SIZE + 10) # 10px spacing
            
            letter, cell_bg, border_c, letter_c = '', config_module.COLORS['WHITE'], config_module.COLORS['EMPTY_BORDER'], config_module.COLORS['BLACK']

            if r < gs.current_guess_idx: # Submitted guess
                word = gs.user_guesses[r]
                if c < len(word):
                    letter = word[c].upper()
                    if c < len(gs.secret_word) and gs.secret_word[c] == word[c]: cell_bg = config_module.COLORS['GREEN']
                    elif c < len(gs.secret_word) and word[c] in gs.secret_word: cell_bg = config_module.COLORS['YELLOW']
                    else: cell_bg = config_module.COLORS['GRAY']
                    letter_c = config_module.COLORS['WHITE']
                border_c = config_module.COLORS['BLACK']
            elif r == gs.current_guess_idx: # Current typing row
                current_word = gs.get_current_word_being_typed()
                if c < len(current_word): letter = current_word[c].upper()
                if c == gs.active_cell_idx and gs.active_cell_idx < gs.difficulty:
                     pygame.draw.rect(gs.screen, (100, 150, 255), (x-2, y-2, config_module.CELL_SIZE+4, config_module.CELL_SIZE+4), border_radius=10) # Active cell highlight
                border_c = config_module.COLORS['BLACK']
            else: # Future rows
                cell_bg = config_module.COLORS['EMPTY_BORDER']
                border_c = (200,200,200)

            pygame.draw.rect(gs.screen, cell_bg, (x, y, config_module.CELL_SIZE, config_module.CELL_SIZE), border_radius=8)
            pygame.draw.rect(gs.screen, border_c, (x, y, config_module.CELL_SIZE, config_module.CELL_SIZE), 2, border_radius=8)
            if letter:
                draw_text_centered(gs.screen, letter, gs.get_font('main'), letter_c, x + config_module.CELL_SIZE // 2, y + config_module.CELL_SIZE // 2)

    # Buttons below grid
    buttons_y = start_y + guesses_to_draw * (config_module.CELL_SIZE + 10) + 20
    enter_rect = pygame.Rect(gs.WIDTH//2 - 130, buttons_y, 120, 50)
    pygame.draw.rect(gs.screen, (180, 220, 180), enter_rect, border_radius=12) # Greenish
    draw_text_centered(gs.screen, "Ввод", gs.get_font('small'), config_module.COLORS['BLACK'], enter_rect.centerx, enter_rect.centery)

    menu_rect = pygame.Rect(gs.WIDTH//2 + 10, buttons_y, 120, 50)
    btn_color = (180, 220, 180) if menu_btn_enabled else config_module.COLORS['DISABLED_BUTTON']
    pygame.draw.rect(gs.screen, btn_color, menu_rect, border_radius=12)
    draw_text_centered(gs.screen, "Меню", gs.get_font('small'), config_module.COLORS['BLACK'], menu_rect.centerx, menu_rect.centery)
    
    return start_x, start_y, enter_rect, menu_rect # Return rects for click detection

def show_result_screen_display(gs, config_module, win_status, secret_word_val, time_taken):
    gs.game_start_time = 0 # Stop active timer

    res_w, res_h = 400, 350
    res_x, res_y = (gs.WIDTH - res_w) // 2, (gs.HEIGHT - res_h) // 2
    continue_btn_rect = pygame.Rect(gs.WIDTH // 2 - 75, res_y + res_h - 60, 150, 40)

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: pygame.quit(); sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN and continue_btn_rect.collidepoint(event.pos):
                running = False

        draw_gradient_background(gs.screen, gs.WIDTH, gs.HEIGHT, config_module.COLORS['BG_COLOR1'], config_module.COLORS['BG_COLOR2'])
        pygame.draw.rect(gs.screen, config_module.COLORS['RESULT_BG'], (res_x, res_y, res_w, res_h), border_radius=15)
        pygame.draw.rect(gs.screen, config_module.COLORS['BLACK'], (res_x, res_y, res_w, res_h), 2, border_radius=15)

        title = "ПОБЕДА!" if win_status else "ПОРАЖЕНИЕ!"
        title_color = config_module.COLORS['GREEN'] if win_status else config_module.COLORS['GRAY']
        draw_text_centered(gs.screen, title, gs.get_font('main'), title_color, gs.WIDTH // 2, res_y + 30 + gs.get_font('main').get_height()//2)
        
        draw_text_centered(gs.screen, f"Загаданное слово: {secret_word_val.upper()}", gs.get_font('small'), config_module.COLORS['BLACK'], gs.WIDTH // 2, res_y + 90 + gs.get_font('small').get_height()//2)
        
        mins, secs = divmod(int(time_taken), 60)
        draw_text_centered(gs.screen, f"Затраченное время: {mins:02d}:{secs:02d}", gs.get_font('small'), config_module.COLORS['BLACK'], gs.WIDTH // 2, res_y + 140 + gs.get_font('small').get_height()//2)

        stats_y_offset = res_y + 190
        if win_status:
            draw_text_centered(gs.screen, f"Угадано за {gs.current_guess_idx + 1} попыток", gs.get_font('stat'), config_module.COLORS['BLACK'], gs.WIDTH // 2, res_y + 180 + gs.get_font('stat').get_height()//2)
            stats_y_offset = res_y + 220
        
        draw_text_centered(gs.screen, f"Общий счёт: {gs.stats['win']} побед, {gs.stats['lose']} поражений", gs.get_font('stat'), config_module.COLORS['BLACK'], gs.WIDTH // 2, stats_y_offset + gs.get_font('stat').get_height()//2)

        pygame.draw.rect(gs.screen, (180, 220, 180), continue_btn_rect, border_radius=10)
        draw_text_centered(gs.screen, "Продолжить", gs.get_font('small'), config_module.COLORS['BLACK'], continue_btn_rect.centerx, continue_btn_rect.centery)

        pygame.display.flip()
        gs.clock.tick(config_module.FPS)

def show_main_menu_display(gs, config_module):
    gs.custom_mode_active = False # Reset flag
    gs.WIDTH, gs.HEIGHT = config_module.DEFAULT_WIDTH, config_module.DEFAULT_HEIGHT
    gs.update_display_mode()

    buttons = []
    available_lengths = sorted([length for length, words in gs.WORD_SETS.items() if words])
    
    btn_y_start, btn_spacing = 180, 70
    
    running = True
    while running:
        draw_gradient_background(gs.screen, gs.WIDTH, gs.HEIGHT, config_module.COLORS['MENU_BG_GRAD1'], config_module.COLORS['MENU_BG_GRAD2'])
        draw_text_centered(gs.screen, "Выберите сложность", gs.get_font('main'), config_module.COLORS['BLACK'], gs.WIDTH // 2, 100 + gs.get_font('main').get_height()//2)
        
        buttons.clear()
        displayed_btns = 0
        for length in available_lengths:
            # Original complex condition for limiting displayed standard difficulties
            if not (3 <= length <= 10) and (len(available_lengths) > 4 and not (4 <= length <= 7)):
                continue

            btn_text = f"{length} букв ({len(gs.WORD_SETS.get(length, []))} слов)"
            rect = pygame.Rect(gs.WIDTH // 2 - 150, btn_y_start + displayed_btns * btn_spacing, 300, 50)
            pygame.draw.rect(gs.screen, config_module.COLORS['GRAY'], rect, border_radius=12)
            draw_text_centered(gs.screen, btn_text, gs.get_font('small'), config_module.COLORS['BLACK'], rect.centerx, rect.centery)
            buttons.append((rect, length))
            displayed_btns += 1
            if displayed_btns >= 5 and len(available_lengths) > 6: break # Limit displayed buttons

        custom_btn_rect = pygame.Rect(gs.WIDTH // 2 - 100, btn_y_start + displayed_btns * btn_spacing, 200, 50)
        pygame.draw.rect(gs.screen, config_module.COLORS['GRAY'], custom_btn_rect, border_radius=12)
        draw_text_centered(gs.screen, "Своя сложность", gs.get_font('custom_difficulty_button'), config_module.COLORS['BLACK'], custom_btn_rect.centerx, custom_btn_rect.centery)
        buttons.append((custom_btn_rect, 'custom'))

        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT: pygame.quit(); sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                for rect, choice in buttons:
                    if rect.collidepoint(event.pos):
                        if choice == 'custom': return 'custom'
                        if isinstance(choice, int) and gs.WORD_SETS.get(choice): return choice
                        # else: (No words for this length, should not happen if available_lengths is correct)

def _draw_custom_difficulty_inputs(gs, config_module, len_str, guess_str, active_field):
    draw_gradient_background(gs.screen, gs.WIDTH, gs.HEIGHT, config_module.COLORS['MENU_BG_GRAD1'], config_module.COLORS['MENU_BG_GRAD2'])
    draw_text_centered(gs.screen, "Введите параметры", gs.get_font('main'), config_module.COLORS['BLACK'], gs.WIDTH // 2, 100 + gs.get_font('main').get_height()//2)

    len_rect = pygame.Rect(gs.WIDTH // 2 - 100, 240, 200, 50)
    guess_rect = pygame.Rect(gs.WIDTH // 2 - 100, 340, 200, 50)

    draw_text_centered(gs.screen, "Длина слова (3-10):", gs.get_font('small'), config_module.COLORS['BLACK'], gs.WIDTH // 2, 200 + gs.get_font('small').get_height()//2)
    pygame.draw.rect(gs.screen, config_module.COLORS['WHITE'] if active_field == 'len' else config_module.COLORS['EMPTY_BORDER'], len_rect, 0, 8)
    pygame.draw.rect(gs.screen, config_module.COLORS['BLACK'], len_rect, 2, 8)
    len_surf = gs.get_font('small').render(len_str + ('|' if active_field == 'len' else ''), True, config_module.COLORS['BLACK'])
    gs.screen.blit(len_surf, (len_rect.x + 10, len_rect.centery - len_surf.get_height()//2))

    draw_text_centered(gs.screen, "Количество попыток (1-15):", gs.get_font('small'), config_module.COLORS['BLACK'], gs.WIDTH // 2, 300 + gs.get_font('small').get_height()//2)
    pygame.draw.rect(gs.screen, config_module.COLORS['WHITE'] if active_field == 'guess' else config_module.COLORS['EMPTY_BORDER'], guess_rect, 0, 8)
    pygame.draw.rect(gs.screen, config_module.COLORS['BLACK'], guess_rect, 2, 8)
    guess_surf = gs.get_font('small').render(guess_str + ('|' if active_field == 'guess' else ''), True, config_module.COLORS['BLACK'])
    gs.screen.blit(guess_surf, (guess_rect.x + 10, guess_rect.centery - guess_surf.get_height()//2))

    if len_str:
        try:
            val = int(len_str)
            count = len(gs.WORD_SETS.get(val, []))
            color = config_module.COLORS['BLACK'] if count > 0 else (255,0,0)
            draw_text_centered(gs.screen, f"Длина: {val} ({count} слов)", gs.get_font('stat'), color, gs.WIDTH // 2, 390 + gs.get_font('stat').get_height()//2)
        except ValueError: pass # Ignore if not a valid int yet

def prompt_custom_difficulty_settings(gs, config_module):
    gs.custom_mode_active = True
    len_str, guess_str = '', ''
    active_field = 'len' # 'len' or 'guess'

    len_input_rect = pygame.Rect(gs.WIDTH // 2 - 100, 240, 200, 50)
    guess_input_rect = pygame.Rect(gs.WIDTH // 2 - 100, 340, 200, 50)
    start_btn_rect = pygame.Rect(gs.WIDTH // 2 - 75, 430, 150, 50)
    
    def _validate_and_start():
        nonlocal len_str, guess_str # To use from outer scope
        try:
            diff = int(len_str)
            g_count = int(guess_str)
            redraw_args = (gs, config_module, len_str, guess_str, active_field)

            if not (3 <= diff <= 10):
                show_message_box(gs, "Длина слова должна быть 3-10!", 1000, _draw_custom_difficulty_inputs, redraw_args)
                return False
            if not (1 <= g_count <= 15):
                show_message_box(gs, "Попыток должно быть 1-15!", 1000, _draw_custom_difficulty_inputs, redraw_args)
                return False
            if not (diff in gs.WORD_SETS and gs.WORD_SETS[diff]):
                show_message_box(gs, "Нет слов такой длины!", 1000, _draw_custom_difficulty_inputs, redraw_args)
                return False
            
            gs.difficulty = diff
            gs.custom_guesses_count = g_count
            return True # Success
        except ValueError:
            show_message_box(gs, "Ошибка ввода чисел!", 1000, _draw_custom_difficulty_inputs, redraw_args)
        return False

    running = True
    while running:
        _draw_custom_difficulty_inputs(gs, config_module, len_str, guess_str, active_field)
        pygame.draw.rect(gs.screen, config_module.COLORS['GRAY'], start_btn_rect, border_radius=12)
        draw_text_centered(gs.screen, "Начать", gs.get_font('small'), config_module.COLORS['BLACK'], start_btn_rect.centerx, start_btn_rect.centery)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT: pygame.quit(); sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if len_input_rect.collidepoint(event.pos): active_field = 'len'
                elif guess_input_rect.collidepoint(event.pos): active_field = 'guess'
                elif start_btn_rect.collidepoint(event.pos):
                    if _validate_and_start(): running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_TAB: active_field = 'guess' if active_field == 'len' else 'len'
                elif event.key == pygame.K_RETURN:
                    if _validate_and_start(): running = False
                elif event.key == pygame.K_BACKSPACE:
                    if active_field == 'len': len_str = len_str[:-1]
                    else: guess_str = guess_str[:-1]
                elif event.unicode.isdigit():
                    if active_field == 'len' and len(len_str) < 2: len_str += event.unicode
                    elif active_field == 'guess' and len(guess_str) < 2: guess_str += event.unicode
        if not running: break # Exit loop if validation successful

    gs.WIDTH, gs.HEIGHT = calculate_window_size(gs.difficulty, gs.custom_guesses_count, config_module.CELL_SIZE)
    gs.update_display_mode()
    # gs.difficulty is now set, game can start

Упростите код без изменения функционала, переведите комментарии на русский, удалите излишние комментарии