import pygame
import sys
import requests
from io import BytesIO
import time

# Initialize Pygame
pygame.init()

# Constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
PLAYER_WIDTH = 70
PLAYER_HEIGHT = 70
PLAYER_SPEED = 5
GRAVITY = 0.5
JUMP_HEIGHT = 10
HEALTH_BAR_X = 20
HEALTH_BAR_Y = 20
HEALTH_BAR_SPACING = 60
HEART_SIZE = (50, 50)
HEALTH_MAX = 5
ATTACK_COOLDOWN = 1.0  # 1 second cooldown for the attack

# Create the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Simple Platformer")

# Load background image
background_image_url = "https://i.postimg.cc/0ysh6P0C/a73d3d43-c748-433b-9bf6-429868abcf94.png"
background_image = pygame.image.load(BytesIO(requests.get(background_image_url).content)).convert_alpha()
background_image = pygame.transform.scale(background_image, (SCREEN_WIDTH, SCREEN_HEIGHT))

# Load player image from URL
player_image_url = "https://i.postimg.cc/HWtqdsnQ/removal.png"
player_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get(player_image_url).content)).convert_alpha(), (PLAYER_WIDTH, PLAYER_HEIGHT))
player_rect = player_image.get_rect(center=(SCREEN_WIDTH // 4, SCREEN_HEIGHT // 2 + 50))

# Load ground image
ground_image_url = "https://i.postimg.cc/Kct6m1nY/ad.png"
ground_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get(ground_image_url).content)).convert_alpha(), (SCREEN_WIDTH * 2, 50))

# Player variables
player_x_speed = 0
player_y_speed = 0
on_ground = False
facing_left = False

# Camera variables
camera_x = 0

# Load heart images from URLs
filled_heart_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get("https://i.postimg.cc/1zqKQNLR/filled-hr.png").content)).convert_alpha(), HEART_SIZE)
unfilled_heart_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get("https://i.postimg.cc/RFxLVZB7/unfilled-hr.png").content)).convert_alpha(), HEART_SIZE)

# Load ability icon image and cooldown timer font
ability_icon_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get("https://i.postimg.cc/0ysh6P0C/a73d3d43-c748-433b-9bf6-429868abcf94.png").content)).convert_alpha(), (50, 50))
cooldown_font = pygame.font.Font(None, 24)

# Load attack slash image
slash_image_url = "https://i.postimg.cc/MHczQTLV/slash.png"
slash_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get(slash_image_url).content)).convert_alpha(), (PLAYER_WIDTH, PLAYER_HEIGHT))

# Health variables
health = HEALTH_MAX
ability_cooldown = 0
last_attack_time = 0

# Menu function
def main_menu():
    menu_font = pygame.font.Font(None, 36)
    menu_options = ["Start Game", "Credits", "Exit"]
    option_rects = [(menu_font.render(option, True, WHITE), menu_font.render(option, True, WHITE).get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + index * 50))) for index, option in enumerate(menu_options)]
    arrow_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get("https://i.postimg.cc/1tXYwzdL/arrow.png").content)).convert_alpha(), (20, 20))

    selection_index = 0
    running_menu = True
    while running_menu:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    selection_index = (selection_index - 1) % len(menu_options)
                elif event.key == pygame.K_DOWN:
                    selection_index = (selection_index + 1) % len(menu_options)
                elif event.key == pygame.K_RETURN:
                    if menu_options[selection_index] == "Start Game":
                        running_menu = False
                    elif menu_options[selection_index] == "Credits":
                        display_credits()
                    elif menu_options[selection_index] == "Exit":
                        pygame.quit()
                        sys.exit()

        screen.fill(BLACK)
        screen.blit(background_image, (0, 0))
        for i, (text, rect) in enumerate(option_rects):
            screen.blit(text, rect)
            if i == selection_index:
                arrow_rect = pygame.Rect(rect.left - 30, rect.centery - 10, 20, 20)
                screen.blit(arrow_image, arrow_rect)
        pygame.display.flip()

# Credits function
def display_credits():
    credits_font = pygame.font.Font(None, 36)
    credits_text = credits_font.render("Credits:", True, WHITE)
    credits_text_rect = credits_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 50))

    names = ["John Doe", "Jane Smith", "Alice Johnson"]
    name_texts = [credits_font.render(name, True, WHITE) for name in names]
    name_rects = [text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + index * 50)) for index, text in enumerate(name_texts)]

    back_text = credits_font.render("Back to Menu (ESC)", True, WHITE)
    back_text_rect = back_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT - 50))

    displaying_credits = True
    while displaying_credits:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    displaying_credits = False

        screen.fill(BLACK)
        screen.blit(background_image, (0, 0))
        screen.blit(credits_text, credits_text_rect)
        for text, rect in zip(name_texts, name_rects):
            screen.blit(text, rect)
        screen.blit(back_text, back_text_rect)
        pygame.display.flip()

# Game over function
def game_over():
    global health, player_x_speed  # Reset player_x_speed here
    player_x_speed = 0  # Reset player's horizontal speed
    game_over_font = pygame.font.Font(None, 72)
    game_over_text = game_over_font.render("Game Over", True, WHITE)
    game_over_rect = game_over_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2))

    retry_font = pygame.font.Font(None, 36)
    retry_text = retry_font.render("Press 'R' to Retry", True, WHITE)
    retry_rect = retry_text.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 100))

    retrying = True
    while retrying:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    health = HEALTH_MAX  # Reset health to HEALTH_MAX
                    return True  # Indicate that the game should be restarted

        screen.fill(BLACK)
        screen.blit(background_image, (0, 0))
        screen.blit(game_over_text, game_over_rect)
        screen.blit(retry_text, retry_rect)
        pygame.display.flip()

