import pygame
import sys
import math

# Initialize Pygame
pygame.init()

# Window settings
WIDTH, HEIGHT = 900, 650
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("🌲 Forest Ice & Fire - 森林冰火人")
clock = pygame.time.Clock()

# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 60, 60)
BLUE = (60, 160, 255)
GREEN = (50, 200, 50)
DARK_GREEN = (30, 120, 30)
BROWN = (139, 69, 19)
GRAY = (150, 150, 150)
LIGHT_GRAY = (220, 220, 220)
ORANGE = (255, 150, 0)
YELLOW = (255, 255, 0)
LAVA = (255, 120, 0)
WATER = (50, 150, 255)
GOLD = (255, 215, 0)

# Fonts
title_font = pygame.font.Font(None, 72)
large_font = pygame.font.Font(None, 56)
font = pygame.font.Font(None, 40)
small_font = pygame.font.Font(None, 28)
tiny_font = pygame.font.Font(None, 20)

# Tile size
TILE_SIZE = 40


class Tile:
    EMPTY = 0
    WALL = 1
    FLOOR = 2
    LAVA = 3
    WATER = 4
    EXIT = 5
    GEM = 6
    ICE_START = 7
    FIRE_START = 8


class Particle:
    def __init__(self, x, y, color, lifetime=30, speed=3):
        self.x = x
        self.y = y
        self.color = color
        self.lifetime = lifetime
        self.max_lifetime = lifetime
        self.speed = speed
        angle = math.radians(360 * (hash((x, y)) % 360) / 360)
        self.vx = math.cos(angle) * speed
        self.vy = math.sin(angle) * speed - 2
        self.size = 4
    
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += 0.1
        self.lifetime -= 1
        return self.lifetime > 0
    
    def draw(self, screen):
        alpha = int(255 * (self.lifetime / self.max_lifetime))
        size = int(self.size * (self.lifetime / self.max_lifetime))
        if size > 0:
            pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), size)


