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

def calculate_window_size(word_length, guesses_count, cell_size):
    """Вычисляет размер окна на основе длины слова и количества попыток."""
    field_width = word_length * cell_size
    field_height = guesses_count * (cell_size + 10)
    width = max(480, field_width + 80)
    height = max(700, field_height + 220)
    return width, height

def wrap_text(text, font, max_width):
    """Разбивает текст на строки, чтобы каждая строка помещалась в max_width."""
    words = text.split(' ')
    lines = []
    current_line = ''

    for word in words:
        test_line = current_line + word + ' '
        if font.size(test_line)[0] <= max_width:
            current_line = test_line
        else:
            lines.append(current_line.strip())
            current_line = word + ' '
    lines.append(current_line.strip())
    return lines

def show_message_box(gs, text, delay=500, redraw_background_func=None, redraw_args=()):
    """Показывает всплывающее сообщение."""
    if redraw_background_func:
        redraw_background_func(*redraw_args)

    main_font = gs.get_font('main')
    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_width = text_w + 2 * padding_x
    max_box_width = gs.WIDTH - 40

    if box_width > max_box_width:
        text_surface = small_font.render(text, True, COLORS['BLACK'])
        text_w, text_h = text_surface.get_size()
        box_width = text_w + 2 * padding_x

    final_width = min(box_width, max_box_width)
    final_height = text_h + 2 * padding_y

    box_rect = pygame.Rect(0, 0, final_width, final_height)
    box_rect.center = (gs.WIDTH // 2, gs.HEIGHT - 70)
    box_rect.clamp_ip(gs.screen.get_rect())

    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)

    gs.screen.blit(text_surface, text_surface.get_rect(center=box_rect.center))
    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_time = gs.elapsed_game_time
    if gs.game_start_time > 0:
        current_time += time.time() - gs.game_start_time

    minutes = int(current_time // 60)
    seconds = int(current_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

    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)

            letter, cell_bg, border_c, letter_c = '', COLORS['WHITE'], COLORS['EMPTY_BORDER'], COLORS['BLACK']

            if r < gs.current_guess_idx:
                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 = COLORS['GREEN']
                    elif c < len(gs.secret_word) and word[c] in gs.secret_word:
                        cell_bg = COLORS['YELLOW']
                    else:
                        cell_bg = COLORS['GRAY']
                    letter_c = COLORS['WHITE']
                border_c = COLORS['BLACK']
            elif r == gs.current_guess_idx:
                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 c < 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)
                border_c = COLORS['BLACK']
            else:
                cell_bg = 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_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)
    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

def show_result_screen_display(gs, config_module, win_status, secret_word_val, time_taken):
    """Показывает экран результатов."""
    gs.game_start_time = 0

    # Размеры окна
    res_w, res_h = 400, 350
    res_x, res_y = (gs.WIDTH - res_w) // 2, (gs.HEIGHT - res_h) // 2

    # Кнопка "Продолжить"
    continue_btn_text = "Продолжить"
    continue_btn_font = gs.get_font('small')
    continue_btn_text_surface = continue_btn_font.render(continue_btn_text, True, config_module.COLORS['BLACK'])
    continue_btn_width = continue_btn_text_surface.get_width() + 80  # Добавляем отступы
    continue_btn_height = continue_btn_text_surface.get_height() + 20
    continue_btn_rect = pygame.Rect(
        gs.WIDTH // 2 - continue_btn_width // 2,
        res_y + res_h - 60,
        continue_btn_width,
        continue_btn_height
    )

    # Текст "Загаданное слово: ..."
    secret_word_text = f"Загаданное слово: {secret_word_val.upper()}"
    secret_word_lines = wrap_text(secret_word_text, gs.get_font('small'), res_w - 40)

    # Пересчитываем высоту окна
    res_h = 200 + len(secret_word_lines) * 30  # Учитываем высоту каждой строки
    res_y = (gs.HEIGHT - res_h) // 2

    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 + 50)

        # Отображаем загаданное слово с переносом строк
        y_offset = res_y + 100
        for line in secret_word_lines:
            draw_text_centered(gs.screen, line, gs.get_font('small'), config_module.COLORS['BLACK'], gs.WIDTH // 2, y_offset)
            y_offset += 30

        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, y_offset)
        y_offset += 40

        stats_y_offset = y_offset
        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, y_offset)
            stats_y_offset = y_offset + 30

        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)

        # Кнопка "Продолжить"
        pygame.draw.rect(gs.screen, (180, 220, 180), continue_btn_rect, border_radius=10)
        draw_text_centered(gs.screen, continue_btn_text, continue_btn_font, 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
    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)

        buttons.clear()
        displayed_btns = 0
        for length in available_lengths:
            if not (3 <= length <= 10) and (len(available_lengths) > 4 and not (4 <= length <= 7)):
                continue

            btn_text = f"{length} {'буквы' if length in [3, 4] else 'букв'} ({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

        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':
                            result = prompt_custom_difficulty_settings(gs, config_module)
                            if result is not None:
                                return result
                        elif isinstance(choice, int) and gs.WORD_SETS.get(choice):
                            return choice

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)

    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)
    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)
    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, 420)
        except ValueError:
            pass

def prompt_custom_difficulty_settings(gs, config_module):
    """Обрабатывает ввод параметров пользовательской сложности."""
    gs.custom_mode_active = True
    len_str, guess_str = '', ''
    active_field = 'len'

    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 - 150, 430, 130, 50)
    back_btn_rect = pygame.Rect(gs.WIDTH // 2 + 20, 430, 130, 50)

    def _validate_and_start():
        redraw_args = (gs, config_module, len_str, guess_str, active_field) 
        try:
            diff = int(len_str)
            g_count = int(guess_str)

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

            gs.difficulty = diff
            gs.custom_guesses_count = g_count
            return True
        except ValueError:
            show_message_box(gs, "Введите число!", 2500, _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.draw.rect(gs.screen, config_module.COLORS['GRAY'], back_btn_rect, border_radius=12)
        draw_text_centered(gs.screen, "Назад", gs.get_font('small'), config_module.COLORS['BLACK'], back_btn_rect.centerx, back_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
                elif back_btn_rect.collidepoint(event.pos):
                    # Возврат в главное меню
                    return None
            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

    return gs.difficulty

В "своей сложности" поле "количество попыток" игнорируется при генерации игрового поля