# Pause menu function
def pause_menu():
    menu_font = pygame.font.Font(None, 36)
    menu_options = ["Resume", "Restart", "Back to Main Menu"]
    option_rects = [(menu_font.render(option, True, WHITE), menu_font.render(option, True, WHITE).get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + index * 50))) for index, option in enumerate(menu_options)]
    arrow_image = pygame.transform.scale(pygame.image.load(BytesIO(requests.get("https://i.postimg.cc/1tXYwzdL/arrow.png").content)).convert_alpha(), (20, 20))

    selection_index = 0
    running_menu = True
    while running_menu:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    selection_index = (selection_index - 1) % len(menu_options)
                elif event.key == pygame.K_DOWN:
                    selection_index = (selection_index + 1) % len(menu_options)
                elif event.key == pygame.K_RETURN:
                    if menu_options[selection_index] == "Resume":
                        return "resume"  # Indicate to resume the game
                    elif menu_options[selection_index] == "Restart":
                        return "restart"
                    elif menu_options[selection_index] == "Back to Main Menu":
                        return True  # Indicate to go back to the main menu

        screen.fill(BLACK)
        screen.blit(background_image, (0, 0))
        for i, (text, rect) in enumerate(option_rects):
            screen.blit(text, rect)
            if i == selection_index:
                arrow_rect = pygame.Rect(rect.left - 30, rect.centery - 10, 20, 20)
                screen.blit(arrow_image, arrow_rect)
        pygame.display.flip()

def game_loop():
    global player_x_speed, player_y_speed, on_ground, facing_left, camera_x, health, ability_cooldown, last_attack_time
    health = HEALTH_MAX  # Initialize health here
    ability_cooldown = 0
    last_attack_time = 0
    running = True
    paused = False
    attack_slash = None
    while running:
        current_time = time.time()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player_x_speed = -PLAYER_SPEED
                    facing_left = True
                elif event.key == pygame.K_RIGHT:
                    player_x_speed = PLAYER_SPEED
                    facing_left = False
                elif event.key == pygame.K_SPACE and on_ground:
                    player_y_speed = -JUMP_HEIGHT
                    on_ground = False
                elif event.key == pygame.K_a:
                    if ability_cooldown == 0:
                        last_attack_time = current_time
                        ability_cooldown = ATTACK_COOLDOWN
                        if facing_left:
                            attack_slash = slash_image.copy()
                        else:
                            attack_slash = pygame.transform.flip(slash_image, True, False)
                elif event.key == pygame.K_ESCAPE:
                    paused = not paused
                    if paused:
                        action = pause_menu()
                        if action == "restart":
                            return "restart"
                        elif action == "resume":
                            paused = False  # Resume the game
                        elif action:
                            return  # Go back to the main menu
                        pygame.event.clear()  # Clear any events that might have occurred during pause
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    player_x_speed = 0  # Stop player movement when arrow keys are released

        if not paused:
            if ability_cooldown > 0:
                ability_cooldown -= current_time - last_attack_time
                last_attack_time = current_time
                if ability_cooldown < 0:
                    ability_cooldown = 0

            player_y_speed += GRAVITY
            player_rect.x += player_x_speed
            player_rect.y += player_y_speed
            camera_x = player_rect.x - SCREEN_WIDTH // 4

            if player_rect.bottom >= SCREEN_HEIGHT - ground_image.get_height():
                player_rect.bottom = SCREEN_HEIGHT - ground_image.get_height()
                player_y_speed = 0
                on_ground = True

            screen.blit(background_image, (0, 0))
            ground_x = -camera_x % ground_image.get_width()
            screen.blit(ground_image, (ground_x - ground_image.get_width(), SCREEN_HEIGHT - ground_image.get_height()))
            screen.blit(ground_image, (ground_x, SCREEN_HEIGHT - ground_image.get_height()))
            player_draw_rect = player_rect.move(-camera_x, 0)
            if facing_left:
                screen.blit(pygame.transform.flip(player_image, True, False), player_draw_rect)
            else:
                screen.blit(player_image, player_draw_rect)

            if attack_slash:
                slash_rect = attack_slash.get_rect(center=player_draw_rect.center)
                if facing_left:
                    slash_rect.x -= PLAYER_WIDTH
                else:
                    slash_rect.x += PLAYER_WIDTH
                screen.blit(attack_slash, slash_rect)
                attack_slash = None

            # Draw health bar
            for i in range(health):
                heart_x = HEALTH_BAR_X + i * HEALTH_BAR_SPACING
                screen.blit(filled_heart_image, (heart_x, HEALTH_BAR_Y))
            for i in range(health, HEALTH_MAX):
                heart_x = HEALTH_BAR_X + i * HEALTH_BAR_SPACING
                screen.blit(unfilled_heart_image, (heart_x, HEALTH_BAR_Y))

            # Draw ability icon
            screen.blit(ability_icon_image, (20, SCREEN_HEIGHT - 70))
            if ability_cooldown > 0:
                cooldown_text = cooldown_font.render(f"{ability_cooldown:.1f}", True, WHITE)
                screen.blit(cooldown_text, (30, SCREEN_HEIGHT - 40))

            pygame.display.flip()
            pygame.time.Clock().tick(60)

# Main function
def main():
    main_menu()
    while True:
        action = game_loop()
        if action == "restart":
            continue
        else:
            main_menu()

if __name__ == "__main__":
    main()

# Quit Pygame
pygame.quit()
sys.exit()