class Player:
    def __init__(self, x, y, color, name, element):
        self.x = x
        self.y = y
        self.width = 28
        self.height = 38
        self.vx = 0
        self.vy = 0
        self.speed = 3.5
        self.jump_power = -9
        self.gravity = 0.5
        self.on_ground = False
        self.color = color
        self.name = name
        self.element = element
        self.alive = True
        self.at_exit = False
        self.gems_collected = 0
        self.facing = 1
        self.walk_frame = 0
        self.frame_counter = 0
        self.respawn_x = x
        self.respawn_y = y
    
    def update(self, tiles):
        if not self.alive:
            return
        
        self.vy += self.gravity
        if self.vy > 15:
            self.vy = 15
        
        # Horizontal
        self.x += self.vx
        for tile in tiles:
            if tile[2] == Tile.WALL:
                tile_rect = pygame.Rect(tile[0] * TILE_SIZE, tile[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                player_rect = pygame.Rect(self.x, self.y, self.width, self.height)
                if player_rect.colliderect(tile_rect):
                    if self.vx > 0:
                        self.x = tile_rect.left - self.width
                    elif self.vx < 0:
                        self.x = tile_rect.right
                    self.vx = 0
        
        # Vertical
        self.y += self.vy
        self.on_ground = False
        for tile in tiles:
            if tile[2] == Tile.WALL:
                tile_rect = pygame.Rect(tile[0] * TILE_SIZE, tile[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                player_rect = pygame.Rect(self.x, self.y, self.width, self.height)
                if player_rect.colliderect(tile_rect):
                    if self.vy > 0:
                        self.y = tile_rect.top - self.height
                        self.vy = 0
                        self.on_ground = True
                    elif self.vy < 0:
                        self.y = tile_rect.bottom
                        self.vy = 0
        
        # Bounds
        if self.x < 0:
            self.x = 0
        if self.x + self.width > WIDTH:
            self.x = WIDTH - self.width
        if self.y + self.height > HEIGHT - 50:
            self.y = HEIGHT - 50 - self.height
            self.vy = 0
            self.on_ground = True
    
    def jump(self):
        if self.on_ground:
            self.vy = self.jump_power
            self.on_ground = False
    
    def move_left(self):
        self.vx = -self.speed
        self.facing = -1
    
    def move_right(self):
        self.vx = self.speed
        self.facing = 1
    
    def stop(self):
        self.vx = 0
    
    def check_hazards(self, tiles):
        if not self.alive:
            return None
        
        player_rect = pygame.Rect(self.x + 4, self.y + 4, self.width - 8, self.height - 8)
        for tile in tiles:
            tile_type = tile[2]
            tile_rect = pygame.Rect(tile[0] * TILE_SIZE, tile[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
            if player_rect.colliderect(tile_rect):
                if tile_type == Tile.GEM:
                    self.gems_collected += 1
                    return "gem", (tile_rect.centerx, tile_rect.centery)
                elif tile_type == Tile.EXIT:
                    self.at_exit = True
                elif tile_type == Tile.LAVA and self.element == "water":
                    self.alive = False
                    return "death", None
                elif tile_type == Tile.WATER and self.element == "fire":
                    self.alive = False
                    return "death", None
        return None
    
    def respawn(self):
        self.x = self.respawn_x
        self.y = self.respawn_y
        self.vx = 0
        self.vy = 0
        self.alive = True
        self.at_exit = False
    
    def draw(self, screen):
        if not self.alive:
            return
        
        # Shadow
        shadow_rect = pygame.Rect(self.x + 4, self.y + self.height, self.width - 8, 4)
        pygame.draw.ellipse(screen, (0, 0, 0, 50), shadow_rect)
        
        # Animation
        if self.vx != 0:
            self.frame_counter += 1
            if self.frame_counter > 6:
                self.frame_counter = 0
                self.walk_frame = (self.walk_frame + 1) % 4
        
        # Body
        body_rect = pygame.Rect(self.x + 2, self.y + 10, self.width - 4, self.height - 12)
        pygame.draw.rect(screen, self.color, body_rect, border_radius=4)
        
        # Head
        head_radius = 11
        head_x = self.x + self.width // 2
        head_y = self.y + 10
        pygame.draw.circle(screen, self.color, (head_x, head_y), head_radius)
        
        # Eyes
        eye_offset = 4 * self.facing
        pygame.draw.circle(screen, WHITE, (head_x - 4 + eye_offset, head_y - 2), 4)
        pygame.draw.circle(screen, WHITE, (head_x + 4 + eye_offset, head_y - 2), 4)
        pygame.draw.circle(screen, BLACK, (head_x - 3 + eye_offset, head_y - 1), 2)
        pygame.draw.circle(screen, BLACK, (head_x + 5 + eye_offset, head_y - 1), 2)
        
        # Glow
        glow_color = (255, 150, 50) if self.element == "fire" else (50, 150, 255)
        glow_surf = pygame.Surface((self.width + 20, self.height + 20), pygame.SRCALPHA)
        pygame.draw.ellipse(glow_surf, (*glow_color, 30), (0, 0, self.width + 20, self.height + 20))
        screen.blit(glow_surf, (self.x - 10, self.y - 10))
        
        # Name
        name_text = tiny_font.render(self.name, True, WHITE)
        name_rect = name_text.get_rect(center=(self.x + self.width//2, self.y - 12))
        name_bg = pygame.Surface((name_rect.width + 10, name_rect.height + 4), pygame.SRCALPHA)
        name_bg.fill((0, 0, 0, 180))
        screen.blit(name_bg, (name_rect.x - 5, name_rect.y - 2))
        screen.blit(name_text, name_rect)


class Menu:
    def __init__(self):
        self.state = "menu"
        self.selected_level = 0
        self.unlocked_levels = 1
        self.total_levels = 3
        self.hover_button = None
        
        self.menu_buttons = [
            {"text": "▶ Start Game", "rect": None, "action": "start"},
            {"text": "📚 Level Select", "rect": None, "action": "levels"},
            {"text": "❓ How to Play", "rect": None, "action": "help"},
            {"text": "🚪 Quit", "rect": None, "action": "quit"}
        ]
        
        self.level_buttons = []
        for i in range(self.total_levels):
            self.level_buttons.append({
                "text": f"Level {i+1}",
                "level": i+1,
                "rect": None,
                "locked": i+1 > self.unlocked_levels
            })
        
        self.help_text = [
            "🎮 How to Play:",
            "",
            "🔥 FireBoy:  WASD  to move and jump",
            "💧 WaterGirl: Arrow Keys to move and jump",
            "",
            "⚡ FireBoy is immune to LAVA",
            "💦 WaterGirl is immune to WATER",
            "💀 Touching the wrong element = DEATH!",
            "",
            "⭐ Collect all gems and reach the exit!",
            "🤝 Work together to solve puzzles!",
            "",
            "Press ESC to return to menu"
        ]
    
    def handle_event(self, event):
        if self.state == "menu":
            if event.type == pygame.MOUSEMOTION:
                self.hover_button = None
                for btn in self.menu_buttons:
                    if btn["rect"] and btn["rect"].collidepoint(event.pos):
                        self.hover_button = btn["text"]
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                for btn in self.menu_buttons:
                    if btn["rect"] and btn["rect"].collidepoint(event.pos):
                        if btn["action"] == "start":
                            self.state = "playing"
                            return "start"
                        elif btn["action"] == "levels":
                            self.state = "level_select"
                        elif btn["action"] == "help":
                            self.state = "help"
                        elif btn["action"] == "quit":
                            return "quit"
            
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                return "quit"
        
        elif self.state == "level_select":
            if event.type == pygame.MOUSEMOTION:
                self.hover_button = None
                for btn in self.level_buttons:
                    if btn["rect"] and btn["rect"].collidepoint(event.pos):
                        self.hover_button = btn["text"]
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                for btn in self.level_buttons:
                    if btn["rect"] and btn["rect"].collidepoint(event.pos):
                        if not btn["locked"]:
                            self.selected_level = btn["level"]
                            self.state = "playing"
                            return "start"
            
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self.state = "menu"
        
        elif self.state == "help":
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                self.state = "menu"
            if event.type == pygame.MOUSEBUTTONDOWN:
                self.state = "menu"
        
        return None
    
    def draw(self, screen):
        if self.state == "menu":
            self.draw_menu(screen)
        elif self.state == "level_select":
            self.draw_level_select(screen)
        elif self.state == "help":
            self.draw_help(screen)
    
    def draw_menu(self, screen):
        # Background
        for y in range(HEIGHT):
            color = (10, 30 + int(80 * (y / HEIGHT)), 20 + int(40 * (y / HEIGHT)))
            pygame.draw.line(screen, color, (0, y), (WIDTH, y))
        
        # Title
        title_text = title_font.render("🌲 Forest", True, (255, 200, 100))
        title_rect = title_text.get_rect(center=(WIDTH//2 - 80, 100))
        screen.blit(title_text, title_rect)
        
        title_text2 = title_font.render("Ice & Fire", True, (100, 200, 255))
        title_rect2 = title_text2.get_rect(center=(WIDTH//2 + 80, 160))
        screen.blit(title_text2, title_rect2)
        
        sub_text = small_font.render("🔥❄️ A cooperative adventure ❄️🔥", True, (200, 200, 200))
        sub_rect = sub_text.get_rect(center=(WIDTH//2, 210))
        screen.blit(sub_text, sub_rect)
        
        # Buttons
        button_y = 270
        for btn in self.menu_buttons:
            is_hover = self.hover_button == btn["text"]
            color = (100, 200, 100) if is_hover else (60, 120, 60)
            border_color = (150, 255, 150) if is_hover else (80, 160, 80)
            
            rect = pygame.Rect(WIDTH//2 - 150, button_y, 300, 50)
            btn["rect"] = rect
            
            pygame.draw.rect(screen, color, rect, border_radius=10)
            pygame.draw.rect(screen, border_color, rect, 2, border_radius=10)
            
            text_color = WHITE if not is_hover else (255, 255, 200)
            text = font.render(btn["text"], True, text_color)
            text_rect = text.get_rect(center=rect.center)
            screen.blit(text, text_rect)
            
            button_y += 65
        
        credit_text = tiny_font.render("WASD (Fire) | Arrow Keys (Water) | ESC to quit", True, (100, 100, 100))
        credit_rect = credit_text.get_rect(center=(WIDTH//2, HEIGHT - 30))
        screen.blit(credit_text, credit_rect)
    
    def draw_level_select(self, screen):
        screen.fill((20, 40, 20))
        
        title_text = large_font.render("📚 Select Level", True, WHITE)
        title_rect = title_text.get_rect(center=(WIDTH//2, 80))
        screen.blit(title_text, title_rect)
        
        button_x = WIDTH//2 - 200
        button_y = 160
        for i, btn in enumerate(self.level_buttons):
            x = button_x + (i % 3) * 200
            y = button_y + (i // 3) * 140
            
            rect = pygame.Rect(x, y, 160, 100)
            btn["rect"] = rect
            
            if btn["locked"]:
                color = (60, 60, 60)
                border_color = (80, 80, 80)
            else:
                is_hover = self.hover_button == btn["text"]
                color = (80, 150, 80) if is_hover else (50, 100, 50)
                border_color = (120, 200, 120) if is_hover else (70, 130, 70)
            
            pygame.draw.rect(screen, color, rect, border_radius=15)
            pygame.draw.rect(screen, border_color, rect, 3, border_radius=15)
            
            text_color = (150, 150, 150) if btn["locked"] else WHITE
            text = font.render(btn["text"], True, text_color)
            text_rect = text.get_rect(center=(rect.centerx, rect.centery - 10))
            screen.blit(text, text_rect)
            
            if btn["locked"]:
                lock_text = small_font.render("🔒 Locked", True, (150, 100, 100))
            else:
                lock_text = small_font.render("✅ Unlocked", True, (100, 200, 100))
            lock_rect = lock_text.get_rect(center=(rect.centerx, rect.centery + 25))
            screen.blit(lock_text, lock_rect)
        
        hint_text = small_font.render("Press ESC to go back", True, (150, 150, 150))
        hint_rect = hint_text.get_rect(center=(WIDTH//2, HEIGHT - 40))
        screen.blit(hint_text, hint_rect)
    
    def draw_help(self, screen):
        screen.fill((20, 30, 40))
        
        title_text = large_font.render("❓ How to Play", True, WHITE)
        title_rect = title_text.get_rect(center=(WIDTH//2, 60))
        screen.blit(title_text, title_rect)
        
        y = 120
        for line in self.help_text:
            color = (200, 200, 200)
            if "🔥" in line:
                color = (255, 150, 50)
            elif "💧" in line:
                color = (50, 150, 255)
            elif "🎮" in line or "⭐" in line or "🤝" in line:
                color = (255, 215, 0)
            
            text = small_font.render(line, True, color)
            text_rect = text.get_rect(center=(WIDTH//2, y))
            screen.blit(text, text_rect)
            y += 32
        
        hint_text = small_font.render("Click or press ESC to return", True, (150, 150, 150))
        hint_rect = hint_text.get_rect(center=(WIDTH//2, HEIGHT - 30))
        screen.blit(hint_text, hint_rect)


class Game:
    def __init__(self):
        self.menu = Menu()
        self.game_state = "menu"
        self.level = 1
        self.tiles = []
        self.fire_boy = None
        self.water_girl = None
        self.particles = []
        self.total_gems = 0
        self.gems_remaining = 0
        self.message = ""
        self.message_timer = 0
        self.level_complete = False
        self.death_message = ""
        self.death_timer = 0
        
        self.load_level(1)
    
    def load_level(self, level_num):
        self.level = level_num
        self.tiles = []
        self.particles = []
        self.total_gems = 0
        self.gems_remaining = 0
        self.level_complete = False
        self.message = ""
        self.message_timer = 0
        
        levels = {
            1: [
                "WWWWWWWWWWWWWWWWWWWW",
                "W                  W",
                "W      F           W",
                "W                  W",
                "W    LLL           W",
                "W                  W",
                "W        I         W",
                "W     G  G         W",
                "W    WWWWW         W",
                "W    W   W         W",
                "W    W   W         W",
                "W   WWW WWW        W",
                "W   W     W        W",
                "W   W     W   E    W",
                "WWWWWWWWWWWWWWWWWWWW",
            ],
            2: [
                "WWWWWWWWWWWWWWWWWWWW",
                "W         F        W",
                "W                  W",
                "W    LLL  GGG      W",
                "W                  W",
                "W    GGG  WWW      W",
                "W         W   E    W",
                "W   GGG    W       W",
                "W          W       W",
                "W    WWWWWWW       W",
                "W                  W",
                "W   GGG  GGG       W",
                "W         I        W",
                "W         W        W",
                "WWWWWWWWWWWWWWWWWWWW",
            ],
            3: [
                "WWWWWWWWWWWWWWWWWWWW",
                "W         F        W",
                "W         W        W",
                "W   LLL   W        W",
                "W         W   G    W",
                "W   GGG   W        W",
                "W         W   E    W",
                "W  WWWWWWWW        W",
                "W                  W",
                "W   G      WWWW    W",
                "W          W       W",
                "W  LLL     W   I   W",
                "W          W       W",
                "W          W       W",
                "WWWWWWWWWWWWWWWWWWWW",
            ]
        }
        
        map_data = levels.get(level_num, levels[1])
        self.parse_map(map_data)
        
        if self.fire_boy:
            self.fire_boy.respawn_x = self.fire_boy.x
            self.fire_boy.respawn_y = self.fire_boy.y
        if self.water_girl:
            self.water_girl.respawn_x = self.water_girl.x
            self.water_girl.respawn_y = self.water_girl.y
    
    def parse_map(self, map_data):
        fire_start = None
        ice_start = None
        
        for row, line in enumerate(map_data):
            for col, char in enumerate(line):
                x = col * TILE_SIZE
                y = row * TILE_SIZE
                
                if char == 'W':
                    self.tiles.append((col, row, Tile.WALL))
                elif char == 'L':
                    self.tiles.append((col, row, Tile.LAVA))
                elif char == 'G':
                    self.tiles.append((col, row, Tile.GEM))
                    self.total_gems += 1
                    self.gems_remaining += 1
                elif char == 'E':
                    self.tiles.append((col, row, Tile.EXIT))
                elif char == 'F':
                    fire_start = (x + 6, y + 6)
                elif char == 'I':
                    ice_start = (x + 6, y + 6)
                elif char == ' ':
                    self.tiles.append((col, row, Tile.FLOOR))
        
        if fire_start:
            self.fire_boy = Player(fire_start[0], fire_start[1], RED, "🔥 Fire", "fire")
        if ice_start:
            self.water_girl = Player(ice_start[0], ice_start[1], BLUE, "💧 Water", "water")
    
    def handle_input(self):
        keys = pygame.key.get_pressed()
        
        if self.fire_boy and self.fire_boy.alive:
            if keys[pygame.K_a]:
                self.fire_boy.move_left()
            elif keys[pygame.K_d]:
                self.fire_boy.move_right()
            else:
                self.fire_boy.stop()
            if keys[pygame.K_w]:
                self.fire_boy.jump()
        
        if self.water_girl and self.water_girl.alive:
            if keys[pygame.K_LEFT]:
                self.water_girl.move_left()
            elif keys[pygame.K_RIGHT]:
                self.water_girl.move_right()
            else:
                self.water_girl.stop()
            if keys[pygame.K_UP]:
                self.water_girl.jump()
    
    def update(self):
        if self.menu.state == "playing":
            self.update_game()
        elif self.menu.state == "game_over":
            if self.death_timer > 0:
                self.death_timer -= 1
        elif self.menu.state == "victory":
            pass
    
    def update_game(self):
        if self.level_complete:
            return
        
        if self.fire_boy:
            self.fire_boy.update(self.tiles)
        if self.water_girl:
            self.water_girl.update(self.tiles)
        
        # Check hazards for FireBoy
        if self.fire_boy:
            result = self.fire_boy.check_hazards(self.tiles)
            if result:
                if result[0] == "gem":
                    self.gems_remaining -= 1
                    self.particles.append(Particle(result[1][0], result[1][1], GOLD, 30, 4))
                    for i, tile in enumerate(self.tiles):
                        if tile[2] == Tile.GEM:
                            tile_rect = pygame.Rect(tile[0] * TILE_SIZE, tile[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                            if tile_rect.collidepoint(result[1]):
                                self.tiles[i] = (tile[0], tile[1], Tile.FLOOR)
                                break
                elif result[0] == "death":
                    self.menu.state = "game_over"
                    self.death_timer = 120
        
        # Check hazards for WaterGirl
        if self.water_girl:
            result = self.water_girl.check_hazards(self.tiles)
            if result:
                if result[0] == "gem":
                    self.gems_remaining -= 1
                    self.particles.append(Particle(result[1][0], result[1][1], GOLD, 30, 4))
                    for i, tile in enumerate(self.tiles):
                        if tile[2] == Tile.GEM:
                            tile_rect = pygame.Rect(tile[0] * TILE_SIZE, tile[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE)
                            if tile_rect.collidepoint(result[1]):
                                self.tiles[i] = (tile[0], tile[1], Tile.FLOOR)
                                break
                elif result[0] == "death":
                    self.menu.state = "game_over"
                    self.death_timer = 120
        
        # Update particles
        self.particles = [p for p in self.particles if p.update()]
        
        # Check level complete
        if self.fire_boy and self.water_girl:
            if (self.fire_boy.at_exit and self.water_girl.at_exit and 
                self.gems_remaining == 0 and self.fire_boy.alive and self.water_girl.alive):
                self.level_complete = True
                if self.level >= 3:
                    self.menu.state = "victory"
                else:
                    self.message = "🎉 Level Complete! 🎉"
                    self.message_timer = 120
                    self.menu.unlocked_levels = max(self.menu.unlocked_levels, self.level + 1)
        
        if self.message_timer > 0:
            self.message_timer -= 1
            if self.message_timer == 0:
                if self.level_complete and self.level < 3:
                    self.level += 1
                    self.load_level(self.level)
    
    def draw(self):
        if self.menu.state == "menu" or self.menu.state == "level_select" or self.menu.state == "help":
            self.menu.draw(screen)
            return
        
        self.draw_game()
        
        if self.menu.state == "game_over":
            self.draw_overlay("💀 GAME OVER", RED, "Press SPACE for menu, R to retry")
        elif self.menu.state == "victory":
            self.draw_overlay("🎉 YOU WIN!", GOLD, "Press SPACE for menu, R to retry")
    
    def draw_game(self):
        # Background
        for y in range(HEIGHT):
            color = (20, 40 + int(60 * (y / HEIGHT)), 20 + int(40 * (y / HEIGHT)))
            pygame.draw.line(screen, color, (0, y), (WIDTH, y))
        
        # Draw tiles
        for tile in self.tiles:
            x = tile[0] * TILE_SIZE
            y = tile[1] * TILE_SIZE
            tile_type = tile[2]
            
            if tile_type == Tile.WALL:
                pygame.draw.rect(screen, (60, 80, 60), (x, y, TILE_SIZE, TILE_SIZE))
                pygame.draw.rect(screen, (80, 110, 80), (x+2, y+2, TILE_SIZE-4, 4))
                pygame.draw.rect(screen, (40, 60, 40), (x, y, TILE_SIZE, TILE_SIZE), 1)
            elif tile_type == Tile.LAVA:
                for i in range(3):
                    ox = math.sin(pygame.time.get_ticks() / 500 + i * 2) * 3
                    oy = math.cos(pygame.time.get_ticks() / 400 + i * 2) * 3
                    color = (255, 80 + i * 30, 0)
                    pygame.draw.rect(screen, color, (x + ox + i*2, y + oy + i*2, TILE_SIZE - i*4, TILE_SIZE - i*4), border_radius=5)
                pygame.draw.rect(screen, (255, 150, 50, 100), (x, y, TILE_SIZE, TILE_SIZE), 1)
            elif tile_type == Tile.WATER:
                for i in range(3):
                    ox = math.sin(pygame.time.get_ticks() / 600 + i * 3) * 4
                    oy = math.cos(pygame.time.get_ticks() / 500 + i * 3) * 4
                    color = (50, 100 + i * 50, 255 - i * 30)
                    pygame.draw.rect(screen, color, (x + ox + i*2, y + oy + i*2, TILE_SIZE - i*4, TILE_SIZE - i*4), border_radius=5)
            elif tile_type == Tile.EXIT:
                pulse = abs(math.sin(pygame.time.get_ticks() / 300)) * 20 + 80
                color = (100, 255, 100, pulse)
                pygame.draw.rect(screen, (50, 200, 50), (x+5, y+5, TILE_SIZE-10, TILE_SIZE-10), border_radius=8)
                pygame.draw.rect(screen, (100, 255, 100), (x+5, y+5, TILE_SIZE-10, TILE_SIZE-10), 3, border_radius=8)
                exit_text = font.render("🚪", True, WHITE)
                screen.blit(exit_text, (x+8, y+5))
            elif tile_type == Tile.GEM:
                pulse = abs(math.sin(pygame.time.get_ticks() / 400)) * 5
                gem_y = y + 5 + pulse
                pygame.draw.polygon(screen, GOLD, [
                    (x + TILE_SIZE//2, gem_y),
                    (x + TILE_SIZE - 8, gem_y + TILE_SIZE//2 - 2),
                    (x + TILE_SIZE//2, gem_y + TILE_SIZE - 8 - pulse//2),
                    (x + 8, gem_y + TILE_SIZE//2 - 2)
                ])
                pygame.draw.polygon(screen, (255, 240, 150), [
                    (x + TILE_SIZE//2, gem_y + 3),
                    (x + TILE_SIZE - 12, gem_y + TILE_SIZE//2 - 2),
                    (x + TILE_SIZE//2, gem_y + TILE_SIZE - 12 - pulse//2)
                ], 1)
        
        # Draw particles
        for p in self.particles:
            p.draw(screen)
        
        # Draw players
        if self.fire_boy:
            self.fire_boy.draw(screen)
        if self.water_girl:
            self.water_girl.draw(screen)
        
        # UI
        ui_bg = pygame.Surface((250, 60), pygame.SRCALPHA)
        ui_bg.fill((0, 0, 0, 150))
        screen.blit(ui_bg, (10, 10))
        
        gems_text = font.render(f"⭐ {self.gems_remaining}", True, GOLD)
        screen.blit(gems_text, (20, 12))
        
        level_text = font.render(f"Level {self.level}", True, WHITE)
        screen.blit(level_text, (120, 12))
        
        if self.message:
            msg_text = font.render(self.message, True, GOLD)
            msg_rect = msg_text.get_rect(center=(WIDTH//2, 100))
            screen.blit(msg_text, msg_rect)
    
    def draw_overlay(self, title, color, hint):
        overlay = pygame.Surface((WIDTH, HEIGHT))
        overlay.set_alpha(180)
        overlay.fill(BLACK)
        screen.blit(overlay, (0, 0))
        
        title_text = large_font.render(title, True, color)
        title_rect = title_text.get_rect(center=(WIDTH//2, 250))
        screen.blit(title_text, title_rect)
        
        hint_text = font.render(hint, True, WHITE)
        hint_rect = hint_text.get_rect(center=(WIDTH//2, 330))
        screen.blit(hint_text, hint_rect)
    
    def reset_level(self):
        self.load_level(self.level)
        self.menu.state = "playing"


def main():
    game = Game()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            result = game.menu.handle_event(event)
            if result == "quit":
                running = False
            elif result == "start":
                game.load_level(game.menu.selected_level if game.menu.selected_level > 0 else 1)
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and (game.menu.state == "game_over" or game.menu.state == "victory"):
                    game.reset_level()
                if event.key == pygame.K_SPACE and (game.menu.state == "game_over" or game.menu.state == "victory"):
                    game.menu.state = "menu"
        
        if game.menu.state == "playing" or game.menu.state == "game_over" or game.menu.state == "victory":
            game.handle_input()
            game.update()
            game.draw()
        else:
            game.draw()
        
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()