# src/saturn2d/ui.py
import pygame


class UIElement:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height)
        self.visible = True

    def handle_event(self, event):
        pass

    def update(self, dt):
        pass

    def render(self, screen):
        pass


class Label(UIElement):
    def __init__(self, x, y, text, font_size=24, color=(255, 255, 255)):
        self.font = pygame.font.SysFont(None, font_size)
        self.text = text
        self.color = color
        text_surface = self.font.render(text, True, color)
        width, height = text_surface.get_size()
        super().__init__(x, y, width, height)

    def set_text(self, new_text):
        self.text = new_text

    def render(self, screen):
        if not self.visible:
            return
        text_surface = self.font.render(self.text, True, self.color)
        screen.blit(text_surface, self.rect.topleft)


class Button(UIElement):
    def __init__(self, x, y, width, height, text, onclick=None,
                 bg_color=(50, 50, 50),
                 hover_color=(80, 80, 80),
                 text_color=(255, 255, 255)):

        super().__init__(x, y, width, height)
        self.onclick = onclick
        self.bg_color = bg_color
        self.hover_color = hover_color
        self.text_color = text_color

        self.font = pygame.font.SysFont(None, 24)
        self.text = text
        self.hovered = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.hovered = self.rect.collidepoint(event.pos)

        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1 and self.hovered:
                if self.onclick:
                    self.onclick()

    def render(self, screen):
        if not self.visible:
            return

        color = self.hover_color if self.hovered else self.bg_color
        pygame.draw.rect(screen, color, self.rect)

        text_surface = self.font.render(self.text, True, self.text_color)
        text_rect = text_surface.get_rect(center=self.rect.center)
        screen.blit(text_surface, text_rect)